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>
105 #include <sys/reboot.h>
112 #include <mach-o/nlist.h>
122 #include <Cytore.hpp>
124 #include "UICaboodle/BrowserView.h"
125 #include "SDURLCache/SDURLCache.h"
127 #include "substrate.h"
134 #define _timestamp ({ \
136 gettimeofday(&tv, NULL); \
137 tv.tv_sec * 1000000 + tv.tv_usec; \
140 typedef std::vector<class ProfileTime *> TimeList;
150 ProfileTime(const char *name) :
154 times_.push_back(this);
157 void AddTime(uint64_t time) {
164 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
176 ProfileTimer(ProfileTime &time) :
183 time_.AddTime(_timestamp - start_);
188 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
190 std::cerr << "========" << std::endl;
193 #define _profile(name) { \
194 static ProfileTime name(#name); \
195 ProfileTimer _ ## name(name);
200 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
202 #define CYPoolStart() \
203 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
205 #define CYPoolEnd() \
209 // Hash Functions/Structures {{{
210 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
218 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
220 void NSLogPoint(const char *fix, const CGPoint &point) {
221 NSLog(@"%s(%g,%g)", fix, point.x, point.y);
224 void NSLogRect(const char *fix, const CGRect &rect) {
225 NSLog(@"%s(%g,%g)+(%g,%g)", fix, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
228 static _finline NSString *CydiaURL(NSString *path) {
230 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = ':';
231 page[5] = '/'; page[6] = '/'; page[7] = 'c'; page[8] = 'y'; page[9] = 'd';
232 page[10] = 'i'; page[11] = 'a'; page[12] = '.'; page[13] = 's'; page[14] = 'a';
233 page[15] = 'u'; page[16] = 'r'; page[17] = 'i'; page[18] = 'k'; page[19] = '.';
234 page[20] = 'c'; page[21] = 'o'; page[22] = 'm'; page[23] = '/'; page[24] = '\0';
235 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
238 static _finline void UpdateExternalStatus(uint64_t newStatus) {
240 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
241 notify_set_state(notify_token, newStatus);
242 notify_cancel(notify_token);
244 notify_post("com.saurik.Cydia.status");
247 /* [NSObject yieldToSelector:(withObject:)] {{{*/
248 @interface NSObject (Cydia)
249 - (id) yieldToSelector:(SEL)selector withObject:(id)object;
250 - (id) yieldToSelector:(SEL)selector;
253 @implementation NSObject (Cydia)
258 - (void) _yieldToContext:(NSMutableArray *)context { _pooled
259 SEL selector(reinterpret_cast<SEL>([[context objectAtIndex:0] pointerValue]));
260 id object([[context objectAtIndex:1] nonretainedObjectValue]);
261 volatile bool &stopped(*reinterpret_cast<bool *>([[context objectAtIndex:2] pointerValue]));
263 /* XXX: deal with exceptions */
264 id value([self performSelector:selector withObject:object]);
266 NSMethodSignature *signature([self methodSignatureForSelector:selector]);
267 [context removeAllObjects];
268 if ([signature methodReturnLength] != 0 && value != nil)
269 [context addObject:value];
274 performSelectorOnMainThread:@selector(doNothing)
280 - (id) yieldToSelector:(SEL)selector withObject:(id)object {
281 volatile bool stopped(false);
283 NSMutableArray *context([NSMutableArray arrayWithObjects:
284 [NSValue valueWithPointer:selector],
285 [NSValue valueWithNonretainedObject:object],
286 [NSValue valueWithPointer:const_cast<bool *>(&stopped)],
289 NSThread *thread([[[NSThread alloc]
291 selector:@selector(_yieldToContext:)
297 NSRunLoop *loop([NSRunLoop currentRunLoop]);
298 NSDate *future([NSDate distantFuture]);
300 while (!stopped && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
302 return [context count] == 0 ? nil : [context objectAtIndex:0];
305 - (id) yieldToSelector:(SEL)selector {
306 return [self yieldToSelector:selector withObject:nil];
312 /* Cydia Action Sheet {{{ */
313 @interface CYActionSheet : UIAlertView {
317 - (int) yieldToPopupAlertAnimated:(BOOL)animated;
320 @implementation CYActionSheet
322 - (id) initWithTitle:(NSString *)title buttons:(NSArray *)buttons defaultButtonIndex:(int)index {
323 if ((self = [super init])) {
324 [self setTitle:title];
325 [self setDelegate:self];
326 for (NSString *button in buttons) [self addButtonWithTitle:button];
327 [self setCancelButtonIndex:index];
331 - (void) _updateFrameForDisplay {
332 [super _updateFrameForDisplay];
333 if ([self cancelButtonIndex] == -1) {
334 NSArray *buttons = [self buttons];
335 if ([buttons count]) {
336 UIImage *background = [[buttons objectAtIndex:0] backgroundForState:0];
337 for (UIThreePartButton *button in buttons)
338 [button setBackground:background forState:0];
343 - (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
344 button_ = buttonIndex + 1;
348 [self dismissWithClickedButtonIndex:-1 animated:YES];
351 - (int) yieldToPopupAlertAnimated:(BOOL)animated {
352 [self setRunsModal:YES];
361 /* NSForcedOrderingSearch doesn't work on the iPhone */
362 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
363 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
364 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
366 /* Information Dictionaries {{{ */
367 @interface NSMutableArray (Cydia)
368 - (void) addInfoDictionary:(NSDictionary *)info;
371 @implementation NSMutableArray (Cydia)
373 - (void) addInfoDictionary:(NSDictionary *)info {
374 [self addObject:info];
379 @interface NSMutableDictionary (Cydia)
380 - (void) addInfoDictionary:(NSDictionary *)info;
383 @implementation NSMutableDictionary (Cydia)
385 - (void) addInfoDictionary:(NSDictionary *)info {
386 [self setObject:info forKey:[info objectForKey:@"CFBundleIdentifier"]];
392 #define lprintf(args...) fprintf(stderr, args)
395 #define TraceLogging (1 && !ForRelease)
396 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
397 #define ProfileTimes (0 && !ForRelease)
398 #define ForSaurik (0 && !ForRelease)
399 #define LogBrowser (0 && !ForRelease)
400 #define TrackResize (0 && !ForRelease)
401 #define ManualRefresh (1 && !ForRelease)
402 #define ShowInternals (0 && !ForRelease)
403 #define IgnoreInstall (0 && !ForRelease)
404 #define AlwaysReload (0 && !ForRelease)
408 #define _trace(args...)
413 #define _profile(name) {
416 #define PrintTimes() do {} while (false)
420 typedef uint32_t (*SKRadixFunction)(id, void *);
422 @interface NSMutableArray (Radix)
423 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
431 @implementation NSMutableArray (Radix)
433 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
434 size_t count([self count]);
435 struct RadixItem_ *swap(new RadixItem_[count * 2]);
437 for (size_t i(0); i != count; ++i) {
438 RadixItem_ &item(swap[i]);
441 id object([self objectAtIndex:i]);
442 item.key = function(object, argument);
445 struct RadixItem_ *lhs(swap), *rhs(swap + count);
447 static const size_t width = 32;
448 static const size_t bits = 11;
449 static const size_t slots = 1 << bits;
450 static const size_t passes = (width + (bits - 1)) / bits;
452 size_t *hist(new size_t[slots]);
454 for (size_t pass(0); pass != passes; ++pass) {
455 memset(hist, 0, sizeof(size_t) * slots);
457 for (size_t i(0); i != count; ++i) {
458 uint32_t key(lhs[i].key);
460 key &= _not(uint32_t) >> width - bits;
465 for (size_t i(0); i != slots; ++i) {
466 size_t local(offset);
471 for (size_t i(0); i != count; ++i) {
472 uint32_t key(lhs[i].key);
474 key &= _not(uint32_t) >> width - bits;
475 rhs[hist[key]++] = lhs[i];
478 RadixItem_ *tmp(lhs);
485 const void **values(new const void *[count]);
486 for (size_t i(0); i != count; ++i)
487 values[i] = [self objectAtIndex:lhs[i].index];
488 CFArrayReplaceValues((CFMutableArrayRef) self, CFRangeMake(0, count), values, count);
496 /* Insertion Sort {{{ */
498 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
499 const char *ptr = (const char *)list;
501 CFIndex half = count / 2;
502 const char *probe = ptr + elementSize * half;
503 CFComparisonResult cr = comparator(element, probe, context);
504 if (0 == cr) return (probe - (const char *)list) / elementSize;
505 ptr = (cr < 0) ? ptr : probe + elementSize;
506 count = (cr < 0) ? half : (half + (count & 1) - 1);
508 return (ptr - (const char *)list) / elementSize;
511 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
512 const char *ptr = (const char *)list;
514 CFIndex half = count / 2;
515 const char *probe = ptr + elementSize * half;
516 CFComparisonResult cr = comparator(element, probe, context);
517 if (0 == cr) return (probe - (const char *)list) / elementSize;
518 ptr = (cr < 0) ? ptr : probe + elementSize;
519 count = (cr < 0) ? half : (half + (count & 1) - 1);
521 return (ptr - (const char *)list) / elementSize;
524 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
525 if (range.length == 0)
527 const void **values(new const void *[range.length]);
528 CFArrayGetValues(array, range, values);
530 #if HistogramInsertionSort > 0
531 uint32_t total(0), *offsets(new uint32_t[range.length]);
534 for (CFIndex index(1); index != range.length; ++index) {
535 const void *value(values[index]);
536 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
537 CFIndex correct(index);
538 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
539 #if HistogramInsertionSort > 1
540 NSLog(@"%@ < %@", value, values[correct - 1]);
545 if (correct != index) {
546 size_t offset(index - correct);
547 #if HistogramInsertionSort
551 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
553 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
554 values[correct] = value;
558 CFArrayReplaceValues(array, range, values, range.length);
561 #if HistogramInsertionSort > 0
562 for (CFIndex index(0); index != range.length; ++index)
563 if (offsets[index] != 0)
564 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
565 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
572 /* Apple Bug Fixes {{{ */
573 @implementation UIWebDocumentView (Cydia)
575 - (void) _setScrollerOffset:(CGPoint)offset {
576 UIScroller *scroller([self _scroller]);
578 CGSize size([scroller contentSize]);
579 CGSize bounds([scroller bounds].size);
582 max.x = size.width - bounds.width;
583 max.y = size.height - bounds.height;
591 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
592 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
594 [scroller setOffset:offset];
600 @implementation WebScriptObject (NSFastEnumeration)
602 - (NSUInteger) countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)objects count:(NSUInteger)count {
603 size_t length([self count] - state->state);
606 else if (length > count)
608 for (size_t i(0); i != length; ++i)
609 objects[i] = [self objectAtIndex:state->state++];
610 state->itemsPtr = objects;
611 state->mutationsPtr = (unsigned long *) self;
617 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
618 size_t length([self length] - state->state);
621 else if (length > count)
623 for (size_t i(0); i != length; ++i)
624 objects[i] = [self item:state->state++];
625 state->itemsPtr = objects;
626 state->mutationsPtr = (unsigned long *) self;
630 /* Cydia NSString Additions {{{ */
631 @interface NSString (Cydia)
632 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
633 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
634 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
635 - (NSComparisonResult) compareByPath:(NSString *)other;
636 - (NSString *) stringByCachingURLWithCurrentCDN;
637 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
640 @implementation NSString (Cydia)
642 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
643 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
646 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
647 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
648 memcpy(data, bytes, length);
649 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
652 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
653 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
656 - (NSComparisonResult) compareByPath:(NSString *)other {
657 NSString *prefix = [self commonPrefixWithString:other options:0];
658 size_t length = [prefix length];
660 NSRange lrange = NSMakeRange(length, [self length] - length);
661 NSRange rrange = NSMakeRange(length, [other length] - length);
663 lrange = [self rangeOfString:@"/" options:0 range:lrange];
664 rrange = [other rangeOfString:@"/" options:0 range:rrange];
666 NSComparisonResult value;
668 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
669 value = NSOrderedSame;
670 else if (lrange.location == NSNotFound)
671 value = NSOrderedAscending;
672 else if (rrange.location == NSNotFound)
673 value = NSOrderedDescending;
675 value = NSOrderedSame;
677 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
678 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
679 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
680 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
682 NSComparisonResult result = [lpath compare:rpath];
683 return result == NSOrderedSame ? value : result;
686 - (NSString *) stringByCachingURLWithCurrentCDN {
688 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
689 withString:@"://cache.cydia.saurik.com/"
693 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
694 return [(id)CFURLCreateStringByAddingPercentEscapes(
699 kCFStringEncodingUTF8
706 /* C++ NSString Wrapper Cache {{{ */
707 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
708 return size == 0 ? NULL :
709 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
710 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
713 static _finline CFStringRef CYStringCreate(const char *data) {
714 return CYStringCreate(data, strlen(data));
723 _finline void clear_() {
724 if (cache_ != NULL) {
731 _finline bool empty() const {
735 _finline size_t size() const {
739 _finline char *data() const {
743 _finline void clear() {
748 _finline CYString() :
755 _finline ~CYString() {
759 void operator =(const CYString &rhs) {
763 if (rhs.cache_ == nil)
766 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
769 void copy(apr_pool_t *pool) {
770 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
771 memcpy(temp, data_, size_);
776 void set(apr_pool_t *pool, const char *data, size_t size) {
782 data_ = const_cast<char *>(data);
790 _finline void set(apr_pool_t *pool, const char *data) {
791 set(pool, data, data == NULL ? 0 : strlen(data));
794 _finline void set(apr_pool_t *pool, const std::string &rhs) {
795 set(pool, rhs.data(), rhs.size());
798 bool operator ==(const CYString &rhs) const {
799 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
802 _finline operator CFStringRef() {
804 cache_ = CYStringCreate(data_, size_);
808 _finline operator id() {
809 return (NSString *) static_cast<CFStringRef>(*this);
812 _finline operator const char *() {
813 return reinterpret_cast<const char *>(data_);
817 /* C++ NSString Algorithm Adapters {{{ */
819 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
822 struct NSStringMapHash :
823 std::unary_function<NSString *, size_t>
825 _finline size_t operator ()(NSString *value) const {
826 return CFStringHashNSString((CFStringRef) value);
830 struct NSStringMapLess :
831 std::binary_function<NSString *, NSString *, bool>
833 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
834 return [lhs compare:rhs] == NSOrderedAscending;
838 struct NSStringMapEqual :
839 std::binary_function<NSString *, NSString *, bool>
841 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
842 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
843 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
844 //[lhs isEqualToString:rhs];
849 /* Perl-Compatible RegEx {{{ */
859 Pcre(const char *regex) :
864 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
867 lprintf("%d:%s\n", offset, error);
871 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
872 matches_ = new int[(capture_ + 1) * 3];
880 NSString *operator [](size_t match) {
881 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
884 bool operator ()(NSString *data) {
885 // XXX: length is for characters, not for bytes
886 return operator ()([data UTF8String], [data length]);
889 bool operator ()(const char *data, size_t size) {
891 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
895 /* Mime Addresses {{{ */
896 @interface Address : NSObject {
902 - (NSString *) address;
904 - (void) setAddress:(NSString *)address;
906 + (Address *) addressWithString:(NSString *)string;
907 - (Address *) initWithString:(NSString *)string;
910 @implementation Address
919 - (NSString *) name {
923 - (NSString *) address {
927 - (void) setAddress:(NSString *)address {
929 [address_ autorelease];
933 address_ = [address retain];
936 + (Address *) addressWithString:(NSString *)string {
937 return [[[Address alloc] initWithString:string] autorelease];
940 + (NSArray *) _attributeKeys {
941 return [NSArray arrayWithObjects:@"address", @"name", nil];
944 - (NSArray *) attributeKeys {
945 return [[self class] _attributeKeys];
948 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
949 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
952 - (Address *) initWithString:(NSString *)string {
953 if ((self = [super init]) != nil) {
954 const char *data = [string UTF8String];
955 size_t size = [string length];
957 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
959 if (address_r(data, size)) {
960 name_ = [address_r[1] retain];
961 address_ = [address_r[2] retain];
963 name_ = [string retain];
971 /* CoreGraphics Primitives {{{ */
976 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
977 CGFloat color[] = {red, green, blue, alpha};
978 return CGColorCreate(space, color);
987 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
988 color_(Create_(space, red, green, blue, alpha))
990 Set(space, red, green, blue, alpha);
995 CGColorRelease(color_);
1002 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
1004 color_ = Create_(space, red, green, blue, alpha);
1007 operator CGColorRef() {
1013 /* Random Global Variables {{{ */
1014 static const int PulseInterval_ = 50000;
1017 static NSArray *Finishes_;
1019 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
1020 #define NotifyConfig_ "/etc/notify.conf"
1022 static bool Queuing_;
1024 static CYColor Blue_;
1025 static CYColor Blueish_;
1026 static CYColor Black_;
1027 static CYColor Off_;
1028 static CYColor White_;
1029 static CYColor Gray_;
1030 static CYColor Green_;
1031 static CYColor Purple_;
1032 static CYColor Purplish_;
1034 static UIColor *InstallingColor_;
1035 static UIColor *RemovingColor_;
1037 static NSString *App_;
1038 static NSString *Home_;
1040 static BOOL Advanced_;
1041 static BOOL Ignored_;
1043 static UIFont *Font12_;
1044 static UIFont *Font12Bold_;
1045 static UIFont *Font14_;
1046 static UIFont *Font18Bold_;
1047 static UIFont *Font22Bold_;
1049 static const char *Machine_ = NULL;
1050 static NSString *System_ = nil;
1051 static NSString *SerialNumber_ = nil;
1052 static NSString *ChipID_ = nil;
1053 static NSString *Token_ = nil;
1054 static NSString *UniqueID_ = nil;
1055 static NSString *PLMN_ = nil;
1056 static NSString *Build_ = nil;
1057 static NSString *Product_ = nil;
1058 static NSString *Safari_ = nil;
1060 static CFLocaleRef Locale_;
1061 static NSArray *Languages_;
1062 static CGColorSpaceRef space_;
1064 static NSDictionary *SectionMap_;
1065 static NSMutableDictionary *Metadata_;
1066 static _transient NSMutableDictionary *Settings_;
1067 static _transient NSString *Role_;
1068 static _transient NSMutableDictionary *Packages_;
1069 static _transient NSMutableDictionary *Sections_;
1070 static _transient NSMutableDictionary *Sources_;
1071 static bool Changed_;
1074 static bool IsWildcat_;
1077 /* Display Helpers {{{ */
1078 inline float Interpolate(float begin, float end, float fraction) {
1079 return (end - begin) * fraction + begin;
1082 /* XXX: localize this! */
1083 NSString *SizeString(double size) {
1084 bool negative = size < 0;
1089 while (size > 1024) {
1094 static const char *powers_[] = {"B", "kB", "MB", "GB"};
1096 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
1099 static _finline const char *StripVersion_(const char *version) {
1100 const char *colon(strchr(version, ':'));
1101 return colon == NULL ? version : colon + 1;
1104 NSString *LocalizeSection(NSString *section) {
1105 static Pcre title_r("^(.*?) \\((.*)\\)$");
1106 if (title_r(section)) {
1107 NSString *parent(title_r[1]);
1108 NSString *child(title_r[2]);
1110 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1111 LocalizeSection(parent),
1112 LocalizeSection(child)
1116 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1119 NSString *Simplify(NSString *title) {
1120 const char *data = [title UTF8String];
1121 size_t size = [title length];
1123 static Pcre square_r("^\\[(.*)\\]$");
1124 if (square_r(data, size))
1125 return Simplify(square_r[1]);
1127 static Pcre paren_r("^\\((.*)\\)$");
1128 if (paren_r(data, size))
1129 return Simplify(paren_r[1]);
1131 static Pcre title_r("^(.*?) \\((.*)\\)$");
1132 if (title_r(data, size))
1133 return Simplify(title_r[1]);
1139 NSString *GetLastUpdate() {
1140 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1143 return UCLocalize("NEVER_OR_UNKNOWN");
1145 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1146 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1148 CFRelease(formatter);
1150 return [(NSString *) formatted autorelease];
1153 bool isSectionVisible(NSString *section) {
1154 NSDictionary *metadata([Sections_ objectForKey:section]);
1155 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1156 return hidden == nil || ![hidden boolValue];
1161 /* Delegate Prototypes {{{ */
1165 @interface NSObject (ProgressDelegate)
1168 @protocol ProgressDelegate
1169 - (void) setProgressError:(NSString *)error withTitle:(NSString *)id;
1170 - (void) setProgressTitle:(NSString *)title;
1171 - (void) setProgressPercent:(float)percent;
1172 - (void) startProgress;
1173 - (void) addProgressOutput:(NSString *)output;
1174 - (bool) isCancelling:(size_t)received;
1177 @protocol ConfigurationDelegate
1178 - (void) repairWithSelector:(SEL)selector;
1179 - (void) setConfigurationData:(NSString *)data;
1182 @class CYPackageController;
1184 @protocol CydiaDelegate
1185 - (void) retainNetworkActivityIndicator;
1186 - (void) releaseNetworkActivityIndicator;
1187 - (void) setPackageController:(CYPackageController *)view;
1188 - (void) clearPackage:(Package *)package;
1189 - (void) installPackage:(Package *)package;
1190 - (void) installPackages:(NSArray *)packages;
1191 - (void) removePackage:(Package *)package;
1192 - (void) beginUpdate;
1194 - (void) distUpgrade;
1196 - (void) updateData;
1198 - (void) showSettings;
1199 - (UIProgressHUD *) addProgressHUD;
1200 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1201 - (CYViewController *) pageForPackage:(NSString *)name;
1202 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
1205 static id<CydiaDelegate> CydiaApp;
1208 /* Status Delegation {{{ */
1210 public pkgAcquireStatus
1213 _transient NSObject<ProgressDelegate> *delegate_;
1221 void setDelegate(id delegate) {
1222 delegate_ = delegate;
1225 NSObject<ProgressDelegate> *getDelegate() const {
1229 virtual bool MediaChange(std::string media, std::string drive) {
1233 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1236 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1237 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1238 [delegate_ setProgressTitle:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), [NSString stringWithUTF8String:item.ShortDesc.c_str()]]];
1241 virtual void Done(pkgAcquire::ItemDesc &item) {
1244 virtual void Fail(pkgAcquire::ItemDesc &item) {
1246 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1247 item.Owner->Status == pkgAcquire::Item::StatDone
1251 std::string &error(item.Owner->ErrorText);
1255 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1256 NSArray *fields([description componentsSeparatedByString:@" "]);
1257 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1259 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
1260 withObject:[NSArray arrayWithObjects:
1261 [NSString stringWithUTF8String:error.c_str()],
1268 virtual bool Pulse(pkgAcquire *Owner) {
1269 bool value = pkgAcquireStatus::Pulse(Owner);
1272 double(CurrentBytes + CurrentItems) /
1273 double(TotalBytes + TotalItems)
1276 [delegate_ setProgressPercent:percent];
1277 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1280 virtual void Start() {
1281 [delegate_ startProgress];
1284 virtual void Stop() {
1288 /* Progress Delegation {{{ */
1293 _transient id<ProgressDelegate> delegate_;
1297 virtual void Update() {
1298 /*if (abs(Percent - percent_) > 2)
1299 //NSLog(@"%s:%s:%f", Op.c_str(), SubOp.c_str(), Percent);
1303 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1304 [delegate_ setProgressPercent:(Percent / 100)];*/
1314 void setDelegate(id delegate) {
1315 delegate_ = delegate;
1318 id getDelegate() const {
1322 virtual void Done() {
1324 //[delegate_ setProgressPercent:1];
1329 /* Database Interface {{{ */
1330 typedef std::map< unsigned long, _H<Source> > SourceMap;
1332 @interface Database : NSObject {
1338 pkgCacheFile cache_;
1339 pkgDepCache::Policy *policy_;
1340 pkgRecords *records_;
1341 pkgProblemResolver *resolver_;
1342 pkgAcquire *fetcher_;
1344 SPtr<pkgPackageManager> manager_;
1345 pkgSourceList *list_;
1348 CFMutableArrayRef packages_;
1350 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1359 + (Database *) sharedInstance;
1362 - (void) _readCydia:(NSNumber *)fd;
1363 - (void) _readStatus:(NSNumber *)fd;
1364 - (void) _readOutput:(NSNumber *)fd;
1368 - (Package *) packageWithName:(NSString *)name;
1370 - (pkgCacheFile &) cache;
1371 - (pkgDepCache::Policy *) policy;
1372 - (pkgRecords *) records;
1373 - (pkgProblemResolver *) resolver;
1374 - (pkgAcquire &) fetcher;
1375 - (pkgSourceList &) list;
1376 - (NSArray *) packages;
1377 - (NSArray *) sources;
1378 - (void) reloadData;
1386 - (void) updateWithStatus:(Status &)status;
1388 - (void) setDelegate:(id)delegate;
1389 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1392 /* Delegate Helpers {{{ */
1393 @implementation NSObject (ProgressDelegate)
1395 - (void) _setProgressErrorPackage:(NSArray *)args {
1396 [self performSelector:@selector(setProgressError:forPackage:)
1397 withObject:[args objectAtIndex:0]
1398 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1402 - (void) _setProgressErrorTitle:(NSArray *)args {
1403 [self performSelector:@selector(setProgressError:withTitle:)
1404 withObject:[args objectAtIndex:0]
1405 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1409 - (void) _setProgressError:(NSString *)error withTitle:(NSString *)title {
1410 [self performSelectorOnMainThread:@selector(_setProgressErrorTitle:)
1411 withObject:[NSArray arrayWithObjects:error, title, nil]
1416 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
1417 Package *package = id == nil ? nil : [[Database sharedInstance] packageWithName:id];
1419 [self performSelector:@selector(setProgressError:withTitle:)
1421 withObject:(package == nil ? id : [package name])
1428 // Cytore Definitions {{{
1429 struct PackageValue :
1432 Cytore::Offset<PackageValue> next_;
1434 uint32_t index_ : 23;
1435 uint32_t subscribed_ : 1;
1452 Cytore::Offset<PackageValue> packages_[1 << 16];
1455 static Cytore::File<MetaValue> MetaFile_;
1457 // Cytore Helper Functions {{{
1458 static PackageValue *PackageFind(const char *name, size_t length) {
1459 SplitHash nhash = { hashlittle(name, length) };
1461 PackageValue *metadata;
1463 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1464 offset: if (offset->IsNull()) {
1465 *offset = MetaFile_.New<PackageValue>(length + 1);
1466 metadata = &MetaFile_.Get(*offset);
1468 memcpy(metadata->name_, name, length + 1);
1469 metadata->nhash_ = nhash.u16[1];
1471 metadata = &MetaFile_.Get(*offset);
1473 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1474 offset = &metadata->next_;
1482 static void PackageImport(const void *key, const void *value, void *context) {
1484 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1485 NSLog(@"failed to import package %@", key);
1489 PackageValue *metadata(PackageFind(buffer, strlen(buffer)));
1490 NSDictionary *package((NSDictionary *) value);
1492 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1493 if ([subscribed boolValue] && !metadata->subscribed_)
1494 metadata->subscribed_ = true;
1496 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1497 time_t time([date timeIntervalSince1970]);
1498 if (metadata->first_ > time || metadata->first_ == 0)
1499 metadata->first_ = time;
1502 NSDate *date([package objectForKey:@"LastSeen"]);
1503 NSString *version([package objectForKey:@"LastVersion"]);
1505 if (date != nil && version != nil) {
1506 time_t time([date timeIntervalSince1970]);
1507 if (metadata->last_ < time || metadata->last_ == 0)
1508 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1509 size_t length(strlen(buffer));
1510 uint16_t vhash(hashlittle(buffer, length));
1512 size_t capped(std::min<size_t>(8, length));
1513 char *latest(buffer + length - capped);
1515 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1516 metadata->vhash_ = vhash;
1518 metadata->last_ = time;
1524 /* Source Class {{{ */
1525 @interface Source : NSObject {
1526 CYString depiction_;
1527 CYString description_;
1533 CYString distribution_;
1538 NSString *authority_;
1540 CYString defaultIcon_;
1542 NSDictionary *record_;
1546 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1548 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1550 - (NSString *) depictionForPackage:(NSString *)package;
1551 - (NSString *) supportForPackage:(NSString *)package;
1553 - (NSDictionary *) record;
1557 - (NSString *) distribution;
1558 - (NSString *) type;
1560 - (NSString *) host;
1562 - (NSString *) name;
1563 - (NSString *) description;
1564 - (NSString *) label;
1565 - (NSString *) origin;
1566 - (NSString *) version;
1568 - (NSString *) defaultIcon;
1572 @implementation Source
1576 distribution_.clear();
1579 description_.clear();
1585 defaultIcon_.clear();
1587 if (record_ != nil) {
1597 if (authority_ != nil) {
1598 [authority_ release];
1604 // XXX: this is a very inefficient way to call these deconstructors
1609 + (NSArray *) _attributeKeys {
1610 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1613 - (NSArray *) attributeKeys {
1614 return [[self class] _attributeKeys];
1617 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1618 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1621 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1624 trusted_ = index->IsTrusted();
1626 uri_.set(pool, index->GetURI());
1627 distribution_.set(pool, index->GetDist());
1628 type_.set(pool, index->GetType());
1630 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1631 if (dindex != NULL) {
1633 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1636 pkgTagFile tags(&fd);
1638 pkgTagSection section;
1645 {"default-icon", &defaultIcon_},
1646 {"depiction", &depiction_},
1647 {"description", &description_},
1649 {"origin", &origin_},
1650 {"support", &support_},
1651 {"version", &version_},
1654 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1655 const char *start, *end;
1657 if (section.Find(names[i].name_, start, end)) {
1658 CYString &value(*names[i].value_);
1659 value.set(pool, start, end - start);
1665 record_ = [Sources_ objectForKey:[self key]];
1667 record_ = [record_ retain];
1669 NSURL *url([NSURL URLWithString:uri_]);
1673 host_ = [[host_ lowercaseString] retain];
1678 authority_ = [url path];
1680 if (authority_ != nil)
1681 authority_ = [authority_ retain];
1684 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1685 if ((self = [super init]) != nil) {
1686 [self setMetaIndex:index inPool:pool];
1690 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1691 NSDictionary *lhr = [self record];
1692 NSDictionary *rhr = [source record];
1695 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1697 NSString *lhs = [self name];
1698 NSString *rhs = [source name];
1700 if ([lhs length] != 0 && [rhs length] != 0) {
1701 unichar lhc = [lhs characterAtIndex:0];
1702 unichar rhc = [rhs characterAtIndex:0];
1704 if (isalpha(lhc) && !isalpha(rhc))
1705 return NSOrderedAscending;
1706 else if (!isalpha(lhc) && isalpha(rhc))
1707 return NSOrderedDescending;
1710 return [lhs compare:rhs options:LaxCompareOptions_];
1713 - (NSString *) depictionForPackage:(NSString *)package {
1714 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1717 - (NSString *) supportForPackage:(NSString *)package {
1718 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1721 - (NSDictionary *) record {
1729 - (NSString *) uri {
1733 - (NSString *) distribution {
1734 return distribution_;
1737 - (NSString *) type {
1741 - (NSString *) key {
1742 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1745 - (NSString *) host {
1749 - (NSString *) name {
1750 return origin_.empty() ? authority_ : origin_;
1753 - (NSString *) description {
1754 return description_;
1757 - (NSString *) label {
1758 return label_.empty() ? authority_ : label_;
1761 - (NSString *) origin {
1765 - (NSString *) version {
1769 - (NSString *) defaultIcon {
1770 return defaultIcon_;
1775 /* Relationship Class {{{ */
1776 @interface Relationship : NSObject {
1781 - (NSString *) type;
1783 - (NSString *) name;
1787 @implementation Relationship
1795 - (NSString *) type {
1803 - (NSString *) name {
1810 /* Package Class {{{ */
1811 struct ParsedPackage {
1816 CYString depiction_;
1826 @interface Package : NSObject {
1828 uint32_t essential_ : 1;
1829 uint32_t obsolete_ : 1;
1830 uint32_t ignored_ : 1;
1834 _transient Database *database_;
1836 pkgCache::VerIterator version_;
1837 pkgCache::PkgIterator iterator_;
1838 pkgCache::VerFileIterator file_;
1844 CYString installed_;
1847 _transient NSString *section$_;
1851 PackageValue *metadata_;
1852 ParsedPackage *parsed_;
1854 NSMutableArray *tags_;
1858 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1859 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1861 - (pkgCache::PkgIterator) iterator;
1864 - (NSString *) section;
1865 - (NSString *) simpleSection;
1867 - (NSString *) longSection;
1868 - (NSString *) shortSection;
1872 - (Address *) maintainer;
1874 - (NSString *) longDescription;
1875 - (NSString *) shortDescription;
1878 - (PackageValue *) metadata;
1881 - (bool) subscribed;
1882 - (bool) setSubscribed:(bool)subscribed;
1886 - (NSString *) latest;
1887 - (NSString *) installed;
1888 - (BOOL) uninstalled;
1891 - (BOOL) upgradableAndEssential:(BOOL)essential;
1894 - (BOOL) unfiltered;
1898 - (BOOL) halfConfigured;
1899 - (BOOL) halfInstalled;
1901 - (NSString *) mode;
1904 - (NSString *) name;
1906 - (NSString *) homepage;
1907 - (NSString *) depiction;
1908 - (Address *) author;
1910 - (NSString *) support;
1912 - (NSArray *) files;
1913 - (NSArray *) warnings;
1914 - (NSArray *) applications;
1916 - (Source *) source;
1917 - (NSString *) role;
1919 - (BOOL) matches:(NSString *)text;
1921 - (bool) hasSupportingRole;
1922 - (BOOL) hasTag:(NSString *)tag;
1923 - (NSString *) primaryPurpose;
1924 - (NSArray *) purposes;
1925 - (bool) isCommercial;
1927 - (void) setIndex:(size_t)index;
1929 - (CYString &) cyname;
1931 - (uint32_t) compareBySection:(NSArray *)sections;
1936 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1937 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1938 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1939 - (bool) isVisibleInSection:(NSString *)section;
1940 - (bool) isVisibleInSource:(Source *)source;
1944 uint32_t PackageChangesRadix(Package *self, void *) {
1949 uint32_t timestamp : 30;
1950 uint32_t ignored : 1;
1951 uint32_t upgradable : 1;
1955 bool upgradable([self upgradableAndEssential:YES]);
1956 value.bits.upgradable = upgradable ? 1 : 0;
1959 value.bits.timestamp = 0;
1960 value.bits.ignored = [self ignored] ? 0 : 1;
1961 value.bits.upgradable = 1;
1963 value.bits.timestamp = [self seen] >> 2;
1964 value.bits.ignored = 0;
1965 value.bits.upgradable = 0;
1968 return _not(uint32_t) - value.key;
1971 uint32_t PackagePrefixRadix(Package *self, void *context) {
1972 size_t offset(reinterpret_cast<size_t>(context));
1973 CYString &name([self cyname]);
1975 size_t size(name.size());
1978 char *text(name.data());
1981 if (!isdigit(text[0]))
1985 while (size != digits && isdigit(text[digits]))
1993 if (offset == 0 && zeros != 0) {
1994 memset(data, '0', zeros);
1995 memcpy(data + zeros, text, 4 - zeros);
1997 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1998 if (size <= offset - zeros)
2001 text += offset - zeros;
2002 size -= offset - zeros;
2005 memcpy(data, text, 4);
2007 memcpy(data, text, size);
2008 memset(data + size, 0, 4 - size);
2011 for (size_t i(0); i != 4; ++i)
2012 if (isalpha(data[i]))
2020 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2022 /* XXX: ntohl may be more honest */
2023 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2026 CYString &(*PackageName)(Package *self, SEL sel);
2028 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2029 _profile(PackageNameCompare)
2030 CYString &lhi(PackageName(lhs, @selector(cyname)));
2031 CYString &rhi(PackageName(rhs, @selector(cyname)));
2032 CFStringRef lhn(lhi), rhn(rhi);
2035 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2036 else if (rhn == NULL)
2037 return NSOrderedDescending;
2039 _profile(PackageNameCompare$NumbersLast)
2040 if (!lhi.empty() && !rhi.empty()) {
2041 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2042 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2043 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2044 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2045 return lha ? NSOrderedAscending : NSOrderedDescending;
2049 CFIndex length = CFStringGetLength(lhn);
2051 _profile(PackageNameCompare$Compare)
2052 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2057 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2058 return PackageNameCompare(*lhs, *rhs, context);
2061 struct PackageNameOrdering :
2062 std::binary_function<Package *, Package *, bool>
2064 _finline bool operator ()(Package *lhs, Package *rhs) const {
2065 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2069 @implementation Package
2071 - (NSString *) description {
2072 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2076 if (parsed_ != NULL)
2090 + (NSString *) webScriptNameForSelector:(SEL)selector {
2091 if (selector == @selector(hasTag:))
2097 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2098 return [self webScriptNameForSelector:selector] == nil;
2101 + (NSArray *) _attributeKeys {
2102 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];
2105 - (NSArray *) attributeKeys {
2106 return [[self class] _attributeKeys];
2109 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2110 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2114 if (parsed_ != NULL)
2116 @synchronized (database_) {
2117 if ([database_ era] != era_ || file_.end())
2120 ParsedPackage *parsed(new ParsedPackage);
2123 _profile(Package$parse)
2124 pkgRecords::Parser *parser;
2126 _profile(Package$parse$Lookup)
2127 parser = &[database_ records]->Lookup(file_);
2132 _profile(Package$parse$Find)
2137 {"icon", &parsed->icon_},
2138 {"depiction", &parsed->depiction_},
2139 {"homepage", &parsed->homepage_},
2140 {"website", &website},
2141 {"bugs", &parsed->bugs_},
2142 {"support", &parsed->support_},
2143 {"sponsor", &parsed->sponsor_},
2144 {"author", &parsed->author_},
2147 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2148 const char *start, *end;
2150 if (parser->Find(names[i].name_, start, end)) {
2151 CYString &value(*names[i].value_);
2152 _profile(Package$parse$Value)
2153 value.set(pool_, start, end - start);
2159 _profile(Package$parse$Tagline)
2160 const char *start, *end;
2161 if (parser->ShortDesc(start, end)) {
2162 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2165 while (stop != start && stop[-1] == '\r')
2167 parsed->tagline_.set(pool_, start, stop - start);
2171 _profile(Package$parse$Retain)
2172 if (parsed->homepage_.empty())
2173 parsed->homepage_ = website;
2174 if (parsed->homepage_ == parsed->depiction_)
2175 parsed->homepage_.clear();
2180 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2181 if ((self = [super init]) != nil) {
2182 _profile(Package$initWithVersion)
2185 database_ = database;
2186 era_ = [database era];
2190 pkgCache::PkgIterator iterator(version.ParentPkg());
2191 iterator_ = iterator;
2193 _profile(Package$initWithVersion$Version)
2194 if (!version_.end())
2195 file_ = version_.FileList();
2197 pkgCache &cache([database_ cache]);
2198 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2202 _profile(Package$initWithVersion$Cache)
2203 name_.set(NULL, iterator.Display());
2205 latest_.set(NULL, StripVersion_(version_.VerStr()));
2207 pkgCache::VerIterator current(iterator.CurrentVer());
2209 installed_.set(NULL, StripVersion_(current.VerStr()));
2212 _profile(Package$initWithVersion$Tags)
2213 pkgCache::TagIterator tag(iterator.TagList());
2215 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2217 const char *name(tag.Name());
2218 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2220 if (role_ == nil && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/)
2221 role_ = (NSString *) CYStringCreate(name + 6);
2223 if (strncmp(name, "cydia::", 7) == 0) {
2224 if (strcmp(name + 7, "essential") == 0)
2226 else if (strcmp(name + 7, "obsolete") == 0)
2231 } while (!tag.end());
2235 _profile(Package$initWithVersion$Metadata)
2236 const char *mixed(iterator.Name());
2237 size_t size(strlen(mixed));
2238 char lower[size + 1];
2240 for (size_t i(0); i != size; ++i)
2241 lower[i] = mixed[i] | 0x20;
2244 PackageValue *metadata(PackageFind(lower, size));
2245 metadata_ = metadata;
2247 id_.set(NULL, metadata->name_, size);
2249 const char *latest(version_.VerStr());
2250 size_t length(strlen(latest));
2252 uint16_t vhash(hashlittle(latest, length));
2254 size_t capped(std::min<size_t>(8, length));
2255 latest = latest + length - capped;
2257 if (metadata->first_ == 0)
2258 metadata->first_ = now_;
2260 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2261 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2262 metadata->vhash_ = vhash;
2263 metadata->last_ = now_;
2264 } else if (metadata->last_ == 0)
2265 metadata->last_ = metadata->first_;
2268 _profile(Package$initWithVersion$Section)
2269 section_.set(NULL, iterator.Section());
2272 _profile(Package$initWithVersion$Flags)
2273 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2274 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2279 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2280 pkgCache::VerIterator version;
2282 _profile(Package$packageWithIterator$GetCandidateVer)
2283 version = [database policy]->GetCandidateVer(iterator);
2291 _profile(Package$packageWithIterator$Allocate)
2292 package = [Package allocWithZone:zone];
2295 _profile(Package$packageWithIterator$Initialize)
2297 initWithVersion:version
2304 _profile(Package$packageWithIterator$Autorelease)
2305 package = [package autorelease];
2311 - (pkgCache::PkgIterator) iterator {
2315 - (NSString *) section {
2316 if (section$_ == nil) {
2317 if (section_.empty())
2320 _profile(Package$section)
2321 std::replace(section_.data(), section_.data() + section_.size(), '_', ' ');
2322 NSString *name(section_);
2323 section$_ = [SectionMap_ objectForKey:name] ?: name;
2328 - (NSString *) simpleSection {
2329 if (NSString *section = [self section])
2330 return Simplify(section);
2335 - (NSString *) longSection {
2336 return LocalizeSection([self section]);
2339 - (NSString *) shortSection {
2340 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2343 - (NSString *) uri {
2346 pkgIndexFile *index;
2347 pkgCache::PkgFileIterator file(file_.File());
2348 if (![database_ list].FindIndex(file, index))
2350 return [NSString stringWithUTF8String:iterator_->Path];
2351 //return [NSString stringWithUTF8String:file.Site()];
2352 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2356 - (Address *) maintainer {
2357 @synchronized (database_) {
2358 if ([database_ era] != era_ || file_.end())
2361 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2362 const std::string &maintainer(parser->Maintainer());
2363 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2367 @synchronized (database_) {
2368 if ([database_ era] != era_ || version_.end())
2371 return version_->InstalledSize;
2374 - (NSString *) longDescription {
2375 @synchronized (database_) {
2376 if ([database_ era] != era_ || file_.end())
2379 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2380 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2382 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2383 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2384 if ([lines count] < 2)
2387 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2388 for (size_t i(1), e([lines count]); i != e; ++i) {
2389 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2390 [trimmed addObject:trim];
2393 return [trimmed componentsJoinedByString:@"\n"];
2396 - (NSString *) shortDescription {
2397 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2401 _profile(Package$index)
2402 CFStringRef name((CFStringRef) [self name]);
2403 if (CFStringGetLength(name) == 0)
2405 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2406 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2408 return toupper(character);
2412 - (PackageValue *) metadata {
2417 PackageValue *metadata([self metadata]);
2418 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2421 - (bool) subscribed {
2422 return [self metadata]->subscribed_;
2425 - (bool) setSubscribed:(bool)subscribed {
2426 PackageValue *metadata([self metadata]);
2427 if (metadata->subscribed_ == subscribed)
2429 metadata->subscribed_ = subscribed;
2437 - (NSString *) latest {
2441 - (NSString *) installed {
2445 - (BOOL) uninstalled {
2446 return installed_.empty();
2450 return !version_.end();
2453 - (BOOL) upgradableAndEssential:(BOOL)essential {
2454 _profile(Package$upgradableAndEssential)
2455 pkgCache::VerIterator current(iterator_.CurrentVer());
2457 return essential && essential_;
2459 return !version_.end() && version_ != current;
2463 - (BOOL) essential {
2468 return [database_ cache][iterator_].InstBroken();
2471 - (BOOL) unfiltered {
2472 _profile(Package$unfiltered$obsolete)
2477 _profile(Package$unfiltered$hasSupportingRole)
2478 if (![self hasSupportingRole])
2486 if (![self unfiltered])
2489 NSString *section([self section]);
2491 _profile(Package$visible$isSectionVisible)
2492 if (section != nil && !isSectionVisible(section))
2500 unsigned char current(iterator_->CurrentState);
2501 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2504 - (BOOL) halfConfigured {
2505 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2508 - (BOOL) halfInstalled {
2509 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2513 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2514 return state.Mode != pkgDepCache::ModeKeep;
2517 - (NSString *) mode {
2518 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2520 switch (state.Mode) {
2521 case pkgDepCache::ModeDelete:
2522 if ((state.iFlags & pkgDepCache::Purge) != 0)
2526 case pkgDepCache::ModeKeep:
2527 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2528 return @"REINSTALL";
2529 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2533 case pkgDepCache::ModeInstall:
2534 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2535 return @"REINSTALL";
2536 else*/ switch (state.Status) {
2538 return @"DOWNGRADE";
2544 return @"NEW_INSTALL";
2555 - (NSString *) name {
2556 return name_.empty() ? id_ : name_;
2559 - (UIImage *) icon {
2560 NSString *section = [self simpleSection];
2563 if (parsed_ != NULL)
2564 if (NSString *href = parsed_->icon_)
2565 if ([href hasPrefix:@"file:///"])
2566 // XXX: correct escaping
2567 icon = [UIImage imageAtPath:[href substringFromIndex:7]];
2568 if (icon == nil) if (section != nil)
2569 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2570 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2571 if ([dicon hasPrefix:@"file:///"])
2572 // XXX: correct escaping
2573 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2575 icon = [UIImage applicationImageNamed:@"unknown.png"];
2579 - (NSString *) homepage {
2580 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2583 - (NSString *) depiction {
2584 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2587 - (Address *) sponsor {
2588 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [Address addressWithString:parsed_->sponsor_];
2591 - (Address *) author {
2592 return parsed_ == NULL || parsed_->author_.empty() ? nil : [Address addressWithString:parsed_->author_];
2595 - (NSString *) support {
2596 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2599 - (NSArray *) files {
2600 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2601 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2604 fin.open([path UTF8String]);
2609 while (std::getline(fin, line))
2610 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2615 - (NSArray *) warnings {
2616 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2617 const char *name(iterator_.Name());
2619 size_t length(strlen(name));
2620 if (length < 2) invalid:
2621 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2622 else for (size_t i(0); i != length; ++i)
2624 /* XXX: technically this is not allowed */
2625 (name[i] < 'A' || name[i] > 'Z') &&
2626 (name[i] < 'a' || name[i] > 'z') &&
2627 (name[i] < '0' || name[i] > '9') &&
2628 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2631 if (strcmp(name, "cydia") != 0) {
2634 bool _private = false;
2637 bool repository = [[self section] isEqualToString:@"Repositories"];
2639 if (NSArray *files = [self files])
2640 for (NSString *file in files)
2641 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2643 else if (!user && [file isEqualToString:@"/User"])
2645 else if (!_private && [file isEqualToString:@"/private"])
2647 else if (!stash && [file isEqualToString:@"/var/stash"])
2650 /* XXX: this is not sensitive enough. only some folders are valid. */
2651 if (cydia && !repository)
2652 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2654 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2656 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2658 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2661 return [warnings count] == 0 ? nil : warnings;
2664 - (NSArray *) applications {
2665 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2667 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2669 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2670 if (NSArray *files = [self files])
2671 for (NSString *file in files)
2672 if (application_r(file)) {
2673 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2674 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2675 if ([id isEqualToString:me])
2678 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2680 display = application_r[1];
2682 NSString *bundle([file stringByDeletingLastPathComponent]);
2683 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2684 if (icon == nil || [icon length] == 0)
2686 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2688 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2689 [applications addObject:application];
2691 [application addObject:id];
2692 [application addObject:display];
2693 [application addObject:url];
2696 return [applications count] == 0 ? nil : applications;
2699 - (Source *) source {
2700 if (source_ == nil) {
2701 @synchronized (database_) {
2702 if ([database_ era] != era_ || file_.end())
2703 source_ = (Source *) [NSNull null];
2705 source_ = [([database_ getSource:file_.File()] ?: (Source *) [NSNull null]) retain];
2709 return source_ == (Source *) [NSNull null] ? nil : source_;
2712 - (NSString *) role {
2716 - (BOOL) matches:(NSString *)text {
2722 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2723 if (range.location != NSNotFound)
2726 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2727 if (range.location != NSNotFound)
2730 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2731 if (range.location != NSNotFound)
2737 - (bool) hasSupportingRole {
2740 if ([role_ isEqualToString:@"enduser"])
2742 if ([Role_ isEqualToString:@"User"])
2744 if ([role_ isEqualToString:@"hacker"])
2746 if ([Role_ isEqualToString:@"Hacker"])
2748 if ([role_ isEqualToString:@"developer"])
2750 if ([Role_ isEqualToString:@"Developer"])
2755 - (BOOL) hasTag:(NSString *)tag {
2756 return tags_ == nil ? NO : [tags_ containsObject:tag];
2759 - (NSString *) primaryPurpose {
2760 for (NSString *tag in tags_)
2761 if ([tag hasPrefix:@"purpose::"])
2762 return [tag substringFromIndex:9];
2766 - (NSArray *) purposes {
2767 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2768 for (NSString *tag in tags_)
2769 if ([tag hasPrefix:@"purpose::"])
2770 [purposes addObject:[tag substringFromIndex:9]];
2771 return [purposes count] == 0 ? nil : purposes;
2774 - (bool) isCommercial {
2775 return [self hasTag:@"cydia::commercial"];
2778 - (void) setIndex:(size_t)index {
2779 if (metadata_->index_ != index)
2780 metadata_->index_ = index;
2783 - (CYString &) cyname {
2784 return name_.empty() ? id_ : name_;
2787 - (uint32_t) compareBySection:(NSArray *)sections {
2788 NSString *section([self section]);
2789 for (size_t i(0), e([sections count]); i != e; ++i) {
2790 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2794 return _not(uint32_t);
2798 @synchronized (database_) {
2799 pkgProblemResolver *resolver = [database_ resolver];
2800 resolver->Clear(iterator_);
2802 pkgCacheFile &cache([database_ cache]);
2803 cache->SetReInstall(iterator_, false);
2804 cache->MarkKeep(iterator_, false);
2808 @synchronized (database_) {
2809 pkgProblemResolver *resolver = [database_ resolver];
2810 resolver->Clear(iterator_);
2811 resolver->Protect(iterator_);
2813 pkgCacheFile &cache([database_ cache]);
2814 cache->SetReInstall(iterator_, false);
2815 cache->MarkInstall(iterator_, false);
2817 pkgDepCache::StateCache &state((*cache)[iterator_]);
2818 if (!state.Install())
2819 cache->SetReInstall(iterator_, true);
2823 @synchronized (database_) {
2824 pkgProblemResolver *resolver = [database_ resolver];
2825 resolver->Clear(iterator_);
2826 resolver->Remove(iterator_);
2827 resolver->Protect(iterator_);
2829 pkgCacheFile &cache([database_ cache]);
2830 cache->SetReInstall(iterator_, false);
2831 cache->MarkDelete(iterator_, true);
2834 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2835 _profile(Package$isUnfilteredAndSearchedForBy)
2838 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2839 value &= [self unfiltered];
2842 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2843 value &= [self matches:search];
2850 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2851 if ([search length] == 0)
2854 _profile(Package$isUnfilteredAndSelectedForBy)
2857 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2858 value &= [self unfiltered];
2861 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2862 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2869 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
2870 return ![self uninstalled] && (![number boolValue] && ![role_ isEqualToString:@"cydia"] || [self unfiltered]);
2873 - (bool) isVisibleInSection:(NSString *)name {
2874 NSString *section([self section]);
2878 section == nil && [name length] == 0 ||
2879 [name isEqualToString:section]
2880 ) && [self visible];
2883 - (bool) isVisibleInSource:(Source *)source {
2884 return [self source] == source && [self visible];
2889 /* Section Class {{{ */
2890 @interface Section : NSObject {
2895 NSString *localized_;
2898 - (NSComparisonResult) compareByLocalized:(Section *)section;
2899 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2900 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2901 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2902 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2903 - (NSString *) name;
2910 - (void) addToCount;
2912 - (void) setCount:(size_t)count;
2913 - (NSString *) localized;
2917 @implementation Section
2921 if (localized_ != nil)
2922 [localized_ release];
2926 - (NSComparisonResult) compareByLocalized:(Section *)section {
2927 NSString *lhs(localized_);
2928 NSString *rhs([section localized]);
2930 /*if ([lhs length] != 0 && [rhs length] != 0) {
2931 unichar lhc = [lhs characterAtIndex:0];
2932 unichar rhc = [rhs characterAtIndex:0];
2934 if (isalpha(lhc) && !isalpha(rhc))
2935 return NSOrderedAscending;
2936 else if (!isalpha(lhc) && isalpha(rhc))
2937 return NSOrderedDescending;
2940 return [lhs compare:rhs options:LaxCompareOptions_];
2943 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2944 if ((self = [self initWithName:name localize:NO]) != nil) {
2945 if (localized != nil)
2946 localized_ = [localized retain];
2950 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2951 return [self initWithName:name row:0 localize:localize];
2954 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2955 if ((self = [super init]) != nil) {
2956 name_ = [name retain];
2960 localized_ = [LocalizeSection(name_) retain];
2964 /* XXX: localize the index thingees */
2965 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2966 if ((self = [super init]) != nil) {
2967 name_ = [[NSString stringWithCharacters:&index length:1] retain];
2973 - (NSString *) name {
2993 - (void) addToCount {
2997 - (void) setCount:(size_t)count {
3001 - (NSString *) localized {
3008 static NSString *Colon_;
3009 static NSString *Elision_;
3010 static NSString *Error_;
3011 static NSString *Warning_;
3013 /* Database Implementation {{{ */
3014 @implementation Database
3016 + (Database *) sharedInstance {
3017 static Database *instance;
3018 if (instance == nil)
3019 instance = [[Database alloc] init];
3027 - (void) releasePackages {
3028 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3029 CFArrayRemoveAllValues(packages_);
3033 // XXX: actually implement this thing
3035 [self releasePackages];
3036 apr_pool_destroy(pool_);
3037 NSRecycleZone(zone_);
3041 - (void) _readCydia:(NSNumber *)fd { _pooled
3042 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3043 std::istream is(&ib);
3046 static Pcre finish_r("^finish:([^:]*)$");
3048 while (std::getline(is, line)) {
3049 const char *data(line.c_str());
3050 size_t size = line.size();
3051 lprintf("C:%s\n", data);
3053 if (finish_r(data, size)) {
3054 NSString *finish = finish_r[1];
3055 int index = [Finishes_ indexOfObject:finish];
3056 if (index != INT_MAX && index > Finish_)
3064 - (void) _readStatus:(NSNumber *)fd { _pooled
3065 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3066 std::istream is(&ib);
3069 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3070 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3072 while (std::getline(is, line)) {
3073 const char *data(line.c_str());
3074 size_t size(line.size());
3075 lprintf("S:%s\n", data);
3077 if (conffile_r(data, size)) {
3078 [delegate_ setConfigurationData:conffile_r[1]];
3079 } else if (strncmp(data, "status: ", 8) == 0) {
3080 NSString *string = [NSString stringWithUTF8String:(data + 8)];
3081 [delegate_ setProgressTitle:string];
3082 } else if (pmstatus_r(data, size)) {
3083 std::string type([pmstatus_r[1] UTF8String]);
3084 NSString *id = pmstatus_r[2];
3086 float percent([pmstatus_r[3] floatValue]);
3087 [delegate_ setProgressPercent:(percent / 100)];
3089 NSString *string = pmstatus_r[4];
3091 if (type == "pmerror")
3092 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3093 withObject:[NSArray arrayWithObjects:string, id, nil]
3096 else if (type == "pmstatus") {
3097 [delegate_ setProgressTitle:string];
3098 } else if (type == "pmconffile")
3099 [delegate_ setConfigurationData:string];
3101 lprintf("E:unknown pmstatus\n");
3103 lprintf("E:unknown status\n");
3109 - (void) _readOutput:(NSNumber *)fd { _pooled
3110 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3111 std::istream is(&ib);
3114 while (std::getline(is, line)) {
3115 lprintf("O:%s\n", line.c_str());
3116 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
3126 - (Package *) packageWithName:(NSString *)name {
3127 @synchronized (self) {
3128 if (static_cast<pkgDepCache *>(cache_) == NULL)
3130 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3131 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3135 if ((self = [super init]) != nil) {
3142 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3143 apr_pool_create(&pool_, NULL);
3145 size_t capacity(MetaFile_->active_);
3151 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3155 _assert(pipe(fds) != -1);
3158 _config->Set("APT::Keep-Fds::", cydiafd_);
3159 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3162 detachNewThreadSelector:@selector(_readCydia:)
3164 withObject:[NSNumber numberWithInt:fds[0]]
3167 _assert(pipe(fds) != -1);
3171 detachNewThreadSelector:@selector(_readStatus:)
3173 withObject:[NSNumber numberWithInt:fds[0]]
3176 _assert(pipe(fds) != -1);
3177 _assert(dup2(fds[0], 0) != -1);
3178 _assert(close(fds[0]) != -1);
3180 input_ = fdopen(fds[1], "a");
3182 _assert(pipe(fds) != -1);
3183 _assert(dup2(fds[1], 1) != -1);
3184 _assert(close(fds[1]) != -1);
3187 detachNewThreadSelector:@selector(_readOutput:)
3189 withObject:[NSNumber numberWithInt:fds[0]]
3194 - (pkgCacheFile &) cache {
3198 - (pkgDepCache::Policy *) policy {
3202 - (pkgRecords *) records {
3206 - (pkgProblemResolver *) resolver {
3210 - (pkgAcquire &) fetcher {
3214 - (pkgSourceList &) list {
3218 - (NSArray *) packages {
3219 return (NSArray *) packages_;
3222 - (NSArray *) sources {
3223 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3224 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3225 [sources addObject:i->second];
3229 - (NSArray *) issues {
3230 if (cache_->BrokenCount() == 0)
3233 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3235 for (Package *package in [self packages]) {
3236 if (![package broken])
3238 pkgCache::PkgIterator pkg([package iterator]);
3240 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3241 [entry addObject:[package name]];
3242 [issues addObject:entry];
3244 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3248 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3249 pkgCache::DepIterator start;
3250 pkgCache::DepIterator end;
3251 dep.GlobOr(start, end); // ++dep
3253 if (!cache_->IsImportantDep(end))
3255 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3258 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3259 [entry addObject:failure];
3260 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3262 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3263 if (Package *package = [self packageWithName:name])
3264 name = [package name];
3265 [failure addObject:name];
3267 pkgCache::PkgIterator target(start.TargetPkg());
3268 if (target->ProvidesList != 0)
3269 [failure addObject:@"?"];
3271 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3273 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3274 else if (!cache_[target].CandidateVerIter(cache_).end())
3275 [failure addObject:@"-"];
3276 else if (target->ProvidesList == 0)
3277 [failure addObject:@"!"];
3279 [failure addObject:@"%"];
3283 if (start.TargetVer() != 0)
3284 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3295 - (bool) popErrorWithTitle:(NSString *)title {
3297 std::string message;
3299 while (!_error->empty()) {
3301 bool warning(!_error->PopMessage(error));
3305 size_t size(error.size());
3306 if (size == 0 || error[size - 1] != '\n')
3308 error.resize(size - 1);
3310 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3312 if (!message.empty())
3317 if (fatal && !message.empty())
3318 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3323 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3324 return [self popErrorWithTitle:title] || !success;
3327 - (void) reloadData { CYPoolStart() {
3328 @synchronized (self) {
3331 [self releasePackages];
3352 apr_pool_clear(pool_);
3354 NSRecycleZone(zone_);
3355 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3357 int chk(creat("/tmp/cydia.chk", 0644));
3361 NSString *title(UCLocalize("DATABASE"));
3364 if (!cache_.Open(progress_, true)) { pop:
3366 bool warning(!_error->PopMessage(error));
3367 lprintf("cache_.Open():[%s]\n", error.c_str());
3369 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3370 [delegate_ repairWithSelector:@selector(configure)];
3371 else if (error == "The package lists or status file could not be parsed or opened.")
3372 [delegate_ repairWithSelector:@selector(update)];
3373 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3374 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3375 // else if (error == "The list of sources could not be read.")
3377 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3386 unlink("/tmp/cydia.chk");
3388 now_ = [[NSDate date] timeIntervalSince1970];
3390 policy_ = new pkgDepCache::Policy();
3391 records_ = new pkgRecords(cache_);
3392 resolver_ = new pkgProblemResolver(cache_);
3393 fetcher_ = new pkgAcquire(&status_);
3396 list_ = new pkgSourceList();
3397 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3400 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3401 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3405 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3408 if (cache_->BrokenCount() != 0) {
3409 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3412 if (cache_->BrokenCount() != 0) {
3413 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3417 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3421 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3422 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3423 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3424 // XXX: this could be more intelligent
3425 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3426 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3428 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3433 /*std::vector<Package *> packages;
3434 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3435 [packages_ release];
3440 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3441 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3442 //packages.push_back(package);
3443 CFArrayAppendValue(packages_, [package retain]);
3447 /*if (packages.empty())
3448 packages_ = [[NSArray alloc] init];
3450 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3453 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3454 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3455 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3463 /*if (!packages.empty())
3464 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3465 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3467 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3469 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3471 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3475 size_t count(CFArrayGetCount(packages_));
3476 MetaFile_->active_ = count;
3478 for (size_t index(0); index != count; ++index)
3479 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3483 } } CYPoolEnd() _trace(); }
3486 @synchronized (self) {
3488 resolver_ = new pkgProblemResolver(cache_);
3490 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator) {
3491 if (!cache_[iterator].Keep()) {
3492 cache_->MarkKeep(iterator, false);
3493 cache_->SetReInstall(iterator, false);
3498 - (void) configure {
3499 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3501 system([dpkg UTF8String]);
3506 // XXX: I don't remember this condition
3511 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3513 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3515 if ([self popErrorWithTitle:title])
3519 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3522 public pkgArchiveCleaner
3525 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3530 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3537 fetcher_->Shutdown();
3539 pkgRecords records(cache_);
3541 lock_ = new FileFd();
3542 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3544 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3546 if ([self popErrorWithTitle:title])
3550 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3553 manager_ = (_system->CreatePM(cache_));
3554 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3561 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3563 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3565 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3567 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3568 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3571 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3576 [CydiaApp retainNetworkActivityIndicator];
3578 bool failed = false;
3579 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3580 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3582 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3585 std::string uri = (*item)->DescURI();
3586 std::string error = (*item)->ErrorText;
3588 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3591 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3592 withObject:[NSArray arrayWithObjects:
3593 [NSString stringWithUTF8String:error.c_str()],
3599 [CydiaApp releaseNetworkActivityIndicator];
3607 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3609 if (_error->PendingError()) {
3614 if (result == pkgPackageManager::Failed) {
3619 if (result != pkgPackageManager::Completed) {
3624 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3626 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3628 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3629 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3632 if (![before isEqualToArray:after])
3637 NSString *title(UCLocalize("UPGRADE"));
3638 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3644 [self updateWithStatus:status_];
3647 - (void) updateWithStatus:(Status &)status {
3648 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3649 NSString *title(UCLocalize("REFRESHING_DATA"));
3652 if (!list.ReadMainList())
3653 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3656 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3657 if ([self popErrorWithTitle:title])
3660 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3661 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */
3662 /* XXX: why the hell is an empty if statement a clang error? */ (void) 0;
3664 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3668 - (void) setDelegate:(id)delegate {
3669 delegate_ = delegate;
3670 status_.setDelegate(delegate);
3671 progress_.setDelegate(delegate);
3674 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3675 SourceMap::const_iterator i(sources_.find(file->ID));
3676 return i == sources_.end() ? nil : i->second;
3682 /* Confirmation Controller {{{ */
3683 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3684 if (!iterator.end())
3685 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3686 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3688 pkgCache::PkgIterator package(dep.TargetPkg());
3691 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3699 /* Web Scripting {{{ */
3700 @interface CydiaObject : NSObject {
3702 _transient id delegate_;
3705 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3708 @implementation CydiaObject
3711 [indirect_ release];
3715 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3716 if ((self = [super init]) != nil) {
3717 indirect_ = [indirect retain];
3721 - (void) setDelegate:(id)delegate {
3722 delegate_ = delegate;
3725 + (NSArray *) _attributeKeys {
3726 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3729 - (NSArray *) attributeKeys {
3730 return [[self class] _attributeKeys];
3733 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3734 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3737 - (NSString *) device {
3738 return [[UIDevice currentDevice] uniqueIdentifier];
3741 #if 0 // XXX: implement!
3742 - (NSString *) mac {
3743 if (![indirect_ promptForSensitive:@"Mac Address"])
3747 - (NSString *) serial {
3748 if (![indirect_ promptForSensitive:@"Serial #"])
3752 - (NSString *) firewire {
3753 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3757 - (NSString *) imei {
3758 if (![indirect_ promptForSensitive:@"IMEI"])
3763 + (NSString *) webScriptNameForSelector:(SEL)selector {
3764 if (selector == @selector(close))
3766 else if (selector == @selector(getInstalledPackages))
3767 return @"getInstalledPackages";
3768 else if (selector == @selector(getPackageById:))
3769 return @"getPackageById";
3770 else if (selector == @selector(installPackages:))
3771 return @"installPackages";
3772 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3773 return @"setButtonImage";
3774 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3775 return @"setButtonTitle";
3776 else if (selector == @selector(setPopupHook:))
3777 return @"setPopupHook";
3778 else if (selector == @selector(setSpecial:))
3779 return @"setSpecial";
3780 else if (selector == @selector(setToken:))
3782 else if (selector == @selector(setViewportWidth:))
3783 return @"setViewportWidth";
3784 else if (selector == @selector(supports:))
3786 else if (selector == @selector(stringWithFormat:arguments:))
3788 else if (selector == @selector(localizedStringForKey:value:table:))
3790 else if (selector == @selector(du:))
3792 else if (selector == @selector(statfs:))
3798 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3799 return [self webScriptNameForSelector:selector] == nil;
3802 - (BOOL) supports:(NSString *)feature {
3803 return [feature isEqualToString:@"window.open"];
3806 - (NSArray *) getInstalledPackages {
3807 NSArray *packages([[Database sharedInstance] packages]);
3808 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
3809 for (Package *package in packages)
3810 if ([package installed] != nil)
3811 [installed addObject:package];
3815 - (Package *) getPackageById:(NSString *)id {
3816 Package *package([[Database sharedInstance] packageWithName:id]);
3821 - (NSArray *) statfs:(NSString *)path {
3824 if (path == nil || statfs([path UTF8String], &stat) == -1)
3827 return [NSArray arrayWithObjects:
3828 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3829 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3830 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3834 - (NSNumber *) du:(NSString *)path {
3835 NSNumber *value(nil);
3838 _assert(pipe(fds) != -1);
3840 pid_t pid(ExecFork());
3842 _assert(dup2(fds[1], 1) != -1);
3843 _assert(close(fds[0]) != -1);
3844 _assert(close(fds[1]) != -1);
3845 /* XXX: this should probably not use du */
3846 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3851 _assert(close(fds[1]) != -1);
3853 if (FILE *du = fdopen(fds[0], "r")) {
3855 while (fgets(line, sizeof(line), du) != NULL) {
3856 size_t length(strlen(line));
3857 while (length != 0 && line[length - 1] == '\n')
3858 line[--length] = '\0';
3859 if (char *tab = strchr(line, '\t')) {
3861 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3866 } else _assert(close(fds[0]));
3870 if (waitpid(pid, &status, 0) == -1)
3873 else _assert(false);
3882 - (void) installPackages:(NSArray *)packages {
3883 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
3886 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3887 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3890 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3891 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3894 - (void) setSpecial:(id)function {
3895 [indirect_ setSpecial:function];
3898 - (void) setToken:(NSString *)token {
3901 Token_ = [token retain];
3903 [Metadata_ setObject:Token_ forKey:@"Token"];
3907 - (void) setPopupHook:(id)function {
3908 [indirect_ setPopupHook:function];
3911 - (void) setViewportWidth:(float)width {
3912 [indirect_ setViewportWidth:width];
3915 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3916 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3917 unsigned count([arguments count]);
3919 for (unsigned i(0); i != count; ++i)
3920 values[i] = [arguments objectAtIndex:i];
3921 return [[[NSString alloc] initWithFormat:format arguments:*(reinterpret_cast<va_list *>(&values))] autorelease];
3924 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3925 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3927 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3929 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3935 /* @ Loading... Indicator {{{ */
3936 @interface CYLoadingIndicator : UIView {
3937 UIActivityIndicatorView *spinner_;
3942 @property (readonly, nonatomic) UILabel *label;
3943 @property (readonly, nonatomic) UIActivityIndicatorView *activityIndicatorView;
3947 @implementation CYLoadingIndicator
3949 - (id)initWithFrame:(CGRect)frame {
3950 if ((self = [super initWithFrame:frame])) {
3951 container_ = [[[UIView alloc] init] autorelease];
3952 [container_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
3954 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
3955 [spinner_ startAnimating];
3956 [container_ addSubview:spinner_];
3958 label_ = [[[UILabel alloc] init] autorelease];
3959 [label_ setFont:[UIFont boldSystemFontOfSize:15.0f]];
3960 [label_ setBackgroundColor:[UIColor clearColor]];
3961 [label_ setTextColor:[UIColor blackColor]];
3962 [label_ setShadowColor:[UIColor whiteColor]];
3963 [label_ setShadowOffset:CGSizeMake(0, 1)];
3964 [label_ setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
3965 [container_ addSubview:label_];
3967 CGSize viewsize = frame.size;
3968 CGSize spinnersize = [spinner_ bounds].size;
3969 CGSize textsize = [[label_ text] sizeWithFont:[label_ font]];
3970 float bothwidth = spinnersize.width + textsize.width + 5.0f;
3972 CGRect containrect = {
3973 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
3974 CGSizeMake(bothwidth, spinnersize.height)
3977 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
3985 [container_ setFrame:containrect];
3986 [spinner_ setFrame:spinrect];
3987 [label_ setFrame:textrect];
3988 [self addSubview:container_];
3994 - (UILabel *)label { return label_; }
3995 - (UIActivityIndicatorView *)activityIndicatorView { return spinner_; }
3999 @interface CYEmulatedLoadingController : UIViewController {
4000 CYLoadingIndicator *indicator_;
4002 UINavigationBar *navbar_;
4006 @implementation CYEmulatedLoadingController
4008 - (CYEmulatedLoadingController *) init {
4009 if ((self = [super init])) {
4010 [[self view] setBackgroundColor:[UIColor pinStripeColor]];
4012 indicator_ = [[CYLoadingIndicator alloc] initWithFrame:[[self view] bounds]];
4013 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4014 [[self view] addSubview:indicator_];
4015 [indicator_ release];
4017 tabbar_ = [[UITabBar alloc] initWithFrame:CGRectMake(0, 0, 0, 49.0f)];
4018 [tabbar_ setFrame:CGRectMake(0.0f, [[self view] bounds].size.height - [tabbar_ bounds].size.height, [[self view] bounds].size.width, [tabbar_ bounds].size.height)];
4019 [tabbar_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth];
4020 [[self view] addSubview:tabbar_];
4023 navbar_ = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 0, 44.0f)];
4024 [navbar_ setFrame:CGRectMake(0.0f, 0.0f, [[self view] bounds].size.width, [navbar_ bounds].size.height)];
4025 [navbar_ setAutoresizingMask:UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth];
4026 [[self view] addSubview:navbar_];
4031 - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
4032 return (IsWildcat_ || orientation == UIInterfaceOrientationPortrait);
4037 /* Cydia Browser Controller {{{ */
4038 @interface CYBrowserController : BrowserController {
4039 CydiaObject *cydia_;
4044 @implementation CYBrowserController
4051 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
4054 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4055 [super webView:view didClearWindowObject:window forFrame:frame];
4057 WebDataSource *source([frame dataSource]);
4058 NSURLResponse *response([source response]);
4059 NSURL *url([response URL]);
4060 NSString *scheme([url scheme]);
4062 NSHTTPURLResponse *http;
4063 if (scheme != nil && ([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"]))
4064 http = (NSHTTPURLResponse *) response;
4068 NSDictionary *headers([http allHeaderFields]);
4069 NSString *host([url host]);
4070 [self setHeaders:headers forHost:host];
4073 [host isEqualToString:@"cydia.saurik.com"] ||
4074 [host hasSuffix:@".cydia.saurik.com"] ||
4075 [scheme isEqualToString:@"file"]
4077 [window setValue:cydia_ forKey:@"cydia"];
4080 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
4081 if (System_ != NULL)
4082 [request setValue:System_ forHTTPHeaderField:@"X-System"];
4083 if (Machine_ != NULL)
4084 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4086 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4088 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
4091 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4092 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4093 [self _setMoreHeaders:copy];
4097 - (void) setDelegate:(id)delegate {
4098 [super setDelegate:delegate];
4099 [cydia_ setDelegate:delegate];
4103 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
4104 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
4106 WebView *webview([[webview_ _documentView] webView]);
4108 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
4110 NSString *application = package == nil ? @"Cydia" : [NSString
4111 stringWithFormat:@"Cydia/%@",
4116 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4118 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4119 if (Product_ != nil)
4120 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4122 [webview setApplicationNameForUserAgent:application];
4129 /* Confirmation {{{ */
4130 @protocol ConfirmationControllerDelegate
4131 - (void) cancelAndClear:(bool)clear;
4132 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4136 @interface ConfirmationController : CYBrowserController {
4137 _transient Database *database_;
4138 UIAlertView *essential_;
4145 - (id) initWithDatabase:(Database *)database;
4149 @implementation ConfirmationController
4156 if (essential_ != nil)
4157 [essential_ release];
4161 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4162 NSString *context([alert context]);
4164 if ([context isEqualToString:@"remove"]) {
4165 if (button == [alert cancelButtonIndex]) {
4166 [self dismissModalViewControllerAnimated:YES];
4167 } else if (button == [alert firstOtherButtonIndex]) {
4170 [delegate_ confirmWithNavigationController:[self navigationController]];
4173 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4174 } else if ([context isEqualToString:@"unable"]) {
4175 [self dismissModalViewControllerAnimated:YES];
4176 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4178 [super alertView:alert clickedButtonAtIndex:button];
4182 - (void) _doContinue {
4183 [self dismissModalViewControllerAnimated:YES];
4184 [delegate_ cancelAndClear:NO];
4187 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4188 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4192 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4193 [super webView:view didClearWindowObject:window forFrame:frame];
4194 [window setValue:changes_ forKey:@"changes"];
4195 [window setValue:issues_ forKey:@"issues"];
4196 [window setValue:sizes_ forKey:@"sizes"];
4197 [window setValue:self forKey:@"queue"];
4200 - (id) initWithDatabase:(Database *)database {
4201 if ((self = [super init]) != nil) {
4202 database_ = database;
4204 [[self navigationItem] setTitle:UCLocalize("CONFIRM")];
4206 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
4207 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
4208 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
4209 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
4210 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
4214 pkgDepCache::Policy *policy([database_ policy]);
4216 pkgCacheFile &cache([database_ cache]);
4217 NSArray *packages = [database_ packages];
4218 for (Package *package in packages) {
4219 pkgCache::PkgIterator iterator = [package iterator];
4220 pkgDepCache::StateCache &state(cache[iterator]);
4222 NSString *name([package name]);
4224 if (state.NewInstall())
4225 [installing addObject:name];
4226 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4227 [reinstalling addObject:name];
4228 else if (state.Upgrade())
4229 [upgrading addObject:name];
4230 else if (state.Downgrade())
4231 [downgrading addObject:name];
4232 else if (state.Delete()) {
4233 if ([package essential])
4235 [removing addObject:name];
4238 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4239 substrate_ |= DepSubstrate(iterator.CurrentVer());
4244 else if (Advanced_) {
4245 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4247 essential_ = [[UIAlertView alloc]
4248 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4249 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4251 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4252 otherButtonTitles:[NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")], nil
4255 [essential_ setContext:@"remove"];
4257 essential_ = [[UIAlertView alloc]
4258 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4259 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4261 cancelButtonTitle:UCLocalize("OKAY")
4262 otherButtonTitles:nil
4265 [essential_ setContext:@"unable"];
4268 changes_ = [[NSArray alloc] initWithObjects:
4276 issues_ = [database_ issues];
4278 issues_ = [issues_ retain];
4280 sizes_ = [[NSArray alloc] initWithObjects:
4281 SizeString([database_ fetcher].FetchNeeded()),
4282 SizeString([database_ fetcher].PartialPresent()),
4285 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
4287 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
4288 initWithTitle:UCLocalize("CANCEL")
4289 // OLD: [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")]
4290 style:UIBarButtonItemStylePlain
4292 action:@selector(cancelButtonClicked)
4297 - (void) applyRightButton {
4298 #if !AlwaysReload && !IgnoreInstall
4299 if (issues_ == nil && ![self isLoading])
4300 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4301 initWithTitle:UCLocalize("CONFIRM")
4302 style:UIBarButtonItemStylePlain
4304 action:@selector(confirmButtonClicked)
4307 [super applyRightButton];
4309 [[self navigationItem] setRightBarButtonItem:nil];
4313 - (void) cancelButtonClicked {
4314 [self dismissModalViewControllerAnimated:YES];
4315 [delegate_ cancelAndClear:YES];
4319 - (void) confirmButtonClicked {
4323 if (essential_ != nil)
4328 [delegate_ confirmWithNavigationController:[self navigationController]];
4336 /* Progress Data {{{ */
4337 @interface ProgressData : NSObject {
4339 // XXX: should these really both be _transient?
4340 _transient id target_;
4341 _transient id object_;
4344 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4351 @implementation ProgressData
4353 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4354 if ((self = [super init]) != nil) {
4355 selector_ = selector;
4375 /* Progress Controller {{{ */
4376 @interface ProgressController : CYViewController <
4377 ConfigurationDelegate,
4380 _transient Database *database_;
4381 UIProgressBar *progress_;
4382 UITextView *output_;
4383 UITextLabel *status_;
4384 UIPushButton *close_;
4386 SHA1SumValue springlist_;
4387 SHA1SumValue notifyconf_;
4391 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4393 - (void) _retachThread;
4394 - (void) _detachNewThreadData:(ProgressData *)data;
4395 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4401 @protocol ProgressControllerDelegate
4402 - (void) progressControllerIsComplete:(ProgressController *)sender;
4405 @implementation ProgressController
4408 [database_ setDelegate:nil];
4409 [progress_ release];
4418 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4419 if ((self = [super init]) != nil) {
4420 database_ = database;
4421 [database_ setDelegate:self];
4422 delegate_ = delegate;
4424 [[self view] setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
4426 progress_ = [[UIProgressBar alloc] init];
4427 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4428 [progress_ setStyle:0];
4430 status_ = [[UITextLabel alloc] init];
4431 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4432 [status_ setColor:[UIColor whiteColor]];
4433 [status_ setBackgroundColor:[UIColor clearColor]];
4434 [status_ setCentersHorizontally:YES];
4435 //[status_ setFont:font];
4437 output_ = [[UITextView alloc] init];
4439 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4440 //[output_ setTextFont:@"Courier New"];
4441 [output_ setFont:[[output_ font] fontWithSize:12]];
4442 [output_ setTextColor:[UIColor whiteColor]];
4443 [output_ setBackgroundColor:[UIColor clearColor]];
4444 [output_ setMarginTop:0];
4445 [output_ setAllowsRubberBanding:YES];
4446 [output_ setEditable:NO];
4447 [[self view] addSubview:output_];
4449 close_ = [[UIPushButton alloc] init];
4450 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4451 [close_ setAutosizesToFit:NO];
4452 [close_ setDrawsShadow:YES];
4453 [close_ setStretchBackground:YES];
4454 [close_ setEnabled:YES];
4455 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
4456 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4457 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4458 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4462 - (void) positionViews {
4463 CGRect bounds = [[self view] bounds];
4464 CGSize prgsize = [UIProgressBar defaultSize];
4467 (bounds.size.width - prgsize.width) / 2,
4468 bounds.size.height - prgsize.height - 20
4471 float closewidth = std::min(bounds.size.width - 20, 300.0f);
4473 [progress_ setFrame:prgrect];
4474 [status_ setFrame:CGRectMake(
4476 bounds.size.height - prgsize.height - 50,
4477 bounds.size.width - 20,
4480 [output_ setFrame:CGRectMake(
4483 bounds.size.width - 20,
4484 bounds.size.height - 62
4486 [close_ setFrame:CGRectMake(
4487 (bounds.size.width - closewidth) / 2,
4488 bounds.size.height - prgsize.height - 50,
4494 - (void) viewWillAppear:(BOOL)animated {
4495 [super viewDidAppear:animated];
4496 [[self navigationItem] setHidesBackButton:YES];
4497 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4499 [self positionViews];
4502 - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4503 [self positionViews];
4506 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4507 NSString *context([alert context]);
4509 if ([context isEqualToString:@"conffile"]) {
4510 FILE *input = [database_ input];
4511 if (button == [alert cancelButtonIndex])
4512 fprintf(input, "N\n");
4513 else if (button == [alert firstOtherButtonIndex])
4514 fprintf(input, "Y\n");
4519 - (void) closeButtonPushed {
4522 UpdateExternalStatus(0);
4526 [self dismissModalViewControllerAnimated:YES];
4530 [delegate_ terminateWithSuccess];
4531 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4532 [delegate_ suspendWithAnimation:YES];
4534 [delegate_ suspend];*/
4546 system("/usr/bin/sbreload");
4552 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
4553 SBReboot(SBSSpringBoardServerPort());
4555 reboot2(RB_AUTOBOOT);
4560 - (void) _retachThread {
4561 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
4563 [[self view] addSubview:close_];
4564 [progress_ removeFromSuperview];
4565 [status_ removeFromSuperview];
4567 [database_ popErrorWithTitle:title_];
4568 [delegate_ progressControllerIsComplete:self];
4572 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4575 MMap mmap(file, MMap::ReadOnly);
4577 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4578 if (!(notifyconf_ == sha1.Result()))
4585 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4588 MMap mmap(file, MMap::ReadOnly);
4590 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4591 if (!(springlist_ == sha1.Result()))
4597 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
4598 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4599 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4600 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4601 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4605 system("su -c /usr/bin/uicache mobile");
4608 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
4610 [delegate_ setStatusBarShowsProgress:NO];
4613 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4614 [[data target] performSelector:[data selector] withObject:[data object]];
4615 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4618 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4619 UpdateExternalStatus(1);
4626 title_ = [title retain];
4628 [[self navigationItem] setTitle:title_];
4630 [status_ setText:nil];
4631 [output_ setText:@""];
4632 [progress_ setProgress:0];
4634 [close_ removeFromSuperview];
4635 [[self view] addSubview:progress_];
4636 [[self view] addSubview:status_];
4638 [delegate_ setStatusBarShowsProgress:YES];
4643 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4646 MMap mmap(file, MMap::ReadOnly);
4648 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4649 notifyconf_ = sha1.Result();
4655 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4658 MMap mmap(file, MMap::ReadOnly);
4660 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4661 springlist_ = sha1.Result();
4666 detachNewThreadSelector:@selector(_detachNewThreadData:)
4668 withObject:[[[ProgressData alloc]
4669 initWithSelector:selector
4676 - (void) repairWithSelector:(SEL)selector {
4678 detachNewThreadSelector:selector
4681 title:UCLocalize("REPAIRING")
4685 - (void) setConfigurationData:(NSString *)data {
4687 performSelectorOnMainThread:@selector(_setConfigurationData:)
4693 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4694 CYActionSheet *sheet([[[CYActionSheet alloc]
4696 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4697 defaultButtonIndex:0
4700 [sheet setMessage:error];
4701 [sheet yieldToPopupAlertAnimated:YES];
4705 - (void) setProgressTitle:(NSString *)title {
4707 performSelectorOnMainThread:@selector(_setProgressTitle:)
4713 - (void) setProgressPercent:(float)percent {
4715 performSelectorOnMainThread:@selector(_setProgressPercent:)
4716 withObject:[NSNumber numberWithFloat:percent]
4721 - (void) startProgress {
4724 - (void) addProgressOutput:(NSString *)output {
4726 performSelectorOnMainThread:@selector(_addProgressOutput:)
4732 - (bool) isCancelling:(size_t)received {
4736 - (void) _setConfigurationData:(NSString *)data {
4737 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4739 if (!conffile_r(data)) {
4740 lprintf("E:invalid conffile\n");
4744 NSString *ofile = conffile_r[1];
4745 //NSString *nfile = conffile_r[2];
4747 UIAlertView *alert = [[[UIAlertView alloc]
4748 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4749 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
4751 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
4752 otherButtonTitles:UCLocalize("ACCEPT_NEW_COPY"),
4753 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4757 [alert setContext:@"conffile"];
4761 - (void) _setProgressTitle:(NSString *)title {
4762 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4763 for (size_t i(0), e([words count]); i != e; ++i) {
4764 NSString *word([words objectAtIndex:i]);
4765 if (Package *package = [database_ packageWithName:word])
4766 [words replaceObjectAtIndex:i withObject:[package name]];
4769 [status_ setText:[words componentsJoinedByString:@" "]];
4772 - (void) _setProgressPercent:(NSNumber *)percent {
4773 [progress_ setProgress:[percent floatValue]];
4776 - (void) _addProgressOutput:(NSString *)output {
4777 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4778 CGSize size = [output_ contentSize];
4779 CGPoint offset = [output_ contentOffset];
4780 if (size.height - offset.y < [output_ frame].size.height + 20.f) {
4781 CGRect rect = {{0, size.height-1}, {size.width, 1}};
4782 [output_ scrollRectToVisible:rect animated:YES];
4786 - (BOOL) isRunning {
4793 /* Cell Content View {{{ */
4794 @protocol ContentDelegate
4795 - (void) drawContentRect:(CGRect)rect;
4798 @interface ContentView : UIView {
4799 _transient id<ContentDelegate> delegate_;
4804 @implementation ContentView
4806 - (id) initWithFrame:(CGRect)frame {
4807 if ((self = [super initWithFrame:frame]) != nil) {
4808 [self setNeedsDisplayOnBoundsChange:YES];
4812 - (void) setDelegate:(id<ContentDelegate>)delegate {
4813 delegate_ = delegate;
4816 - (void) drawRect:(CGRect)rect {
4817 [super drawRect:rect];
4818 [delegate_ drawContentRect:rect];
4823 /* Cydia TableView Cell {{{ */
4824 @interface CYTableViewCell : UITableViewCell {
4825 ContentView *content_;
4831 @implementation CYTableViewCell
4838 - (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
4839 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
4841 if (view == content_) {
4842 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
4843 highlighted_ = highlighted;
4846 [super _updateHighlightColorsForView:view highlighted:highlighted];
4849 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
4850 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
4851 highlighted_ = selected;
4853 [super setSelected:selected animated:animated];
4854 [content_ setNeedsDisplay];
4859 /* Package Cell {{{ */
4860 @interface PackageCell : CYTableViewCell <
4865 NSString *description_;
4873 - (PackageCell *) init;
4874 - (void) setPackage:(Package *)package;
4876 + (int) heightForPackage:(Package *)package;
4877 - (void) drawContentRect:(CGRect)rect;
4881 @implementation PackageCell
4883 - (void) clearPackage {
4894 if (description_ != nil) {
4895 [description_ release];
4899 if (source_ != nil) {
4904 if (badge_ != nil) {
4909 if (placard_ != nil) {
4919 [self clearPackage];
4923 - (PackageCell *) init {
4924 CGRect frame(CGRectMake(0, 0, 320, 74));
4925 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4926 UIView *content([self contentView]);
4927 CGRect bounds([content bounds]);
4929 content_ = [[ContentView alloc] initWithFrame:bounds];
4930 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4931 [content addSubview:content_];
4933 [content_ setDelegate:self];
4934 [content_ setOpaque:YES];
4938 - (void) _setBackgroundColor {
4940 if (NSString *mode = [package_ mode]) {
4941 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4942 color = remove ? RemovingColor_ : InstallingColor_;
4944 color = [UIColor whiteColor];
4946 [content_ setBackgroundColor:color];
4947 [self setNeedsDisplay];
4950 - (void) setPackage:(Package *)package {
4951 [self clearPackage];
4954 Source *source = [package source];
4956 icon_ = [[package icon] retain];
4957 name_ = [[package name] retain];
4960 description_ = [package longDescription];
4961 if (description_ == nil)
4962 description_ = [package shortDescription];
4963 if (description_ != nil)
4964 description_ = [description_ retain];
4966 commercial_ = [package isCommercial];
4968 package_ = [package retain];
4970 NSString *label = nil;
4971 bool trusted = false;
4973 if (source != nil) {
4974 label = [source label];
4975 trusted = [source trusted];
4976 } else if ([[package id] isEqualToString:@"firmware"])
4977 label = UCLocalize("APPLE");
4979 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
4981 NSString *from(label);
4983 NSString *section = [package simpleSection];
4984 if (section != nil && ![section isEqualToString:label]) {
4985 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4986 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
4989 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
4990 source_ = [from retain];
4992 if (NSString *purpose = [package primaryPurpose])
4993 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4994 badge_ = [badge_ retain];
4996 if ([package installed] != nil)
4997 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/installed.png", App_]]) != nil)
4998 placard_ = [placard_ retain];
5000 [self _setBackgroundColor];
5001 [content_ setNeedsDisplay];
5004 - (void) drawContentRect:(CGRect)rect {
5005 bool highlighted(highlighted_);
5006 float width([self bounds].size.width);
5009 CGContextRef context(UIGraphicsGetCurrentContext());
5010 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
5011 CGContextFillRect(context, rect);
5016 rect.size = [icon_ size];
5018 rect.size.width /= 2;
5019 rect.size.height /= 2;
5021 rect.origin.x = 25 - rect.size.width / 2;
5022 rect.origin.y = 25 - rect.size.height / 2;
5024 [icon_ drawInRect:rect];
5027 if (badge_ != nil) {
5029 rect.size = [badge_ size];
5031 rect.size.width /= 2;
5032 rect.size.height /= 2;
5034 rect.origin.x = 36 - rect.size.width / 2;
5035 rect.origin.y = 36 - rect.size.height / 2;
5037 [badge_ drawInRect:rect];
5044 UISetColor(commercial_ ? Purple_ : Black_);
5045 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5046 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5049 UISetColor(commercial_ ? Purplish_ : Gray_);
5050 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5052 if (placard_ != nil)
5053 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5056 + (int) heightForPackage:(Package *)package {
5062 /* Section Cell {{{ */
5063 @interface SectionCell : CYTableViewCell <
5075 - (void) setSection:(Section *)section editing:(BOOL)editing;
5079 @implementation SectionCell
5081 - (void) clearSection {
5082 if (basic_ != nil) {
5087 if (section_ != nil) {
5097 if (count_ != nil) {
5104 [self clearSection];
5110 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5111 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5112 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
5113 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
5114 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5116 UIView *content([self contentView]);
5117 CGRect bounds([content bounds]);
5119 content_ = [[ContentView alloc] initWithFrame:bounds];
5120 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5121 [content addSubview:content_];
5122 [content_ setBackgroundColor:[UIColor whiteColor]];
5124 [content_ setDelegate:self];
5128 - (void) onSwitch:(id)sender {
5129 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5130 if (metadata == nil) {
5131 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5132 [Sections_ setObject:metadata forKey:basic_];
5135 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5139 - (void) setSection:(Section *)section editing:(BOOL)editing {
5140 if (editing != editing_) {
5142 [switch_ removeFromSuperview];
5144 [self addSubview:switch_];
5148 [self clearSection];
5150 if (section == nil) {
5151 name_ = [UCLocalize("ALL_PACKAGES") retain];
5154 basic_ = [section name];
5156 basic_ = [basic_ retain];
5158 section_ = [section localized];
5159 if (section_ != nil)
5160 section_ = [section_ retain];
5162 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
5163 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
5166 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5169 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5170 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5172 [content_ setNeedsDisplay];
5175 - (void) setFrame:(CGRect)frame {
5176 [super setFrame:frame];
5178 CGRect rect([switch_ frame]);
5179 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5182 - (void) drawContentRect:(CGRect)rect {
5183 bool highlighted(highlighted_);
5185 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5190 float width(rect.size.width);
5196 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5198 CGSize size = [count_ sizeWithFont:Font14_];
5202 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5208 /* File Table {{{ */
5209 @interface FileTable : CYViewController <
5210 UITableViewDataSource,
5213 _transient Database *database_;
5216 NSMutableArray *files_;
5220 - (id) initWithDatabase:(Database *)database;
5221 - (void) setPackage:(Package *)package;
5225 @implementation FileTable
5228 if (package_ != nil)
5237 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5238 return files_ == nil ? 0 : [files_ count];
5241 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5245 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5246 static NSString *reuseIdentifier = @"Cell";
5248 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5250 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5251 [cell setFont:[UIFont systemFontOfSize:16]];
5253 [cell setText:[files_ objectAtIndex:indexPath.row]];
5254 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5259 - (id) initWithDatabase:(Database *)database {
5260 if ((self = [super init]) != nil) {
5261 database_ = database;
5263 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5265 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5267 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5268 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5269 [list_ setRowHeight:24.0f];
5270 [[self view] addSubview:list_];
5272 [list_ setDataSource:self];
5273 [list_ setDelegate:self];
5277 - (void) setPackage:(Package *)package {
5278 if (package_ != nil) {
5279 [package_ autorelease];
5288 [files_ removeAllObjects];
5290 if (package != nil) {
5291 package_ = [package retain];
5292 name_ = [[package id] retain];
5294 if (NSArray *files = [package files])
5295 [files_ addObjectsFromArray:files];
5297 if ([files_ count] != 0) {
5298 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5299 [files_ removeObjectAtIndex:0];
5300 [files_ sortUsingSelector:@selector(compareByPath:)];
5302 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5303 [stack addObject:@"/"];
5305 for (int i(0), e([files_ count]); i != e; ++i) {
5306 NSString *file = [files_ objectAtIndex:i];
5307 while (![file hasPrefix:[stack lastObject]])
5308 [stack removeLastObject];
5309 NSString *directory = [stack lastObject];
5310 [stack addObject:[file stringByAppendingString:@"/"]];
5311 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5312 ([stack count] - 2) * 3, "",
5313 [file substringFromIndex:[directory length]]
5322 - (void) reloadData {
5323 [self setPackage:[database_ packageWithName:name_]];
5328 /* Package Controller {{{ */
5329 @interface CYPackageController : CYBrowserController <
5330 UIActionSheetDelegate
5332 _transient Database *database_;
5336 NSMutableArray *buttons_;
5337 UIBarButtonItem *button_;
5340 - (id) initWithDatabase:(Database *)database;
5341 - (void) setPackage:(Package *)package;
5345 @implementation CYPackageController
5348 if (package_ != nil)
5362 if ([self retainCount] == 1)
5363 [delegate_ setPackageController:self];
5367 /* XXX: this is not safe at all... localization of /fail/ */
5368 - (void) _clickButtonWithName:(NSString *)name {
5369 if ([name isEqualToString:UCLocalize("CLEAR")])
5370 [delegate_ clearPackage:package_];
5371 else if ([name isEqualToString:UCLocalize("INSTALL")])
5372 [delegate_ installPackage:package_];
5373 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5374 [delegate_ installPackage:package_];
5375 else if ([name isEqualToString:UCLocalize("REMOVE")])
5376 [delegate_ removePackage:package_];
5377 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5378 [delegate_ installPackage:package_];
5379 else _assert(false);
5382 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5383 NSString *context([sheet context]);
5385 if ([context isEqualToString:@"modify"]) {
5386 if (button != [sheet cancelButtonIndex]) {
5387 NSString *buttonName = [buttons_ objectAtIndex:button];
5388 [self _clickButtonWithName:buttonName];
5391 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5395 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5396 [super webView:view didClearWindowObject:window forFrame:frame];
5397 [window setValue:package_ forKey:@"package"];
5400 - (bool) _allowJavaScriptPanel {
5405 - (void) _customButtonClicked {
5406 int count([buttons_ count]);
5411 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5413 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5414 [buttons addObjectsFromArray:buttons_];
5416 UIActionSheet *sheet = [[[UIActionSheet alloc]
5419 cancelButtonTitle:nil
5420 destructiveButtonTitle:nil
5421 otherButtonTitles:nil
5424 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5426 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5427 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5429 [sheet setContext:@"modify"];
5431 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5435 // We don't want to allow non-commercial packages to do custom things to the install button,
5436 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5437 - (void) customButtonClicked {
5439 [super customButtonClicked];
5441 [self _customButtonClicked];
5444 - (void) reloadButtonClicked {
5445 // Don't reload a commerical package by tapping the loading button,
5446 // but if it's not an Install button, we should forward it on.
5447 if (![package_ uninstalled])
5448 [self _customButtonClicked];
5451 - (void) applyLoadingTitle {
5452 // Don't show "Loading" as the title. Ever.
5455 - (UIBarButtonItem *) rightButton {
5460 - (id) initWithDatabase:(Database *)database {
5461 if ((self = [super init]) != nil) {
5462 database_ = database;
5463 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5464 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
5468 - (void) setPackage:(Package *)package {
5469 if (package_ != nil) {
5470 [package_ autorelease];
5479 [buttons_ removeAllObjects];
5481 if (package != nil) {
5484 package_ = [package retain];
5485 name_ = [[package id] retain];
5486 commercial_ = [package isCommercial];
5488 if ([package_ mode] != nil)
5489 [buttons_ addObject:UCLocalize("CLEAR")];
5490 if ([package_ source] == nil);
5491 else if ([package_ upgradableAndEssential:NO])
5492 [buttons_ addObject:UCLocalize("UPGRADE")];
5493 else if ([package_ uninstalled])
5494 [buttons_ addObject:UCLocalize("INSTALL")];
5496 [buttons_ addObject:UCLocalize("REINSTALL")];
5497 if (![package_ uninstalled])
5498 [buttons_ addObject:UCLocalize("REMOVE")];
5505 switch ([buttons_ count]) {
5506 case 0: title = nil; break;
5507 case 1: title = [buttons_ objectAtIndex:0]; break;
5508 default: title = UCLocalize("MODIFY"); break;
5511 button_ = [[UIBarButtonItem alloc]
5513 style:UIBarButtonItemStylePlain
5515 action:@selector(customButtonClicked)
5521 - (bool) isLoading {
5522 return commercial_ ? [super isLoading] : false;
5525 - (void) reloadData {
5526 [self setPackage:[database_ packageWithName:name_]];
5531 /* Package Table {{{ */
5532 @interface PackageTable : UIView <
5533 UITableViewDataSource,
5536 _transient Database *database_;
5538 NSMutableArray *packages_;
5539 NSMutableArray *sections_;
5541 NSMutableArray *index_;
5542 NSMutableDictionary *indices_;
5543 // XXX: this target_ seems to be delegate_. :(
5544 _transient id target_;
5546 // XXX: why do we even have this delegate_?
5547 _transient id delegate_;
5550 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action;
5552 - (void) setDelegate:(id)delegate;
5554 - (void) reloadData;
5555 - (void) resetCursor;
5557 - (UITableView *) list;
5559 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5561 - (void) deselectWithAnimation:(BOOL)animated;
5565 @implementation PackageTable
5568 [packages_ release];
5569 [sections_ release];
5577 + (BOOL) hasIndexedCollation {
5578 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
5581 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5582 NSInteger count([sections_ count]);
5583 return count == 0 ? 1 : count;
5586 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5587 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
5589 return [[sections_ objectAtIndex:section] name];
5592 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5593 if ([sections_ count] == 0)
5595 return [[sections_ objectAtIndex:section] count];
5598 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5599 @synchronized (database_) {
5600 if ([database_ era] != era_)
5603 Section *section([sections_ objectAtIndex:[path section]]);
5604 NSInteger row([path row]);
5605 Package *package([packages_ objectAtIndex:([section row] + row)]);
5606 return [[package retain] autorelease];
5609 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5610 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5612 cell = [[[PackageCell alloc] init] autorelease];
5613 [cell setPackage:[self packageAtIndexPath:path]];
5617 - (void) deselectWithAnimation:(BOOL)animated {
5618 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5621 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
5622 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
5625 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5626 Package *package([self packageAtIndexPath:path]);
5627 package = [database_ packageWithName:[package id]];
5628 [target_ performSelector:action_ withObject:package];
5632 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5633 // XXX: is 20 the most optimal number here?
5634 return [packages_ count] > 20 ? index_ : nil;
5637 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5638 if ([[self class] hasIndexedCollation]) {
5639 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
5645 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action {
5646 if ((self = [super initWithFrame:frame]) != nil) {
5647 database_ = database;
5652 index_ = [[self class] hasIndexedCollation]
5653 ? [[[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles] retain]
5654 : [[NSMutableArray alloc] initWithCapacity:32];
5655 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5657 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5658 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5660 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
5661 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5662 [list_ setRowHeight:73.0f];
5663 [self addSubview:list_];
5665 [list_ setDataSource:self];
5666 [list_ setDelegate:self];
5670 - (void) setDelegate:(id)delegate {
5671 delegate_ = delegate;
5674 - (bool) hasPackage:(Package *)package {
5678 - (void) reloadData {
5679 era_ = [database_ era];
5680 NSArray *packages = [database_ packages];
5682 [packages_ removeAllObjects];
5683 [sections_ removeAllObjects];
5685 _profile(PackageTable$reloadData$Filter)
5686 for (Package *package in packages)
5687 if ([self hasPackage:package])
5688 [packages_ addObject:package];
5691 [indices_ removeAllObjects];
5693 Section *section = nil;
5695 if ([[self class] hasIndexedCollation]) {
5696 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
5697 NSArray *titles = [collation sectionIndexTitles];
5700 _profile(PackageTable$reloadData$Section)
5701 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5705 _profile(PackageTable$reloadData$Section$Package)
5706 package = [packages_ objectAtIndex:offset];
5707 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
5710 while (secidx < index) {
5713 _profile(PackageTable$reloadData$Section$Allocate)
5714 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
5717 _profile(PackageTable$reloadData$Section$Add)
5718 [sections_ addObject:section];
5722 [section addToCount];
5726 [index_ removeAllObjects];
5728 _profile(PackageTable$reloadData$Section)
5729 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5733 _profile(PackageTable$reloadData$Section$Package)
5734 package = [packages_ objectAtIndex:offset];
5735 index = [package index];
5738 if (section == nil || [section index] != index) {
5739 _profile(PackageTable$reloadData$Section$Allocate)
5740 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5743 [index_ addObject:[section name]];
5744 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5746 _profile(PackageTable$reloadData$Section$Add)
5747 [sections_ addObject:section];
5751 [section addToCount];
5756 _profile(PackageTable$reloadData$List)
5761 - (void) resetCursor {
5762 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5765 - (UITableView *) list {
5769 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5770 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
5775 /* Filtered Package Table {{{ */
5776 @interface FilteredPackageTable : PackageTable {
5782 - (void) setObject:(id)object;
5783 - (void) setObject:(id)object forFilter:(SEL)filter;
5785 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object;
5789 @implementation FilteredPackageTable
5797 - (void) setFilter:(SEL)filter {
5800 /* XXX: this is an unsafe optimization of doomy hell */
5801 Method method(class_getInstanceMethod([Package class], filter));
5802 _assert(method != NULL);
5803 imp_ = method_getImplementation(method);
5804 _assert(imp_ != NULL);
5807 - (void) setObject:(id)object {
5813 object_ = [object retain];
5816 - (void) setObject:(id)object forFilter:(SEL)filter {
5817 [self setFilter:filter];
5818 [self setObject:object];
5821 - (bool) hasPackage:(Package *)package {
5822 _profile(FilteredPackageTable$hasPackage)
5823 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5827 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object {
5828 if ((self = [super initWithFrame:frame database:database target:target action:action]) != nil) {
5829 [self setFilter:filter];
5830 object_ = [object retain];
5838 /* Filtered Package Controller {{{ */
5839 @interface FilteredPackageController : CYViewController {
5840 _transient Database *database_;
5841 FilteredPackageTable *packages_;
5845 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5849 @implementation FilteredPackageController
5852 [packages_ release];
5858 - (void) viewDidAppear:(BOOL)animated {
5859 [super viewDidAppear:animated];
5860 [packages_ deselectWithAnimation:animated];
5863 - (void) didSelectPackage:(Package *)package {
5864 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_] autorelease]);
5865 [view setPackage:package];
5866 [view setDelegate:delegate_];
5867 [[self navigationController] pushViewController:view animated:YES];
5870 - (NSString *) title { return title_; }
5872 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5873 if ((self = [super init]) != nil) {
5874 database_ = database;
5875 title_ = [title copy];
5876 [[self navigationItem] setTitle:title_];
5878 packages_ = [[FilteredPackageTable alloc]
5879 initWithFrame:[[self view] bounds]
5882 action:@selector(didSelectPackage:)
5887 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5888 [[self view] addSubview:packages_];
5892 - (void) reloadData {
5893 [packages_ reloadData];
5896 - (void) setDelegate:(id)delegate {
5897 [super setDelegate:delegate];
5898 [packages_ setDelegate:delegate];
5905 /* Source Cell {{{ */
5906 @interface SourceCell : CYTableViewCell <
5911 NSString *description_;
5915 - (void) setSource:(Source *)source;
5919 @implementation SourceCell
5921 - (void) clearSource {
5924 [description_ release];
5933 - (void) setSource:(Source *)source {
5937 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5939 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5940 icon_ = [icon_ retain];
5942 origin_ = [[source name] retain];
5943 label_ = [[source uri] retain];
5944 description_ = [[source description] retain];
5946 [content_ setNeedsDisplay];
5954 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5955 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5956 UIView *content([self contentView]);
5957 CGRect bounds([content bounds]);
5959 content_ = [[ContentView alloc] initWithFrame:bounds];
5960 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5961 [content_ setBackgroundColor:[UIColor whiteColor]];
5962 [content addSubview:content_];
5964 [content_ setDelegate:self];
5965 [content_ setOpaque:YES];
5969 - (void) drawContentRect:(CGRect)rect {
5970 bool highlighted(highlighted_);
5971 float width(rect.size.width);
5974 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5981 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5985 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5989 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 40) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5994 /* Source Table {{{ */
5995 @interface CYSourcesController : CYViewController <
5996 UITableViewDataSource,
5999 _transient Database *database_;
6001 NSMutableArray *sources_;
6005 UIProgressHUD *hud_;
6008 //NSURLConnection *installer_;
6009 NSURLConnection *trivial_;
6010 NSURLConnection *trivial_bz2_;
6011 NSURLConnection *trivial_gz_;
6012 //NSURLConnection *automatic_;
6017 - (id) initWithDatabase:(Database *)database;
6019 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
6023 @implementation CYSourcesController
6025 - (void) _releaseConnection:(NSURLConnection *)connection {
6026 if (connection != nil) {
6027 [connection cancel];
6028 //[connection setDelegate:nil];
6029 [connection release];
6041 //[self _releaseConnection:installer_];
6042 [self _releaseConnection:trivial_];
6043 [self _releaseConnection:trivial_gz_];
6044 [self _releaseConnection:trivial_bz2_];
6045 //[self _releaseConnection:automatic_];
6052 - (void) viewDidAppear:(BOOL)animated {
6053 [super viewDidAppear:animated];
6054 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6057 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
6058 return offset_ == 0 ? 1 : 2;
6061 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
6062 switch (section + (offset_ == 0 ? 1 : 0)) {
6063 case 0: return UCLocalize("ENTERED_BY_USER");
6064 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
6070 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6071 int count = [sources_ count];
6073 case 0: return (offset_ == 0 ? count : offset_);
6074 case 1: return count - offset_;
6080 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
6082 switch (indexPath.section) {
6083 case 0: idx = indexPath.row; break;
6084 case 1: idx = indexPath.row + offset_; break;
6088 return [sources_ objectAtIndex:idx];
6091 - (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6092 Source *source = [self sourceAtIndexPath:indexPath];
6093 return [source description] == nil ? 56 : 73;
6096 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6097 static NSString *cellIdentifier = @"SourceCell";
6099 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
6100 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
6101 [cell setSource:[self sourceAtIndexPath:indexPath]];
6106 - (UITableViewCellAccessoryType) tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath {
6107 return UITableViewCellAccessoryDisclosureIndicator;
6110 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6111 Source *source = [self sourceAtIndexPath:indexPath];
6113 FilteredPackageController *packages = [[[FilteredPackageController alloc]
6114 initWithDatabase:database_
6115 title:[source label]
6116 filter:@selector(isVisibleInSource:)
6120 [packages setDelegate:delegate_];
6122 [[self navigationController] pushViewController:packages animated:YES];
6125 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
6126 Source *source = [self sourceAtIndexPath:indexPath];
6127 return [source record] != nil;
6130 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
6131 Source *source = [self sourceAtIndexPath:indexPath];
6132 [Sources_ removeObjectForKey:[source key]];
6133 [delegate_ syncData];
6137 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
6140 @"./", @"Distribution",
6141 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
6143 [delegate_ syncData];
6146 - (NSString *) getWarning {
6147 NSString *href(href_);
6148 NSRange colon([href rangeOfString:@"://"]);
6149 if (colon.location != NSNotFound)
6150 href = [href substringFromIndex:(colon.location + 3)];
6151 href = [href stringByAddingPercentEscapes];
6152 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
6153 href = [href stringByCachingURLWithCurrentCDN];
6155 NSURL *url([NSURL URLWithString:href]);
6157 NSStringEncoding encoding;
6158 NSError *error(nil);
6160 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
6161 return [warning length] == 0 ? nil : warning;
6165 - (void) _endConnection:(NSURLConnection *)connection {
6166 // XXX: the memory management in this method is horribly awkward
6168 NSURLConnection **field = NULL;
6169 if (connection == trivial_)
6171 else if (connection == trivial_bz2_)
6172 field = &trivial_bz2_;
6173 else if (connection == trivial_gz_)
6174 field = &trivial_gz_;
6175 _assert(field != NULL);
6176 [connection release];
6181 trivial_bz2_ == nil &&
6187 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
6190 UIAlertView *alert = [[[UIAlertView alloc]
6191 initWithTitle:UCLocalize("SOURCE_WARNING")
6194 cancelButtonTitle:UCLocalize("CANCEL")
6195 otherButtonTitles:UCLocalize("ADD_ANYWAY"), nil
6198 [alert setContext:@"warning"];
6199 [alert setNumberOfRows:1];
6203 } else if (error_ != nil) {
6204 UIAlertView *alert = [[[UIAlertView alloc]
6205 initWithTitle:UCLocalize("VERIFICATION_ERROR")
6206 message:[error_ localizedDescription]
6208 cancelButtonTitle:UCLocalize("OK")
6209 otherButtonTitles:nil
6212 [alert setContext:@"urlerror"];
6215 UIAlertView *alert = [[[UIAlertView alloc]
6216 initWithTitle:UCLocalize("NOT_REPOSITORY")
6217 message:UCLocalize("NOT_REPOSITORY_EX")
6219 cancelButtonTitle:UCLocalize("OK")
6220 otherButtonTitles:nil
6223 [alert setContext:@"trivial"];
6227 [delegate_ setStatusBarShowsProgress:NO];
6228 [delegate_ removeProgressHUD:hud_];
6238 if (error_ != nil) {
6245 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
6246 switch ([response statusCode]) {
6252 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
6253 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
6255 error_ = [error retain];
6256 [self _endConnection:connection];
6259 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
6260 [self _endConnection:connection];
6263 - (NSString *) title { return UCLocalize("SOURCES"); }
6265 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
6266 NSMutableURLRequest *request = [NSMutableURLRequest
6267 requestWithURL:[NSURL URLWithString:href]
6268 cachePolicy:NSURLRequestUseProtocolCachePolicy
6269 timeoutInterval:120.0
6272 [request setHTTPMethod:method];
6274 if (Machine_ != NULL)
6275 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
6276 if (UniqueID_ != nil)
6277 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6279 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
6281 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
6284 - (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
6285 NSString *context([alert context]);
6287 if ([context isEqualToString:@"source"]) {
6290 NSString *href = [[alert textField] text];
6292 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
6294 if (![href hasSuffix:@"/"])
6295 href_ = [href stringByAppendingString:@"/"];
6298 href_ = [href_ retain];
6300 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
6301 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
6302 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
6303 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
6307 // XXX: this is stupid
6308 hud_ = [[delegate_ addProgressHUD] retain];
6309 [hud_ setText:UCLocalize("VERIFYING_URL")];
6318 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6319 } else if ([context isEqualToString:@"trivial"])
6320 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6321 else if ([context isEqualToString:@"urlerror"])
6322 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6323 else if ([context isEqualToString:@"warning"]) {
6338 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6342 - (id) initWithDatabase:(Database *)database {
6343 if ((self = [super init]) != nil) {
6344 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
6345 [self updateButtonsForEditingStatus:NO animated:NO];
6347 database_ = database;
6348 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
6350 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6351 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6352 [[self view] addSubview:list_];
6354 [list_ setDataSource:self];
6355 [list_ setDelegate:self];
6361 - (void) reloadData {
6363 if (!list.ReadMainList())
6366 [sources_ removeAllObjects];
6367 [sources_ addObjectsFromArray:[database_ sources]];
6369 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
6372 int count([sources_ count]);
6374 for (int i = 0; i != count; i++) {
6375 if ([[sources_ objectAtIndex:i] record] == nil)
6380 [list_ setEditing:NO];
6381 [self updateButtonsForEditingStatus:NO animated:NO];
6385 - (void) showAddSourcePrompt {
6386 /*[book_ pushPage:[[[AddCYSourcesController alloc]
6391 UIAlertView *alert = [[[UIAlertView alloc]
6392 initWithTitle:UCLocalize("ENTER_APT_URL")
6395 cancelButtonTitle:UCLocalize("CANCEL")
6396 otherButtonTitles:UCLocalize("ADD_SOURCE"), nil
6399 [alert setContext:@"source"];
6400 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
6402 [alert setNumberOfRows:1];
6403 [alert addTextFieldWithValue:@"http://" label:@""];
6405 UITextInputTraits *traits = [[alert textField] textInputTraits];
6406 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6407 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6408 [traits setKeyboardType:UIKeyboardTypeURL];
6409 // XXX: UIReturnKeyDone
6410 [traits setReturnKeyType:UIReturnKeyNext];
6415 - (void) addButtonClicked {
6416 [self showAddSourcePrompt];
6419 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
6420 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
6421 initWithTitle:UCLocalize("ADD")
6422 style:UIBarButtonItemStylePlain
6424 action:@selector(addButtonClicked)
6425 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
6427 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6428 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
6429 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
6431 action:@selector(editButtonClicked)
6432 ] autorelease] animated:animated];
6434 if (IsWildcat_ && !editing)
6435 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6436 initWithTitle:UCLocalize("SETTINGS")
6437 style:UIBarButtonItemStylePlain
6439 action:@selector(settingsButtonClicked)
6443 - (void) settingsButtonClicked {
6444 [delegate_ showSettings];
6447 - (void) editButtonClicked {
6448 [list_ setEditing:![list_ isEditing] animated:YES];
6450 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
6456 /* Installed Controller {{{ */
6457 @interface CYInstalledController : FilteredPackageController {
6461 - (id) initWithDatabase:(Database *)database;
6463 - (void) updateRoleButton;
6464 - (void) queueStatusDidChange;
6468 @implementation CYInstalledController
6474 - (NSString *) title { return UCLocalize("INSTALLED"); }
6476 - (id) initWithDatabase:(Database *)database {
6477 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
6478 [self updateRoleButton];
6479 [self queueStatusDidChange];
6484 - (void) queueButtonClicked {
6489 - (void) queueStatusDidChange {
6493 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6494 initWithTitle:UCLocalize("QUEUE")
6495 style:UIBarButtonItemStyleDone
6497 action:@selector(queueButtonClicked)
6500 [[self navigationItem] setLeftBarButtonItem:nil];
6506 - (void) reloadData {
6507 [packages_ reloadData];
6510 - (void) updateRoleButton {
6511 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
6512 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6513 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
6514 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
6516 action:@selector(roleButtonClicked)
6520 - (void) roleButtonClicked {
6521 [packages_ setObject:[NSNumber numberWithBool:expert_]];
6522 [packages_ reloadData];
6525 [self updateRoleButton];
6528 - (void) setDelegate:(id)delegate {
6529 [super setDelegate:delegate];
6530 [packages_ setDelegate:delegate];
6535 /* Section Controller {{{ */
6536 @interface CYSectionController : FilteredPackageController {
6539 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
6543 @implementation CYSectionController
6549 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
6553 title = UCLocalize("ALL_PACKAGES");
6554 } else if (![name isEqual:@""]) {
6555 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6557 title = UCLocalize("NO_SECTION");
6560 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
6564 - (void) reloadData {
6565 [packages_ reloadData];
6568 - (void) setDelegate:(id)delegate {
6569 [super setDelegate:delegate];
6570 [packages_ setDelegate:delegate];
6576 /* Home Controller {{{ */
6577 @interface CYHomeController : CYBrowserController {
6582 @implementation CYHomeController
6584 + (BOOL)shouldHideNavigationBar {
6588 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6589 [super _setMoreHeaders:request];
6592 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6593 if (UniqueID_ != nil)
6594 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6596 [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"];
6599 - (void) aboutButtonClicked {
6600 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6602 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6603 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6604 [alert setCancelButtonIndex:0];
6607 @"Copyright (C) 2008-2010\n"
6608 "Jay Freeman (saurik)\n"
6609 "saurik@saurik.com\n"
6610 "http://www.saurik.com/"
6616 - (void) viewWillAppear:(BOOL)animated {
6617 [super viewWillAppear:animated];
6619 if ([[self class] shouldHideNavigationBar])
6620 [[self navigationController] setNavigationBarHidden:YES animated:animated];
6623 - (void) viewWillDisappear:(BOOL)animated {
6624 [super viewWillDisappear:animated];
6626 if ([[self class] shouldHideNavigationBar])
6627 [[self navigationController] setNavigationBarHidden:NO animated:animated];
6631 if ((self = [super init]) != nil) {
6632 [self loadURL:[NSURL URLWithString:CydiaURL(@"")]];
6634 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6635 initWithTitle:UCLocalize("ABOUT")
6636 style:UIBarButtonItemStylePlain
6638 action:@selector(aboutButtonClicked)
6645 /* Manage Controller {{{ */
6646 @interface CYManageController : CYBrowserController {
6649 - (void) queueStatusDidChange;
6652 @implementation CYManageController
6655 if ((self = [super init]) != nil) {
6656 [[self navigationItem] setTitle:UCLocalize("MANAGE")];
6658 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]];
6660 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6661 initWithTitle:UCLocalize("SETTINGS")
6662 style:UIBarButtonItemStylePlain
6664 action:@selector(settingsButtonClicked)
6667 [self queueStatusDidChange];
6671 - (void) settingsButtonClicked {
6672 [delegate_ showSettings];
6676 - (void) queueButtonClicked {
6680 - (void) applyLoadingTitle {
6681 // No "Loading" title.
6684 - (void) applyRightButton {
6689 - (void) queueStatusDidChange {
6691 if (!IsWildcat_ && Queuing_) {
6692 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6693 initWithTitle:UCLocalize("QUEUE")
6694 style:UIBarButtonItemStyleDone
6696 action:@selector(queueButtonClicked)
6699 [[self navigationItem] setRightBarButtonItem:nil];
6704 - (bool) isLoading {
6711 /* Refresh Bar {{{ */
6712 @interface RefreshBar : UINavigationBar {
6713 UIProgressIndicator *indicator_;
6714 UITextLabel *prompt_;
6715 UIProgressBar *progress_;
6716 UINavigationButton *cancel_;
6721 @implementation RefreshBar
6724 [indicator_ release];
6726 [progress_ release];
6731 - (void) positionViews {
6732 CGRect frame = [cancel_ frame];
6733 frame.size = [cancel_ sizeThatFits:frame.size];
6734 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6735 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6736 [cancel_ setFrame:frame];
6738 CGSize prgsize = {75, 100};
6740 [self frame].size.width - prgsize.width - 10,
6741 ([self frame].size.height - prgsize.height) / 2
6743 [progress_ setFrame:prgrect];
6745 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6746 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6747 CGRect indrect = {{indoffset, indoffset}, indsize};
6748 [indicator_ setFrame:indrect];
6750 CGSize prmsize = {215, indsize.height + 4};
6752 indoffset * 2 + indsize.width,
6753 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6755 [prompt_ setFrame:prmrect];
6758 - (void)setFrame:(CGRect)frame {
6759 [super setFrame:frame];
6761 [self positionViews];
6764 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6765 if ((self = [super initWithFrame:frame])) {
6766 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6768 [self setBarStyle:UIBarStyleBlack];
6770 UIBarStyle barstyle([self _barStyle:NO]);
6771 bool ugly(barstyle == UIBarStyleDefault);
6773 UIProgressIndicatorStyle style = ugly ?
6774 UIProgressIndicatorStyleMediumBrown :
6775 UIProgressIndicatorStyleMediumWhite;
6777 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6778 [indicator_ setStyle:style];
6779 [indicator_ startAnimation];
6780 [self addSubview:indicator_];
6782 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6783 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6784 [prompt_ setBackgroundColor:[UIColor clearColor]];
6785 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6786 [self addSubview:prompt_];
6788 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6789 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6790 [progress_ setStyle:0];
6791 [self addSubview:progress_];
6793 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6794 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6795 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6796 [cancel_ setBarStyle:barstyle];
6798 [self positionViews];
6803 [cancel_ removeFromSuperview];
6807 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6808 [progress_ setProgress:0];
6809 [self addSubview:cancel_];
6813 [cancel_ removeFromSuperview];
6816 - (void) setPrompt:(NSString *)prompt {
6817 [prompt_ setText:prompt];
6820 - (void) setProgress:(float)progress {
6821 [progress_ setProgress:progress];
6827 @class CYNavigationController;
6829 /* Cydia Tab Bar Controller {{{ */
6830 @interface CYTabBarController : UITabBarController <
6833 _transient Database *database_;
6834 RefreshBar *refreshbar_;
6838 // XXX: ok, "updatedelegate_"?...
6839 _transient NSObject<CydiaDelegate> *updatedelegate_;
6844 - (void) dropBar:(BOOL)animated;
6845 - (void) beginUpdate;
6846 - (void) raiseBar:(BOOL)animated;
6851 @implementation CYTabBarController
6853 - (void) reloadData {
6854 size_t count([[self viewControllers] count]);
6855 for (size_t i(0); i != count; ++i) {
6856 CYNavigationController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6861 - (id) initWithDatabase:(Database *)database {
6862 if ((self = [super init]) != nil) {
6863 database_ = database;
6865 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6866 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6868 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
6872 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
6873 return IsWildcat_ || orientation == UIInterfaceOrientationPortrait;
6876 - (void) setUpdate:(NSDate *)date {
6880 - (void) beginUpdate {
6881 [refreshbar_ start];
6884 [updatedelegate_ retainNetworkActivityIndicator];
6888 detachNewThreadSelector:@selector(performUpdate)
6894 - (void) performUpdate { _pooled
6896 status.setDelegate(self);
6897 [database_ updateWithStatus:status];
6900 performSelectorOnMainThread:@selector(completeUpdate)
6906 - (void) stopUpdateWithSelector:(SEL)selector {
6908 [updatedelegate_ releaseNetworkActivityIndicator];
6910 [self raiseBar:YES];
6913 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6916 - (void) completeUpdate {
6919 [self stopUpdateWithSelector:@selector(reloadData)];
6922 - (void) cancelUpdate {
6923 [self stopUpdateWithSelector:@selector(updateData)];
6926 - (void) cancelPressed {
6927 [self cancelUpdate];
6934 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
6935 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
6938 - (void) startProgress {
6941 - (void) setProgressTitle:(NSString *)title {
6943 performSelectorOnMainThread:@selector(_setProgressTitle:)
6949 - (bool) isCancelling:(size_t)received {
6953 - (void) setProgressPercent:(float)percent {
6955 performSelectorOnMainThread:@selector(_setProgressPercent:)
6956 withObject:[NSNumber numberWithFloat:percent]
6961 - (void) addProgressOutput:(NSString *)output {
6963 performSelectorOnMainThread:@selector(_addProgressOutput:)
6969 - (void) _setProgressTitle:(NSString *)title {
6970 [refreshbar_ setPrompt:title];
6973 - (void) _setProgressPercent:(NSNumber *)percent {
6974 [refreshbar_ setProgress:[percent floatValue]];
6977 - (void) _addProgressOutput:(NSString *)output {
6980 - (void) setUpdateDelegate:(id)delegate {
6981 updatedelegate_ = delegate;
6984 - (CGFloat) statusBarHeight {
6985 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
6986 return [[UIApplication sharedApplication] statusBarFrame].size.height;
6988 return [[UIApplication sharedApplication] statusBarFrame].size.width;
6992 - (UIView *) transitionView {
6993 if ([self respondsToSelector:@selector(_transitionView)])
6994 return [self _transitionView];
6996 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6999 - (void) dropBar:(BOOL)animated {
7004 UIView *transition([self transitionView]);
7005 [[self view] addSubview:refreshbar_];
7007 CGRect barframe([refreshbar_ frame]);
7009 if (false) // XXX: _UIApplicationLinkedOnOrAfter(4)
7010 barframe.origin.y = [self statusBarHeight];
7012 barframe.origin.y = 0;
7014 [refreshbar_ setFrame:barframe];
7017 [UIView beginAnimations:nil context:NULL];
7019 CGRect viewframe = [transition frame];
7020 viewframe.origin.y += barframe.size.height;
7021 viewframe.size.height -= barframe.size.height;
7022 [transition setFrame:viewframe];
7025 [UIView commitAnimations];
7027 // Ensure bar has the proper width for our view, it might have changed
7028 barframe.size.width = viewframe.size.width;
7029 [refreshbar_ setFrame:barframe];
7031 // XXX: fix Apple's layout bug
7032 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7035 - (void) raiseBar:(BOOL)animated {
7040 UIView *transition([self transitionView]);
7041 [refreshbar_ removeFromSuperview];
7043 CGRect barframe([refreshbar_ frame]);
7046 [UIView beginAnimations:nil context:NULL];
7048 CGRect viewframe = [transition frame];
7049 viewframe.origin.y -= barframe.size.height;
7050 viewframe.size.height += barframe.size.height;
7051 [transition setFrame:viewframe];
7054 [UIView commitAnimations];
7056 // XXX: fix Apple's layout bug
7057 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7061 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7062 // XXX: fix Apple's layout bug
7063 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7067 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7068 bool dropped(dropped_);
7073 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
7078 // XXX: fix Apple's layout bug
7079 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7082 - (void) statusBarFrameChanged:(NSNotification *)notification {
7090 [refreshbar_ release];
7091 [[NSNotificationCenter defaultCenter] removeObserver:self];
7098 /* Cydia Navigation Controller {{{ */
7099 @interface CYNavigationController : UINavigationController {
7100 _transient Database *database_;
7101 _transient id<UINavigationControllerDelegate> delegate_;
7104 - (id) initWithDatabase:(Database *)database;
7105 - (void) reloadData;
7110 @implementation CYNavigationController
7112 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7113 // Inherit autorotation settings for modal parents.
7114 if ([self parentViewController] && [[self parentViewController] modalViewController] == self) {
7115 return [[self parentViewController] shouldAutorotateToInterfaceOrientation:orientation];
7116 } else if ([self parentViewController]) {
7117 return [[self parentViewController] shouldAutorotateToInterfaceOrientation:orientation];
7119 return [super shouldAutorotateToInterfaceOrientation:orientation];
7127 - (void) reloadData {
7128 size_t count([[self viewControllers] count]);
7129 for (size_t i(0); i != count; ++i) {
7130 CYViewController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
7135 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
7136 delegate_ = delegate;
7139 - (id) initWithDatabase:(Database *)database {
7140 if ((self = [super init]) != nil) {
7141 database_ = database;
7147 /* Cydia:// Protocol {{{ */
7148 @interface CydiaURLProtocol : NSURLProtocol {
7153 @implementation CydiaURLProtocol
7155 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7156 NSURL *url([request URL]);
7159 NSString *scheme([[url scheme] lowercaseString]);
7160 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
7165 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7169 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7170 id<NSURLProtocolClient> client([self client]);
7172 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7174 NSData *data(UIImagePNGRepresentation(icon));
7176 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7177 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7178 [client URLProtocol:self didLoadData:data];
7179 [client URLProtocolDidFinishLoading:self];
7183 - (void) startLoading {
7184 id<NSURLProtocolClient> client([self client]);
7185 NSURLRequest *request([self request]);
7187 NSURL *url([request URL]);
7188 NSString *href([url absoluteString]);
7190 NSString *path([href substringFromIndex:8]);
7191 NSRange slash([path rangeOfString:@"/"]);
7194 if (slash.location == NSNotFound) {
7198 command = [path substringToIndex:slash.location];
7199 path = [path substringFromIndex:(slash.location + 1)];
7202 Database *database([Database sharedInstance]);
7204 if ([command isEqualToString:@"package-icon"]) {
7207 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7208 Package *package([database packageWithName:path]);
7211 UIImage *icon([package icon]);
7212 [self _returnPNGWithImage:icon forRequest:request];
7213 } else if ([command isEqualToString:@"source-icon"]) {
7216 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7217 NSString *source(Simplify(path));
7218 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
7220 icon = [UIImage applicationImageNamed:@"unknown.png"];
7221 [self _returnPNGWithImage:icon forRequest:request];
7222 } else if ([command isEqualToString:@"uikit-image"]) {
7225 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7226 UIImage *icon(_UIImageWithName(path));
7227 [self _returnPNGWithImage:icon forRequest:request];
7228 } else if ([command isEqualToString:@"section-icon"]) {
7231 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7232 NSString *section(Simplify(path));
7233 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
7235 icon = [UIImage applicationImageNamed:@"unknown.png"];
7236 [self _returnPNGWithImage:icon forRequest:request];
7238 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7242 - (void) stopLoading {
7248 /* Sections Controller {{{ */
7249 @interface CYSectionsController : CYViewController <
7250 UITableViewDataSource,
7253 _transient Database *database_;
7254 NSMutableArray *sections_;
7255 NSMutableArray *filtered_;
7261 - (id) initWithDatabase:(Database *)database;
7262 - (void) reloadData;
7265 - (void) editButtonClicked;
7269 @implementation CYSectionsController
7272 [list_ setDataSource:nil];
7273 [list_ setDelegate:nil];
7275 [sections_ release];
7276 [filtered_ release];
7278 [accessory_ release];
7282 - (void) setEditing:(BOOL)editing {
7283 if ((editing_ = editing))
7286 [delegate_ updateData];
7288 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7289 [[[self navigationItem] rightBarButtonItem] setTitle:[sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT")];
7290 [[[self navigationItem] rightBarButtonItem] setStyle:editing_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain];
7293 - (void) viewDidAppear:(BOOL)animated {
7294 [super viewDidAppear:animated];
7295 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7298 - (void) viewWillDisappear:(BOOL)animated {
7299 [super viewWillDisappear:animated];
7300 if (editing_) [self setEditing:NO];
7303 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7304 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
7308 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7309 return editing_ ? [sections_ count] : [filtered_ count] + 1;
7312 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7316 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7317 static NSString *reuseIdentifier = @"SectionCell";
7319 SectionCell *cell = (SectionCell *) [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7321 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7323 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
7328 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7332 Section *section = [self sectionAtIndexPath:indexPath];
7334 CYSectionController *controller = [[[CYSectionController alloc]
7335 initWithDatabase:database_
7336 section:[section name]
7338 [controller setDelegate:delegate_];
7340 [[self navigationController] pushViewController:controller animated:YES];
7343 - (id) initWithDatabase:(Database *)database {
7344 if ((self = [super init]) != nil) {
7345 database_ = database;
7347 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7349 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7350 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
7352 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
7353 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7354 [list_ setRowHeight:45.0f];
7355 [[self view] addSubview:list_];
7357 [list_ setDataSource:self];
7358 [list_ setDelegate:self];
7364 - (void) reloadData {
7365 NSArray *packages = [database_ packages];
7367 [sections_ removeAllObjects];
7368 [filtered_ removeAllObjects];
7370 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7373 for (Package *package in packages) {
7374 NSString *name([package section]);
7375 NSString *key(name == nil ? @"" : name);
7379 _profile(SectionsView$reloadData$Section)
7380 section = [sections objectForKey:key];
7381 if (section == nil) {
7382 _profile(SectionsView$reloadData$Section$Allocate)
7383 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
7384 [sections setObject:section forKey:key];
7389 [section addToCount];
7391 _profile(SectionsView$reloadData$Filter)
7392 if (![package valid] || ![package visible])
7400 [sections_ addObjectsFromArray:[sections allValues]];
7402 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7404 for (Section *section in sections_) {
7405 size_t count([section row]);
7409 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7410 [section setCount:count];
7411 [filtered_ addObject:section];
7414 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7415 initWithTitle:([sections_ count] == 0 ? nil : UCLocalize("EDIT"))
7416 style:UIBarButtonItemStylePlain
7418 action:@selector(editButtonClicked)
7419 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7425 - (void) resetView {
7427 [self editButtonClicked];
7430 - (void)editButtonClicked {
7431 [self setEditing:!editing_];
7434 - (UIView *) accessoryView {
7440 /* Changes Controller {{{ */
7441 @interface CYChangesController : CYViewController <
7442 UITableViewDataSource,
7445 _transient Database *database_;
7447 CFMutableArrayRef packages_;
7448 NSMutableArray *sections_;
7451 BOOL hasSentFirstLoad_;
7454 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
7455 - (void) reloadData;
7459 @implementation CYChangesController
7462 [list_ setDelegate:nil];
7463 [list_ setDataSource:nil];
7465 CFRelease(packages_);
7467 [sections_ release];
7472 - (void) viewDidAppear:(BOOL)animated {
7473 [super viewDidAppear:animated];
7474 if (!hasSentFirstLoad_) {
7475 hasSentFirstLoad_ = YES;
7476 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
7478 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7482 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7483 NSInteger count([sections_ count]);
7484 return count == 0 ? 1 : count;
7487 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7488 if ([sections_ count] == 0)
7490 return [[sections_ objectAtIndex:section] name];
7493 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7494 if ([sections_ count] == 0)
7496 return [[sections_ objectAtIndex:section] count];
7499 - (Package *) packageAtIndex:(NSUInteger)index {
7500 return (Package *) CFArrayGetValueAtIndex(packages_, index);
7503 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7504 @synchronized (database_) {
7505 if ([database_ era] != era_)
7508 Section *section([sections_ objectAtIndex:[path section]]);
7509 NSInteger row([path row]);
7510 return [[[self packageAtIndex:([section row] + row)] retain] autorelease];
7513 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7514 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7516 cell = [[[PackageCell alloc] init] autorelease];
7517 [cell setPackage:[self packageAtIndexPath:path]];
7521 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
7522 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
7525 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7526 Package *package([self packageAtIndexPath:path]);
7527 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_] autorelease]);
7528 [view setDelegate:delegate_];
7529 [view setPackage:package];
7530 [[self navigationController] pushViewController:view animated:YES];
7534 - (void) refreshButtonClicked {
7535 [delegate_ beginUpdate];
7536 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7539 - (void) upgradeButtonClicked {
7540 [delegate_ distUpgrade];
7543 - (NSString *) title { return UCLocalize("CHANGES"); }
7545 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7546 if ((self = [super init]) != nil) {
7547 database_ = database;
7548 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7550 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7552 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7554 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7555 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7556 [list_ setRowHeight:73.0f];
7557 [[self view] addSubview:list_];
7559 [list_ setDataSource:self];
7560 [list_ setDelegate:self];
7562 delegate_ = delegate;
7566 - (void) _reloadPackages:(NSArray *)packages {
7568 for (Package *package in packages)
7569 if ([package upgradableAndEssential:YES] || [package visible])
7570 CFArrayAppendValue(packages_, package);
7573 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7577 - (void) reloadData {
7578 era_ = [database_ era];
7579 NSArray *packages = [database_ packages];
7581 CFArrayRemoveAllValues(packages_);
7583 [sections_ removeAllObjects];
7586 UIProgressHUD *hud([delegate_ addProgressHUD]);
7587 [hud setText:UCLocalize("LOADING")];
7588 //NSLog(@"HUD:%@::%@", delegate_, hud);
7589 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7590 [delegate_ removeProgressHUD:hud];
7592 [self _reloadPackages:packages];
7595 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7596 Section *ignored = nil;
7597 Section *section = nil;
7601 bool unseens = false;
7603 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7605 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7606 Package *package = [self packageAtIndex:offset];
7608 BOOL uae = [package upgradableAndEssential:YES];
7612 time_t seen([package seen]);
7614 if (section == nil || last != seen) {
7618 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7621 _profile(CYChangesController$reloadData$Allocate)
7622 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7623 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7624 [sections_ addObject:section];
7628 [section addToCount];
7629 } else if ([package ignored]) {
7630 if (ignored == nil) {
7631 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7633 [ignored addToCount];
7636 [upgradable addToCount];
7641 CFRelease(formatter);
7644 Section *last = [sections_ lastObject];
7645 size_t count = [last count];
7646 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7647 [sections_ removeLastObject];
7650 if ([ignored count] != 0)
7651 [sections_ insertObject:ignored atIndex:0];
7653 [sections_ insertObject:upgradable atIndex:0];
7658 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7659 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7660 style:UIBarButtonItemStylePlain
7662 action:@selector(upgradeButtonClicked)
7665 if (![delegate_ updating])
7666 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7667 initWithTitle:UCLocalize("REFRESH")
7668 style:UIBarButtonItemStylePlain
7670 action:@selector(refreshButtonClicked)
7676 /* Search Controller {{{ */
7677 @interface CYSearchController : FilteredPackageController <
7680 UISearchBar *search_;
7683 - (void) setSearchTerm:(NSString *)searchTerm;
7684 - (id) initWithDatabase:(Database *)database;
7685 - (void) reloadData;
7689 @implementation CYSearchController
7696 - (void) setSearchTerm:(NSString *)searchTerm {
7697 [search_ setText:searchTerm];
7700 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7701 [packages_ setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7702 [search_ resignFirstResponder];
7706 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7707 [packages_ setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7711 - (NSString *) title { return nil; }
7713 - (id) initWithDatabase:(Database *)database {
7714 return [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil];
7717 - (void)viewDidAppear:(BOOL)animated {
7718 [super viewDidAppear:animated];
7720 search_ = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7721 [search_ layoutSubviews];
7722 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7724 UITextField *textField;
7725 if ([search_ respondsToSelector:@selector(searchField)])
7726 textField = [search_ searchField];
7728 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7730 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7731 [search_ setDelegate:self];
7732 [textField setEnablesReturnKeyAutomatically:NO];
7733 [[self navigationItem] setTitleView:textField];
7737 - (void) _reloadData {
7740 - (void) reloadData {
7741 _profile(CYSearchController$reloadData)
7742 [packages_ reloadData];
7745 [packages_ resetCursor];
7748 - (void) didSelectPackage:(Package *)package {
7749 [search_ resignFirstResponder];
7750 [super didSelectPackage:package];
7755 /* Settings Controller {{{ */
7756 @interface CYPackageSettingsController : CYViewController <
7757 UITableViewDataSource,
7760 _transient Database *database_;
7763 UITableView *table_;
7764 UISwitch *subscribedSwitch_;
7765 UISwitch *ignoredSwitch_;
7766 UITableViewCell *subscribedCell_;
7767 UITableViewCell *ignoredCell_;
7770 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7774 @implementation CYPackageSettingsController
7778 if (package_ != nil)
7781 [subscribedSwitch_ release];
7782 [ignoredSwitch_ release];
7783 [subscribedCell_ release];
7784 [ignoredCell_ release];
7789 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7790 if (package_ == nil)
7796 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7797 if (package_ == nil)
7803 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7804 return UCLocalize("CHANGE_PACKAGE_SETTINGS");
7807 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7808 return UCLocalize("SHOW_ALL_CHANGES_EX");
7811 - (void) onSubscribed:(id)control {
7812 bool value([control isOn]);
7813 if (package_ == nil)
7815 if ([package_ setSubscribed:value])
7816 [delegate_ updateData];
7819 - (void) onIgnored:(id)control {
7820 // TODO: set Held state - possibly call out to dpkg, etc.
7823 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7824 if (package_ == nil)
7827 switch ([indexPath row]) {
7828 case 0: return subscribedCell_;
7829 case 1: return ignoredCell_;
7837 - (NSString *) title { return UCLocalize("SETTINGS"); }
7839 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7840 if ((self = [super init])) {
7841 database_ = database;
7842 name_ = [package retain];
7844 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7846 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7847 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7848 [[self view] addSubview:table_];
7850 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7851 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7852 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7854 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7855 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7856 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7857 // Disable this switch, since it only reflects (not modifies) the ignored state.
7858 [ignoredSwitch_ setUserInteractionEnabled:NO];
7860 subscribedCell_ = [[UITableViewCell alloc] init];
7861 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7862 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7863 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7865 ignoredCell_ = [[UITableViewCell alloc] init];
7866 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7867 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7868 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7870 [table_ setDataSource:self];
7871 [table_ setDelegate:self];
7876 - (void) reloadData {
7877 if (package_ != nil)
7878 [package_ autorelease];
7879 package_ = [database_ packageWithName:name_];
7880 if (package_ != nil) {
7882 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7883 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7886 [table_ reloadData];
7891 /* Signature Controller {{{ */
7892 @interface SignatureController : CYBrowserController {
7893 _transient Database *database_;
7897 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7901 @implementation SignatureController
7908 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7910 [super webView:view didClearWindowObject:window forFrame:frame];
7913 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7914 if ((self = [super init]) != nil) {
7915 database_ = database;
7916 package_ = [package retain];
7921 - (void) reloadData {
7922 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7928 /* Role Controller {{{ */
7929 @interface CYSettingsController : CYViewController <
7930 UITableViewDataSource,
7933 _transient Database *database_;
7934 // XXX: ok, "roledelegate_"?...
7935 _transient id roledelegate_;
7936 UITableView *table_;
7937 UISegmentedControl *segment_;
7941 - (void) showDoneButton;
7942 - (void) resizeSegmentedControl;
7946 @implementation CYSettingsController
7950 [container_ release];
7955 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7956 if ((self = [super init])) {
7957 database_ = database;
7958 roledelegate_ = delegate;
7960 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
7962 NSArray *items = [NSArray arrayWithObjects:
7964 UCLocalize("HACKER"),
7965 UCLocalize("DEVELOPER"),
7967 segment_ = [[UISegmentedControl alloc] initWithItems:items];
7968 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
7969 [container_ addSubview:segment_];
7972 if ([Role_ isEqualToString:@"User"]) index = 0;
7973 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
7974 if ([Role_ isEqualToString:@"Developer"]) index = 2;
7976 [segment_ setSelectedSegmentIndex:index];
7977 [self showDoneButton];
7980 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
7981 [self resizeSegmentedControl];
7983 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7984 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7985 [table_ setDelegate:self];
7986 [table_ setDataSource:self];
7987 [[self view] addSubview:table_];
7988 [table_ reloadData];
7992 - (void) resizeSegmentedControl {
7993 CGFloat width = [[self view] frame].size.width;
7994 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
7997 - (void) viewWillAppear:(BOOL)animated {
7998 [super viewWillAppear:animated];
8000 [self resizeSegmentedControl];
8003 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8004 [self resizeSegmentedControl];
8007 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8008 [self resizeSegmentedControl];
8012 NSString *role(nil);
8014 switch ([segment_ selectedSegmentIndex]) {
8015 case 0: role = @"User"; break;
8016 case 1: role = @"Hacker"; break;
8017 case 2: role = @"Developer"; break;
8022 if (![role isEqualToString:Role_]) {
8023 bool rolling(Role_ == nil);
8026 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8030 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8034 [roledelegate_ loadData];
8036 [roledelegate_ updateData];
8040 - (void) segmentChanged:(UISegmentedControl *)control {
8041 [self showDoneButton];
8044 - (void) saveAndClose {
8047 [[self navigationItem] setRightBarButtonItem:nil];
8048 [[self navigationController] dismissModalViewControllerAnimated:YES];
8051 - (void) doneButtonClicked {
8052 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8053 [spinner startAnimating];
8054 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8055 [[self navigationItem] setRightBarButtonItem:spinItem];
8057 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8060 - (void) showDoneButton {
8061 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8062 initWithTitle:UCLocalize("DONE")
8063 style:UIBarButtonItemStyleDone
8065 action:@selector(doneButtonClicked)
8066 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8069 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8070 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8074 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8078 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8079 return nil; // This method is required by the protocol.
8082 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8084 return UCLocalize("ROLE_EX");
8086 return [NSString stringWithFormat:
8087 @"%@: %@\n%@: %@\n%@: %@",
8088 UCLocalize("USER"), UCLocalize("USER_EX"),
8089 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8090 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8095 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8096 return section == 3 ? 44.0f : 0;
8099 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8100 return section == 3 ? container_ : nil;
8105 /* Stash Controller {{{ */
8106 @interface CYStashController : CYViewController {
8107 // XXX: just delete these things
8108 _transient UIActivityIndicatorView *spinner_;
8109 _transient UILabel *status_;
8110 _transient UILabel *caption_;
8114 @implementation CYStashController
8116 if ((self = [super init])) {
8117 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8119 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8120 CGRect spinrect = [spinner_ frame];
8121 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8122 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8123 [spinner_ setFrame:spinrect];
8124 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8125 [[self view] addSubview:spinner_];
8126 [spinner_ startAnimating];
8129 captrect.size.width = [[self view] frame].size.width;
8130 captrect.size.height = 40.0f;
8131 captrect.origin.x = 0;
8132 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8133 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8134 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8135 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8136 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8137 [caption_ setTextColor:[UIColor whiteColor]];
8138 [caption_ setBackgroundColor:[UIColor clearColor]];
8139 [caption_ setShadowColor:[UIColor blackColor]];
8140 [caption_ setTextAlignment:UITextAlignmentCenter];
8141 [[self view] addSubview:caption_];
8144 statusrect.size.width = [[self view] frame].size.width;
8145 statusrect.size.height = 30.0f;
8146 statusrect.origin.x = 0;
8147 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8148 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8149 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8150 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8151 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8152 [status_ setTextColor:[UIColor whiteColor]];
8153 [status_ setBackgroundColor:[UIColor clearColor]];
8154 [status_ setShadowColor:[UIColor blackColor]];
8155 [status_ setTextAlignment:UITextAlignmentCenter];
8156 [[self view] addSubview:status_];
8160 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
8161 return IsWildcat_ || orientation == UIInterfaceOrientationPortrait;
8176 @interface Cydia : UIApplication <
8177 ConfirmationControllerDelegate,
8178 ProgressControllerDelegate,
8180 UINavigationControllerDelegate,
8181 UITabBarControllerDelegate
8183 // XXX: evaluate all fields for _transient
8186 CYTabBarController *tabbar_;
8188 NSMutableArray *essential_;
8189 NSMutableArray *broken_;
8191 Database *database_;
8200 CYStashController *stash_;
8205 - (void) setPage:(CYViewController *)page;
8208 // XXX: I hate prototypes
8209 - (id) queueBadgeController;
8213 @implementation Cydia
8215 - (void) beginUpdate {
8216 [tabbar_ beginUpdate];
8220 return [tabbar_ updating];
8224 if ([broken_ count] != 0) {
8225 int count = [broken_ count];
8227 UIAlertView *alert = [[[UIAlertView alloc]
8228 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8229 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8231 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8232 otherButtonTitles:UCLocalize("TEMPORARY_IGNORE"), nil
8235 [alert setContext:@"fixhalf"];
8237 } else if (!Ignored_ && [essential_ count] != 0) {
8238 int count = [essential_ count];
8240 UIAlertView *alert = [[[UIAlertView alloc]
8241 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8242 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8244 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8245 otherButtonTitles:UCLocalize("UPGRADE_ESSENTIAL"), UCLocalize("COMPLETE_UPGRADE"), nil
8248 [alert setContext:@"upgrade"];
8253 - (void) _saveConfig {
8259 NSString *error(nil);
8261 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8263 NSError *error(nil);
8264 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8265 NSLog(@"failure to save metadata data: %@", error);
8270 NSLog(@"failure to serialize metadata: %@", error);
8275 - (void) _updateData {
8278 [tabbar_ reloadData];
8280 [queueDelegate_ queueStatusDidChange];
8281 [[[self queueBadgeController] tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8284 - (int)indexOfTabWithTag:(int)tag {
8286 for (UINavigationController *controller in [tabbar_ viewControllers]) {
8287 if ([[controller tabBarItem] tag] == tag)
8295 - (void) _refreshIfPossible {
8296 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8298 bool recently = false;
8299 NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
8300 if (update != nil) {
8301 NSTimeInterval interval([update timeIntervalSinceNow]);
8302 if (interval <= 0 && interval > -(15*60))
8306 // Don't automatic refresh if:
8307 // - We already refreshed recently.
8308 // - We already auto-refreshed this launch.
8309 // - Auto-refresh is disabled.
8310 if (recently || loaded_ || ManualRefresh) {
8311 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8313 // If we are cancelling due to ManualRefresh or a recent refresh
8314 // we need to make sure it knows it's already loaded.
8318 // We are going to load, so remember that.
8322 SCNetworkReachabilityFlags flags; {
8323 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8324 SCNetworkReachabilityGetFlags(reachability, &flags);
8325 CFRelease(reachability);
8328 // XXX: this elaborate mess is what Apple is using to determine this? :(
8329 // XXX: do we care if the user has to intervene? maybe that's ok?
8331 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8332 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8333 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8334 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8335 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8336 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8340 // If we can reach the server, auto-refresh!
8342 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8347 - (void) refreshIfPossible {
8348 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
8351 - (void) _reloadData {
8352 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8353 [hud setText:UCLocalize("RELOADING_DATA")];
8355 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
8358 [self removeProgressHUD:hud];
8362 [essential_ removeAllObjects];
8363 [broken_ removeAllObjects];
8365 NSArray *packages([database_ packages]);
8366 for (Package *package in packages) {
8368 [broken_ addObject:package];
8369 if ([package upgradableAndEssential:NO]) {
8370 if ([package essential])
8371 [essential_ addObject:package];
8376 NSLog(@"changes:#%u", changes);
8378 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem];
8381 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8382 [changesItem setBadgeValue:badge];
8383 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8384 [self setApplicationIconBadgeNumber:changes];
8387 [changesItem setBadgeValue:nil];
8388 [changesItem setAnimatedBadge:NO];
8389 [self setApplicationIconBadgeNumber:0];
8394 [self refreshIfPossible];
8397 - (void) updateData {
8406 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8407 _assert(file != NULL);
8409 for (NSString *key in [Sources_ allKeys]) {
8410 NSDictionary *source([Sources_ objectForKey:key]);
8412 fprintf(file, "%s %s %s\n",
8413 [[source objectForKey:@"Type"] UTF8String],
8414 [[source objectForKey:@"URI"] UTF8String],
8415 [[source objectForKey:@"Distribution"] UTF8String]
8423 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8424 CYNavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8426 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8427 [tabbar_ presentModalViewController:navigation animated:YES];
8430 detachNewThreadSelector:@selector(update_)
8433 title:UCLocalize("UPDATING_SOURCES")
8437 - (void) reloadData {
8438 @synchronized (self) {
8444 pkgProblemResolver *resolver = [database_ resolver];
8446 resolver->InstallProtect();
8447 if (!resolver->Resolve(true))
8452 if (![database_ prepare])
8455 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8456 [page setDelegate:self];
8457 CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]);
8458 [confirm_ setDelegate:self];
8461 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8462 [tabbar_ presentModalViewController:confirm_ animated:YES];
8468 @synchronized (self) {
8473 - (void) clearPackage:(Package *)package {
8474 @synchronized (self) {
8481 - (void) installPackages:(NSArray *)packages {
8482 @synchronized (self) {
8483 for (Package *package in packages)
8490 - (void) installPackage:(Package *)package {
8491 @synchronized (self) {
8498 - (void) removePackage:(Package *)package {
8499 @synchronized (self) {
8506 - (void) distUpgrade {
8507 @synchronized (self) {
8508 if (![database_ upgrade])
8515 @synchronized (self) {
8520 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8523 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8525 if (navigation != nil) {
8526 [navigation pushViewController:progress animated:YES];
8528 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8530 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8531 [tabbar_ presentModalViewController:navigation animated:YES];
8535 detachNewThreadSelector:@selector(perform)
8538 title:UCLocalize("RUNNING")
8544 - (void) progressControllerIsComplete:(ProgressController *)progress {
8549 - (void) setPage:(CYViewController *)page {
8550 [page setDelegate:self];
8552 CYNavigationController *navController = (CYNavigationController *) [tabbar_ selectedViewController];
8553 [navController setViewControllers:[NSArray arrayWithObject:page]];
8554 NSLog(@"page: %@ nav: %@", page, navController);
8557 - (void) showSettings {
8558 CYSettingsController *role = [[[CYSettingsController alloc] initWithDatabase:database_ delegate:self] autorelease];
8559 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
8561 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
8562 [tabbar_ presentModalViewController:nav animated:YES];
8565 - (void) retainNetworkActivityIndicator {
8566 if (activity_++ == 0)
8567 [self setNetworkActivityIndicatorVisible:YES];
8570 - (void) releaseNetworkActivityIndicator {
8571 if (--activity_ == 0)
8572 [self setNetworkActivityIndicatorVisible:NO];
8575 - (void) setPackageController:(CYPackageController *)view {
8577 [view setPackage:nil];
8581 // Returns the navigation controller for the queuing badge.
8582 - (id) queueBadgeController {
8583 int index = [self indexOfTabWithTag:kManageTag];
8585 index = [self indexOfTabWithTag:kInstalledTag];
8587 return [[tabbar_ viewControllers] objectAtIndex:index];
8590 - (void) cancelAndClear:(bool)clear {
8591 @synchronized (self) {
8603 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8604 NSString *context([alert context]);
8606 if ([context isEqualToString:@"fixhalf"]) {
8607 if (button == [alert firstOtherButtonIndex]) {
8608 @synchronized (self) {
8609 for (Package *broken in broken_) {
8612 NSString *id = [broken id];
8613 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8614 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8615 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8616 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8622 } else if (button == [alert cancelButtonIndex]) {
8623 [broken_ removeAllObjects];
8627 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8628 } else if ([context isEqualToString:@"upgrade"]) {
8629 if (button == [alert firstOtherButtonIndex]) {
8630 @synchronized (self) {
8631 for (Package *essential in essential_)
8632 [essential install];
8637 } else if (button == [alert firstOtherButtonIndex] + 1) {
8639 } else if (button == [alert cancelButtonIndex]) {
8643 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8647 - (void) system:(NSString *)command { _pooled
8649 system([command UTF8String]);
8653 - (void) applicationWillSuspend {
8655 [super applicationWillSuspend];
8658 - (BOOL) isSafeToSuspend {
8659 // Use external process status API internally.
8660 // This is probably a really bad idea.
8661 // XXX: what is the point of this? does this solve anything at all?
8662 uint64_t status = 0;
8664 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
8665 notify_get_state(notify_token, &status);
8666 notify_cancel(notify_token);
8669 return locked_ == 0 && status == 0;
8672 - (void) applicationSuspend:(__GSEvent *)event {
8673 if ([self isSafeToSuspend])
8674 [super applicationSuspend:event];
8677 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8678 if ([self isSafeToSuspend])
8679 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8682 - (void) _setSuspended:(BOOL)value {
8683 if ([self isSafeToSuspend])
8684 [super _setSuspended:value];
8687 - (UIProgressHUD *) addProgressHUD {
8688 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8689 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8691 [window_ setUserInteractionEnabled:NO];
8694 UIViewController *target = tabbar_;
8695 while ([target modalViewController] != nil) target = [target modalViewController];
8696 [[target view] addSubview:hud];
8702 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8704 [hud removeFromSuperview];
8705 [window_ setUserInteractionEnabled:YES];
8709 - (CYViewController *) pageForPackage:(NSString *)name {
8710 if (Package *package = [database_ packageWithName:name]) {
8711 CYPackageController *view = [[[CYPackageController alloc] initWithDatabase:database_] autorelease];
8712 [view setPackage:package];
8715 NSURL *url([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"unknown" ofType:@"html"]]);
8716 url = [NSURL URLWithString:[[url absoluteString] stringByAppendingString:[NSString stringWithFormat:@"?%@", name]]];
8717 CYBrowserController *browser = [[[CYBrowserController alloc] init] autorelease];
8718 [browser loadURL:url];
8723 - (CYViewController *) pageForURL:(NSURL *)url {
8724 NSString *scheme([[url scheme] lowercaseString]);
8725 if ([[url absoluteString] length] <= [scheme length] + 3)
8727 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
8728 NSArray *components([path pathComponents]);
8730 if ([scheme isEqualToString:@"apptapp"] && [components count] && [[components objectAtIndex:0] isEqualToString:@"package"])
8731 return [self pageForPackage:[components objectAtIndex:1]];
8733 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
8736 NSString *base([components objectAtIndex:0]);
8738 if ([components count] == 1) {
8739 if ([base isEqualToString:@"storage"]) {
8740 CYBrowserController *browser = [[[CYBrowserController alloc] init] autorelease];
8741 [browser loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]]];
8745 if ([base isEqualToString:@"sources"]) {
8746 CYSourcesController *source = [[[CYSourcesController alloc] initWithDatabase:database_] autorelease];
8750 if ([base isEqualToString:@"home"]) {
8751 CYHomeController *home = [[[CYHomeController alloc] init] autorelease];
8755 if ([base isEqualToString:@"sections"]) {
8756 CYSectionsController *sections = [[[CYSectionsController alloc] initWithDatabase:database_] autorelease];
8760 if ([base isEqualToString:@"search"]) {
8761 CYSearchController *search = [[[CYSearchController alloc] initWithDatabase:database_] autorelease];
8765 if ([base isEqualToString:@"changes"]) {
8766 CYChangesController *changes = [[[CYChangesController alloc] initWithDatabase:database_ delegate:self] autorelease];
8770 if ([base isEqualToString:@"installed"]) {
8771 CYInstalledController *installed = [[[CYInstalledController alloc] initWithDatabase:database_] autorelease];
8774 } else if ([components count] == 2) {
8775 NSString *argument = [components objectAtIndex:1];
8777 if ([base isEqualToString:@"package"]) {
8778 CYViewController *package = [self pageForPackage:argument];
8782 if ([base isEqualToString:@"search"]) {
8783 CYSearchController *search = [[[CYSearchController alloc] initWithDatabase:database_] autorelease];
8784 [search setSearchTerm:argument];
8788 if ([base isEqualToString:@"sections"]) {
8789 if ([argument isEqualToString:@"all"])
8791 CYSectionController *section = [[[CYSectionController alloc] initWithDatabase:database_ section:argument] autorelease];
8792 [section setDelegate:self];
8796 if ([base isEqualToString:@"sources"]) {
8797 if ([argument isEqualToString:@"add"]) {
8798 CYSourcesController *source = [[[CYSourcesController alloc] initWithDatabase:database_] autorelease];
8799 [source showAddSourcePrompt];
8802 // XXX: Create page of the source specfified.
8806 if ([base isEqualToString:@"url"]) {
8807 CYBrowserController *browser = [[[CYBrowserController alloc] init] autorelease];
8808 [browser loadURL:[NSURL URLWithString:argument]];
8812 if ([base isEqualToString:@"launch"]) {
8813 [self launchApplicationWithIdentifier:argument suspended:NO];
8815 } else if ([components count] == 3) {
8816 NSString *arg1 = [components objectAtIndex:1];
8817 NSString *arg2 = [components objectAtIndex:2];
8819 if ([base isEqualToString:@"package"]) {
8820 if ([arg2 isEqualToString:@"settings"]) {
8821 return [[[CYPackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
8822 } else if ([arg2 isEqualToString:@"signature"]) {
8823 return [[[SignatureController alloc] initWithDatabase:database_ package:arg1] autorelease];
8824 } else if ([arg2 isEqualToString:@"files"]) {
8825 if (Package *package = [database_ packageWithName:arg1]) {
8826 FileTable *files = [[[FileTable alloc] initWithDatabase:database_] autorelease];
8827 [files setPackage:package];
8837 - (BOOL) openCydiaURL:(NSURL *)url {
8838 CYViewController *page([self pageForURL:url]);
8841 [self setPage:page];
8846 - (void) applicationOpenURL:(NSURL *)url {
8847 [super applicationOpenURL:url];
8849 if (!loaded_) starturl_ = [url retain];
8850 else [self openCydiaURL:url];
8853 - (void) applicationWillResignActive:(UIApplication *)application {
8854 // Stop refreshing if you get a phone call or lock the device.
8855 if ([tabbar_ updating])
8856 [tabbar_ cancelUpdate];
8858 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
8859 [super applicationWillResignActive:application];
8862 - (void) addStashController {
8864 stash_ = [[CYStashController alloc] init];
8865 [window_ addSubview:[stash_ view]];
8868 - (void) removeStashController {
8869 [[stash_ view] removeFromSuperview];
8875 [self setIdleTimerDisabled:YES];
8877 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
8878 [self setStatusBarShowsProgress:YES];
8879 UpdateExternalStatus(1);
8881 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
8883 UpdateExternalStatus(0);
8884 [self setStatusBarShowsProgress:NO];
8886 [self removeStashController];
8888 if (ExecFork() == 0) {
8889 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
8890 perror("launchctl stop");
8894 - (void) setupViewControllers {
8895 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
8896 [tabbar_ setDelegate:self];
8898 NSMutableArray *items([NSMutableArray arrayWithObjects:
8899 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:kCydiaTag] autorelease],
8900 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:kSectionsTag] autorelease],
8901 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:kChangesTag] autorelease],
8902 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:kSearchTag] autorelease],
8905 NSMutableArray *pages([NSMutableArray arrayWithObjects:
8906 [[[CYHomeController alloc] init] autorelease],
8907 [[[CYSectionsController alloc] initWithDatabase:database_] autorelease],
8908 [[[CYChangesController alloc] initWithDatabase:database_ delegate:self] autorelease],
8909 [[[CYSearchController alloc] initWithDatabase:database_] autorelease],
8913 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:kSourcesTag] autorelease] atIndex:3];
8914 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:kInstalledTag] autorelease] atIndex:3];
8915 [pages insertObject:[[[CYSourcesController alloc] initWithDatabase:database_] autorelease] atIndex:3];
8916 [pages insertObject:[[[CYInstalledController alloc] initWithDatabase:database_] autorelease] atIndex:3];
8917 queueDelegate_ = [pages objectAtIndex:3];
8919 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:kManageTag] autorelease] atIndex:3];
8920 [pages insertObject:[[[CYManageController alloc] init] autorelease] atIndex:3];
8921 queueDelegate_ = [pages objectAtIndex:3];
8924 NSMutableArray *controllers([NSMutableArray array]);
8926 for (unsigned int i = 0; i < [pages count]; i++) {
8927 UITabBarItem *item = [items objectAtIndex:i];
8928 CYViewController *page = [pages objectAtIndex:i];
8929 [page setDelegate:self];
8931 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
8932 [controller setViewControllers:[NSArray arrayWithObject:page]];
8933 [controller setTabBarItem:item];
8934 [controllers addObject:controller];
8937 [tabbar_ setViewControllers:controllers];
8938 [tabbar_ setUpdateDelegate:self];
8939 [window_ addSubview:[tabbar_ view]];
8942 - (void)showEmulatedLoadingControllerInView:(UIView *)view {
8943 static CYEmulatedLoadingController *fake = [[CYEmulatedLoadingController alloc] init];
8945 [view addSubview:[fake view]];
8947 [[fake view] removeFromSuperview];
8951 - (void) applicationDidFinishLaunching:(id)unused {
8955 [NSURLCache setSharedURLCache:[[[SDURLCache alloc]
8956 initWithMemoryCapacity:524288
8957 diskCapacity:10485760
8958 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
8961 [CYBrowserController _initialize];
8963 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8965 Font12_ = [[UIFont systemFontOfSize:12] retain];
8966 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8967 Font14_ = [[UIFont systemFontOfSize:14] retain];
8968 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8969 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8971 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8972 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8974 window_ = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
8975 [window_ orderFront:self];
8976 [window_ makeKey:self];
8977 [window_ setHidden:NO];
8980 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8981 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8982 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8983 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
8984 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8985 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8986 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8987 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
8988 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
8991 [self addStashController];
8992 // XXX: this would be much cleaner as a yieldToSelector:
8993 // that way the removeStashController could happen right here inline
8994 // we also could no longer require the useless stash_ field anymore
8995 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
8999 database_ = [Database sharedInstance];
9001 [self showEmulatedLoadingControllerInView:window_];
9003 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9010 [self showSettings];
9014 [window_ setUserInteractionEnabled:NO];
9017 [window_ setUserInteractionEnabled:YES];
9019 [self setupViewControllers];
9020 [tabbar_ setSelectedIndex:0];
9021 [self showEmulatedLoadingControllerInView:nil];
9022 // XXX: does this actually slow anything down?
9023 [[tabbar_ view] setBackgroundColor:[UIColor clearColor]];
9025 // Show the initial page
9026 if (starturl_ != nil) {
9027 [self openCydiaURL:starturl_];
9028 [starturl_ release];
9033 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9034 if (item != nil && IsWildcat_) {
9035 [sheet showFromBarButtonItem:item animated:YES];
9037 [sheet showInView:window_];
9044 id Alloc_(id self, SEL selector) {
9045 id object = alloc_(self, selector);
9046 lprintf("[%s]A-%p\n", self->isa->name, object);
9051 id Dealloc_(id self, SEL selector) {
9052 id object = dealloc_(self, selector);
9053 lprintf("[%s]D-%p\n", self->isa->name, object);
9057 Class $WebDefaultUIKitDelegate;
9059 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9060 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9061 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9062 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9065 static NSNumber *shouldPlayKeyboardSounds;
9069 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
9071 case 1104: // Keyboard Button Clicked
9072 case 1105: // Keyboard Delete Repeated
9073 if (shouldPlayKeyboardSounds == nil) {
9074 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
9075 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
9078 if (![shouldPlayKeyboardSounds boolValue])
9082 _UIHardware$_playSystemSound$(self, _cmd, sound);
9086 int main(int argc, char *argv[]) { _pooled
9089 if (Class $UIDevice = objc_getClass("UIDevice")) {
9090 UIDevice *device([$UIDevice currentDevice]);
9091 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
9095 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9097 /* Library Hacks {{{ */
9098 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
9100 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
9101 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
9102 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
9103 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
9104 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
9107 $UIHardware = objc_getClass("UIHardware");
9108 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
9109 if (UIHardware$_playSystemSound$ != NULL) {
9110 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
9111 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
9114 /* Set Locale {{{ */
9115 Locale_ = CFLocaleCopyCurrent();
9116 Languages_ = [NSLocale preferredLanguages];
9117 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
9118 //NSLog(@"%@", [Languages_ description]);
9121 if (Languages_ == nil || [Languages_ count] == 0)
9122 // XXX: consider just setting to C and then falling through?
9125 lang = [[Languages_ objectAtIndex:0] UTF8String];
9126 setenv("LANG", lang, true);
9129 //std::setlocale(LC_ALL, lang);
9130 NSLog(@"Setting Language: %s", lang);
9133 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
9135 /* Parse Arguments {{{ */
9136 bool substrate(false);
9142 for (int argi(1); argi != argc; ++argi)
9143 if (strcmp(argv[argi], "--") == 0) {
9145 argv[argi] = argv[0];
9151 for (int argi(1); argi != arge; ++argi)
9152 if (strcmp(args[argi], "--substrate") == 0)
9155 fprintf(stderr, "unknown argument: %s\n", args[argi]);
9159 App_ = [[NSBundle mainBundle] bundlePath];
9160 Home_ = NSHomeDirectory();
9166 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
9167 alloc_ = alloc->method_imp;
9168 alloc->method_imp = (IMP) &Alloc_;*/
9170 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
9171 dealloc_ = dealloc->method_imp;
9172 dealloc->method_imp = (IMP) &Dealloc_;*/
9174 /* System Information {{{ */
9178 size = sizeof(maxproc);
9179 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9180 perror("sysctlbyname(\"kern.maxproc\", ?)");
9181 else if (maxproc < 64) {
9183 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9184 perror("sysctlbyname(\"kern.maxproc\", #)");
9187 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
9188 char *osversion = new char[size];
9189 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
9190 perror("sysctlbyname(\"kern.osversion\", ?)");
9192 System_ = [NSString stringWithUTF8String:osversion];
9194 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
9195 char *machine = new char[size];
9196 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
9197 perror("sysctlbyname(\"hw.machine\", ?)");
9201 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
9202 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
9203 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
9204 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
9208 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
9209 NSData *data((NSData *) ecid);
9210 size_t length([data length]);
9211 uint8_t bytes[length];
9212 [data getBytes:bytes];
9213 char string[length * 2 + 1];
9214 for (size_t i(0); i != length; ++i)
9215 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
9216 ChipID_ = [NSString stringWithUTF8String:string];
9220 IOObjectRelease(service);
9224 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
9226 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
9227 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9228 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
9230 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
9231 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9232 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
9234 if (mcc != NULL && mnc != NULL)
9235 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9242 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9243 Build_ = [system objectForKey:@"ProductBuildVersion"];
9244 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9245 Product_ = [info objectForKey:@"SafariProductVersion"];
9246 Safari_ = [info objectForKey:@"CFBundleVersion"];
9249 /* Load Database {{{ */
9251 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9253 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9255 if (Metadata_ == NULL)
9256 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9258 Settings_ = [Metadata_ objectForKey:@"Settings"];
9260 Packages_ = [Metadata_ objectForKey:@"Packages"];
9261 Sections_ = [Metadata_ objectForKey:@"Sections"];
9262 Sources_ = [Metadata_ objectForKey:@"Sources"];
9264 Token_ = [Metadata_ objectForKey:@"Token"];
9267 if (Settings_ != nil)
9268 Role_ = [Settings_ objectForKey:@"Role"];
9270 if (Sections_ == nil) {
9271 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9272 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9275 if (Sources_ == nil) {
9276 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9277 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9282 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
9285 if (Packages_ != nil) {
9286 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, NULL);
9288 [Metadata_ removeObjectForKey:@"Packages"];
9293 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9295 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", F_OK) == 0)
9296 dlopen("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", RTLD_LAZY | RTLD_GLOBAL);
9297 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
9298 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
9299 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9300 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9302 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9304 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9305 unlink("/tmp/.cydia.fw");
9307 } else if (access("/User", F_OK) != 0 || version < 2) {
9310 system("/usr/libexec/cydia/firmware.sh");
9314 _assert([[NSFileManager defaultManager]
9315 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9316 withIntermediateDirectories:YES
9321 if (access("/tmp/cydia.chk", F_OK) == 0) {
9322 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9323 _assert(errno == ENOENT);
9324 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9325 _assert(errno == ENOENT);
9328 /* APT Initialization {{{ */
9329 _assert(pkgInitConfig(*_config));
9330 _assert(pkgInitSystem(*_config, _system));
9333 _config->Set("APT::Acquire::Translation", lang);
9335 // XXX: this timeout might be important :(
9336 //_config->Set("Acquire::http::Timeout", 15);
9338 _config->Set("Acquire::http::MaxParallel", 3);
9340 /* Color Choices {{{ */
9341 space_ = CGColorSpaceCreateDeviceRGB();
9343 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9344 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9345 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9346 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9347 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9348 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9349 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9350 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9351 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9353 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9354 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9356 /* UIKit Configuration {{{ */
9357 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9358 if ($GSFontSetUseLegacyFontMetrics != NULL)
9359 $GSFontSetUseLegacyFontMetrics(YES);
9361 // XXX: I have a feeling this was important
9362 //UIKeyboardDisableAutomaticAppearance();
9365 Colon_ = UCLocalize("COLON_DELIMITED");
9366 Elision_ = UCLocalize("ELISION");
9367 Error_ = UCLocalize("ERROR");
9368 Warning_ = UCLocalize("WARNING");
9371 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9373 CGColorSpaceRelease(space_);