1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2010 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>
111 #include <mach-o/nlist.h>
121 #include "UICaboodle/BrowserView.h"
123 #include "substrate.h"
130 #define _timestamp ({ \
132 gettimeofday(&tv, NULL); \
133 tv.tv_sec * 1000000 + tv.tv_usec; \
136 typedef std::vector<class ProfileTime *> TimeList;
146 ProfileTime(const char *name) :
150 times_.push_back(this);
153 void AddTime(uint64_t time) {
160 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
172 ProfileTimer(ProfileTime &time) :
179 time_.AddTime(_timestamp - start_);
184 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
186 std::cerr << "========" << std::endl;
189 #define _profile(name) { \
190 static ProfileTime name(#name); \
191 ProfileTimer _ ## name(name);
196 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
198 #define CYPoolStart() \
199 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
201 #define CYPoolEnd() \
205 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
207 void NSLogPoint(const char *fix, const CGPoint &point) {
208 NSLog(@"%s(%g,%g)", fix, point.x, point.y);
211 void NSLogRect(const char *fix, const CGRect &rect) {
212 NSLog(@"%s(%g,%g)+(%g,%g)", fix, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
215 static _finline NSString *CydiaURL(NSString *path) {
217 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = ':';
218 page[5] = '/'; page[6] = '/'; page[7] = 'c'; page[8] = 'y'; page[9] = 'd';
219 page[10] = 'i'; page[11] = 'a'; page[12] = '.'; page[13] = 's'; page[14] = 'a';
220 page[15] = 'u'; page[16] = 'r'; page[17] = 'i'; page[18] = 'k'; page[19] = '.';
221 page[20] = 'c'; page[21] = 'o'; page[22] = 'm'; page[23] = '/'; page[24] = '\0';
222 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
225 static _finline void UpdateExternalStatus(uint64_t newStatus) {
227 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
228 notify_set_state(notify_token, newStatus);
229 notify_cancel(notify_token);
231 notify_post("com.saurik.Cydia.status");
234 /* [NSObject yieldToSelector:(withObject:)] {{{*/
235 @interface NSObject (Cydia)
236 - (id) yieldToSelector:(SEL)selector withObject:(id)object;
237 - (id) yieldToSelector:(SEL)selector;
240 @implementation NSObject (Cydia)
245 - (void) _yieldToContext:(NSMutableArray *)context { _pooled
246 SEL selector(reinterpret_cast<SEL>([[context objectAtIndex:0] pointerValue]));
247 id object([[context objectAtIndex:1] nonretainedObjectValue]);
248 volatile bool &stopped(*reinterpret_cast<bool *>([[context objectAtIndex:2] pointerValue]));
250 /* XXX: deal with exceptions */
251 id value([self performSelector:selector withObject:object]);
253 NSMethodSignature *signature([self methodSignatureForSelector:selector]);
254 [context removeAllObjects];
255 if ([signature methodReturnLength] != 0 && value != nil)
256 [context addObject:value];
261 performSelectorOnMainThread:@selector(doNothing)
267 - (id) yieldToSelector:(SEL)selector withObject:(id)object {
268 /*return [self performSelector:selector withObject:object];*/
270 volatile bool stopped(false);
272 NSMutableArray *context([NSMutableArray arrayWithObjects:
273 [NSValue valueWithPointer:selector],
274 [NSValue valueWithNonretainedObject:object],
275 [NSValue valueWithPointer:const_cast<bool *>(&stopped)],
278 NSThread *thread([[[NSThread alloc]
280 selector:@selector(_yieldToContext:)
286 NSRunLoop *loop([NSRunLoop currentRunLoop]);
287 NSDate *future([NSDate distantFuture]);
289 while (!stopped && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
291 return [context count] == 0 ? nil : [context objectAtIndex:0];
294 - (id) yieldToSelector:(SEL)selector {
295 return [self yieldToSelector:selector withObject:nil];
301 /* Cydia Action Sheet {{{ */
302 @interface CYActionSheet : UIAlertView {
306 - (int) yieldToPopupAlertAnimated:(BOOL)animated;
309 @implementation CYActionSheet
311 - (id) initWithTitle:(NSString *)title buttons:(NSArray *)buttons defaultButtonIndex:(int)index {
312 if ((self = [super init])) {
313 [self setTitle:title];
314 [self setDelegate:self];
315 for (NSString *button in buttons) [self addButtonWithTitle:button];
316 [self setCancelButtonIndex:index];
320 - (void) _updateFrameForDisplay {
321 [super _updateFrameForDisplay];
322 if ([self cancelButtonIndex] == -1) {
323 NSArray *buttons = [self buttons];
324 if ([buttons count]) {
325 UIImage *background = [[buttons objectAtIndex:0] backgroundForState:0];
326 for (UIThreePartButton *button in buttons)
327 [button setBackground:background forState:0];
332 - (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
333 button_ = buttonIndex + 1;
337 [self dismissWithClickedButtonIndex:-1 animated:YES];
340 - (int) yieldToPopupAlertAnimated:(BOOL)animated {
341 [self setRunsModal:YES];
350 /* NSForcedOrderingSearch doesn't work on the iPhone */
351 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
352 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
353 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
355 /* Information Dictionaries {{{ */
356 @interface NSMutableArray (Cydia)
357 - (void) addInfoDictionary:(NSDictionary *)info;
360 @implementation NSMutableArray (Cydia)
362 - (void) addInfoDictionary:(NSDictionary *)info {
363 [self addObject:info];
368 @interface NSMutableDictionary (Cydia)
369 - (void) addInfoDictionary:(NSDictionary *)info;
372 @implementation NSMutableDictionary (Cydia)
374 - (void) addInfoDictionary:(NSDictionary *)info {
375 [self setObject:info forKey:[info objectForKey:@"CFBundleIdentifier"]];
381 #define lprintf(args...) fprintf(stderr, args)
384 #define TraceLogging (1 && !ForRelease)
385 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
386 #define ProfileTimes (0 && !ForRelease)
387 #define ForSaurik (0 && !ForRelease)
388 #define LogBrowser (0 && !ForRelease)
389 #define TrackResize (0 && !ForRelease)
390 #define ManualRefresh (1 && !ForRelease)
391 #define ShowInternals (0 && !ForRelease)
392 #define IgnoreInstall (0 && !ForRelease)
393 #define AlwaysReload (0 && !ForRelease)
397 #define _trace(args...)
402 #define _profile(name) {
405 #define PrintTimes() do {} while (false)
409 typedef uint32_t (*SKRadixFunction)(id, void *);
411 @interface NSMutableArray (Radix)
412 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
420 @implementation NSMutableArray (Radix)
422 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
423 size_t count([self count]);
424 struct RadixItem_ *swap(new RadixItem_[count * 2]);
426 for (size_t i(0); i != count; ++i) {
427 RadixItem_ &item(swap[i]);
430 id object([self objectAtIndex:i]);
431 item.key = function(object, argument);
434 struct RadixItem_ *lhs(swap), *rhs(swap + count);
436 static const size_t width = 32;
437 static const size_t bits = 11;
438 static const size_t slots = 1 << bits;
439 static const size_t passes = (width + (bits - 1)) / bits;
441 size_t *hist(new size_t[slots]);
443 for (size_t pass(0); pass != passes; ++pass) {
444 memset(hist, 0, sizeof(size_t) * slots);
446 for (size_t i(0); i != count; ++i) {
447 uint32_t key(lhs[i].key);
449 key &= _not(uint32_t) >> width - bits;
454 for (size_t i(0); i != slots; ++i) {
455 size_t local(offset);
460 for (size_t i(0); i != count; ++i) {
461 uint32_t key(lhs[i].key);
463 key &= _not(uint32_t) >> width - bits;
464 rhs[hist[key]++] = lhs[i];
467 RadixItem_ *tmp(lhs);
474 const void **values(new const void *[count]);
475 for (size_t i(0); i != count; ++i)
476 values[i] = [self objectAtIndex:lhs[i].index];
477 CFArrayReplaceValues((CFMutableArrayRef) self, CFRangeMake(0, count), values, count);
485 /* Insertion Sort {{{ */
487 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
488 const char *ptr = (const char *)list;
490 CFIndex half = count / 2;
491 const char *probe = ptr + elementSize * half;
492 CFComparisonResult cr = comparator(element, probe, context);
493 if (0 == cr) return (probe - (const char *)list) / elementSize;
494 ptr = (cr < 0) ? ptr : probe + elementSize;
495 count = (cr < 0) ? half : (half + (count & 1) - 1);
497 return (ptr - (const char *)list) / elementSize;
500 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
501 const char *ptr = (const char *)list;
503 CFIndex half = count / 2;
504 const char *probe = ptr + elementSize * half;
505 CFComparisonResult cr = comparator(element, probe, context);
506 if (0 == cr) return (probe - (const char *)list) / elementSize;
507 ptr = (cr < 0) ? ptr : probe + elementSize;
508 count = (cr < 0) ? half : (half + (count & 1) - 1);
510 return (ptr - (const char *)list) / elementSize;
513 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
514 if (range.length == 0)
516 const void **values(new const void *[range.length]);
517 CFArrayGetValues(array, range, values);
519 #if HistogramInsertionSort > 0
520 uint32_t total(0), *offsets(new uint32_t[range.length]);
523 for (CFIndex index(1); index != range.length; ++index) {
524 const void *value(values[index]);
525 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
526 CFIndex correct(index);
527 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
528 #if HistogramInsertionSort > 1
529 NSLog(@"%@ < %@", value, values[correct - 1]);
534 if (correct != index) {
535 size_t offset(index - correct);
536 #if HistogramInsertionSort
540 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
542 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
543 values[correct] = value;
547 CFArrayReplaceValues(array, range, values, range.length);
550 #if HistogramInsertionSort > 0
551 for (CFIndex index(0); index != range.length; ++index)
552 if (offsets[index] != 0)
553 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
554 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
561 /* Apple Bug Fixes {{{ */
562 @implementation UIWebDocumentView (Cydia)
564 - (void) _setScrollerOffset:(CGPoint)offset {
565 UIScroller *scroller([self _scroller]);
567 CGSize size([scroller contentSize]);
568 CGSize bounds([scroller bounds].size);
571 max.x = size.width - bounds.width;
572 max.y = size.height - bounds.height;
580 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
581 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
583 [scroller setOffset:offset];
589 @implementation WebScriptObject (NSFastEnumeration)
591 - (NSUInteger) countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)objects count:(NSUInteger)count {
592 size_t length([self count] - state->state);
595 else if (length > count)
597 for (size_t i(0); i != length; ++i)
598 objects[i] = [self objectAtIndex:state->state++];
599 state->itemsPtr = objects;
600 state->mutationsPtr = (unsigned long *) self;
606 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
607 size_t length([self length] - state->state);
610 else if (length > count)
612 for (size_t i(0); i != length; ++i)
613 objects[i] = [self item:state->state++];
614 state->itemsPtr = objects;
615 state->mutationsPtr = (unsigned long *) self;
619 /* Cydia NSString Additions {{{ */
620 @interface NSString (Cydia)
621 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
622 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
623 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
624 - (NSComparisonResult) compareByPath:(NSString *)other;
625 - (NSString *) stringByCachingURLWithCurrentCDN;
626 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
629 @implementation NSString (Cydia)
631 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
632 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
635 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
636 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
637 memcpy(data, bytes, length);
638 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
641 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
642 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
645 - (NSComparisonResult) compareByPath:(NSString *)other {
646 NSString *prefix = [self commonPrefixWithString:other options:0];
647 size_t length = [prefix length];
649 NSRange lrange = NSMakeRange(length, [self length] - length);
650 NSRange rrange = NSMakeRange(length, [other length] - length);
652 lrange = [self rangeOfString:@"/" options:0 range:lrange];
653 rrange = [other rangeOfString:@"/" options:0 range:rrange];
655 NSComparisonResult value;
657 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
658 value = NSOrderedSame;
659 else if (lrange.location == NSNotFound)
660 value = NSOrderedAscending;
661 else if (rrange.location == NSNotFound)
662 value = NSOrderedDescending;
664 value = NSOrderedSame;
666 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
667 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
668 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
669 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
671 NSComparisonResult result = [lpath compare:rpath];
672 return result == NSOrderedSame ? value : result;
675 - (NSString *) stringByCachingURLWithCurrentCDN {
677 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
678 withString:@"://cache.cydia.saurik.com/"
682 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
683 return [(id)CFURLCreateStringByAddingPercentEscapes(
688 kCFStringEncodingUTF8
695 /* C++ NSString Wrapper Cache {{{ */
696 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
697 return size == 0 ? NULL :
698 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
699 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
702 static _finline CFStringRef CYStringCreate(const char *data) {
703 return CYStringCreate(data, strlen(data));
712 _finline void clear_() {
713 if (cache_ != NULL) {
720 _finline bool empty() const {
724 _finline size_t size() const {
728 _finline char *data() const {
732 _finline void clear() {
737 _finline CYString() :
744 _finline ~CYString() {
748 void operator =(const CYString &rhs) {
752 if (rhs.cache_ == nil)
755 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
758 void set(apr_pool_t *pool, const char *data, size_t size) {
764 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size + 1)));
765 memcpy(temp, data, size);
772 _finline void set(apr_pool_t *pool, const char *data) {
773 set(pool, data, data == NULL ? 0 : strlen(data));
776 _finline void set(apr_pool_t *pool, const std::string &rhs) {
777 set(pool, rhs.data(), rhs.size());
780 bool operator ==(const CYString &rhs) const {
781 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
784 _finline operator CFStringRef() {
786 cache_ = CYStringCreate(data_, size_);
790 _finline operator id() {
791 return (NSString *) static_cast<CFStringRef>(*this);
795 /* C++ NSString Algorithm Adapters {{{ */
797 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
800 struct NSStringMapHash :
801 std::unary_function<NSString *, size_t>
803 _finline size_t operator ()(NSString *value) const {
804 return CFStringHashNSString((CFStringRef) value);
808 struct NSStringMapLess :
809 std::binary_function<NSString *, NSString *, bool>
811 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
812 return [lhs compare:rhs] == NSOrderedAscending;
816 struct NSStringMapEqual :
817 std::binary_function<NSString *, NSString *, bool>
819 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
820 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
821 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
822 //[lhs isEqualToString:rhs];
827 /* Perl-Compatible RegEx {{{ */
837 Pcre(const char *regex) :
842 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
845 lprintf("%d:%s\n", offset, error);
849 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
850 matches_ = new int[(capture_ + 1) * 3];
858 NSString *operator [](size_t match) {
859 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
862 bool operator ()(NSString *data) {
863 // XXX: length is for characters, not for bytes
864 return operator ()([data UTF8String], [data length]);
867 bool operator ()(const char *data, size_t size) {
869 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
873 /* Mime Addresses {{{ */
874 @interface Address : NSObject {
880 - (NSString *) address;
882 - (void) setAddress:(NSString *)address;
884 + (Address *) addressWithString:(NSString *)string;
885 - (Address *) initWithString:(NSString *)string;
888 @implementation Address
897 - (NSString *) name {
901 - (NSString *) address {
905 - (void) setAddress:(NSString *)address {
907 [address_ autorelease];
911 address_ = [address retain];
914 + (Address *) addressWithString:(NSString *)string {
915 return [[[Address alloc] initWithString:string] autorelease];
918 + (NSArray *) _attributeKeys {
919 return [NSArray arrayWithObjects:@"address", @"name", nil];
922 - (NSArray *) attributeKeys {
923 return [[self class] _attributeKeys];
926 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
927 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
930 - (Address *) initWithString:(NSString *)string {
931 if ((self = [super init]) != nil) {
932 const char *data = [string UTF8String];
933 size_t size = [string length];
935 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
937 if (address_r(data, size)) {
938 name_ = [address_r[1] retain];
939 address_ = [address_r[2] retain];
941 name_ = [string retain];
949 /* CoreGraphics Primitives {{{ */
960 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
963 Set(space, red, green, blue, alpha);
968 CGColorRelease(color_);
975 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
977 float color[] = {red, green, blue, alpha};
978 color_ = CGColorCreate(space, (CGFloat *) color);
981 operator CGColorRef() {
987 /* Random Global Variables {{{ */
988 static const int PulseInterval_ = 50000;
989 static const int ButtonBarWidth_ = 60;
990 static const int ButtonBarHeight_ = 48;
991 static const float KeyboardTime_ = 0.3f;
994 static NSArray *Finishes_;
996 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
997 #define NotifyConfig_ "/etc/notify.conf"
999 static bool Queuing_;
1001 static CYColor Blue_;
1002 static CYColor Blueish_;
1003 static CYColor Black_;
1004 static CYColor Off_;
1005 static CYColor White_;
1006 static CYColor Gray_;
1007 static CYColor Green_;
1008 static CYColor Purple_;
1009 static CYColor Purplish_;
1011 static UIColor *InstallingColor_;
1012 static UIColor *RemovingColor_;
1014 static NSString *App_;
1015 static NSString *Home_;
1017 static BOOL Advanced_;
1018 static BOOL Ignored_;
1020 static UIFont *Font12_;
1021 static UIFont *Font12Bold_;
1022 static UIFont *Font14_;
1023 static UIFont *Font18Bold_;
1024 static UIFont *Font22Bold_;
1026 static const char *Machine_ = NULL;
1027 static NSString *System_ = nil;
1028 static NSString *SerialNumber_ = nil;
1029 static NSString *ChipID_ = nil;
1030 static NSString *Token_ = nil;
1031 static NSString *UniqueID_ = nil;
1032 static NSString *PLMN_ = nil;
1033 static NSString *Build_ = nil;
1034 static NSString *Product_ = nil;
1035 static NSString *Safari_ = nil;
1037 static CFLocaleRef Locale_;
1038 static NSArray *Languages_;
1039 static CGColorSpaceRef space_;
1041 static NSDictionary *SectionMap_;
1042 static NSMutableDictionary *Metadata_;
1043 static _transient NSMutableDictionary *Settings_;
1044 static _transient NSString *Role_;
1045 static _transient NSMutableDictionary *Packages_;
1046 static _transient NSMutableDictionary *Sections_;
1047 static _transient NSMutableDictionary *Sources_;
1048 static bool Changed_;
1049 static NSDate *now_;
1051 static bool IsWildcat_;
1054 /* Display Helpers {{{ */
1055 inline float Interpolate(float begin, float end, float fraction) {
1056 return (end - begin) * fraction + begin;
1059 /* XXX: localize this! */
1060 NSString *SizeString(double size) {
1061 bool negative = size < 0;
1066 while (size > 1024) {
1071 static const char *powers_[] = {"B", "kB", "MB", "GB"};
1073 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
1076 static _finline const char *StripVersion_(const char *version) {
1077 const char *colon(strchr(version, ':'));
1079 version = colon + 1;
1083 NSString *LocalizeSection(NSString *section) {
1084 static Pcre title_r("^(.*?) \\((.*)\\)$");
1085 if (title_r(section)) {
1086 NSString *parent(title_r[1]);
1087 NSString *child(title_r[2]);
1089 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1090 LocalizeSection(parent),
1091 LocalizeSection(child)
1095 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1098 NSString *Simplify(NSString *title) {
1099 const char *data = [title UTF8String];
1100 size_t size = [title length];
1102 static Pcre square_r("^\\[(.*)\\]$");
1103 if (square_r(data, size))
1104 return Simplify(square_r[1]);
1106 static Pcre paren_r("^\\((.*)\\)$");
1107 if (paren_r(data, size))
1108 return Simplify(paren_r[1]);
1110 static Pcre title_r("^(.*?) \\((.*)\\)$");
1111 if (title_r(data, size))
1112 return Simplify(title_r[1]);
1118 NSString *GetLastUpdate() {
1119 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1122 return UCLocalize("NEVER_OR_UNKNOWN");
1124 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1125 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1127 CFRelease(formatter);
1129 return [(NSString *) formatted autorelease];
1132 bool isSectionVisible(NSString *section) {
1133 NSDictionary *metadata([Sections_ objectForKey:section]);
1134 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1135 return hidden == nil || ![hidden boolValue];
1140 /* Delegate Prototypes {{{ */
1144 @interface NSObject (ProgressDelegate)
1147 @protocol ProgressDelegate
1148 - (void) setProgressError:(NSString *)error withTitle:(NSString *)id;
1149 - (void) setProgressTitle:(NSString *)title;
1150 - (void) setProgressPercent:(float)percent;
1151 - (void) startProgress;
1152 - (void) addProgressOutput:(NSString *)output;
1153 - (bool) isCancelling:(size_t)received;
1156 @protocol ConfigurationDelegate
1157 - (void) repairWithSelector:(SEL)selector;
1158 - (void) setConfigurationData:(NSString *)data;
1161 @class PackageController;
1163 @protocol CydiaDelegate
1164 - (void) setPackageController:(PackageController *)view;
1165 - (void) clearPackage:(Package *)package;
1166 - (void) installPackage:(Package *)package;
1167 - (void) installPackages:(NSArray *)packages;
1168 - (void) removePackage:(Package *)package;
1169 - (void) beginUpdate;
1171 - (void) distUpgrade;
1173 - (void) updateData;
1175 - (void) showSettings;
1176 - (UIProgressHUD *) addProgressHUD;
1177 - (BOOL) hudIsShowing;
1178 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1179 - (CYViewController *) pageForPackage:(NSString *)name;
1180 - (PackageController *) packageController;
1181 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
1185 /* Status Delegation {{{ */
1187 public pkgAcquireStatus
1190 _transient NSObject<ProgressDelegate> *delegate_;
1198 void setDelegate(id delegate) {
1199 delegate_ = delegate;
1202 NSObject<ProgressDelegate> *getDelegate() const {
1206 virtual bool MediaChange(std::string media, std::string drive) {
1210 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1213 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1214 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1215 [delegate_ setProgressTitle:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), [NSString stringWithUTF8String:item.ShortDesc.c_str()]]];
1218 virtual void Done(pkgAcquire::ItemDesc &item) {
1221 virtual void Fail(pkgAcquire::ItemDesc &item) {
1223 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1224 item.Owner->Status == pkgAcquire::Item::StatDone
1228 std::string &error(item.Owner->ErrorText);
1232 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1233 NSArray *fields([description componentsSeparatedByString:@" "]);
1234 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1236 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
1237 withObject:[NSArray arrayWithObjects:
1238 [NSString stringWithUTF8String:error.c_str()],
1245 virtual bool Pulse(pkgAcquire *Owner) {
1246 bool value = pkgAcquireStatus::Pulse(Owner);
1249 double(CurrentBytes + CurrentItems) /
1250 double(TotalBytes + TotalItems)
1253 [delegate_ setProgressPercent:percent];
1254 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1257 virtual void Start() {
1258 [delegate_ startProgress];
1261 virtual void Stop() {
1265 /* Progress Delegation {{{ */
1270 _transient id<ProgressDelegate> delegate_;
1274 virtual void Update() {
1275 /*if (abs(Percent - percent_) > 2)
1276 //NSLog(@"%s:%s:%f", Op.c_str(), SubOp.c_str(), Percent);
1280 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1281 [delegate_ setProgressPercent:(Percent / 100)];*/
1291 void setDelegate(id delegate) {
1292 delegate_ = delegate;
1295 id getDelegate() const {
1299 virtual void Done() {
1301 //[delegate_ setProgressPercent:1];
1306 /* Database Interface {{{ */
1307 typedef std::map< unsigned long, _H<Source> > SourceMap;
1309 @interface Database : NSObject {
1315 pkgCacheFile cache_;
1316 pkgDepCache::Policy *policy_;
1317 pkgRecords *records_;
1318 pkgProblemResolver *resolver_;
1319 pkgAcquire *fetcher_;
1321 SPtr<pkgPackageManager> manager_;
1322 pkgSourceList *list_;
1325 CFMutableArrayRef packages_;
1327 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1336 + (Database *) sharedInstance;
1339 - (void) _readCydia:(NSNumber *)fd;
1340 - (void) _readStatus:(NSNumber *)fd;
1341 - (void) _readOutput:(NSNumber *)fd;
1345 - (Package *) packageWithName:(NSString *)name;
1347 - (pkgCacheFile &) cache;
1348 - (pkgDepCache::Policy *) policy;
1349 - (pkgRecords *) records;
1350 - (pkgProblemResolver *) resolver;
1351 - (pkgAcquire &) fetcher;
1352 - (pkgSourceList &) list;
1353 - (NSArray *) packages;
1354 - (NSArray *) sources;
1355 - (void) reloadData;
1363 - (void) updateWithStatus:(Status &)status;
1365 - (void) setDelegate:(id)delegate;
1366 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1369 /* Delegate Helpers {{{ */
1370 @implementation NSObject (ProgressDelegate)
1372 - (void) _setProgressErrorPackage:(NSArray *)args {
1373 [self performSelector:@selector(setProgressError:forPackage:)
1374 withObject:[args objectAtIndex:0]
1375 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1379 - (void) _setProgressErrorTitle:(NSArray *)args {
1380 [self performSelector:@selector(setProgressError:withTitle:)
1381 withObject:[args objectAtIndex:0]
1382 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1386 - (void) _setProgressError:(NSString *)error withTitle:(NSString *)title {
1387 [self performSelectorOnMainThread:@selector(_setProgressErrorTitle:)
1388 withObject:[NSArray arrayWithObjects:error, title, nil]
1393 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
1394 Package *package = id == nil ? nil : [[Database sharedInstance] packageWithName:id];
1396 [self performSelector:@selector(setProgressError:withTitle:)
1398 withObject:(package == nil ? id : [package name])
1405 /* Source Class {{{ */
1406 @interface Source : NSObject {
1407 CYString depiction_;
1408 CYString description_;
1414 CYString distribution_;
1419 NSString *authority_;
1421 CYString defaultIcon_;
1423 NSDictionary *record_;
1427 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1429 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1431 - (NSString *) depictionForPackage:(NSString *)package;
1432 - (NSString *) supportForPackage:(NSString *)package;
1434 - (NSDictionary *) record;
1438 - (NSString *) distribution;
1439 - (NSString *) type;
1441 - (NSString *) host;
1443 - (NSString *) name;
1444 - (NSString *) description;
1445 - (NSString *) label;
1446 - (NSString *) origin;
1447 - (NSString *) version;
1449 - (NSString *) defaultIcon;
1453 @implementation Source
1457 distribution_.clear();
1460 description_.clear();
1466 defaultIcon_.clear();
1468 if (record_ != nil) {
1478 if (authority_ != nil) {
1479 [authority_ release];
1485 // XXX: this is a very inefficient way to call these deconstructors
1490 + (NSArray *) _attributeKeys {
1491 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1494 - (NSArray *) attributeKeys {
1495 return [[self class] _attributeKeys];
1498 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1499 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1502 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1505 trusted_ = index->IsTrusted();
1507 uri_.set(pool, index->GetURI());
1508 distribution_.set(pool, index->GetDist());
1509 type_.set(pool, index->GetType());
1511 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1512 if (dindex != NULL) {
1514 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1517 pkgTagFile tags(&fd);
1519 pkgTagSection section;
1526 {"default-icon", &defaultIcon_},
1527 {"depiction", &depiction_},
1528 {"description", &description_},
1530 {"origin", &origin_},
1531 {"support", &support_},
1532 {"version", &version_},
1535 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1536 const char *start, *end;
1538 if (section.Find(names[i].name_, start, end)) {
1539 CYString &value(*names[i].value_);
1540 value.set(pool, start, end - start);
1546 record_ = [Sources_ objectForKey:[self key]];
1548 record_ = [record_ retain];
1550 NSURL *url([NSURL URLWithString:uri_]);
1554 host_ = [[host_ lowercaseString] retain];
1559 authority_ = [url path];
1561 if (authority_ != nil)
1562 authority_ = [authority_ retain];
1565 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1566 if ((self = [super init]) != nil) {
1567 [self setMetaIndex:index inPool:pool];
1571 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1572 NSDictionary *lhr = [self record];
1573 NSDictionary *rhr = [source record];
1576 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1578 NSString *lhs = [self name];
1579 NSString *rhs = [source name];
1581 if ([lhs length] != 0 && [rhs length] != 0) {
1582 unichar lhc = [lhs characterAtIndex:0];
1583 unichar rhc = [rhs characterAtIndex:0];
1585 if (isalpha(lhc) && !isalpha(rhc))
1586 return NSOrderedAscending;
1587 else if (!isalpha(lhc) && isalpha(rhc))
1588 return NSOrderedDescending;
1591 return [lhs compare:rhs options:LaxCompareOptions_];
1594 - (NSString *) depictionForPackage:(NSString *)package {
1595 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1598 - (NSString *) supportForPackage:(NSString *)package {
1599 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1602 - (NSDictionary *) record {
1610 - (NSString *) uri {
1614 - (NSString *) distribution {
1615 return distribution_;
1618 - (NSString *) type {
1622 - (NSString *) key {
1623 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1626 - (NSString *) host {
1630 - (NSString *) name {
1631 return origin_.empty() ? authority_ : origin_;
1634 - (NSString *) description {
1635 return description_;
1638 - (NSString *) label {
1639 return label_.empty() ? authority_ : label_;
1642 - (NSString *) origin {
1646 - (NSString *) version {
1650 - (NSString *) defaultIcon {
1651 return defaultIcon_;
1656 /* Relationship Class {{{ */
1657 @interface Relationship : NSObject {
1662 - (NSString *) type;
1664 - (NSString *) name;
1668 @implementation Relationship
1676 - (NSString *) type {
1684 - (NSString *) name {
1691 /* Package Class {{{ */
1692 @interface Package : NSObject {
1696 pkgCache::VerIterator version_;
1697 pkgCache::PkgIterator iterator_;
1698 _transient Database *database_;
1699 pkgCache::VerFileIterator file_;
1705 _transient NSString *section$_;
1710 CYString installed_;
1716 CYString depiction_;
1727 NSMutableArray *tags_;
1730 NSMutableDictionary *metadata_;
1731 _transient NSDate *firstSeen_;
1732 _transient NSDate *lastSeen_;
1736 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1737 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1739 - (pkgCache::PkgIterator) iterator;
1742 - (NSString *) section;
1743 - (NSString *) simpleSection;
1745 - (NSString *) longSection;
1746 - (NSString *) shortSection;
1750 - (Address *) maintainer;
1752 - (NSString *) longDescription;
1753 - (NSString *) shortDescription;
1756 - (NSMutableDictionary *) metadata;
1758 - (BOOL) subscribed;
1761 - (NSString *) latest;
1762 - (NSString *) installed;
1763 - (BOOL) uninstalled;
1766 - (BOOL) upgradableAndEssential:(BOOL)essential;
1769 - (BOOL) unfiltered;
1773 - (BOOL) halfConfigured;
1774 - (BOOL) halfInstalled;
1776 - (NSString *) mode;
1779 - (NSString *) name;
1781 - (NSString *) homepage;
1782 - (NSString *) depiction;
1783 - (Address *) author;
1785 - (NSString *) support;
1787 - (NSArray *) files;
1788 - (NSArray *) warnings;
1789 - (NSArray *) applications;
1791 - (Source *) source;
1792 - (NSString *) role;
1794 - (BOOL) matches:(NSString *)text;
1796 - (bool) hasSupportingRole;
1797 - (BOOL) hasTag:(NSString *)tag;
1798 - (NSString *) primaryPurpose;
1799 - (NSArray *) purposes;
1800 - (bool) isCommercial;
1802 - (CYString &) cyname;
1804 - (uint32_t) compareBySection:(NSArray *)sections;
1806 - (uint32_t) compareForChanges;
1811 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1812 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1813 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1814 - (bool) isVisibleInSection:(NSString *)section;
1815 - (bool) isVisibleInSource:(Source *)source;
1819 uint32_t PackageChangesRadix(Package *self, void *) {
1824 uint32_t timestamp : 30;
1825 uint32_t ignored : 1;
1826 uint32_t upgradable : 1;
1830 bool upgradable([self upgradableAndEssential:YES]);
1831 value.bits.upgradable = upgradable ? 1 : 0;
1834 value.bits.timestamp = 0;
1835 value.bits.ignored = [self ignored] ? 0 : 1;
1836 value.bits.upgradable = 1;
1838 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
1839 value.bits.ignored = 0;
1840 value.bits.upgradable = 0;
1843 return _not(uint32_t) - value.key;
1846 _finline static void Stifle(uint8_t &value) {
1849 uint32_t PackagePrefixRadix(Package *self, void *context) {
1850 size_t offset(reinterpret_cast<size_t>(context));
1851 CYString &name([self cyname]);
1853 size_t size(name.size());
1856 char *text(name.data());
1859 if (!isdigit(text[0]))
1863 while (size != digits && isdigit(text[digits]))
1873 if (offset == 0 && zeros != 0) {
1874 memset(data, '0', zeros);
1875 memcpy(data + zeros, text, 4 - zeros);
1877 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1878 if (size <= offset - zeros)
1881 text += offset - zeros;
1882 size -= offset - zeros;
1885 memcpy(data, text, 4);
1887 memcpy(data, text, size);
1888 memset(data + size, 0, 4 - size);
1891 for (size_t i(0); i != 4; ++i)
1892 if (isalpha(data[i]))
1900 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
1902 /* XXX: ntohl may be more honest */
1903 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
1906 CYString &(*PackageName)(Package *self, SEL sel);
1908 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
1909 _profile(PackageNameCompare)
1910 CYString &lhi(PackageName(lhs, @selector(cyname)));
1911 CYString &rhi(PackageName(rhs, @selector(cyname)));
1912 CFStringRef lhn(lhi), rhn(rhi);
1915 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
1916 else if (rhn == NULL)
1917 return NSOrderedDescending;
1919 _profile(PackageNameCompare$NumbersLast)
1920 if (!lhi.empty() && !rhi.empty()) {
1921 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
1922 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
1923 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
1924 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
1925 return lha ? NSOrderedAscending : NSOrderedDescending;
1929 CFIndex length = CFStringGetLength(lhn);
1931 _profile(PackageNameCompare$Compare)
1932 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
1937 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
1938 return PackageNameCompare(*lhs, *rhs, context);
1941 struct PackageNameOrdering :
1942 std::binary_function<Package *, Package *, bool>
1944 _finline bool operator ()(Package *lhs, Package *rhs) const {
1945 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
1949 @implementation Package
1951 - (NSString *) description {
1952 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
1962 if (sponsor$_ != nil)
1963 [sponsor$_ release];
1964 if (author$_ != nil)
1971 if (metadata_ != nil)
1972 [metadata_ release];
1977 + (NSString *) webScriptNameForSelector:(SEL)selector {
1978 if (selector == @selector(hasTag:))
1984 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1985 return [self webScriptNameForSelector:selector] == nil;
1988 + (NSArray *) _attributeKeys {
1989 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];
1992 - (NSArray *) attributeKeys {
1993 return [[self class] _attributeKeys];
1996 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1997 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2007 _profile(Package$parse)
2008 pkgRecords::Parser *parser;
2010 _profile(Package$parse$Lookup)
2011 parser = &[database_ records]->Lookup(file_);
2016 _profile(Package$parse$Find)
2022 {"depiction", &depiction_},
2023 {"homepage", &homepage_},
2024 {"website", &website},
2026 {"support", &support_},
2027 {"sponsor", &sponsor_},
2028 {"author", &author_},
2031 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2032 const char *start, *end;
2034 if (parser->Find(names[i].name_, start, end)) {
2035 CYString &value(*names[i].value_);
2036 _profile(Package$parse$Value)
2037 value.set(pool_, start, end - start);
2043 _profile(Package$parse$Tagline)
2044 const char *start, *end;
2045 if (parser->ShortDesc(start, end)) {
2046 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2049 while (stop != start && stop[-1] == '\r')
2051 tagline_.set(pool_, start, stop - start);
2055 _profile(Package$parse$Retain)
2056 if (homepage_.empty())
2057 homepage_ = website;
2058 if (homepage_ == depiction_)
2064 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2065 if ((self = [super init]) != nil) {
2066 _profile(Package$initWithVersion)
2067 era_ = [database era];
2072 _profile(Package$initWithVersion$ParentPkg)
2073 iterator_ = version.ParentPkg();
2076 database_ = database;
2078 _profile(Package$initWithVersion$Latest)
2079 const char *latest(StripVersion_(version_.VerStr()));
2080 latest_ = (NSString *) CFStringCreateWithBytes(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(latest), strlen(latest), kCFStringEncodingASCII, NO);
2083 pkgCache::VerIterator current;
2084 _profile(Package$initWithVersion$Versions)
2085 current = iterator_.CurrentVer();
2087 installed_.set(pool_, StripVersion_(current.VerStr()));
2089 if (!version_.end())
2090 file_ = version_.FileList();
2092 pkgCache &cache([database_ cache]);
2093 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2097 _profile(Package$initWithVersion$Name)
2098 id_.set(pool_, iterator_.Name());
2099 name_.set(pool, iterator_.Display());
2102 _profile(Package$initWithVersion$lowercaseString)
2103 char *data(id_.data());
2104 for (size_t i(0), e(id_.size()); i != e; ++i)
2105 // XXX: do not use tolower() as this is not locale-specific? :(
2109 _profile(Package$initWithVersion$Tags)
2110 pkgCache::TagIterator tag(iterator_.TagList());
2112 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2114 const char *name(tag.Name());
2115 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2116 if (role_ == nil && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/)
2117 role_ = (NSString *) CYStringCreate(name + 6);
2119 } while (!tag.end());
2123 bool changed(false);
2125 _profile(Package$initWithVersion$Metadata)
2126 metadata_ = [Packages_ objectForKey:id_];
2128 if (metadata_ == nil) {
2131 metadata_ = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
2132 firstSeen_, @"FirstSeen",
2133 latest_, @"LastVersion",
2138 firstSeen_ = [metadata_ objectForKey:@"FirstSeen"];
2139 lastSeen_ = [metadata_ objectForKey:@"LastSeen"];
2141 if (NSNumber *subscribed = [metadata_ objectForKey:@"IsSubscribed"])
2142 subscribed_ = [subscribed boolValue];
2144 NSString *version([metadata_ objectForKey:@"LastVersion"]);
2146 if (firstSeen_ == nil) {
2147 firstSeen_ = lastSeen_ == nil ? now_ : lastSeen_;
2148 [metadata_ setObject:firstSeen_ forKey:@"FirstSeen"];
2152 if (version == nil) {
2153 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2155 } else if (![version isEqualToString:latest_]) {
2156 [metadata_ setObject:latest_ forKey:@"LastVersion"];
2158 [metadata_ setObject:lastSeen_ forKey:@"LastSeen"];
2163 metadata_ = [metadata_ retain];
2166 [Packages_ setObject:metadata_ forKey:id_];
2171 _profile(Package$initWithVersion$Section)
2172 section_.set(pool_, iterator_.Section());
2175 _profile(Package$initWithVersion$hasTag)
2176 obsolete_ = [self hasTag:@"cydia::obsolete"];
2177 essential_ = ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES) || [self hasTag:@"cydia::essential"];
2182 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2183 pkgCache::VerIterator version;
2185 _profile(Package$packageWithIterator$GetCandidateVer)
2186 version = [database policy]->GetCandidateVer(iterator);
2192 return [[[Package alloc]
2193 initWithVersion:version
2200 - (pkgCache::PkgIterator) iterator {
2204 - (NSString *) section {
2205 if (section$_ == nil) {
2206 if (section_.empty())
2209 _profile(Package$section)
2210 std::replace(section_.data(), section_.data() + section_.size(), '_', ' ');
2211 NSString *name(section_);
2212 section$_ = [SectionMap_ objectForKey:name] ?: name;
2217 - (NSString *) simpleSection {
2218 if (NSString *section = [self section])
2219 return Simplify(section);
2224 - (NSString *) longSection {
2225 return LocalizeSection([self section]);
2228 - (NSString *) shortSection {
2229 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2232 - (NSString *) uri {
2235 pkgIndexFile *index;
2236 pkgCache::PkgFileIterator file(file_.File());
2237 if (![database_ list].FindIndex(file, index))
2239 return [NSString stringWithUTF8String:iterator_->Path];
2240 //return [NSString stringWithUTF8String:file.Site()];
2241 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2245 - (Address *) maintainer {
2248 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2249 const std::string &maintainer(parser->Maintainer());
2250 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2254 return version_.end() ? 0 : version_->InstalledSize;
2257 - (NSString *) longDescription {
2258 @synchronized (database_) {
2259 if ([database_ era] != era_ || file_.end())
2262 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2263 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2265 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2266 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2267 if ([lines count] < 2)
2270 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2271 for (size_t i(1), e([lines count]); i != e; ++i) {
2272 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2273 [trimmed addObject:trim];
2276 return [trimmed componentsJoinedByString:@"\n"];
2279 - (NSString *) shortDescription {
2284 _profile(Package$index)
2285 CFStringRef name((CFStringRef) [self name]);
2286 if (CFStringGetLength(name) == 0)
2288 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2289 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2291 return toupper(character);
2295 - (NSMutableDictionary *) metadata {
2300 if (subscribed_ && lastSeen_ != nil)
2305 - (BOOL) subscribed {
2310 NSDictionary *metadata([self metadata]);
2311 if (NSNumber *ignored = [metadata objectForKey:@"IsIgnored"])
2312 return [ignored boolValue];
2317 - (NSString *) latest {
2321 - (NSString *) installed {
2325 - (BOOL) uninstalled {
2326 return installed_.empty();
2330 return !version_.end();
2333 - (BOOL) upgradableAndEssential:(BOOL)essential {
2334 _profile(Package$upgradableAndEssential)
2335 pkgCache::VerIterator current(iterator_.CurrentVer());
2337 return essential && essential_;
2339 return !version_.end() && version_ != current;
2343 - (BOOL) essential {
2348 return [database_ cache][iterator_].InstBroken();
2351 - (BOOL) unfiltered {
2352 _profile(Package$unfiltered$obsolete)
2357 _profile(Package$unfiltered$hasSupportingRole)
2358 if (![self hasSupportingRole])
2366 if (![self unfiltered])
2369 NSString *section([self section]);
2371 _profile(Package$visible$isSectionVisible)
2372 if (section != nil && !isSectionVisible(section))
2380 unsigned char current(iterator_->CurrentState);
2381 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2384 - (BOOL) halfConfigured {
2385 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2388 - (BOOL) halfInstalled {
2389 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2393 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2394 return state.Mode != pkgDepCache::ModeKeep;
2397 - (NSString *) mode {
2398 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2400 switch (state.Mode) {
2401 case pkgDepCache::ModeDelete:
2402 if ((state.iFlags & pkgDepCache::Purge) != 0)
2406 case pkgDepCache::ModeKeep:
2407 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2408 return @"REINSTALL";
2409 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2413 case pkgDepCache::ModeInstall:
2414 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2415 return @"REINSTALL";
2416 else*/ switch (state.Status) {
2418 return @"DOWNGRADE";
2424 return @"NEW_INSTALL";
2435 - (NSString *) name {
2436 return name_.empty() ? id_ : name_;
2439 - (UIImage *) icon {
2440 NSString *section = [self simpleSection];
2444 if ([static_cast<id>(icon_) hasPrefix:@"file:///"])
2445 // XXX: correct escaping
2446 icon = [UIImage imageAtPath:[static_cast<id>(icon_) substringFromIndex:7]];
2447 if (icon == nil) if (section != nil)
2448 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2449 if (icon == nil) if (source_ != nil) if (NSString *dicon = [source_ defaultIcon])
2450 if ([dicon hasPrefix:@"file:///"])
2451 // XXX: correct escaping
2452 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2454 icon = [UIImage applicationImageNamed:@"unknown.png"];
2458 - (NSString *) homepage {
2462 - (NSString *) depiction {
2463 return !depiction_.empty() ? depiction_ : [[self source] depictionForPackage:id_];
2466 - (Address *) sponsor {
2467 if (sponsor$_ == nil) {
2468 if (sponsor_.empty())
2470 sponsor$_ = [[Address addressWithString:sponsor_] retain];
2474 - (Address *) author {
2475 if (author$_ == nil) {
2476 if (author_.empty())
2478 author$_ = [[Address addressWithString:author_] retain];
2482 - (NSString *) support {
2483 return !bugs_.empty() ? bugs_ : [[self source] supportForPackage:id_];
2486 - (NSArray *) files {
2487 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2488 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2491 fin.open([path UTF8String]);
2496 while (std::getline(fin, line))
2497 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2502 - (NSArray *) warnings {
2503 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2504 const char *name(iterator_.Name());
2506 size_t length(strlen(name));
2507 if (length < 2) invalid:
2508 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2509 else for (size_t i(0); i != length; ++i)
2511 /* XXX: technically this is not allowed */
2512 (name[i] < 'A' || name[i] > 'Z') &&
2513 (name[i] < 'a' || name[i] > 'z') &&
2514 (name[i] < '0' || name[i] > '9') &&
2515 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2518 if (strcmp(name, "cydia") != 0) {
2521 bool _private = false;
2524 bool repository = [[self section] isEqualToString:@"Repositories"];
2526 if (NSArray *files = [self files])
2527 for (NSString *file in files)
2528 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2530 else if (!user && [file isEqualToString:@"/User"])
2532 else if (!_private && [file isEqualToString:@"/private"])
2534 else if (!stash && [file isEqualToString:@"/var/stash"])
2537 /* XXX: this is not sensitive enough. only some folders are valid. */
2538 if (cydia && !repository)
2539 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2541 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2543 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2545 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2548 return [warnings count] == 0 ? nil : warnings;
2551 - (NSArray *) applications {
2552 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2554 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2556 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2557 if (NSArray *files = [self files])
2558 for (NSString *file in files)
2559 if (application_r(file)) {
2560 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2561 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2562 if ([id isEqualToString:me])
2565 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2567 display = application_r[1];
2569 NSString *bundle([file stringByDeletingLastPathComponent]);
2570 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2571 if (icon == nil || [icon length] == 0)
2573 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2575 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2576 [applications addObject:application];
2578 [application addObject:id];
2579 [application addObject:display];
2580 [application addObject:url];
2583 return [applications count] == 0 ? nil : applications;
2586 - (Source *) source {
2587 if (source_ == nil) {
2588 @synchronized (database_) {
2589 if ([database_ era] != era_ || file_.end())
2590 source_ = (Source *) [NSNull null];
2592 source_ = [([database_ getSource:file_.File()] ?: (Source *) [NSNull null]) retain];
2596 return source_ == (Source *) [NSNull null] ? nil : source_;
2599 - (NSString *) role {
2603 - (BOOL) matches:(NSString *)text {
2609 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2610 if (range.location != NSNotFound)
2613 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2614 if (range.location != NSNotFound)
2617 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2618 if (range.location != NSNotFound)
2624 - (bool) hasSupportingRole {
2627 if ([role_ isEqualToString:@"enduser"])
2629 if ([Role_ isEqualToString:@"User"])
2631 if ([role_ isEqualToString:@"hacker"])
2633 if ([Role_ isEqualToString:@"Hacker"])
2635 if ([role_ isEqualToString:@"developer"])
2637 if ([Role_ isEqualToString:@"Developer"])
2642 - (BOOL) hasTag:(NSString *)tag {
2643 return tags_ == nil ? NO : [tags_ containsObject:tag];
2646 - (NSString *) primaryPurpose {
2647 for (NSString *tag in tags_)
2648 if ([tag hasPrefix:@"purpose::"])
2649 return [tag substringFromIndex:9];
2653 - (NSArray *) purposes {
2654 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2655 for (NSString *tag in tags_)
2656 if ([tag hasPrefix:@"purpose::"])
2657 [purposes addObject:[tag substringFromIndex:9]];
2658 return [purposes count] == 0 ? nil : purposes;
2661 - (bool) isCommercial {
2662 return [self hasTag:@"cydia::commercial"];
2665 - (CYString &) cyname {
2666 return name_.empty() ? id_ : name_;
2669 - (uint32_t) compareBySection:(NSArray *)sections {
2670 NSString *section([self section]);
2671 for (size_t i(0), e([sections count]); i != e; ++i) {
2672 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2676 return _not(uint32_t);
2679 - (uint32_t) compareForChanges {
2684 uint32_t timestamp : 30;
2685 uint32_t ignored : 1;
2686 uint32_t upgradable : 1;
2690 bool upgradable([self upgradableAndEssential:YES]);
2691 value.bits.upgradable = upgradable ? 1 : 0;
2694 value.bits.timestamp = 0;
2695 value.bits.ignored = [self ignored] ? 0 : 1;
2696 value.bits.upgradable = 1;
2698 value.bits.timestamp = static_cast<uint32_t>([[self seen] timeIntervalSince1970]) >> 2;
2699 value.bits.ignored = 0;
2700 value.bits.upgradable = 0;
2703 return _not(uint32_t) - value.key;
2707 @synchronized (database_) {
2708 pkgProblemResolver *resolver = [database_ resolver];
2709 resolver->Clear(iterator_);
2711 pkgCacheFile &cache([database_ cache]);
2712 cache->SetReInstall(iterator_, false);
2713 cache->MarkKeep(iterator_, false);
2717 @synchronized (database_) {
2718 pkgProblemResolver *resolver = [database_ resolver];
2719 resolver->Clear(iterator_);
2720 resolver->Protect(iterator_);
2722 pkgCacheFile &cache([database_ cache]);
2723 cache->SetReInstall(iterator_, false);
2724 cache->MarkInstall(iterator_, false);
2726 pkgDepCache::StateCache &state((*cache)[iterator_]);
2727 if (!state.Install())
2728 cache->SetReInstall(iterator_, true);
2732 @synchronized (database_) {
2733 pkgProblemResolver *resolver = [database_ resolver];
2734 resolver->Clear(iterator_);
2735 resolver->Remove(iterator_);
2736 resolver->Protect(iterator_);
2738 pkgCacheFile &cache([database_ cache]);
2739 cache->SetReInstall(iterator_, false);
2740 cache->MarkDelete(iterator_, true);
2743 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2744 _profile(Package$isUnfilteredAndSearchedForBy)
2747 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2748 value &= [self unfiltered];
2751 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2752 value &= [self matches:search];
2759 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2760 if ([search length] == 0)
2763 _profile(Package$isUnfilteredAndSelectedForBy)
2766 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2767 value &= [self unfiltered];
2770 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2771 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2778 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
2779 return ![self uninstalled] && (![number boolValue] && ![role_ isEqualToString:@"cydia"] || [self unfiltered]);
2782 - (bool) isVisibleInSection:(NSString *)name {
2783 NSString *section([self section]);
2787 section == nil && [name length] == 0 ||
2788 [name isEqualToString:section]
2789 ) && [self visible];
2792 - (bool) isVisibleInSource:(Source *)source {
2793 return [self source] == source && [self visible];
2798 /* Section Class {{{ */
2799 @interface Section : NSObject {
2804 NSString *localized_;
2807 - (NSComparisonResult) compareByLocalized:(Section *)section;
2808 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2809 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2810 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2811 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2812 - (NSString *) name;
2819 - (void) addToCount;
2821 - (void) setCount:(size_t)count;
2822 - (NSString *) localized;
2826 @implementation Section
2830 if (localized_ != nil)
2831 [localized_ release];
2835 - (NSComparisonResult) compareByLocalized:(Section *)section {
2836 NSString *lhs(localized_);
2837 NSString *rhs([section localized]);
2839 /*if ([lhs length] != 0 && [rhs length] != 0) {
2840 unichar lhc = [lhs characterAtIndex:0];
2841 unichar rhc = [rhs characterAtIndex:0];
2843 if (isalpha(lhc) && !isalpha(rhc))
2844 return NSOrderedAscending;
2845 else if (!isalpha(lhc) && isalpha(rhc))
2846 return NSOrderedDescending;
2849 return [lhs compare:rhs options:LaxCompareOptions_];
2852 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2853 if ((self = [self initWithName:name localize:NO]) != nil) {
2854 if (localized != nil)
2855 localized_ = [localized retain];
2859 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2860 return [self initWithName:name row:0 localize:localize];
2863 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2864 if ((self = [super init]) != nil) {
2865 name_ = [name retain];
2869 localized_ = [LocalizeSection(name_) retain];
2873 /* XXX: localize the index thingees */
2874 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2875 if ((self = [super init]) != nil) {
2876 name_ = [[NSString stringWithCharacters:&index length:1] retain];
2882 - (NSString *) name {
2902 - (void) addToCount {
2906 - (void) setCount:(size_t)count {
2910 - (NSString *) localized {
2917 static NSString *Colon_;
2918 static NSString *Elision_;
2919 static NSString *Error_;
2920 static NSString *Warning_;
2922 /* Database Implementation {{{ */
2923 @implementation Database
2925 + (Database *) sharedInstance {
2926 static Database *instance;
2927 if (instance == nil)
2928 instance = [[Database alloc] init];
2937 // XXX: actually implement this thing
2939 NSRecycleZone(zone_);
2940 // XXX: malloc_destroy_zone(zone_);
2941 apr_pool_destroy(pool_);
2945 - (void) _readCydia:(NSNumber *)fd { _pooled
2946 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2947 std::istream is(&ib);
2950 static Pcre finish_r("^finish:([^:]*)$");
2952 while (std::getline(is, line)) {
2953 const char *data(line.c_str());
2954 size_t size = line.size();
2955 lprintf("C:%s\n", data);
2957 if (finish_r(data, size)) {
2958 NSString *finish = finish_r[1];
2959 int index = [Finishes_ indexOfObject:finish];
2960 if (index != INT_MAX && index > Finish_)
2968 - (void) _readStatus:(NSNumber *)fd { _pooled
2969 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
2970 std::istream is(&ib);
2973 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
2974 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
2976 while (std::getline(is, line)) {
2977 const char *data(line.c_str());
2978 size_t size(line.size());
2979 lprintf("S:%s\n", data);
2981 if (conffile_r(data, size)) {
2982 [delegate_ setConfigurationData:conffile_r[1]];
2983 } else if (strncmp(data, "status: ", 8) == 0) {
2984 NSString *string = [NSString stringWithUTF8String:(data + 8)];
2985 [delegate_ setProgressTitle:string];
2986 } else if (pmstatus_r(data, size)) {
2987 std::string type([pmstatus_r[1] UTF8String]);
2988 NSString *id = pmstatus_r[2];
2990 float percent([pmstatus_r[3] floatValue]);
2991 [delegate_ setProgressPercent:(percent / 100)];
2993 NSString *string = pmstatus_r[4];
2995 if (type == "pmerror")
2996 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
2997 withObject:[NSArray arrayWithObjects:string, id, nil]
3000 else if (type == "pmstatus") {
3001 [delegate_ setProgressTitle:string];
3002 } else if (type == "pmconffile")
3003 [delegate_ setConfigurationData:string];
3005 lprintf("E:unknown pmstatus\n");
3007 lprintf("E:unknown status\n");
3013 - (void) _readOutput:(NSNumber *)fd { _pooled
3014 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3015 std::istream is(&ib);
3018 while (std::getline(is, line)) {
3019 lprintf("O:%s\n", line.c_str());
3020 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
3030 - (Package *) packageWithName:(NSString *)name {
3031 @synchronized (self) {
3032 if (static_cast<pkgDepCache *>(cache_) == NULL)
3034 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3035 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3039 if ((self = [super init]) != nil) {
3046 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3047 apr_pool_create(&pool_, NULL);
3049 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
3053 _assert(pipe(fds) != -1);
3056 _config->Set("APT::Keep-Fds::", cydiafd_);
3057 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3060 detachNewThreadSelector:@selector(_readCydia:)
3062 withObject:[NSNumber numberWithInt:fds[0]]
3065 _assert(pipe(fds) != -1);
3069 detachNewThreadSelector:@selector(_readStatus:)
3071 withObject:[NSNumber numberWithInt:fds[0]]
3074 _assert(pipe(fds) != -1);
3075 _assert(dup2(fds[0], 0) != -1);
3076 _assert(close(fds[0]) != -1);
3078 input_ = fdopen(fds[1], "a");
3080 _assert(pipe(fds) != -1);
3081 _assert(dup2(fds[1], 1) != -1);
3082 _assert(close(fds[1]) != -1);
3085 detachNewThreadSelector:@selector(_readOutput:)
3087 withObject:[NSNumber numberWithInt:fds[0]]
3092 - (pkgCacheFile &) cache {
3096 - (pkgDepCache::Policy *) policy {
3100 - (pkgRecords *) records {
3104 - (pkgProblemResolver *) resolver {
3108 - (pkgAcquire &) fetcher {
3112 - (pkgSourceList &) list {
3116 - (NSArray *) packages {
3117 return (NSArray *) packages_;
3120 - (NSArray *) sources {
3121 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3122 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3123 [sources addObject:i->second];
3127 - (NSArray *) issues {
3128 if (cache_->BrokenCount() == 0)
3131 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3133 for (Package *package in [self packages]) {
3134 if (![package broken])
3136 pkgCache::PkgIterator pkg([package iterator]);
3138 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3139 [entry addObject:[package name]];
3140 [issues addObject:entry];
3142 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3146 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3147 pkgCache::DepIterator start;
3148 pkgCache::DepIterator end;
3149 dep.GlobOr(start, end); // ++dep
3151 if (!cache_->IsImportantDep(end))
3153 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3156 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3157 [entry addObject:failure];
3158 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3160 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3161 if (Package *package = [self packageWithName:name])
3162 name = [package name];
3163 [failure addObject:name];
3165 pkgCache::PkgIterator target(start.TargetPkg());
3166 if (target->ProvidesList != 0)
3167 [failure addObject:@"?"];
3169 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3171 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3172 else if (!cache_[target].CandidateVerIter(cache_).end())
3173 [failure addObject:@"-"];
3174 else if (target->ProvidesList == 0)
3175 [failure addObject:@"!"];
3177 [failure addObject:@"%"];
3181 if (start.TargetVer() != 0)
3182 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3193 - (bool) popErrorWithTitle:(NSString *)title {
3195 std::string message;
3197 while (!_error->empty()) {
3199 bool warning(!_error->PopMessage(error));
3203 size_t size(error.size());
3204 if (size == 0 || error[size - 1] != '\n')
3206 error.resize(size - 1);
3208 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3210 if (!message.empty())
3215 if (fatal && !message.empty())
3216 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3221 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3222 return [self popErrorWithTitle:title] || !success;
3225 - (void) reloadData { CYPoolStart() {
3226 @synchronized (self) {
3229 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3230 CFArrayRemoveAllValues(packages_);
3257 apr_pool_clear(pool_);
3258 NSRecycleZone(zone_);
3260 int chk(creat("/tmp/cydia.chk", 0644));
3264 NSString *title(UCLocalize("DATABASE"));
3267 if (!cache_.Open(progress_, true)) { pop:
3269 bool warning(!_error->PopMessage(error));
3270 lprintf("cache_.Open():[%s]\n", error.c_str());
3272 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3273 [delegate_ repairWithSelector:@selector(configure)];
3274 else if (error == "The package lists or status file could not be parsed or opened.")
3275 [delegate_ repairWithSelector:@selector(update)];
3276 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3277 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3278 // else if (error == "The list of sources could not be read.")
3280 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3289 unlink("/tmp/cydia.chk");
3291 now_ = [[NSDate date] retain];
3293 policy_ = new pkgDepCache::Policy();
3294 records_ = new pkgRecords(cache_);
3295 resolver_ = new pkgProblemResolver(cache_);
3296 fetcher_ = new pkgAcquire(&status_);
3299 list_ = new pkgSourceList();
3300 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3303 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3304 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3308 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3311 if (cache_->BrokenCount() != 0) {
3312 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3315 if (cache_->BrokenCount() != 0) {
3316 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3320 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3324 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3325 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3326 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3327 // XXX: this could be more intelligent
3328 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3329 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3331 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3336 /*std::vector<Package *> packages;
3337 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3338 [packages_ release];
3343 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3344 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3345 //packages.push_back(package);
3346 CFArrayAppendValue(packages_, [package retain]);
3350 /*if (packages.empty())
3351 packages_ = [[NSArray alloc] init];
3353 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3356 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3357 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3358 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3366 /*if (!packages.empty())
3367 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3368 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3370 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3372 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3374 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3378 } } CYPoolEnd() _trace(); }
3381 @synchronized (self) {
3383 resolver_ = new pkgProblemResolver(cache_);
3385 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator) {
3386 if (!cache_[iterator].Keep()) {
3387 cache_->MarkKeep(iterator, false);
3388 cache_->SetReInstall(iterator, false);
3393 - (void) configure {
3394 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3395 system([dpkg UTF8String]);
3399 // XXX: I don't remember this condition
3404 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3406 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3408 if ([self popErrorWithTitle:title])
3412 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3415 public pkgArchiveCleaner
3418 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3423 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3430 fetcher_->Shutdown();
3432 pkgRecords records(cache_);
3434 lock_ = new FileFd();
3435 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3437 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3439 if ([self popErrorWithTitle:title])
3443 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3446 manager_ = (_system->CreatePM(cache_));
3447 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3454 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3456 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3458 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3460 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3461 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3464 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3469 bool failed = false;
3470 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3471 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3473 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3476 std::string uri = (*item)->DescURI();
3477 std::string error = (*item)->ErrorText;
3479 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3482 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3483 withObject:[NSArray arrayWithObjects:
3484 [NSString stringWithUTF8String:error.c_str()],
3496 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3498 if (_error->PendingError()) {
3503 if (result == pkgPackageManager::Failed) {
3508 if (result != pkgPackageManager::Completed) {
3513 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3515 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3517 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3518 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3521 if (![before isEqualToArray:after])
3526 NSString *title(UCLocalize("UPGRADE"));
3527 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3533 [self updateWithStatus:status_];
3536 - (void) updateWithStatus:(Status &)status {
3537 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3538 NSString *title(UCLocalize("REFRESHING_DATA"));
3541 if (!list.ReadMainList())
3542 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3545 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3546 if ([self popErrorWithTitle:title])
3549 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3550 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */
3551 /* XXX: why the hell is an empty if statement a clang error? */ (void) 0;
3553 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3557 - (void) setDelegate:(id)delegate {
3558 delegate_ = delegate;
3559 status_.setDelegate(delegate);
3560 progress_.setDelegate(delegate);
3563 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3564 SourceMap::const_iterator i(sources_.find(file->ID));
3565 return i == sources_.end() ? nil : i->second;
3571 /* Confirmation Controller {{{ */
3572 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3573 if (!iterator.end())
3574 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3575 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3577 pkgCache::PkgIterator package(dep.TargetPkg());
3580 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3588 /* Web Scripting {{{ */
3589 @interface CydiaObject : NSObject {
3591 _transient id delegate_;
3594 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3597 @implementation CydiaObject
3600 [indirect_ release];
3604 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3605 if ((self = [super init]) != nil) {
3606 indirect_ = [indirect retain];
3610 - (void) setDelegate:(id)delegate {
3611 delegate_ = delegate;
3614 + (NSArray *) _attributeKeys {
3615 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3618 - (NSArray *) attributeKeys {
3619 return [[self class] _attributeKeys];
3622 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3623 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3626 - (NSString *) device {
3627 return [[UIDevice currentDevice] uniqueIdentifier];
3630 #if 0 // XXX: implement!
3631 - (NSString *) mac {
3632 if (![indirect_ promptForSensitive:@"Mac Address"])
3636 - (NSString *) serial {
3637 if (![indirect_ promptForSensitive:@"Serial #"])
3641 - (NSString *) firewire {
3642 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3646 - (NSString *) imei {
3647 if (![indirect_ promptForSensitive:@"IMEI"])
3652 + (NSString *) webScriptNameForSelector:(SEL)selector {
3653 if (selector == @selector(close))
3655 else if (selector == @selector(getInstalledPackages))
3656 return @"getInstalledPackages";
3657 else if (selector == @selector(getPackageById:))
3658 return @"getPackageById";
3659 else if (selector == @selector(installPackages:))
3660 return @"installPackages";
3661 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3662 return @"setButtonImage";
3663 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3664 return @"setButtonTitle";
3665 else if (selector == @selector(setPopupHook:))
3666 return @"setPopupHook";
3667 else if (selector == @selector(setSpecial:))
3668 return @"setSpecial";
3669 else if (selector == @selector(setToken:))
3671 else if (selector == @selector(setViewportWidth:))
3672 return @"setViewportWidth";
3673 else if (selector == @selector(supports:))
3675 else if (selector == @selector(stringWithFormat:arguments:))
3677 else if (selector == @selector(localizedStringForKey:value:table:))
3679 else if (selector == @selector(du:))
3681 else if (selector == @selector(statfs:))
3687 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3688 return [self webScriptNameForSelector:selector] == nil;
3691 - (BOOL) supports:(NSString *)feature {
3692 return [feature isEqualToString:@"window.open"];
3695 - (NSArray *) getInstalledPackages {
3696 NSArray *packages([[Database sharedInstance] packages]);
3697 NSMutableArray *installed([NSMutableArray arrayWithCapacity:[packages count]]);
3698 for (Package *package in packages)
3699 if ([package installed] != nil)
3700 [installed addObject:package];
3704 - (Package *) getPackageById:(NSString *)id {
3705 Package *package([[Database sharedInstance] packageWithName:id]);
3710 - (NSArray *) statfs:(NSString *)path {
3713 if (path == nil || statfs([path UTF8String], &stat) == -1)
3716 return [NSArray arrayWithObjects:
3717 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3718 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3719 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3723 - (NSNumber *) du:(NSString *)path {
3724 NSNumber *value(nil);
3727 _assert(pipe(fds) != -1);
3729 pid_t pid(ExecFork());
3731 _assert(dup2(fds[1], 1) != -1);
3732 _assert(close(fds[0]) != -1);
3733 _assert(close(fds[1]) != -1);
3734 /* XXX: this should probably not use du */
3735 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3740 _assert(close(fds[1]) != -1);
3742 if (FILE *du = fdopen(fds[0], "r")) {
3744 while (fgets(line, sizeof(line), du) != NULL) {
3745 size_t length(strlen(line));
3746 while (length != 0 && line[length - 1] == '\n')
3747 line[--length] = '\0';
3748 if (char *tab = strchr(line, '\t')) {
3750 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3755 } else _assert(close(fds[0]));
3759 if (waitpid(pid, &status, 0) == -1)
3762 else _assert(false);
3771 - (void) installPackages:(NSArray *)packages {
3772 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
3775 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3776 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3779 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3780 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3783 - (void) setSpecial:(id)function {
3784 [indirect_ setSpecial:function];
3787 - (void) setToken:(NSString *)token {
3790 Token_ = [token retain];
3792 [Metadata_ setObject:Token_ forKey:@"Token"];
3796 - (void) setPopupHook:(id)function {
3797 [indirect_ setPopupHook:function];
3800 - (void) setViewportWidth:(float)width {
3801 [indirect_ setViewportWidth:width];
3804 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3805 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3806 unsigned count([arguments count]);
3808 for (unsigned i(0); i != count; ++i)
3809 values[i] = [arguments objectAtIndex:i];
3810 return [[[NSString alloc] initWithFormat:format arguments:*(reinterpret_cast<va_list *>(&values))] autorelease];
3813 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3814 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3816 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3818 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3824 /* Cydia Browser Controller {{{ */
3825 @interface CYBrowserController : BrowserController {
3826 CydiaObject *cydia_;
3831 @implementation CYBrowserController
3838 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
3841 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3842 [super webView:view didClearWindowObject:window forFrame:frame];
3844 WebDataSource *source([frame dataSource]);
3845 NSURLResponse *response([source response]);
3846 NSURL *url([response URL]);
3847 NSString *scheme([url scheme]);
3849 NSHTTPURLResponse *http;
3850 if (scheme != nil && ([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"]))
3851 http = (NSHTTPURLResponse *) response;
3855 NSDictionary *headers([http allHeaderFields]);
3856 NSString *host([url host]);
3857 [self setHeaders:headers forHost:host];
3860 [host isEqualToString:@"cydia.saurik.com"] ||
3861 [host hasSuffix:@".cydia.saurik.com"] ||
3862 [scheme isEqualToString:@"file"]
3864 [window setValue:cydia_ forKey:@"cydia"];
3867 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
3868 if (System_ != NULL)
3869 [request setValue:System_ forHTTPHeaderField:@"X-System"];
3870 if (Machine_ != NULL)
3871 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
3873 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
3875 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
3878 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
3879 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
3880 [self _setMoreHeaders:copy];
3884 - (void) setDelegate:(id)delegate {
3885 [super setDelegate:delegate];
3886 [cydia_ setDelegate:delegate];
3890 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
3891 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
3893 WebView *webview([[webview_ _documentView] webView]);
3895 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
3897 NSString *application = package == nil ? @"Cydia" : [NSString
3898 stringWithFormat:@"Cydia/%@",
3903 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
3905 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
3906 if (Product_ != nil)
3907 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
3909 [webview setApplicationNameForUserAgent:application];
3916 /* Confirmation {{{ */
3917 @protocol ConfirmationControllerDelegate
3918 - (void) cancelAndClear:(bool)clear;
3919 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
3923 @interface ConfirmationController : CYBrowserController {
3924 _transient Database *database_;
3925 UIAlertView *essential_;
3932 - (id) initWithDatabase:(Database *)database;
3936 @implementation ConfirmationController
3943 if (essential_ != nil)
3944 [essential_ release];
3948 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
3949 NSString *context([alert context]);
3951 if ([context isEqualToString:@"remove"]) {
3952 if (button == [alert cancelButtonIndex]) {
3953 [self dismissModalViewControllerAnimated:YES];
3954 } else if (button == [alert firstOtherButtonIndex]) {
3957 [delegate_ confirmWithNavigationController:[self navigationController]];
3960 [alert dismissWithClickedButtonIndex:-1 animated:YES];
3961 } else if ([context isEqualToString:@"unable"]) {
3962 [self dismissModalViewControllerAnimated:YES];
3963 [alert dismissWithClickedButtonIndex:-1 animated:YES];
3965 [super alertView:alert clickedButtonAtIndex:button];
3969 - (void) _doContinue {
3970 [self dismissModalViewControllerAnimated:YES];
3971 [delegate_ cancelAndClear:NO];
3974 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
3975 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
3979 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3980 [super webView:view didClearWindowObject:window forFrame:frame];
3981 [window setValue:changes_ forKey:@"changes"];
3982 [window setValue:issues_ forKey:@"issues"];
3983 [window setValue:sizes_ forKey:@"sizes"];
3984 [window setValue:self forKey:@"queue"];
3987 - (id) initWithDatabase:(Database *)database {
3988 if ((self = [super init]) != nil) {
3989 database_ = database;
3991 [[self navigationItem] setTitle:UCLocalize("CONFIRM")];
3993 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
3994 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
3995 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
3996 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
3997 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
4001 pkgDepCache::Policy *policy([database_ policy]);
4003 pkgCacheFile &cache([database_ cache]);
4004 NSArray *packages = [database_ packages];
4005 for (Package *package in packages) {
4006 pkgCache::PkgIterator iterator = [package iterator];
4007 pkgDepCache::StateCache &state(cache[iterator]);
4009 NSString *name([package name]);
4011 if (state.NewInstall())
4012 [installing addObject:name];
4013 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4014 [reinstalling addObject:name];
4015 else if (state.Upgrade())
4016 [upgrading addObject:name];
4017 else if (state.Downgrade())
4018 [downgrading addObject:name];
4019 else if (state.Delete()) {
4020 if ([package essential])
4022 [removing addObject:name];
4025 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4026 substrate_ |= DepSubstrate(iterator.CurrentVer());
4031 else if (Advanced_) {
4032 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4034 essential_ = [[UIAlertView alloc]
4035 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4036 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4038 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4039 otherButtonTitles:[NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")], nil
4042 [essential_ setContext:@"remove"];
4044 essential_ = [[UIAlertView alloc]
4045 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4046 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4048 cancelButtonTitle:UCLocalize("OKAY")
4049 otherButtonTitles:nil
4052 [essential_ setContext:@"unable"];
4055 changes_ = [[NSArray alloc] initWithObjects:
4063 issues_ = [database_ issues];
4065 issues_ = [issues_ retain];
4067 sizes_ = [[NSArray alloc] initWithObjects:
4068 SizeString([database_ fetcher].FetchNeeded()),
4069 SizeString([database_ fetcher].PartialPresent()),
4072 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
4074 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
4075 initWithTitle:UCLocalize("CANCEL")
4076 // OLD: [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")]
4077 style:UIBarButtonItemStylePlain
4079 action:@selector(cancelButtonClicked)
4084 - (void) applyRightButton {
4085 #if !AlwaysReload && !IgnoreInstall
4086 if (issues_ == nil && ![self isLoading])
4087 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4088 initWithTitle:UCLocalize("CONFIRM")
4089 style:UIBarButtonItemStylePlain
4091 action:@selector(confirmButtonClicked)
4094 [super applyRightButton];
4096 [[self navigationItem] setRightBarButtonItem:nil];
4100 - (void) cancelButtonClicked {
4101 [self dismissModalViewControllerAnimated:YES];
4102 [delegate_ cancelAndClear:YES];
4106 - (void) confirmButtonClicked {
4110 if (essential_ != nil)
4115 [delegate_ confirmWithNavigationController:[self navigationController]];
4123 /* Progress Data {{{ */
4124 @interface ProgressData : NSObject {
4126 // XXX: should these really both be _transient?
4127 _transient id target_;
4128 _transient id object_;
4131 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4138 @implementation ProgressData
4140 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4141 if ((self = [super init]) != nil) {
4142 selector_ = selector;
4162 /* Progress Controller {{{ */
4163 @interface ProgressController : CYViewController <
4164 ConfigurationDelegate,
4167 _transient Database *database_;
4168 UIProgressBar *progress_;
4169 UITextView *output_;
4170 UITextLabel *status_;
4171 UIPushButton *close_;
4173 SHA1SumValue springlist_;
4174 SHA1SumValue notifyconf_;
4178 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4180 - (void) _retachThread;
4181 - (void) _detachNewThreadData:(ProgressData *)data;
4182 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4188 @protocol ProgressControllerDelegate
4189 - (void) progressControllerIsComplete:(ProgressController *)sender;
4192 @implementation ProgressController
4195 [database_ setDelegate:nil];
4196 [progress_ release];
4205 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4206 if ((self = [super init]) != nil) {
4207 database_ = database;
4208 [database_ setDelegate:self];
4209 delegate_ = delegate;
4211 [[self view] setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
4213 progress_ = [[UIProgressBar alloc] init];
4214 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4215 [progress_ setStyle:0];
4217 status_ = [[UITextLabel alloc] init];
4218 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4219 [status_ setColor:[UIColor whiteColor]];
4220 [status_ setBackgroundColor:[UIColor clearColor]];
4221 [status_ setCentersHorizontally:YES];
4222 //[status_ setFont:font];
4224 output_ = [[UITextView alloc] init];
4226 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4227 //[output_ setTextFont:@"Courier New"];
4228 [output_ setFont:[[output_ font] fontWithSize:12]];
4229 [output_ setTextColor:[UIColor whiteColor]];
4230 [output_ setBackgroundColor:[UIColor clearColor]];
4231 [output_ setMarginTop:0];
4232 [output_ setAllowsRubberBanding:YES];
4233 [output_ setEditable:NO];
4234 [[self view] addSubview:output_];
4236 close_ = [[UIPushButton alloc] init];
4237 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4238 [close_ setAutosizesToFit:NO];
4239 [close_ setDrawsShadow:YES];
4240 [close_ setStretchBackground:YES];
4241 [close_ setEnabled:YES];
4242 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
4243 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4244 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4245 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4249 - (void) positionViews {
4250 CGRect bounds = [[self view] bounds];
4251 CGSize prgsize = [UIProgressBar defaultSize];
4254 (bounds.size.width - prgsize.width) / 2,
4255 bounds.size.height - prgsize.height - 20
4258 float closewidth = std::min(bounds.size.width - 20, 300.0f);
4260 [progress_ setFrame:prgrect];
4261 [status_ setFrame:CGRectMake(
4263 bounds.size.height - prgsize.height - 50,
4264 bounds.size.width - 20,
4267 [output_ setFrame:CGRectMake(
4270 bounds.size.width - 20,
4271 bounds.size.height - 62
4273 [close_ setFrame:CGRectMake(
4274 (bounds.size.width - closewidth) / 2,
4275 bounds.size.height - prgsize.height - 50,
4281 - (void) viewWillAppear:(BOOL)animated {
4282 [super viewDidAppear:animated];
4283 [[self navigationItem] setHidesBackButton:YES];
4284 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4286 [self positionViews];
4289 - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4290 [self positionViews];
4293 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4294 NSString *context([alert context]);
4296 if ([context isEqualToString:@"conffile"]) {
4297 FILE *input = [database_ input];
4298 if (button == [alert cancelButtonIndex])
4299 fprintf(input, "N\n");
4300 else if (button == [alert firstOtherButtonIndex])
4301 fprintf(input, "Y\n");
4306 - (void) closeButtonPushed {
4309 UpdateExternalStatus(0);
4313 [self dismissModalViewControllerAnimated:YES];
4317 [delegate_ terminateWithSuccess];
4318 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4319 [delegate_ suspendWithAnimation:YES];
4321 [delegate_ suspend];*/
4325 system("launchctl stop com.apple.SpringBoard");
4329 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
4338 - (void) _retachThread {
4339 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
4341 [[self view] addSubview:close_];
4342 [progress_ removeFromSuperview];
4343 [status_ removeFromSuperview];
4345 [database_ popErrorWithTitle:title_];
4346 [delegate_ progressControllerIsComplete:self];
4350 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4353 MMap mmap(file, MMap::ReadOnly);
4355 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4356 if (!(notifyconf_ == sha1.Result()))
4363 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4366 MMap mmap(file, MMap::ReadOnly);
4368 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4369 if (!(springlist_ == sha1.Result()))
4375 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
4376 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4377 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4378 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4379 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4382 system("su -c /usr/bin/uicache mobile");
4384 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
4386 [delegate_ setStatusBarShowsProgress:NO];
4389 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4390 [[data target] performSelector:[data selector] withObject:[data object]];
4391 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4394 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4395 UpdateExternalStatus(1);
4402 title_ = [title retain];
4404 [[self navigationItem] setTitle:title_];
4406 [status_ setText:nil];
4407 [output_ setText:@""];
4408 [progress_ setProgress:0];
4410 [close_ removeFromSuperview];
4411 [[self view] addSubview:progress_];
4412 [[self view] addSubview:status_];
4414 [delegate_ setStatusBarShowsProgress:YES];
4419 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4422 MMap mmap(file, MMap::ReadOnly);
4424 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4425 notifyconf_ = sha1.Result();
4431 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4434 MMap mmap(file, MMap::ReadOnly);
4436 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4437 springlist_ = sha1.Result();
4442 detachNewThreadSelector:@selector(_detachNewThreadData:)
4444 withObject:[[[ProgressData alloc]
4445 initWithSelector:selector
4452 - (void) repairWithSelector:(SEL)selector {
4454 detachNewThreadSelector:selector
4457 title:UCLocalize("REPAIRING")
4461 - (void) setConfigurationData:(NSString *)data {
4463 performSelectorOnMainThread:@selector(_setConfigurationData:)
4469 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4470 CYActionSheet *sheet([[[CYActionSheet alloc]
4472 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4473 defaultButtonIndex:0
4476 [sheet setMessage:error];
4477 [sheet yieldToPopupAlertAnimated:YES];
4481 - (void) setProgressTitle:(NSString *)title {
4483 performSelectorOnMainThread:@selector(_setProgressTitle:)
4489 - (void) setProgressPercent:(float)percent {
4491 performSelectorOnMainThread:@selector(_setProgressPercent:)
4492 withObject:[NSNumber numberWithFloat:percent]
4497 - (void) startProgress {
4500 - (void) addProgressOutput:(NSString *)output {
4502 performSelectorOnMainThread:@selector(_addProgressOutput:)
4508 - (bool) isCancelling:(size_t)received {
4512 - (void) _setConfigurationData:(NSString *)data {
4513 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4515 if (!conffile_r(data)) {
4516 lprintf("E:invalid conffile\n");
4520 NSString *ofile = conffile_r[1];
4521 //NSString *nfile = conffile_r[2];
4523 UIAlertView *alert = [[[UIAlertView alloc]
4524 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4525 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
4527 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
4528 otherButtonTitles:UCLocalize("ACCEPT_NEW_COPY"),
4529 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4533 [alert setContext:@"conffile"];
4537 - (void) _setProgressTitle:(NSString *)title {
4538 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4539 for (size_t i(0), e([words count]); i != e; ++i) {
4540 NSString *word([words objectAtIndex:i]);
4541 if (Package *package = [database_ packageWithName:word])
4542 [words replaceObjectAtIndex:i withObject:[package name]];
4545 [status_ setText:[words componentsJoinedByString:@" "]];
4548 - (void) _setProgressPercent:(NSNumber *)percent {
4549 [progress_ setProgress:[percent floatValue]];
4552 - (void) _addProgressOutput:(NSString *)output {
4553 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4554 CGSize size = [output_ contentSize];
4555 CGRect rect = {{0, size.height}, {size.width, 0}};
4556 [output_ scrollRectToVisible:rect animated:YES];
4559 - (BOOL) isRunning {
4566 /* Cell Content View {{{ */
4567 @protocol ContentDelegate
4568 - (void) drawContentRect:(CGRect)rect;
4571 @interface ContentView : UIView {
4572 _transient id<ContentDelegate> delegate_;
4577 @implementation ContentView
4579 - (id) initWithFrame:(CGRect)frame {
4580 if ((self = [super initWithFrame:frame]) != nil) {
4581 [self setNeedsDisplayOnBoundsChange:YES];
4585 - (void) setDelegate:(id<ContentDelegate>)delegate {
4586 delegate_ = delegate;
4589 - (void) drawRect:(CGRect)rect {
4590 [super drawRect:rect];
4591 [delegate_ drawContentRect:rect];
4596 /* Cydia TableView Cell {{{ */
4597 @interface CYTableViewCell : UITableViewCell {
4598 ContentView *content_;
4604 @implementation CYTableViewCell
4611 - (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
4612 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
4614 if (view == content_) {
4615 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
4616 highlighted_ = highlighted;
4619 [super _updateHighlightColorsForView:view highlighted:highlighted];
4622 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
4623 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
4624 highlighted_ = selected;
4626 [super setSelected:selected animated:animated];
4627 [content_ setNeedsDisplay];
4632 /* Package Cell {{{ */
4633 @interface PackageCell : CYTableViewCell <
4638 NSString *description_;
4649 - (PackageCell *) init;
4650 - (void) setPackage:(Package *)package;
4652 + (int) heightForPackage:(Package *)package;
4653 - (void) drawContentRect:(CGRect)rect;
4657 @implementation PackageCell
4659 - (void) clearPackage {
4670 if (description_ != nil) {
4671 [description_ release];
4675 if (source_ != nil) {
4680 if (badge_ != nil) {
4685 if (placard_ != nil) {
4695 [self clearPackage];
4701 return faded_ ? [self selectionPercent] : fade_;
4704 - (PackageCell *) init {
4705 CGRect frame(CGRectMake(0, 0, 320, 74));
4706 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4707 UIView *content([self contentView]);
4708 CGRect bounds([content bounds]);
4710 content_ = [[ContentView alloc] initWithFrame:bounds];
4711 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4712 [content addSubview:content_];
4714 [content_ setDelegate:self];
4715 [content_ setOpaque:YES];
4716 if ([self respondsToSelector:@selector(selectionPercent)])
4721 - (void) _setBackgroundColor {
4723 if (NSString *mode = [package_ mode]) {
4724 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4725 color = remove ? RemovingColor_ : InstallingColor_;
4727 color = [UIColor whiteColor];
4729 [content_ setBackgroundColor:color];
4730 [self setNeedsDisplay];
4733 - (void) setPackage:(Package *)package {
4734 [self clearPackage];
4737 Source *source = [package source];
4739 icon_ = [[package icon] retain];
4740 name_ = [[package name] retain];
4743 description_ = [package longDescription];
4744 if (description_ == nil)
4745 description_ = [package shortDescription];
4746 if (description_ != nil)
4747 description_ = [description_ retain];
4749 commercial_ = [package isCommercial];
4751 package_ = [package retain];
4753 NSString *label = nil;
4754 bool trusted = false;
4756 if (source != nil) {
4757 label = [source label];
4758 trusted = [source trusted];
4759 } else if ([[package id] isEqualToString:@"firmware"])
4760 label = UCLocalize("APPLE");
4762 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
4764 NSString *from(label);
4766 NSString *section = [package simpleSection];
4767 if (section != nil && ![section isEqualToString:label]) {
4768 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4769 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
4772 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
4773 source_ = [from retain];
4775 if (NSString *purpose = [package primaryPurpose])
4776 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4777 badge_ = [badge_ retain];
4779 if ([package installed] != nil)
4780 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/installed.png", App_]]) != nil)
4781 placard_ = [placard_ retain];
4783 [self _setBackgroundColor];
4784 [content_ setNeedsDisplay];
4787 - (void) drawContentRect:(CGRect)rect {
4788 bool highlighted(highlighted_);
4789 float width([self bounds].size.width);
4792 CGContextRef context(UIGraphicsGetCurrentContext());
4793 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
4794 CGContextFillRect(context, rect);
4799 rect.size = [icon_ size];
4801 rect.size.width /= 2;
4802 rect.size.height /= 2;
4804 rect.origin.x = 25 - rect.size.width / 2;
4805 rect.origin.y = 25 - rect.size.height / 2;
4807 [icon_ drawInRect:rect];
4810 if (badge_ != nil) {
4811 CGSize size = [badge_ size];
4813 [badge_ drawAtPoint:CGPointMake(
4814 36 - size.width / 2,
4815 36 - size.height / 2
4823 UISetColor(commercial_ ? Purple_ : Black_);
4824 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
4825 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
4828 UISetColor(commercial_ ? Purplish_ : Gray_);
4829 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
4831 if (placard_ != nil)
4832 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
4835 + (int) heightForPackage:(Package *)package {
4841 /* Section Cell {{{ */
4842 @interface SectionCell : CYTableViewCell <
4854 - (void) setSection:(Section *)section editing:(BOOL)editing;
4858 @implementation SectionCell
4860 - (void) clearSection {
4861 if (basic_ != nil) {
4866 if (section_ != nil) {
4876 if (count_ != nil) {
4883 [self clearSection];
4889 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
4890 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
4891 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4892 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4893 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
4895 UIView *content([self contentView]);
4896 CGRect bounds([content bounds]);
4898 content_ = [[ContentView alloc] initWithFrame:bounds];
4899 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4900 [content addSubview:content_];
4901 [content_ setBackgroundColor:[UIColor whiteColor]];
4903 [content_ setDelegate:self];
4907 - (void) onSwitch:(id)sender {
4908 NSMutableDictionary *metadata = [Sections_ objectForKey:basic_];
4909 if (metadata == nil) {
4910 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4911 [Sections_ setObject:metadata forKey:basic_];
4915 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
4918 - (void) setSection:(Section *)section editing:(BOOL)editing {
4919 if (editing != editing_) {
4921 [switch_ removeFromSuperview];
4923 [self addSubview:switch_];
4927 [self clearSection];
4929 if (section == nil) {
4930 name_ = [UCLocalize("ALL_PACKAGES") retain];
4933 basic_ = [section name];
4935 basic_ = [basic_ retain];
4937 section_ = [section localized];
4938 if (section_ != nil)
4939 section_ = [section_ retain];
4941 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
4942 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
4945 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
4948 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
4949 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
4951 [content_ setNeedsDisplay];
4954 - (void) setFrame:(CGRect)frame {
4955 [super setFrame:frame];
4957 CGRect rect([switch_ frame]);
4958 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
4961 - (void) drawContentRect:(CGRect)rect {
4962 bool highlighted(highlighted_);
4964 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
4969 float width(rect.size.width);
4975 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
4977 CGSize size = [count_ sizeWithFont:Font14_];
4981 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
4987 /* File Table {{{ */
4988 @interface FileTable : CYViewController <
4989 UITableViewDataSource,
4992 _transient Database *database_;
4995 NSMutableArray *files_;
4999 - (id) initWithDatabase:(Database *)database;
5000 - (void) setPackage:(Package *)package;
5004 @implementation FileTable
5007 if (package_ != nil)
5016 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5017 return files_ == nil ? 0 : [files_ count];
5020 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5024 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5025 static NSString *reuseIdentifier = @"Cell";
5027 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5029 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5030 [cell setFont:[UIFont systemFontOfSize:16]];
5032 [cell setText:[files_ objectAtIndex:indexPath.row]];
5033 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5038 - (id) initWithDatabase:(Database *)database {
5039 if ((self = [super init]) != nil) {
5040 database_ = database;
5042 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5044 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5046 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5047 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5048 [list_ setRowHeight:24.0f];
5049 [[self view] addSubview:list_];
5051 [list_ setDataSource:self];
5052 [list_ setDelegate:self];
5056 - (void) setPackage:(Package *)package {
5057 if (package_ != nil) {
5058 [package_ autorelease];
5067 [files_ removeAllObjects];
5069 if (package != nil) {
5070 package_ = [package retain];
5071 name_ = [[package id] retain];
5073 if (NSArray *files = [package files])
5074 [files_ addObjectsFromArray:files];
5076 if ([files_ count] != 0) {
5077 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5078 [files_ removeObjectAtIndex:0];
5079 [files_ sortUsingSelector:@selector(compareByPath:)];
5081 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5082 [stack addObject:@"/"];
5084 for (int i(0), e([files_ count]); i != e; ++i) {
5085 NSString *file = [files_ objectAtIndex:i];
5086 while (![file hasPrefix:[stack lastObject]])
5087 [stack removeLastObject];
5088 NSString *directory = [stack lastObject];
5089 [stack addObject:[file stringByAppendingString:@"/"]];
5090 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5091 ([stack count] - 2) * 3, "",
5092 [file substringFromIndex:[directory length]]
5101 - (void) reloadData {
5102 [self setPackage:[database_ packageWithName:name_]];
5107 /* Package Controller {{{ */
5108 @interface PackageController : CYBrowserController <
5109 UIActionSheetDelegate
5111 _transient Database *database_;
5115 NSMutableArray *buttons_;
5116 UIBarButtonItem *button_;
5119 - (id) initWithDatabase:(Database *)database;
5120 - (void) setPackage:(Package *)package;
5124 @implementation PackageController
5127 if (package_ != nil)
5141 if ([self retainCount] == 1)
5142 [delegate_ setPackageController:self];
5146 /* XXX: this is not safe at all... localization of /fail/ */
5147 - (void) _clickButtonWithName:(NSString *)name {
5148 if ([name isEqualToString:UCLocalize("CLEAR")])
5149 [delegate_ clearPackage:package_];
5150 else if ([name isEqualToString:UCLocalize("INSTALL")])
5151 [delegate_ installPackage:package_];
5152 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5153 [delegate_ installPackage:package_];
5154 else if ([name isEqualToString:UCLocalize("REMOVE")])
5155 [delegate_ removePackage:package_];
5156 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5157 [delegate_ installPackage:package_];
5158 else _assert(false);
5161 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5162 NSString *context([sheet context]);
5164 if ([context isEqualToString:@"modify"]) {
5165 if (button != [sheet cancelButtonIndex]) {
5166 NSString *buttonName = [buttons_ objectAtIndex:button];
5167 [self _clickButtonWithName:buttonName];
5170 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5174 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5175 [super webView:view didClearWindowObject:window forFrame:frame];
5176 [window setValue:package_ forKey:@"package"];
5179 - (bool) _allowJavaScriptPanel {
5184 - (void) _customButtonClicked {
5185 int count([buttons_ count]);
5190 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5192 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5193 [buttons addObjectsFromArray:buttons_];
5195 UIActionSheet *sheet = [[[UIActionSheet alloc]
5198 cancelButtonTitle:nil
5199 destructiveButtonTitle:nil
5200 otherButtonTitles:nil
5203 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5205 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5206 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5208 [sheet setContext:@"modify"];
5210 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5214 // We don't want to allow non-commercial packages to do custom things to the install button,
5215 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5216 - (void) customButtonClicked {
5218 [super customButtonClicked];
5220 [self _customButtonClicked];
5223 - (void) reloadButtonClicked {
5224 // Don't reload a package view by clicking the button.
5227 - (void) applyLoadingTitle {
5228 // Don't show "Loading" as the title. Ever.
5231 - (UIBarButtonItem *) rightButton {
5236 - (id) initWithDatabase:(Database *)database {
5237 if ((self = [super init]) != nil) {
5238 database_ = database;
5239 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5240 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
5244 - (void) setPackage:(Package *)package {
5245 if (package_ != nil) {
5246 [package_ autorelease];
5255 [buttons_ removeAllObjects];
5257 if (package != nil) {
5260 package_ = [package retain];
5261 name_ = [[package id] retain];
5262 commercial_ = [package isCommercial];
5264 if ([package_ mode] != nil)
5265 [buttons_ addObject:UCLocalize("CLEAR")];
5266 if ([package_ source] == nil);
5267 else if ([package_ upgradableAndEssential:NO])
5268 [buttons_ addObject:UCLocalize("UPGRADE")];
5269 else if ([package_ uninstalled])
5270 [buttons_ addObject:UCLocalize("INSTALL")];
5272 [buttons_ addObject:UCLocalize("REINSTALL")];
5273 if (![package_ uninstalled])
5274 [buttons_ addObject:UCLocalize("REMOVE")];
5281 switch ([buttons_ count]) {
5282 case 0: title = nil; break;
5283 case 1: title = [buttons_ objectAtIndex:0]; break;
5284 default: title = UCLocalize("MODIFY"); break;
5287 button_ = [[UIBarButtonItem alloc]
5289 style:UIBarButtonItemStylePlain
5291 action:@selector(customButtonClicked)
5297 - (bool) isLoading {
5298 return commercial_ ? [super isLoading] : false;
5301 - (void) reloadData {
5302 [self setPackage:[database_ packageWithName:name_]];
5307 /* Package Table {{{ */
5308 @interface PackageTable : UIView <
5309 UITableViewDataSource,
5312 _transient Database *database_;
5313 NSMutableArray *packages_;
5314 NSMutableArray *sections_;
5316 NSMutableArray *index_;
5317 NSMutableDictionary *indices_;
5318 // XXX: this target_ seems to be delegate_. :(
5319 _transient id target_;
5321 // XXX: why do we even have this delegate_?
5322 _transient id delegate_;
5325 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action;
5327 - (void) setDelegate:(id)delegate;
5329 - (void) reloadData;
5330 - (void) resetCursor;
5332 - (UITableView *) list;
5334 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5336 - (void) deselectWithAnimation:(BOOL)animated;
5340 @implementation PackageTable
5343 [packages_ release];
5344 [sections_ release];
5352 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5353 NSInteger count([sections_ count]);
5354 return count == 0 ? 1 : count;
5357 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5358 if ([sections_ count] == 0)
5360 return [[sections_ objectAtIndex:section] name];
5363 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5364 if ([sections_ count] == 0)
5366 return [[sections_ objectAtIndex:section] count];
5369 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5370 Section *section([sections_ objectAtIndex:[path section]]);
5371 NSInteger row([path row]);
5372 Package *package([packages_ objectAtIndex:([section row] + row)]);
5376 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5377 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5379 cell = [[[PackageCell alloc] init] autorelease];
5380 [cell setPackage:[self packageAtIndexPath:path]];
5384 - (void) deselectWithAnimation:(BOOL)animated {
5385 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5388 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
5389 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
5392 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5393 Package *package([self packageAtIndexPath:path]);
5394 package = [database_ packageWithName:[package id]];
5395 [target_ performSelector:action_ withObject:package];
5399 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5400 return [packages_ count] > 20 ? index_ : nil;
5403 - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5407 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action {
5408 if ((self = [super initWithFrame:frame]) != nil) {
5409 database_ = database;
5414 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5415 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5417 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5418 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5420 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
5421 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5422 [list_ setRowHeight:73.0f];
5423 [self addSubview:list_];
5425 [list_ setDataSource:self];
5426 [list_ setDelegate:self];
5430 - (void) setDelegate:(id)delegate {
5431 delegate_ = delegate;
5434 - (bool) hasPackage:(Package *)package {
5438 - (void) reloadData {
5439 NSArray *packages = [database_ packages];
5441 [packages_ removeAllObjects];
5442 [sections_ removeAllObjects];
5444 _profile(PackageTable$reloadData$Filter)
5445 for (Package *package in packages)
5446 if ([self hasPackage:package])
5447 [packages_ addObject:package];
5450 [index_ removeAllObjects];
5451 [indices_ removeAllObjects];
5453 Section *section = nil;
5455 _profile(PackageTable$reloadData$Section)
5456 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5460 _profile(PackageTable$reloadData$Section$Package)
5461 package = [packages_ objectAtIndex:offset];
5462 index = [package index];
5465 if (section == nil || [section index] != index) {
5466 _profile(PackageTable$reloadData$Section$Allocate)
5467 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5470 [index_ addObject:[section name]];
5471 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5473 _profile(PackageTable$reloadData$Section$Add)
5474 [sections_ addObject:section];
5478 [section addToCount];
5482 _profile(PackageTable$reloadData$List)
5487 - (void) resetCursor {
5488 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5491 - (UITableView *) list {
5495 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5496 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
5501 /* Filtered Package Table {{{ */
5502 @interface FilteredPackageTable : PackageTable {
5508 - (void) setObject:(id)object;
5509 - (void) setObject:(id)object forFilter:(SEL)filter;
5511 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object;
5515 @implementation FilteredPackageTable
5523 - (void) setFilter:(SEL)filter {
5526 /* XXX: this is an unsafe optimization of doomy hell */
5527 Method method(class_getInstanceMethod([Package class], filter));
5528 _assert(method != NULL);
5529 imp_ = method_getImplementation(method);
5530 _assert(imp_ != NULL);
5533 - (void) setObject:(id)object {
5539 object_ = [object retain];
5542 - (void) setObject:(id)object forFilter:(SEL)filter {
5543 [self setFilter:filter];
5544 [self setObject:object];
5547 - (bool) hasPackage:(Package *)package {
5548 _profile(FilteredPackageTable$hasPackage)
5549 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5553 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object {
5554 if ((self = [super initWithFrame:frame database:database target:target action:action]) != nil) {
5555 [self setFilter:filter];
5556 object_ = [object retain];
5564 /* Filtered Package Controller {{{ */
5565 @interface FilteredPackageController : CYViewController {
5566 _transient Database *database_;
5567 FilteredPackageTable *packages_;
5571 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5575 @implementation FilteredPackageController
5578 [packages_ release];
5584 - (void) viewDidAppear:(BOOL)animated {
5585 [super viewDidAppear:animated];
5586 [packages_ deselectWithAnimation:animated];
5589 - (void) didSelectPackage:(Package *)package {
5590 PackageController *view([delegate_ packageController]);
5591 [view setPackage:package];
5592 [view setDelegate:delegate_];
5593 [[self navigationController] pushViewController:view animated:YES];
5596 - (NSString *) title { return title_; }
5598 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5599 if ((self = [super init]) != nil) {
5600 database_ = database;
5601 title_ = [title copy];
5602 [[self navigationItem] setTitle:title_];
5604 packages_ = [[FilteredPackageTable alloc]
5605 initWithFrame:[[self view] bounds]
5608 action:@selector(didSelectPackage:)
5613 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5614 [[self view] addSubview:packages_];
5618 - (void) reloadData {
5619 [packages_ reloadData];
5622 - (void) setDelegate:(id)delegate {
5623 [super setDelegate:delegate];
5624 [packages_ setDelegate:delegate];
5631 /* Add Source Controller {{{ */
5632 @interface AddSourceController : CYViewController {
5633 _transient Database *database_;
5636 - (id) initWithDatabase:(Database *)database;
5640 @implementation AddSourceController
5642 - (id) initWithDatabase:(Database *)database {
5643 if ((self = [super init]) != nil) {
5644 database_ = database;
5650 /* Source Cell {{{ */
5651 @interface SourceCell : CYTableViewCell <
5656 NSString *description_;
5660 - (void) setSource:(Source *)source;
5664 @implementation SourceCell
5666 - (void) clearSource {
5669 [description_ release];
5678 - (void) setSource:(Source *)source {
5682 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5684 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5685 icon_ = [icon_ retain];
5687 origin_ = [[source name] retain];
5688 label_ = [[source uri] retain];
5689 description_ = [[source description] retain];
5691 [content_ setNeedsDisplay];
5699 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5700 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5701 UIView *content([self contentView]);
5702 CGRect bounds([content bounds]);
5704 content_ = [[ContentView alloc] initWithFrame:bounds];
5705 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5706 [content_ setBackgroundColor:[UIColor whiteColor]];
5707 [content addSubview:content_];
5709 [content_ setDelegate:self];
5710 [content_ setOpaque:YES];
5714 - (void) drawContentRect:(CGRect)rect {
5715 bool highlighted(highlighted_);
5716 float width(rect.size.width);
5719 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5726 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5730 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5734 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 40) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5739 /* Source Table {{{ */
5740 @interface SourceTable : CYViewController <
5741 UITableViewDataSource,
5744 _transient Database *database_;
5746 NSMutableArray *sources_;
5750 UIProgressHUD *hud_;
5753 //NSURLConnection *installer_;
5754 NSURLConnection *trivial_;
5755 NSURLConnection *trivial_bz2_;
5756 NSURLConnection *trivial_gz_;
5757 //NSURLConnection *automatic_;
5762 - (id) initWithDatabase:(Database *)database;
5764 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
5768 @implementation SourceTable
5770 - (void) _releaseConnection:(NSURLConnection *)connection {
5771 if (connection != nil) {
5772 [connection cancel];
5773 //[connection setDelegate:nil];
5774 [connection release];
5786 //[self _releaseConnection:installer_];
5787 [self _releaseConnection:trivial_];
5788 [self _releaseConnection:trivial_gz_];
5789 [self _releaseConnection:trivial_bz2_];
5790 //[self _releaseConnection:automatic_];
5797 - (void) viewDidAppear:(BOOL)animated {
5798 [super viewDidAppear:animated];
5799 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5802 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
5803 return offset_ == 0 ? 1 : 2;
5806 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
5807 switch (section + (offset_ == 0 ? 1 : 0)) {
5808 case 0: return UCLocalize("ENTERED_BY_USER");
5809 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
5815 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5816 int count = [sources_ count];
5818 case 0: return (offset_ == 0 ? count : offset_);
5819 case 1: return count - offset_;
5825 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
5827 switch (indexPath.section) {
5828 case 0: idx = indexPath.row; break;
5829 case 1: idx = indexPath.row + offset_; break;
5833 return [sources_ objectAtIndex:idx];
5836 - (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5837 Source *source = [self sourceAtIndexPath:indexPath];
5838 return [source description] == nil ? 56 : 73;
5841 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5842 static NSString *cellIdentifier = @"SourceCell";
5844 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
5845 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
5846 [cell setSource:[self sourceAtIndexPath:indexPath]];
5851 - (UITableViewCellAccessoryType) tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath {
5852 return UITableViewCellAccessoryDisclosureIndicator;
5855 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
5856 Source *source = [self sourceAtIndexPath:indexPath];
5858 FilteredPackageController *packages = [[[FilteredPackageController alloc]
5859 initWithDatabase:database_
5860 title:[source label]
5861 filter:@selector(isVisibleInSource:)
5865 [packages setDelegate:delegate_];
5867 [[self navigationController] pushViewController:packages animated:YES];
5870 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
5871 Source *source = [self sourceAtIndexPath:indexPath];
5872 return [source record] != nil;
5875 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
5876 Source *source = [self sourceAtIndexPath:indexPath];
5877 [Sources_ removeObjectForKey:[source key]];
5878 [delegate_ syncData];
5882 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5885 @"./", @"Distribution",
5886 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5888 [delegate_ syncData];
5891 - (NSString *) getWarning {
5892 NSString *href(href_);
5893 NSRange colon([href rangeOfString:@"://"]);
5894 if (colon.location != NSNotFound)
5895 href = [href substringFromIndex:(colon.location + 3)];
5896 href = [href stringByAddingPercentEscapes];
5897 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
5898 href = [href stringByCachingURLWithCurrentCDN];
5900 NSURL *url([NSURL URLWithString:href]);
5902 NSStringEncoding encoding;
5903 NSError *error(nil);
5905 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5906 return [warning length] == 0 ? nil : warning;
5910 - (void) _endConnection:(NSURLConnection *)connection {
5911 // XXX: the memory management in this method is horribly awkward
5913 NSURLConnection **field = NULL;
5914 if (connection == trivial_)
5916 else if (connection == trivial_bz2_)
5917 field = &trivial_bz2_;
5918 else if (connection == trivial_gz_)
5919 field = &trivial_gz_;
5920 _assert(field != NULL);
5921 [connection release];
5926 trivial_bz2_ == nil &&
5932 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
5935 UIAlertView *alert = [[[UIAlertView alloc]
5936 initWithTitle:UCLocalize("SOURCE_WARNING")
5939 cancelButtonTitle:UCLocalize("CANCEL")
5940 otherButtonTitles:UCLocalize("ADD_ANYWAY"), nil
5943 [alert setContext:@"warning"];
5944 [alert setNumberOfRows:1];
5948 } else if (error_ != nil) {
5949 UIAlertView *alert = [[[UIAlertView alloc]
5950 initWithTitle:UCLocalize("VERIFICATION_ERROR")
5951 message:[error_ localizedDescription]
5953 cancelButtonTitle:UCLocalize("OK")
5954 otherButtonTitles:nil
5957 [alert setContext:@"urlerror"];
5960 UIAlertView *alert = [[[UIAlertView alloc]
5961 initWithTitle:UCLocalize("NOT_REPOSITORY")
5962 message:UCLocalize("NOT_REPOSITORY_EX")
5964 cancelButtonTitle:UCLocalize("OK")
5965 otherButtonTitles:nil
5968 [alert setContext:@"trivial"];
5972 [delegate_ setStatusBarShowsProgress:NO];
5973 [delegate_ removeProgressHUD:hud_];
5983 if (error_ != nil) {
5990 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
5991 switch ([response statusCode]) {
5997 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
5998 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
6000 error_ = [error retain];
6001 [self _endConnection:connection];
6004 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
6005 [self _endConnection:connection];
6008 - (NSString *) title { return UCLocalize("SOURCES"); }
6010 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
6011 NSMutableURLRequest *request = [NSMutableURLRequest
6012 requestWithURL:[NSURL URLWithString:href]
6013 cachePolicy:NSURLRequestUseProtocolCachePolicy
6014 timeoutInterval:120.0
6017 [request setHTTPMethod:method];
6019 if (Machine_ != NULL)
6020 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
6021 if (UniqueID_ != nil)
6022 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6024 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
6026 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
6029 - (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
6030 NSString *context([alert context]);
6032 if ([context isEqualToString:@"source"]) {
6035 NSString *href = [[alert textField] text];
6037 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
6039 if (![href hasSuffix:@"/"])
6040 href_ = [href stringByAppendingString:@"/"];
6043 href_ = [href_ retain];
6045 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
6046 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
6047 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
6048 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
6052 // XXX: this is stupid
6053 hud_ = [[delegate_ addProgressHUD] retain];
6054 [hud_ setText:UCLocalize("VERIFYING_URL")];
6063 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6064 } else if ([context isEqualToString:@"trivial"])
6065 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6066 else if ([context isEqualToString:@"urlerror"])
6067 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6068 else if ([context isEqualToString:@"warning"]) {
6083 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6087 - (id) initWithDatabase:(Database *)database {
6088 if ((self = [super init]) != nil) {
6089 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
6090 [self updateButtonsForEditingStatus:NO animated:NO];
6092 database_ = database;
6093 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
6095 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6096 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6097 [[self view] addSubview:list_];
6099 [list_ setDataSource:self];
6100 [list_ setDelegate:self];
6106 - (void) reloadData {
6108 if (!list.ReadMainList())
6111 [sources_ removeAllObjects];
6112 [sources_ addObjectsFromArray:[database_ sources]];
6114 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
6117 int count([sources_ count]);
6119 for (int i = 0; i != count; i++) {
6120 if ([[sources_ objectAtIndex:i] record] == nil)
6125 [list_ setEditing:NO];
6126 [self updateButtonsForEditingStatus:NO animated:NO];
6130 - (void) addButtonClicked {
6131 /*[book_ pushPage:[[[AddSourceController alloc]
6136 UIAlertView *alert = [[[UIAlertView alloc]
6137 initWithTitle:UCLocalize("ENTER_APT_URL")
6140 cancelButtonTitle:UCLocalize("CANCEL")
6141 otherButtonTitles:UCLocalize("ADD_SOURCE"), nil
6144 [alert setContext:@"source"];
6145 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
6147 [alert setNumberOfRows:1];
6148 [alert addTextFieldWithValue:@"http://" label:@""];
6150 UITextInputTraits *traits = [[alert textField] textInputTraits];
6151 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6152 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6153 [traits setKeyboardType:UIKeyboardTypeURL];
6154 // XXX: UIReturnKeyDone
6155 [traits setReturnKeyType:UIReturnKeyNext];
6160 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
6161 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
6162 initWithTitle:UCLocalize("ADD")
6163 style:UIBarButtonItemStylePlain
6165 action:@selector(addButtonClicked)
6166 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
6168 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6169 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
6170 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
6172 action:@selector(editButtonClicked)
6173 ] autorelease] animated:animated];
6175 if (IsWildcat_ && !editing)
6176 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6177 initWithTitle:UCLocalize("SETTINGS")
6178 style:UIBarButtonItemStylePlain
6180 action:@selector(settingsButtonClicked)
6184 - (void) settingsButtonClicked {
6185 [delegate_ showSettings];
6188 - (void) editButtonClicked {
6189 [list_ setEditing:![list_ isEditing] animated:YES];
6191 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
6197 /* Installed Controller {{{ */
6198 @interface InstalledController : FilteredPackageController {
6202 - (id) initWithDatabase:(Database *)database;
6204 - (void) updateRoleButton;
6205 - (void) queueStatusDidChange;
6209 @implementation InstalledController
6215 - (NSString *) title { return UCLocalize("INSTALLED"); }
6217 - (id) initWithDatabase:(Database *)database {
6218 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
6219 [self updateRoleButton];
6220 [self queueStatusDidChange];
6225 - (void) queueButtonClicked {
6230 - (void) queueStatusDidChange {
6234 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6235 initWithTitle:UCLocalize("QUEUE")
6236 style:UIBarButtonItemStyleDone
6238 action:@selector(queueButtonClicked)
6241 [[self navigationItem] setLeftBarButtonItem:nil];
6247 - (void) reloadData {
6248 [packages_ reloadData];
6251 - (void) updateRoleButton {
6252 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
6253 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6254 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
6255 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
6257 action:@selector(roleButtonClicked)
6261 - (void) roleButtonClicked {
6262 [packages_ setObject:[NSNumber numberWithBool:expert_]];
6263 [packages_ reloadData];
6266 [self updateRoleButton];
6269 - (void) setDelegate:(id)delegate {
6270 [super setDelegate:delegate];
6271 [packages_ setDelegate:delegate];
6277 /* Home Controller {{{ */
6278 @interface HomeController : CYBrowserController {
6283 @implementation HomeController
6285 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6286 [super _setMoreHeaders:request];
6289 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6290 if (UniqueID_ != nil)
6291 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6293 [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"];
6296 - (void) aboutButtonClicked {
6297 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6299 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6300 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6301 [alert setCancelButtonIndex:0];
6304 @"Copyright (C) 2008-2010\n"
6305 "Jay Freeman (saurik)\n"
6306 "saurik@saurik.com\n"
6307 "http://www.saurik.com/"
6313 - (void) viewWillAppear:(BOOL)animated {
6314 [super viewWillAppear:animated];
6315 //[[self navigationController] setNavigationBarHidden:YES animated:animated];
6318 - (void) viewWillDisappear:(BOOL)animated {
6319 [super viewWillDisappear:animated];
6320 //[[self navigationController] setNavigationBarHidden:NO animated:animated];
6324 if ((self = [super init]) != nil) {
6325 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6326 initWithTitle:UCLocalize("ABOUT")
6327 style:UIBarButtonItemStylePlain
6329 action:@selector(aboutButtonClicked)
6336 /* Manage Controller {{{ */
6337 @interface ManageController : CYBrowserController {
6340 - (void) queueStatusDidChange;
6343 @implementation ManageController
6346 if ((self = [super init]) != nil) {
6347 [[self navigationItem] setTitle:UCLocalize("MANAGE")];
6349 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6350 initWithTitle:UCLocalize("SETTINGS")
6351 style:UIBarButtonItemStylePlain
6353 action:@selector(settingsButtonClicked)
6356 [self queueStatusDidChange];
6360 - (void) settingsButtonClicked {
6361 [delegate_ showSettings];
6365 - (void) queueButtonClicked {
6369 - (void) applyLoadingTitle {
6370 // No "Loading" title.
6373 - (void) applyRightButton {
6378 - (void) queueStatusDidChange {
6380 if (!IsWildcat_ && Queuing_) {
6381 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6382 initWithTitle:UCLocalize("QUEUE")
6383 style:UIBarButtonItemStyleDone
6385 action:@selector(queueButtonClicked)
6388 [[self navigationItem] setRightBarButtonItem:nil];
6393 - (bool) isLoading {
6400 /* Refresh Bar {{{ */
6401 @interface RefreshBar : UINavigationBar {
6402 UIProgressIndicator *indicator_;
6403 UITextLabel *prompt_;
6404 UIProgressBar *progress_;
6405 UINavigationButton *cancel_;
6410 @implementation RefreshBar
6413 [indicator_ release];
6415 [progress_ release];
6420 - (void) positionViews {
6421 CGRect frame = [cancel_ frame];
6422 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6423 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6424 [cancel_ setFrame:frame];
6426 CGSize prgsize = {75, 100};
6428 [self frame].size.width - prgsize.width - 10,
6429 ([self frame].size.height - prgsize.height) / 2
6431 [progress_ setFrame:prgrect];
6433 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6434 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6435 CGRect indrect = {{indoffset, indoffset}, indsize};
6436 [indicator_ setFrame:indrect];
6438 CGSize prmsize = {215, indsize.height + 4};
6440 indoffset * 2 + indsize.width,
6441 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6443 [prompt_ setFrame:prmrect];
6446 - (void)setFrame:(CGRect)frame {
6447 [super setFrame:frame];
6449 [self positionViews];
6452 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6453 if ((self = [super initWithFrame:frame])) {
6454 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6456 [self setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
6457 [self setBarStyle:UIBarStyleBlack];
6459 UIBarStyle barstyle([self _barStyle:NO]);
6460 bool ugly(barstyle == UIBarStyleDefault);
6462 UIProgressIndicatorStyle style = ugly ?
6463 UIProgressIndicatorStyleMediumBrown :
6464 UIProgressIndicatorStyleMediumWhite;
6466 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6467 [indicator_ setStyle:style];
6468 [indicator_ startAnimation];
6469 [self addSubview:indicator_];
6471 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6472 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6473 [prompt_ setBackgroundColor:[UIColor clearColor]];
6474 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6475 [self addSubview:prompt_];
6477 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6478 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6479 [progress_ setStyle:0];
6480 [self addSubview:progress_];
6482 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6483 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6484 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6485 [cancel_ setBarStyle:barstyle];
6487 [self positionViews];
6492 [cancel_ removeFromSuperview];
6496 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6497 [progress_ setProgress:0];
6498 [self addSubview:cancel_];
6502 [cancel_ removeFromSuperview];
6505 - (void) setPrompt:(NSString *)prompt {
6506 [prompt_ setText:prompt];
6509 - (void) setProgress:(float)progress {
6510 [progress_ setProgress:progress];
6516 @class CYNavigationController;
6518 /* Cydia Tab Bar Controller {{{ */
6519 @interface CYTabBarController : UITabBarController {
6520 _transient Database *database_;
6525 @implementation CYTabBarController
6527 /* XXX: some logic should probably go here related to
6528 freeing the view controllers on tab change */
6530 - (void) reloadData {
6531 size_t count([[self viewControllers] count]);
6532 for (size_t i(0); i != count; ++i) {
6533 CYNavigationController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6538 - (id) initWithDatabase:(Database *)database {
6539 if ((self = [super init]) != nil) {
6540 database_ = database;
6547 /* Cydia Navigation Controller {{{ */
6548 @interface CYNavigationController : UINavigationController {
6549 _transient Database *database_;
6550 _transient id<UINavigationControllerDelegate> delegate_;
6553 - (id) initWithDatabase:(Database *)database;
6554 - (void) reloadData;
6559 @implementation CYNavigationController
6561 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
6562 // Inherit autorotation settings for modal parents.
6563 if ([self parentViewController] && [[self parentViewController] modalViewController] == self) {
6564 return [[self parentViewController] shouldAutorotateToInterfaceOrientation:orientation];
6566 return [super shouldAutorotateToInterfaceOrientation:orientation];
6574 - (void) reloadData {
6575 size_t count([[self viewControllers] count]);
6576 for (size_t i(0); i != count; ++i) {
6577 CYViewController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6582 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
6583 delegate_ = delegate;
6586 - (id) initWithDatabase:(Database *)database {
6587 if ((self = [super init]) != nil) {
6588 database_ = database;
6594 /* Cydia:// Protocol {{{ */
6595 @interface CydiaURLProtocol : NSURLProtocol {
6600 @implementation CydiaURLProtocol
6602 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6603 NSURL *url([request URL]);
6606 NSString *scheme([[url scheme] lowercaseString]);
6607 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6612 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6616 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6617 id<NSURLProtocolClient> client([self client]);
6619 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6621 NSData *data(UIImagePNGRepresentation(icon));
6623 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6624 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6625 [client URLProtocol:self didLoadData:data];
6626 [client URLProtocolDidFinishLoading:self];
6630 - (void) startLoading {
6631 id<NSURLProtocolClient> client([self client]);
6632 NSURLRequest *request([self request]);
6634 NSURL *url([request URL]);
6635 NSString *href([url absoluteString]);
6637 NSString *path([href substringFromIndex:8]);
6638 NSRange slash([path rangeOfString:@"/"]);
6641 if (slash.location == NSNotFound) {
6645 command = [path substringToIndex:slash.location];
6646 path = [path substringFromIndex:(slash.location + 1)];
6649 Database *database([Database sharedInstance]);
6651 if ([command isEqualToString:@"package-icon"]) {
6654 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6655 Package *package([database packageWithName:path]);
6658 UIImage *icon([package icon]);
6659 [self _returnPNGWithImage:icon forRequest:request];
6660 } else if ([command isEqualToString:@"source-icon"]) {
6663 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6664 NSString *source(Simplify(path));
6665 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6667 icon = [UIImage applicationImageNamed:@"unknown.png"];
6668 [self _returnPNGWithImage:icon forRequest:request];
6669 } else if ([command isEqualToString:@"uikit-image"]) {
6672 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6673 UIImage *icon(_UIImageWithName(path));
6674 [self _returnPNGWithImage:icon forRequest:request];
6675 } else if ([command isEqualToString:@"section-icon"]) {
6678 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6679 NSString *section(Simplify(path));
6680 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6682 icon = [UIImage applicationImageNamed:@"unknown.png"];
6683 [self _returnPNGWithImage:icon forRequest:request];
6685 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6689 - (void) stopLoading {
6695 /* Sections Controller {{{ */
6696 @interface SectionsController : CYViewController <
6697 UITableViewDataSource,
6700 _transient Database *database_;
6701 NSMutableArray *sections_;
6702 NSMutableArray *filtered_;
6708 - (id) initWithDatabase:(Database *)database;
6709 - (void) reloadData;
6712 - (void) editButtonClicked;
6716 @implementation SectionsController
6719 [list_ setDataSource:nil];
6720 [list_ setDelegate:nil];
6722 [sections_ release];
6723 [filtered_ release];
6725 [accessory_ release];
6729 - (void) viewDidAppear:(BOOL)animated {
6730 [super viewDidAppear:animated];
6731 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6734 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
6735 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
6739 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6740 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6743 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6747 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6748 static NSString *reuseIdentifier = @"SectionCell";
6750 SectionCell *cell = (SectionCell *) [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6752 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6754 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
6759 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6763 Section *section = [self sectionAtIndexPath:indexPath];
6764 NSString *name = [section name];
6767 if ([indexPath row] == 0) {
6770 title = UCLocalize("ALL_PACKAGES");
6773 name = [NSString stringWithString:name];
6774 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6777 title = UCLocalize("NO_SECTION");
6781 FilteredPackageController *table = [[[FilteredPackageController alloc]
6782 initWithDatabase:database_
6784 filter:@selector(isVisibleInSection:)
6788 [table setDelegate:delegate_];
6790 [[self navigationController] pushViewController:table animated:YES];
6793 - (NSString *) title { return UCLocalize("SECTIONS"); }
6795 - (id) initWithDatabase:(Database *)database {
6796 if ((self = [super init]) != nil) {
6797 database_ = database;
6799 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
6801 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6802 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6804 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
6805 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6806 [list_ setRowHeight:45.0f];
6807 [[self view] addSubview:list_];
6809 [list_ setDataSource:self];
6810 [list_ setDelegate:self];
6816 - (void) reloadData {
6817 NSArray *packages = [database_ packages];
6819 [sections_ removeAllObjects];
6820 [filtered_ removeAllObjects];
6822 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6825 for (Package *package in packages) {
6826 NSString *name([package section]);
6827 NSString *key(name == nil ? @"" : name);
6831 _profile(SectionsView$reloadData$Section)
6832 section = [sections objectForKey:key];
6833 if (section == nil) {
6834 _profile(SectionsView$reloadData$Section$Allocate)
6835 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6836 [sections setObject:section forKey:key];
6841 [section addToCount];
6843 _profile(SectionsView$reloadData$Filter)
6844 if (![package valid] || ![package visible])
6852 [sections_ addObjectsFromArray:[sections allValues]];
6854 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6856 for (Section *section in sections_) {
6857 size_t count([section row]);
6861 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6862 [section setCount:count];
6863 [filtered_ addObject:section];
6866 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6867 initWithTitle:([sections_ count] == 0 ? nil : UCLocalize("EDIT"))
6868 style:UIBarButtonItemStylePlain
6870 action:@selector(editButtonClicked)
6871 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] != nil)];
6877 - (void) resetView {
6879 [self editButtonClicked];
6882 - (void) editButtonClicked {
6883 if ((editing_ = !editing_))
6886 [delegate_ updateData];
6888 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6889 [[[self navigationItem] rightBarButtonItem] setTitle:[sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT")];
6890 [[[self navigationItem] rightBarButtonItem] setStyle:editing_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain];
6893 - (UIView *) accessoryView {
6899 /* Changes Controller {{{ */
6900 @interface ChangesController : CYViewController <
6901 UITableViewDataSource,
6904 _transient Database *database_;
6905 CFMutableArrayRef packages_;
6906 NSMutableArray *sections_;
6909 BOOL hasSentFirstLoad_;
6912 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
6913 - (void) reloadData;
6917 @implementation ChangesController
6920 [list_ setDelegate:nil];
6921 [list_ setDataSource:nil];
6923 CFRelease(packages_);
6925 [sections_ release];
6930 - (void) viewDidAppear:(BOOL)animated {
6931 [super viewDidAppear:animated];
6932 if (!hasSentFirstLoad_) {
6933 hasSentFirstLoad_ = YES;
6934 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
6936 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6940 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6941 NSInteger count([sections_ count]);
6942 return count == 0 ? 1 : count;
6945 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6946 if ([sections_ count] == 0)
6948 return [[sections_ objectAtIndex:section] name];
6951 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6952 if ([sections_ count] == 0)
6954 return [[sections_ objectAtIndex:section] count];
6957 - (Package *) packageAtIndex:(NSUInteger)index {
6958 return (Package *) CFArrayGetValueAtIndex(packages_, index);
6961 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6962 Section *section([sections_ objectAtIndex:[path section]]);
6963 NSInteger row([path row]);
6964 return [self packageAtIndex:([section row] + row)];
6967 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6968 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6970 cell = [[[PackageCell alloc] init] autorelease];
6971 [cell setPackage:[self packageAtIndexPath:path]];
6975 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
6976 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
6979 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
6980 Package *package([self packageAtIndexPath:path]);
6981 PackageController *view([delegate_ packageController]);
6982 [view setDelegate:delegate_];
6983 [view setPackage:package];
6984 [[self navigationController] pushViewController:view animated:YES];
6988 - (void) refreshButtonClicked {
6989 [delegate_ beginUpdate];
6990 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
6993 - (void) upgradeButtonClicked {
6994 [delegate_ distUpgrade];
6997 - (NSString *) title { return UCLocalize("CHANGES"); }
6999 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7000 if ((self = [super init]) != nil) {
7001 database_ = database;
7002 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7004 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7006 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7008 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7009 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7010 [list_ setRowHeight:73.0f];
7011 [[self view] addSubview:list_];
7013 [list_ setDataSource:self];
7014 [list_ setDelegate:self];
7016 delegate_ = delegate;
7020 - (void) _reloadPackages:(NSArray *)packages {
7022 for (Package *package in packages)
7023 if ([package upgradableAndEssential:YES] || [package visible])
7024 CFArrayAppendValue(packages_, package);
7027 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7031 - (void) reloadData {
7032 NSArray *packages = [database_ packages];
7034 CFArrayRemoveAllValues(packages_);
7036 [sections_ removeAllObjects];
7039 UIProgressHUD *hud([delegate_ addProgressHUD]);
7040 [hud setText:UCLocalize("LOADING")];
7041 //NSLog(@"HUD:%@::%@", delegate_, hud);
7042 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7043 [delegate_ removeProgressHUD:hud];
7045 [self _reloadPackages:packages];
7048 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7049 Section *ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") localize:NO] autorelease];
7050 Section *section = nil;
7054 bool unseens = false;
7056 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7058 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7059 Package *package = [self packageAtIndex:offset];
7061 BOOL uae = [package upgradableAndEssential:YES];
7067 _profile(ChangesController$reloadData$Remember)
7068 seen = [package seen];
7071 if (section == nil || last != seen && (seen == nil || [seen compare:last] != NSOrderedSame)) {
7076 name = UCLocalize("UNKNOWN");
7078 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) seen);
7082 _profile(ChangesController$reloadData$Allocate)
7083 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7084 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7085 [sections_ addObject:section];
7089 [section addToCount];
7090 } else if ([package ignored])
7091 [ignored addToCount];
7094 [upgradable addToCount];
7099 CFRelease(formatter);
7102 Section *last = [sections_ lastObject];
7103 size_t count = [last count];
7104 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7105 [sections_ removeLastObject];
7108 if ([ignored count] != 0)
7109 [sections_ insertObject:ignored atIndex:0];
7111 [sections_ insertObject:upgradable atIndex:0];
7116 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7117 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7118 style:UIBarButtonItemStylePlain
7120 action:@selector(upgradeButtonClicked)
7123 if (![delegate_ updating])
7124 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7125 initWithTitle:UCLocalize("REFRESH")
7126 style:UIBarButtonItemStylePlain
7128 action:@selector(refreshButtonClicked)
7134 /* Search Controller {{{ */
7135 @interface SearchController : FilteredPackageController <
7138 UISearchBar *search_;
7141 - (id) initWithDatabase:(Database *)database;
7142 - (void) reloadData;
7146 @implementation SearchController
7153 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7154 [packages_ setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7155 [search_ resignFirstResponder];
7159 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7160 [packages_ setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7164 - (NSString *) title { return nil; }
7166 - (id) initWithDatabase:(Database *)database {
7167 return [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil];
7170 - (void)viewDidAppear:(BOOL)animated {
7171 [super viewDidAppear:animated];
7173 search_ = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7174 [search_ layoutSubviews];
7175 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7176 UITextField *textField = [search_ searchField];
7177 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7178 [search_ setDelegate:self];
7179 [textField setEnablesReturnKeyAutomatically:NO];
7180 [[self navigationItem] setTitleView:textField];
7184 - (void) _reloadData {
7187 - (void) reloadData {
7188 _profile(SearchController$reloadData)
7189 [packages_ reloadData];
7192 [packages_ resetCursor];
7195 - (void) didSelectPackage:(Package *)package {
7196 [search_ resignFirstResponder];
7197 [super didSelectPackage:package];
7202 /* Settings Controller {{{ */
7203 @interface SettingsController : CYViewController <
7204 UITableViewDataSource,
7207 _transient Database *database_;
7210 UITableView *table_;
7211 UISwitch *subscribedSwitch_;
7212 UISwitch *ignoredSwitch_;
7213 UITableViewCell *subscribedCell_;
7214 UITableViewCell *ignoredCell_;
7217 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7221 @implementation SettingsController
7225 if (package_ != nil)
7228 [subscribedSwitch_ release];
7229 [ignoredSwitch_ release];
7230 [subscribedCell_ release];
7231 [ignoredCell_ release];
7236 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7237 if (package_ == nil)
7243 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7244 if (package_ == nil)
7250 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7251 return UCLocalize("SHOW_ALL_CHANGES_EX");
7254 - (void) onSomething:(BOOL)value withKey:(NSString *)key {
7255 if (package_ == nil)
7258 NSMutableDictionary *metadata([package_ metadata]);
7261 if (NSNumber *number = [metadata objectForKey:key])
7262 before = [number boolValue];
7266 if (value != before) {
7267 [metadata setObject:[NSNumber numberWithBool:value] forKey:key];
7269 [delegate_ updateData];
7273 - (void) onSubscribed:(id)control {
7274 [self onSomething:(int) [control isOn] withKey:@"IsSubscribed"];
7277 - (void) onIgnored:(id)control {
7278 [self onSomething:(int) [control isOn] withKey:@"IsIgnored"];
7281 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7282 if (package_ == nil)
7285 switch ([indexPath row]) {
7286 case 0: return subscribedCell_;
7287 case 1: return ignoredCell_;
7295 - (NSString *) title { return UCLocalize("SETTINGS"); }
7297 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7298 if ((self = [super init])) {
7299 database_ = database;
7300 name_ = [package retain];
7302 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7304 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7305 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7306 [[self view] addSubview:table_];
7308 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7309 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7310 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7312 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7313 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7314 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7316 subscribedCell_ = [[UITableViewCell alloc] init];
7317 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7318 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7319 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7321 ignoredCell_ = [[UITableViewCell alloc] init];
7322 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7323 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7324 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7326 [table_ setDataSource:self];
7327 [table_ setDelegate:self];
7332 - (void) reloadData {
7333 if (package_ != nil)
7334 [package_ autorelease];
7335 package_ = [database_ packageWithName:name_];
7336 if (package_ != nil) {
7338 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7339 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7342 [table_ reloadData];
7347 /* Signature Controller {{{ */
7348 @interface SignatureController : CYBrowserController {
7349 _transient Database *database_;
7353 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7357 @implementation SignatureController
7364 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7366 [super webView:view didClearWindowObject:window forFrame:frame];
7369 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7370 if ((self = [super init]) != nil) {
7371 database_ = database;
7372 package_ = [package retain];
7377 - (void) reloadData {
7378 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7384 /* Role Controller {{{ */
7385 @interface RoleController : CYViewController <
7386 UITableViewDataSource,
7389 _transient Database *database_;
7390 // XXX: ok, "roledelegate_"?...
7391 _transient id roledelegate_;
7392 UITableView *table_;
7393 UISegmentedControl *segment_;
7397 - (void) showDoneButton;
7398 - (void) resizeSegmentedControl;
7402 @implementation RoleController
7406 [container_ release];
7411 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7412 if ((self = [super init])) {
7413 database_ = database;
7414 roledelegate_ = delegate;
7416 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
7418 NSArray *items = [NSArray arrayWithObjects:
7420 UCLocalize("HACKER"),
7421 UCLocalize("DEVELOPER"),
7423 segment_ = [[UISegmentedControl alloc] initWithItems:items];
7424 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
7425 [container_ addSubview:segment_];
7428 if ([Role_ isEqualToString:@"User"]) index = 0;
7429 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
7430 if ([Role_ isEqualToString:@"Developer"]) index = 2;
7432 [segment_ setSelectedSegmentIndex:index];
7433 [self showDoneButton];
7436 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
7437 [self resizeSegmentedControl];
7439 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7440 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7441 [table_ setDelegate:self];
7442 [table_ setDataSource:self];
7443 [[self view] addSubview:table_];
7444 [table_ reloadData];
7448 - (void) resizeSegmentedControl {
7449 CGFloat width = [[self view] frame].size.width;
7450 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
7453 - (void) viewWillAppear:(BOOL)animated {
7454 [super viewWillAppear:animated];
7456 [self resizeSegmentedControl];
7459 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7460 [self resizeSegmentedControl];
7463 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7464 [self resizeSegmentedControl];
7468 NSString *role(nil);
7470 switch ([segment_ selectedSegmentIndex]) {
7471 case 0: role = @"User"; break;
7472 case 1: role = @"Hacker"; break;
7473 case 2: role = @"Developer"; break;
7478 if (![role isEqualToString:Role_]) {
7479 bool rolling(Role_ == nil);
7482 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7486 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7491 [roledelegate_ loadData];
7493 [roledelegate_ updateData];
7497 - (void) segmentChanged:(UISegmentedControl *)control {
7498 [self showDoneButton];
7501 - (void) saveAndClose {
7504 [[self navigationItem] setRightBarButtonItem:nil];
7505 [[self navigationController] dismissModalViewControllerAnimated:YES];
7508 - (void) doneButtonClicked {
7509 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
7510 [spinner startAnimating];
7511 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
7512 [[self navigationItem] setRightBarButtonItem:spinItem];
7514 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
7517 - (void) showDoneButton {
7518 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7519 initWithTitle:UCLocalize("DONE")
7520 style:UIBarButtonItemStyleDone
7522 action:@selector(doneButtonClicked)
7523 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
7526 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7527 // XXX: For not having a single cell in the table, this sure is a lot of sections.
7531 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7535 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7536 return nil; // This method is required by the protocol.
7539 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7541 return UCLocalize("ROLE_EX");
7543 return [NSString stringWithFormat:
7544 @"%@: %@\n%@: %@\n%@: %@",
7545 UCLocalize("USER"), UCLocalize("USER_EX"),
7546 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
7547 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
7552 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
7553 return section == 3 ? 44.0f : 0;
7556 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
7557 return section == 3 ? container_ : nil;
7562 /* Stash Controller {{{ */
7563 @interface CYStashController : CYViewController {
7564 // XXX: just delete these things
7565 _transient UIActivityIndicatorView *spinner_;
7566 _transient UILabel *status_;
7567 _transient UILabel *caption_;
7571 @implementation CYStashController
7573 if ((self = [super init])) {
7574 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
7576 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
7577 CGRect spinrect = [spinner_ frame];
7578 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
7579 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
7580 [spinner_ setFrame:spinrect];
7581 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
7582 [[self view] addSubview:spinner_];
7583 [spinner_ startAnimating];
7586 captrect.size.width = [[self view] frame].size.width;
7587 captrect.size.height = 40.0f;
7588 captrect.origin.x = 0;
7589 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
7590 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
7591 [caption_ setText:@"Initializing Filesystem"];
7592 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7593 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
7594 [caption_ setTextColor:[UIColor whiteColor]];
7595 [caption_ setBackgroundColor:[UIColor clearColor]];
7596 [caption_ setShadowColor:[UIColor blackColor]];
7597 [caption_ setTextAlignment:UITextAlignmentCenter];
7598 [[self view] addSubview:caption_];
7601 statusrect.size.width = [[self view] frame].size.width;
7602 statusrect.size.height = 30.0f;
7603 statusrect.origin.x = 0;
7604 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
7605 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
7606 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7607 [status_ setText:@"(Cydia will exit when complete.)"];
7608 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
7609 [status_ setTextColor:[UIColor whiteColor]];
7610 [status_ setBackgroundColor:[UIColor clearColor]];
7611 [status_ setShadowColor:[UIColor blackColor]];
7612 [status_ setTextAlignment:UITextAlignmentCenter];
7613 [[self view] addSubview:status_];
7617 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7618 return IsWildcat_ || orientation == UIInterfaceOrientationPortrait;
7623 /* Cydia Container {{{ */
7624 @interface CYContainer : UIViewController <ProgressDelegate> {
7625 _transient Database *database_;
7626 RefreshBar *refreshbar_;
7630 // XXX: ok, "updatedelegate_"?...
7631 _transient NSObject<CydiaDelegate> *updatedelegate_;
7632 // XXX: can't we query for this variable when we need it?
7633 _transient UITabBarController *root_;
7636 - (void) setTabBarController:(UITabBarController *)controller;
7638 - (void) dropBar:(BOOL)animated;
7639 - (void) beginUpdate;
7640 - (void) raiseBar:(BOOL)animated;
7645 @implementation CYContainer
7647 - (BOOL) _reallyWantsFullScreenLayout {
7651 // NOTE: UIWindow only sends the top controller these messages,
7652 // So we have to forward them on.
7654 - (void) viewDidAppear:(BOOL)animated {
7655 [super viewDidAppear:animated];
7656 [root_ viewDidAppear:animated];
7659 - (void) viewWillAppear:(BOOL)animated {
7660 [super viewWillAppear:animated];
7661 [root_ viewWillAppear:animated];
7664 - (void) viewDidDisappear:(BOOL)animated {
7665 [super viewDidDisappear:animated];
7666 [root_ viewDidDisappear:animated];
7669 - (void) viewWillDisappear:(BOOL)animated {
7670 [super viewWillDisappear:animated];
7671 [root_ viewWillDisappear:animated];
7674 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7675 return ![updatedelegate_ hudIsShowing] && (IsWildcat_ || orientation == UIInterfaceOrientationPortrait);
7678 - (void) setTabBarController:(UITabBarController *)controller {
7680 [[self view] addSubview:[root_ view]];
7683 - (void) setUpdate:(NSDate *)date {
7687 - (void) beginUpdate {
7689 [refreshbar_ start];
7694 detachNewThreadSelector:@selector(performUpdate)
7700 - (void) performUpdate { _pooled
7702 status.setDelegate(self);
7703 [database_ updateWithStatus:status];
7706 performSelectorOnMainThread:@selector(completeUpdate)
7712 - (void) completeUpdate {
7717 [self raiseBar:YES];
7719 [updatedelegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
7722 - (void) cancelUpdate {
7724 [self raiseBar:YES];
7726 [updatedelegate_ performSelector:@selector(updateData) withObject:nil afterDelay:0];
7729 - (void) cancelPressed {
7730 [self cancelUpdate];
7737 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
7738 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
7741 - (void) startProgress {
7744 - (void) setProgressTitle:(NSString *)title {
7746 performSelectorOnMainThread:@selector(_setProgressTitle:)
7752 - (bool) isCancelling:(size_t)received {
7756 - (void) setProgressPercent:(float)percent {
7758 performSelectorOnMainThread:@selector(_setProgressPercent:)
7759 withObject:[NSNumber numberWithFloat:percent]
7764 - (void) addProgressOutput:(NSString *)output {
7766 performSelectorOnMainThread:@selector(_addProgressOutput:)
7772 - (void) _setProgressTitle:(NSString *)title {
7773 [refreshbar_ setPrompt:title];
7776 - (void) _setProgressPercent:(NSNumber *)percent {
7777 [refreshbar_ setProgress:[percent floatValue]];
7780 - (void) _addProgressOutput:(NSString *)output {
7783 - (void) setUpdateDelegate:(id)delegate {
7784 updatedelegate_ = delegate;
7787 - (CGFloat) statusBarHeight {
7788 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
7789 return [[UIApplication sharedApplication] statusBarFrame].size.height;
7791 return [[UIApplication sharedApplication] statusBarFrame].size.width;
7795 - (void) dropBar:(BOOL)animated {
7800 [[self view] addSubview:refreshbar_];
7802 CGFloat sboffset = [self statusBarHeight];
7804 CGRect barframe = [refreshbar_ frame];
7805 barframe.origin.y = sboffset;
7806 [refreshbar_ setFrame:barframe];
7809 [UIView beginAnimations:nil context:NULL];
7810 CGRect viewframe = [[root_ view] frame];
7811 viewframe.origin.y += barframe.size.height + sboffset;
7812 viewframe.size.height -= barframe.size.height + sboffset;
7813 [[root_ view] setFrame:viewframe];
7815 [UIView commitAnimations];
7817 // Ensure bar has the proper width for our view, it might have changed
7818 barframe.size.width = viewframe.size.width;
7819 [refreshbar_ setFrame:barframe];
7821 // XXX: fix Apple's layout bug
7822 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7825 - (void) raiseBar:(BOOL)animated {
7830 [refreshbar_ removeFromSuperview];
7832 CGFloat sboffset = [self statusBarHeight];
7835 [UIView beginAnimations:nil context:NULL];
7836 CGRect barframe = [refreshbar_ frame];
7837 CGRect viewframe = [[root_ view] frame];
7838 viewframe.origin.y -= barframe.size.height + sboffset;
7839 viewframe.size.height += barframe.size.height + sboffset;
7840 [[root_ view] setFrame:viewframe];
7842 [UIView commitAnimations];
7844 // XXX: fix Apple's layout bug
7845 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7848 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7849 // XXX: fix Apple's layout bug
7850 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7853 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7859 // XXX: fix Apple's layout bug
7860 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7863 - (void) statusBarFrameChanged:(NSNotification *)notification {
7871 [refreshbar_ release];
7872 [[NSNotificationCenter defaultCenter] removeObserver:self];
7876 - (id) initWithDatabase:(Database *)database {
7877 if ((self = [super init]) != nil) {
7878 database_ = database;
7880 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7881 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
7883 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
7900 @interface Cydia : UIApplication <
7901 ConfirmationControllerDelegate,
7902 ProgressControllerDelegate,
7904 UINavigationControllerDelegate,
7905 UITabBarControllerDelegate
7907 // XXX: evaluate all fields for _transient
7910 CYContainer *container_;
7911 CYTabBarController *tabbar_;
7913 NSMutableArray *essential_;
7914 NSMutableArray *broken_;
7916 Database *database_;
7920 UIKeyboard *keyboard_;
7923 SectionsController *sections_;
7924 ChangesController *changes_;
7925 ManageController *manage_;
7926 SearchController *search_;
7927 SourceTable *sources_;
7928 InstalledController *installed_;
7931 CYStashController *stash_;
7936 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class;
7937 - (void) setPage:(CYViewController *)page;
7942 static _finline void _setHomePage(Cydia *self) {
7943 [self setPage:[self _pageForURL:[NSURL URLWithString:CydiaURL(@"")] withClass:[HomeController class]]];
7946 @implementation Cydia
7948 - (void) beginUpdate {
7949 [container_ beginUpdate];
7953 return [container_ updating];
7956 - (UIView *) rotatingContentViewForWindow:(UIWindow *)window {
7961 if ([broken_ count] != 0) {
7962 int count = [broken_ count];
7964 UIAlertView *alert = [[[UIAlertView alloc]
7965 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
7966 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
7968 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
7969 otherButtonTitles:UCLocalize("TEMPORARY_IGNORE"), nil
7972 [alert setContext:@"fixhalf"];
7974 } else if (!Ignored_ && [essential_ count] != 0) {
7975 int count = [essential_ count];
7977 UIAlertView *alert = [[[UIAlertView alloc]
7978 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
7979 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
7981 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
7982 otherButtonTitles:UCLocalize("UPGRADE_ESSENTIAL"), UCLocalize("COMPLETE_UPGRADE"), nil
7985 [alert setContext:@"upgrade"];
7990 - (void) _saveConfig {
7993 NSString *error(nil);
7994 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
7996 NSError *error(nil);
7997 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
7998 NSLog(@"failure to save metadata data: %@", error);
8001 NSLog(@"failure to serialize metadata: %@", error);
8009 - (void) _updateData {
8012 /* XXX: this is just stupid */
8013 if (tag_ != 1 && sections_ != nil)
8014 [sections_ reloadData];
8015 if (tag_ != 2 && changes_ != nil)
8016 [changes_ reloadData];
8017 if (tag_ != 4 && search_ != nil)
8018 [search_ reloadData];
8020 [(CYNavigationController *)[tabbar_ selectedViewController] reloadData];
8023 - (int)indexOfTabWithTag:(int)tag {
8025 for (UINavigationController *controller in [tabbar_ viewControllers]) {
8026 if ([[controller tabBarItem] tag] == tag)
8034 - (void) _refreshIfPossible {
8035 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8037 bool recently = false;
8038 NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
8039 if (update != nil) {
8040 NSTimeInterval interval([update timeIntervalSinceNow]);
8041 if (interval <= 0 && interval > -(15*60))
8045 // Don't automatic refresh if:
8046 // - We already refreshed recently.
8047 // - We already auto-refreshed this launch.
8048 // - Auto-refresh is disabled.
8049 if (recently || loaded_ || ManualRefresh) {
8050 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8052 // If we are cancelling due to ManualRefresh or a recent refresh
8053 // we need to make sure it knows it's already loaded.
8057 // We are going to load, so remember that.
8061 SCNetworkReachabilityFlags flags; {
8062 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8063 SCNetworkReachabilityGetFlags(reachability, &flags);
8064 CFRelease(reachability);
8067 // XXX: this elaborate mess is what Apple is using to determine this? :(
8068 // XXX: do we care if the user has to intervene? maybe that's ok?
8070 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8071 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8072 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8073 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8074 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8075 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8079 // If we can reach the server, auto-refresh!
8081 [container_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8086 - (void) refreshIfPossible {
8087 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
8090 - (void) _reloadData {
8091 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8092 [hud setText:UCLocalize("RELOADING_DATA")];
8094 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
8097 [self removeProgressHUD:hud];
8101 [essential_ removeAllObjects];
8102 [broken_ removeAllObjects];
8104 NSArray *packages([database_ packages]);
8105 for (Package *package in packages) {
8107 [broken_ addObject:package];
8108 if ([package upgradableAndEssential:NO]) {
8109 if ([package essential])
8110 [essential_ addObject:package];
8115 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem];
8117 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8118 [changesItem setBadgeValue:badge];
8119 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8121 if ([self respondsToSelector:@selector(setApplicationBadge:)])
8122 [self setApplicationBadge:badge];
8124 [self setApplicationBadgeString:badge];
8126 [changesItem setBadgeValue:nil];
8127 [changesItem setAnimatedBadge:NO];
8129 if ([self respondsToSelector:@selector(removeApplicationBadge)])
8130 [self removeApplicationBadge];
8131 else // XXX: maybe use setApplicationBadgeString also?
8132 [self setApplicationIconBadgeNumber:0];
8137 [self refreshIfPossible];
8140 - (void) updateData {
8149 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8150 _assert(file != NULL);
8152 for (NSString *key in [Sources_ allKeys]) {
8153 NSDictionary *source([Sources_ objectForKey:key]);
8155 fprintf(file, "%s %s %s\n",
8156 [[source objectForKey:@"Type"] UTF8String],
8157 [[source objectForKey:@"URI"] UTF8String],
8158 [[source objectForKey:@"Distribution"] UTF8String]
8166 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8167 CYNavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8169 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8170 [container_ presentModalViewController:navigation animated:YES];
8173 detachNewThreadSelector:@selector(update_)
8176 title:UCLocalize("UPDATING_SOURCES")
8180 - (void) reloadData {
8181 @synchronized (self) {
8187 pkgProblemResolver *resolver = [database_ resolver];
8189 resolver->InstallProtect();
8190 if (!resolver->Resolve(true))
8194 - (CGRect) popUpBounds {
8195 return [[tabbar_ view] bounds];
8199 if (![database_ prepare])
8202 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8203 [page setDelegate:self];
8204 CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]);
8205 [confirm_ setDelegate:self];
8208 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8209 [container_ presentModalViewController:confirm_ animated:YES];
8215 @synchronized (self) {
8220 - (void) clearPackage:(Package *)package {
8221 @synchronized (self) {
8228 - (void) installPackages:(NSArray *)packages {
8229 @synchronized (self) {
8230 for (Package *package in packages)
8237 - (void) installPackage:(Package *)package {
8238 @synchronized (self) {
8245 - (void) removePackage:(Package *)package {
8246 @synchronized (self) {
8253 - (void) distUpgrade {
8254 @synchronized (self) {
8255 if (![database_ upgrade])
8262 @synchronized (self) {
8267 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8268 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8270 if (navigation != nil) {
8271 [navigation pushViewController:progress animated:YES];
8273 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8275 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8276 [container_ presentModalViewController:navigation animated:YES];
8280 detachNewThreadSelector:@selector(perform)
8283 title:UCLocalize("RUNNING")
8287 - (void) progressControllerIsComplete:(ProgressController *)progress {
8291 - (void) setPage:(CYViewController *)page {
8292 [page setDelegate:self];
8294 CYNavigationController *navController = (CYNavigationController *) [tabbar_ selectedViewController];
8295 [navController setViewControllers:[NSArray arrayWithObject:page]];
8296 for (CYNavigationController *page in [tabbar_ viewControllers])
8297 if (page != navController)
8298 [page setViewControllers:nil];
8301 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class {
8302 CYBrowserController *browser = [[[_class alloc] init] autorelease];
8303 [browser loadURL:url];
8307 - (SectionsController *) sectionsController {
8308 if (sections_ == nil)
8309 sections_ = [[SectionsController alloc] initWithDatabase:database_];
8313 - (ChangesController *) changesController {
8314 if (changes_ == nil)
8315 changes_ = [[ChangesController alloc] initWithDatabase:database_ delegate:self];
8319 - (ManageController *) manageController {
8320 if (manage_ == nil) {
8321 manage_ = (ManageController *) [[self
8322 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
8323 withClass:[ManageController class]
8326 queueDelegate_ = manage_;
8331 - (SearchController *) searchController {
8333 search_ = [[SearchController alloc] initWithDatabase:database_];
8337 - (SourceTable *) sourcesController {
8338 if (sources_ == nil)
8339 sources_ = [[SourceTable alloc] initWithDatabase:database_];
8343 - (InstalledController *) installedController {
8344 if (installed_ == nil) {
8345 installed_ = [[InstalledController alloc] initWithDatabase:database_];
8347 queueDelegate_ = installed_;
8352 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
8353 int tag = [[viewController tabBarItem] tag];
8355 [(CYNavigationController *)[tabbar_ selectedViewController] popToRootViewControllerAnimated:YES];
8357 } else if (tag_ == 1) {
8358 [[self sectionsController] resetView];
8362 case kCydiaTag: _setHomePage(self); break;
8364 case kSectionsTag: [self setPage:[self sectionsController]]; break;
8365 case kChangesTag: [self setPage:[self changesController]]; break;
8366 case kManageTag: [self setPage:[self manageController]]; break;
8367 case kInstalledTag: [self setPage:[self installedController]]; break;
8368 case kSourcesTag: [self setPage:[self sourcesController]]; break;
8369 case kSearchTag: [self setPage:[self searchController]]; break;
8377 - (void) showSettings {
8378 RoleController *role = [[[RoleController alloc] initWithDatabase:database_ delegate:self] autorelease];
8379 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
8381 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
8382 [container_ presentModalViewController:nav animated:YES];
8385 - (void) setPackageController:(PackageController *)view {
8387 [view setPackage:nil];
8391 - (PackageController *) _packageController {
8392 return [[[PackageController alloc] initWithDatabase:database_] autorelease];
8395 - (PackageController *) packageController {
8396 return [self _packageController];
8399 // Returns the navigation controller for the queuing badge.
8400 - (id) queueBadgeController {
8401 int index = [self indexOfTabWithTag:kManageTag];
8403 index = [self indexOfTabWithTag:kInstalledTag];
8405 return [[tabbar_ viewControllers] objectAtIndex:index];
8408 - (void) cancelAndClear:(bool)clear {
8409 @synchronized (self) {
8415 [[[self queueBadgeController] tabBarItem] setBadgeValue:nil];
8419 [[[self queueBadgeController] tabBarItem] setBadgeValue:UCLocalize("Q_D")];
8423 [queueDelegate_ queueStatusDidChange];
8427 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8428 NSString *context([alert context]);
8430 if ([context isEqualToString:@"fixhalf"]) {
8431 if (button == [alert firstOtherButtonIndex]) {
8432 @synchronized (self) {
8433 for (Package *broken in broken_) {
8436 NSString *id = [broken id];
8437 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8438 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8439 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8440 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8446 } else if (button == [alert cancelButtonIndex]) {
8447 [broken_ removeAllObjects];
8451 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8452 } else if ([context isEqualToString:@"upgrade"]) {
8453 if (button == [alert firstOtherButtonIndex]) {
8454 @synchronized (self) {
8455 for (Package *essential in essential_)
8456 [essential install];
8461 } else if (button == [alert firstOtherButtonIndex] + 1) {
8463 } else if (button == [alert cancelButtonIndex]) {
8467 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8471 - (void) system:(NSString *)command { _pooled
8472 system([command UTF8String]);
8475 - (void) applicationWillSuspend {
8477 [super applicationWillSuspend];
8480 - (BOOL) hudIsShowing {
8484 - (void) applicationSuspend:(__GSEvent *)event {
8485 // Use external process status API internally.
8486 // This is probably a really bad idea.
8487 uint64_t status = 0;
8489 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
8490 notify_get_state(notify_token, &status);
8491 notify_cancel(notify_token);
8494 if (![self hudIsShowing] && status == 0)
8495 [super applicationSuspend:event];
8498 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8499 if (![self hudIsShowing])
8500 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8503 - (void) _setSuspended:(BOOL)value {
8504 if (![self hudIsShowing])
8505 [super _setSuspended:value];
8508 - (UIProgressHUD *) addProgressHUD {
8509 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8510 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8512 [window_ setUserInteractionEnabled:NO];
8515 UIViewController *target = container_;
8516 while ([target modalViewController] != nil) target = [target modalViewController];
8517 [[target view] addSubview:hud];
8523 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8525 [hud removeFromSuperview];
8526 [window_ setUserInteractionEnabled:YES];
8530 - (CYViewController *) pageForPackage:(NSString *)name {
8531 if (Package *package = [database_ packageWithName:name]) {
8532 PackageController *view([self packageController]);
8533 [view setPackage:package];
8536 NSURL *url([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"unknown" ofType:@"html"]]);
8537 url = [NSURL URLWithString:[[url absoluteString] stringByAppendingString:[NSString stringWithFormat:@"?%@", name]]];
8538 return [self _pageForURL:url withClass:[CYBrowserController class]];
8542 - (CYViewController *) pageForURL:(NSURL *)url hasTag:(int *)tag {
8546 NSString *href([url absoluteString]);
8547 if ([href hasPrefix:@"apptapp://package/"])
8548 return [self pageForPackage:[href substringFromIndex:18]];
8550 NSString *scheme([[url scheme] lowercaseString]);
8551 if (![scheme isEqualToString:@"cydia"])
8553 NSString *path([url absoluteString]);
8554 if ([path length] < 8)
8556 path = [path substringFromIndex:8];
8557 if (![path hasPrefix:@"/"])
8558 path = [@"/" stringByAppendingString:path];
8560 if ([path isEqualToString:@"/add-source"])
8561 return [[[AddSourceController alloc] initWithDatabase:database_] autorelease];
8562 else if ([path isEqualToString:@"/storage"])
8563 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CYBrowserController class]];
8564 else if ([path isEqualToString:@"/sources"])
8565 return [[[SourceTable alloc] initWithDatabase:database_] autorelease];
8566 else if ([path isEqualToString:@"/packages"])
8567 return [[[InstalledController alloc] initWithDatabase:database_] autorelease];
8568 else if ([path hasPrefix:@"/url/"])
8569 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[CYBrowserController class]];
8570 else if ([path hasPrefix:@"/launch/"])
8571 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8572 else if ([path hasPrefix:@"/package-settings/"])
8573 return [[[SettingsController alloc] initWithDatabase:database_ package:[path substringFromIndex:18]] autorelease];
8574 else if ([path hasPrefix:@"/package-signature/"])
8575 return [[[SignatureController alloc] initWithDatabase:database_ package:[path substringFromIndex:19]] autorelease];
8576 else if ([path hasPrefix:@"/package/"])
8577 return [self pageForPackage:[path substringFromIndex:9]];
8578 else if ([path hasPrefix:@"/files/"]) {
8579 NSString *name = [path substringFromIndex:7];
8581 if (Package *package = [database_ packageWithName:name]) {
8582 FileTable *files = [[[FileTable alloc] initWithDatabase:database_] autorelease];
8583 [files setPackage:package];
8591 - (void) applicationOpenURL:(NSURL *)url {
8592 [super applicationOpenURL:url];
8594 if (CYViewController *page = [self pageForURL:url hasTag:&tag]) {
8595 [self setPage:page];
8597 [tabbar_ setSelectedViewController:(tag_ == -1 ? nil : [[tabbar_ viewControllers] objectAtIndex:tag_])];
8601 - (void) applicationWillResignActive:(UIApplication *)application {
8602 // Stop refreshing if you get a phone call or lock the device.
8603 if ([container_ updating])
8604 [container_ cancelUpdate];
8606 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
8607 [super applicationWillResignActive:application];
8610 - (void) addStashController {
8611 stash_ = [[CYStashController alloc] init];
8612 [window_ addSubview:[stash_ view]];
8615 - (void) removeStashController {
8616 [[stash_ view] removeFromSuperview];
8621 [self setIdleTimerDisabled:YES];
8623 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
8624 [self setStatusBarShowsProgress:YES];
8625 UpdateExternalStatus(1);
8627 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
8629 UpdateExternalStatus(0);
8630 [self setStatusBarShowsProgress:NO];
8632 [self removeStashController];
8634 if (ExecFork() == 0) {
8635 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
8636 perror("launchctl stop");
8640 - (void) setupTabBarController {
8641 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
8642 [tabbar_ setDelegate:self];
8644 NSMutableArray *items([NSMutableArray arrayWithObjects:
8645 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:kCydiaTag] autorelease],
8646 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:kSectionsTag] autorelease],
8647 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:kChangesTag] autorelease],
8648 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:kSearchTag] autorelease],
8652 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:kSourcesTag] autorelease] atIndex:3];
8653 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:kInstalledTag] autorelease] atIndex:3];
8655 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:kManageTag] autorelease] atIndex:3];
8658 NSMutableArray *controllers([NSMutableArray array]);
8660 for (UITabBarItem *item in items) {
8661 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
8662 [controller setTabBarItem:item];
8663 [controllers addObject:controller];
8666 [tabbar_ setViewControllers:controllers];
8669 - (void) applicationDidFinishLaunching:(id)unused {
8670 [CYBrowserController _initialize];
8672 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8674 Font12_ = [[UIFont systemFontOfSize:12] retain];
8675 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8676 Font14_ = [[UIFont systemFontOfSize:14] retain];
8677 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8678 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8682 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8683 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8685 UIScreen *screen([UIScreen mainScreen]);
8687 window_ = [[UIWindow alloc] initWithFrame:[screen bounds]];
8688 [window_ orderFront:self];
8689 [window_ makeKey:self];
8690 [window_ setHidden:NO];
8693 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8694 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8695 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8696 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
8697 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8698 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8699 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8700 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
8701 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
8704 [self addStashController];
8705 // XXX: this would be much cleaner as a yieldToSelector:
8706 // that way the removeStashController could happen right here inline
8707 // we also could no longer require the useless stash_ field anymore
8708 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
8712 database_ = [Database sharedInstance];
8714 [self setupTabBarController];
8716 container_ = [[CYContainer alloc] initWithDatabase:database_];
8717 [container_ setUpdateDelegate:self];
8718 [container_ setTabBarController:tabbar_];
8719 [window_ addSubview:[container_ view]];
8721 // Show pinstripes while loading data.
8722 [[container_ view] setBackgroundColor:[UIColor pinStripeColor]];
8724 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
8731 [self showSettings];
8735 [window_ setUserInteractionEnabled:NO];
8737 UIView *container = [[[UIView alloc] init] autorelease];
8738 [container setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
8740 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
8741 [spinner startAnimating];
8742 [container addSubview:spinner];
8744 UILabel *label = [[[UILabel alloc] init] autorelease];
8745 [label setFont:[UIFont boldSystemFontOfSize:15.0f]];
8746 [label setBackgroundColor:[UIColor clearColor]];
8747 [label setTextColor:[UIColor blackColor]];
8748 [label setShadowColor:[UIColor whiteColor]];
8749 [label setShadowOffset:CGSizeMake(0, 1)];
8750 [label setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
8751 [container addSubview:label];
8753 CGSize viewsize = [[tabbar_ view] frame].size;
8754 CGSize spinnersize = [spinner bounds].size;
8755 CGSize textsize = [[label text] sizeWithFont:[label font]];
8756 float bothwidth = spinnersize.width + textsize.width + 5.0f;
8758 CGRect containrect = {
8759 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
8760 CGSizeMake(bothwidth, spinnersize.height)
8763 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
8771 [container setFrame:containrect];
8772 [spinner setFrame:spinrect];
8773 [label setFrame:textrect];
8774 [[container_ view] addSubview:container];
8779 // Show the home page
8780 [tabbar_ setSelectedIndex:0];
8782 [window_ setUserInteractionEnabled:YES];
8784 // XXX: does this actually slow anything down?
8785 [[container_ view] setBackgroundColor:[UIColor clearColor]];
8786 [container removeFromSuperview];
8789 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
8790 if (item != nil && IsWildcat_) {
8791 [sheet showFromBarButtonItem:item animated:YES];
8793 [sheet showInView:window_];
8800 id Alloc_(id self, SEL selector) {
8801 id object = alloc_(self, selector);
8802 lprintf("[%s]A-%p\n", self->isa->name, object);
8807 id Dealloc_(id self, SEL selector) {
8808 id object = dealloc_(self, selector);
8809 lprintf("[%s]D-%p\n", self->isa->name, object);
8813 Class $WebDefaultUIKitDelegate;
8815 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
8816 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8817 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8818 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
8821 static NSNumber *shouldPlayKeyboardSounds;
8825 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
8827 case 1104: // Keyboard Button Clicked
8828 case 1105: // Keyboard Delete Repeated
8829 if (shouldPlayKeyboardSounds == nil) {
8830 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
8831 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
8834 if (![shouldPlayKeyboardSounds boolValue])
8838 _UIHardware$_playSystemSound$(self, _cmd, sound);
8842 int main(int argc, char *argv[]) { _pooled
8845 if (Class $UIDevice = objc_getClass("UIDevice")) {
8846 UIDevice *device([$UIDevice currentDevice]);
8847 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
8851 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8853 /* Library Hacks {{{ */
8854 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8856 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8857 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8858 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8859 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8860 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8863 $UIHardware = objc_getClass("UIHardware");
8864 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
8865 if (UIHardware$_playSystemSound$ != NULL) {
8866 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
8867 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
8870 /* Set Locale {{{ */
8871 Locale_ = CFLocaleCopyCurrent();
8872 Languages_ = [NSLocale preferredLanguages];
8873 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
8874 //NSLog(@"%@", [Languages_ description]);
8877 if (Languages_ == nil || [Languages_ count] == 0)
8878 // XXX: consider just setting to C and then falling through?
8881 lang = [[Languages_ objectAtIndex:0] UTF8String];
8882 setenv("LANG", lang, true);
8885 //std::setlocale(LC_ALL, lang);
8886 NSLog(@"Setting Language: %s", lang);
8889 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
8891 /* Parse Arguments {{{ */
8892 bool substrate(false);
8898 for (int argi(1); argi != argc; ++argi)
8899 if (strcmp(argv[argi], "--") == 0) {
8901 argv[argi] = argv[0];
8907 for (int argi(1); argi != arge; ++argi)
8908 if (strcmp(args[argi], "--substrate") == 0)
8911 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8915 App_ = [[NSBundle mainBundle] bundlePath];
8916 Home_ = NSHomeDirectory();
8922 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
8923 alloc_ = alloc->method_imp;
8924 alloc->method_imp = (IMP) &Alloc_;*/
8926 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
8927 dealloc_ = dealloc->method_imp;
8928 dealloc->method_imp = (IMP) &Dealloc_;*/
8930 /* System Information {{{ */
8934 size = sizeof(maxproc);
8935 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
8936 perror("sysctlbyname(\"kern.maxproc\", ?)");
8937 else if (maxproc < 64) {
8939 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
8940 perror("sysctlbyname(\"kern.maxproc\", #)");
8943 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
8944 char *osversion = new char[size];
8945 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
8946 perror("sysctlbyname(\"kern.osversion\", ?)");
8948 System_ = [NSString stringWithUTF8String:osversion];
8950 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
8951 char *machine = new char[size];
8952 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
8953 perror("sysctlbyname(\"hw.machine\", ?)");
8957 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
8958 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
8959 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
8960 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
8964 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
8965 NSData *data((NSData *) ecid);
8966 size_t length([data length]);
8967 uint8_t bytes[length];
8968 [data getBytes:bytes];
8969 char string[length * 2 + 1];
8970 for (size_t i(0); i != length; ++i)
8971 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
8972 ChipID_ = [NSString stringWithUTF8String:string];
8976 IOObjectRelease(service);
8980 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
8982 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
8983 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
8984 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
8986 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
8987 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
8988 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
8990 if (mcc != NULL && mnc != NULL)
8991 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
8998 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
8999 Build_ = [system objectForKey:@"ProductBuildVersion"];
9000 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9001 Product_ = [info objectForKey:@"SafariProductVersion"];
9002 Safari_ = [info objectForKey:@"CFBundleVersion"];
9005 /* Load Database {{{ */
9007 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9009 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9011 if (Metadata_ == NULL)
9012 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9014 Settings_ = [Metadata_ objectForKey:@"Settings"];
9016 Packages_ = [Metadata_ objectForKey:@"Packages"];
9017 Sections_ = [Metadata_ objectForKey:@"Sections"];
9018 Sources_ = [Metadata_ objectForKey:@"Sources"];
9020 Token_ = [Metadata_ objectForKey:@"Token"];
9023 if (Settings_ != nil)
9024 Role_ = [Settings_ objectForKey:@"Role"];
9026 if (Packages_ == nil) {
9027 Packages_ = [[[NSMutableDictionary alloc] initWithCapacity:128] autorelease];
9028 [Metadata_ setObject:Packages_ forKey:@"Packages"];
9031 if (Sections_ == nil) {
9032 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9033 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9036 if (Sources_ == nil) {
9037 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9038 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9042 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9044 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", F_OK) == 0)
9045 dlopen("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", RTLD_LAZY | RTLD_GLOBAL);
9046 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
9047 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
9048 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9049 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9051 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9053 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9054 unlink("/tmp/.cydia.fw");
9056 } else if (access("/User", F_OK) != 0 || version < 2) {
9059 system("/usr/libexec/cydia/firmware.sh");
9063 _assert([[NSFileManager defaultManager]
9064 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9065 withIntermediateDirectories:YES
9070 if (access("/tmp/cydia.chk", F_OK) == 0) {
9071 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9072 _assert(errno == ENOENT);
9073 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9074 _assert(errno == ENOENT);
9077 /* APT Initialization {{{ */
9078 _assert(pkgInitConfig(*_config));
9079 _assert(pkgInitSystem(*_config, _system));
9082 _config->Set("APT::Acquire::Translation", lang);
9084 // XXX: this timeout might be important :(
9085 //_config->Set("Acquire::http::Timeout", 15);
9087 _config->Set("Acquire::http::MaxParallel", 3);
9089 /* Color Choices {{{ */
9090 space_ = CGColorSpaceCreateDeviceRGB();
9092 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9093 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9094 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9095 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9096 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9097 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9098 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9099 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9100 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9102 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9103 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9105 /* UIKit Configuration {{{ */
9106 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9107 if ($GSFontSetUseLegacyFontMetrics != NULL)
9108 $GSFontSetUseLegacyFontMetrics(YES);
9110 // XXX: I have a feeling this was important
9111 //UIKeyboardDisableAutomaticAppearance();
9114 Colon_ = UCLocalize("COLON_DELIMITED");
9115 Elision_ = UCLocalize("ELISION");
9116 Error_ = UCLocalize("ERROR");
9117 Warning_ = UCLocalize("WARNING");
9120 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9122 CGColorSpaceRelease(space_);