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 PackageController;
1184 @protocol CydiaDelegate
1185 - (void) retainNetworkActivityIndicator;
1186 - (void) releaseNetworkActivityIndicator;
1187 - (void) setPackageController:(PackageController *)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 - (PackageController *) packageController;
1203 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
1206 static id<CydiaDelegate> CydiaApp;
1209 /* Status Delegation {{{ */
1211 public pkgAcquireStatus
1214 _transient NSObject<ProgressDelegate> *delegate_;
1222 void setDelegate(id delegate) {
1223 delegate_ = delegate;
1226 NSObject<ProgressDelegate> *getDelegate() const {
1230 virtual bool MediaChange(std::string media, std::string drive) {
1234 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1237 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1238 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1239 [delegate_ setProgressTitle:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), [NSString stringWithUTF8String:item.ShortDesc.c_str()]]];
1242 virtual void Done(pkgAcquire::ItemDesc &item) {
1245 virtual void Fail(pkgAcquire::ItemDesc &item) {
1247 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1248 item.Owner->Status == pkgAcquire::Item::StatDone
1252 std::string &error(item.Owner->ErrorText);
1256 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1257 NSArray *fields([description componentsSeparatedByString:@" "]);
1258 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1260 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
1261 withObject:[NSArray arrayWithObjects:
1262 [NSString stringWithUTF8String:error.c_str()],
1269 virtual bool Pulse(pkgAcquire *Owner) {
1270 bool value = pkgAcquireStatus::Pulse(Owner);
1273 double(CurrentBytes + CurrentItems) /
1274 double(TotalBytes + TotalItems)
1277 [delegate_ setProgressPercent:percent];
1278 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1281 virtual void Start() {
1282 [delegate_ startProgress];
1285 virtual void Stop() {
1289 /* Progress Delegation {{{ */
1294 _transient id<ProgressDelegate> delegate_;
1298 virtual void Update() {
1299 /*if (abs(Percent - percent_) > 2)
1300 //NSLog(@"%s:%s:%f", Op.c_str(), SubOp.c_str(), Percent);
1304 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1305 [delegate_ setProgressPercent:(Percent / 100)];*/
1315 void setDelegate(id delegate) {
1316 delegate_ = delegate;
1319 id getDelegate() const {
1323 virtual void Done() {
1325 //[delegate_ setProgressPercent:1];
1330 /* Database Interface {{{ */
1331 typedef std::map< unsigned long, _H<Source> > SourceMap;
1333 @interface Database : NSObject {
1339 pkgCacheFile cache_;
1340 pkgDepCache::Policy *policy_;
1341 pkgRecords *records_;
1342 pkgProblemResolver *resolver_;
1343 pkgAcquire *fetcher_;
1345 SPtr<pkgPackageManager> manager_;
1346 pkgSourceList *list_;
1349 CFMutableArrayRef packages_;
1351 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1359 std::map<const char *, _H<NSString> > sections_;
1362 + (Database *) sharedInstance;
1365 - (void) _readCydia:(NSNumber *)fd;
1366 - (void) _readStatus:(NSNumber *)fd;
1367 - (void) _readOutput:(NSNumber *)fd;
1371 - (Package *) packageWithName:(NSString *)name;
1373 - (pkgCacheFile &) cache;
1374 - (pkgDepCache::Policy *) policy;
1375 - (pkgRecords *) records;
1376 - (pkgProblemResolver *) resolver;
1377 - (pkgAcquire &) fetcher;
1378 - (pkgSourceList &) list;
1379 - (NSArray *) packages;
1380 - (NSArray *) sources;
1381 - (void) reloadData;
1389 - (void) updateWithStatus:(Status &)status;
1391 - (void) setDelegate:(id)delegate;
1392 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1394 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1398 /* Delegate Helpers {{{ */
1399 @implementation NSObject (ProgressDelegate)
1401 - (void) _setProgressErrorPackage:(NSArray *)args {
1402 [self performSelector:@selector(setProgressError:forPackage:)
1403 withObject:[args objectAtIndex:0]
1404 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1408 - (void) _setProgressErrorTitle:(NSArray *)args {
1409 [self performSelector:@selector(setProgressError:withTitle:)
1410 withObject:[args objectAtIndex:0]
1411 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1415 - (void) _setProgressError:(NSString *)error withTitle:(NSString *)title {
1416 [self performSelectorOnMainThread:@selector(_setProgressErrorTitle:)
1417 withObject:[NSArray arrayWithObjects:error, title, nil]
1422 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
1423 Package *package = id == nil ? nil : [[Database sharedInstance] packageWithName:id];
1425 [self performSelector:@selector(setProgressError:withTitle:)
1427 withObject:(package == nil ? id : [package name])
1434 // Cytore Definitions {{{
1435 struct PackageValue :
1438 Cytore::Offset<PackageValue> next_;
1440 uint32_t index_ : 23;
1441 uint32_t subscribed_ : 1;
1458 Cytore::Offset<PackageValue> packages_[1 << 16];
1461 static Cytore::File<MetaValue> MetaFile_;
1463 // Cytore Helper Functions {{{
1464 static PackageValue *PackageFind(const char *name, size_t length) {
1465 SplitHash nhash = { hashlittle(name, length) };
1467 PackageValue *metadata;
1469 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1470 offset: if (offset->IsNull()) {
1471 *offset = MetaFile_.New<PackageValue>(length + 1);
1472 metadata = &MetaFile_.Get(*offset);
1474 memcpy(metadata->name_, name, length + 1);
1475 metadata->nhash_ = nhash.u16[1];
1477 metadata = &MetaFile_.Get(*offset);
1479 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1480 offset = &metadata->next_;
1488 static void PackageImport(const void *key, const void *value, void *context) {
1490 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1491 NSLog(@"failed to import package %@", key);
1495 PackageValue *metadata(PackageFind(buffer, strlen(buffer)));
1496 NSDictionary *package((NSDictionary *) value);
1498 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1499 if ([subscribed boolValue] && !metadata->subscribed_)
1500 metadata->subscribed_ = true;
1502 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1503 time_t time([date timeIntervalSince1970]);
1504 if (metadata->first_ > time || metadata->first_ == 0)
1505 metadata->first_ = time;
1508 NSDate *date([package objectForKey:@"LastSeen"]);
1509 NSString *version([package objectForKey:@"LastVersion"]);
1511 if (date != nil && version != nil) {
1512 time_t time([date timeIntervalSince1970]);
1513 if (metadata->last_ < time || metadata->last_ == 0)
1514 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1515 size_t length(strlen(buffer));
1516 uint16_t vhash(hashlittle(buffer, length));
1518 size_t capped(std::min<size_t>(8, length));
1519 char *latest(buffer + length - capped);
1521 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1522 metadata->vhash_ = vhash;
1524 metadata->last_ = time;
1530 /* Source Class {{{ */
1531 @interface Source : NSObject {
1532 CYString depiction_;
1533 CYString description_;
1539 CYString distribution_;
1544 NSString *authority_;
1546 CYString defaultIcon_;
1548 NSDictionary *record_;
1552 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1554 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1556 - (NSString *) depictionForPackage:(NSString *)package;
1557 - (NSString *) supportForPackage:(NSString *)package;
1559 - (NSDictionary *) record;
1563 - (NSString *) distribution;
1564 - (NSString *) type;
1566 - (NSString *) host;
1568 - (NSString *) name;
1569 - (NSString *) description;
1570 - (NSString *) label;
1571 - (NSString *) origin;
1572 - (NSString *) version;
1574 - (NSString *) defaultIcon;
1578 @implementation Source
1582 distribution_.clear();
1585 description_.clear();
1591 defaultIcon_.clear();
1593 if (record_ != nil) {
1603 if (authority_ != nil) {
1604 [authority_ release];
1610 // XXX: this is a very inefficient way to call these deconstructors
1615 + (NSArray *) _attributeKeys {
1616 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1619 - (NSArray *) attributeKeys {
1620 return [[self class] _attributeKeys];
1623 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1624 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1627 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1630 trusted_ = index->IsTrusted();
1632 uri_.set(pool, index->GetURI());
1633 distribution_.set(pool, index->GetDist());
1634 type_.set(pool, index->GetType());
1636 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1637 if (dindex != NULL) {
1639 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1642 pkgTagFile tags(&fd);
1644 pkgTagSection section;
1651 {"default-icon", &defaultIcon_},
1652 {"depiction", &depiction_},
1653 {"description", &description_},
1655 {"origin", &origin_},
1656 {"support", &support_},
1657 {"version", &version_},
1660 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1661 const char *start, *end;
1663 if (section.Find(names[i].name_, start, end)) {
1664 CYString &value(*names[i].value_);
1665 value.set(pool, start, end - start);
1671 record_ = [Sources_ objectForKey:[self key]];
1673 record_ = [record_ retain];
1675 NSURL *url([NSURL URLWithString:uri_]);
1679 host_ = [[host_ lowercaseString] retain];
1684 authority_ = [url path];
1686 if (authority_ != nil)
1687 authority_ = [authority_ retain];
1690 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1691 if ((self = [super init]) != nil) {
1692 [self setMetaIndex:index inPool:pool];
1696 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1697 NSDictionary *lhr = [self record];
1698 NSDictionary *rhr = [source record];
1701 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1703 NSString *lhs = [self name];
1704 NSString *rhs = [source name];
1706 if ([lhs length] != 0 && [rhs length] != 0) {
1707 unichar lhc = [lhs characterAtIndex:0];
1708 unichar rhc = [rhs characterAtIndex:0];
1710 if (isalpha(lhc) && !isalpha(rhc))
1711 return NSOrderedAscending;
1712 else if (!isalpha(lhc) && isalpha(rhc))
1713 return NSOrderedDescending;
1716 return [lhs compare:rhs options:LaxCompareOptions_];
1719 - (NSString *) depictionForPackage:(NSString *)package {
1720 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1723 - (NSString *) supportForPackage:(NSString *)package {
1724 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1727 - (NSDictionary *) record {
1735 - (NSString *) uri {
1739 - (NSString *) distribution {
1740 return distribution_;
1743 - (NSString *) type {
1747 - (NSString *) key {
1748 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1751 - (NSString *) host {
1755 - (NSString *) name {
1756 return origin_.empty() ? authority_ : origin_;
1759 - (NSString *) description {
1760 return description_;
1763 - (NSString *) label {
1764 return label_.empty() ? authority_ : label_;
1767 - (NSString *) origin {
1771 - (NSString *) version {
1775 - (NSString *) defaultIcon {
1776 return defaultIcon_;
1781 /* Relationship Class {{{ */
1782 @interface Relationship : NSObject {
1787 - (NSString *) type;
1789 - (NSString *) name;
1793 @implementation Relationship
1801 - (NSString *) type {
1809 - (NSString *) name {
1816 /* Package Class {{{ */
1817 struct ParsedPackage {
1822 CYString depiction_;
1832 @interface Package : NSObject {
1835 uint32_t essential_ : 1;
1836 uint32_t obsolete_ : 1;
1837 uint32_t ignored_ : 1;
1841 _transient Database *database_;
1843 pkgCache::VerIterator version_;
1844 pkgCache::PkgIterator iterator_;
1845 pkgCache::VerFileIterator file_;
1851 CYString installed_;
1853 const char *section_;
1854 _transient NSString *section$_;
1858 PackageValue *metadata_;
1859 ParsedPackage *parsed_;
1861 NSMutableArray *tags_;
1864 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1865 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1867 - (pkgCache::PkgIterator) iterator;
1870 - (NSString *) section;
1871 - (NSString *) simpleSection;
1873 - (NSString *) longSection;
1874 - (NSString *) shortSection;
1878 - (Address *) maintainer;
1880 - (NSString *) longDescription;
1881 - (NSString *) shortDescription;
1884 - (PackageValue *) metadata;
1887 - (bool) subscribed;
1888 - (bool) setSubscribed:(bool)subscribed;
1892 - (NSString *) latest;
1893 - (NSString *) installed;
1894 - (BOOL) uninstalled;
1897 - (BOOL) upgradableAndEssential:(BOOL)essential;
1900 - (BOOL) unfiltered;
1904 - (BOOL) halfConfigured;
1905 - (BOOL) halfInstalled;
1907 - (NSString *) mode;
1910 - (NSString *) name;
1912 - (NSString *) homepage;
1913 - (NSString *) depiction;
1914 - (Address *) author;
1916 - (NSString *) support;
1918 - (NSArray *) files;
1919 - (NSArray *) warnings;
1920 - (NSArray *) applications;
1922 - (Source *) source;
1924 - (BOOL) matches:(NSString *)text;
1926 - (bool) hasSupportingRole;
1927 - (BOOL) hasTag:(NSString *)tag;
1928 - (NSString *) primaryPurpose;
1929 - (NSArray *) purposes;
1930 - (bool) isCommercial;
1932 - (void) setIndex:(size_t)index;
1934 - (CYString &) cyname;
1936 - (uint32_t) compareBySection:(NSArray *)sections;
1941 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1942 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1943 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1944 - (bool) isVisibleInSection:(NSString *)section;
1945 - (bool) isVisibleInSource:(Source *)source;
1949 uint32_t PackageChangesRadix(Package *self, void *) {
1954 uint32_t timestamp : 30;
1955 uint32_t ignored : 1;
1956 uint32_t upgradable : 1;
1960 bool upgradable([self upgradableAndEssential:YES]);
1961 value.bits.upgradable = upgradable ? 1 : 0;
1964 value.bits.timestamp = 0;
1965 value.bits.ignored = [self ignored] ? 0 : 1;
1966 value.bits.upgradable = 1;
1968 value.bits.timestamp = [self seen] >> 2;
1969 value.bits.ignored = 0;
1970 value.bits.upgradable = 0;
1973 return _not(uint32_t) - value.key;
1976 uint32_t PackagePrefixRadix(Package *self, void *context) {
1977 size_t offset(reinterpret_cast<size_t>(context));
1978 CYString &name([self cyname]);
1980 size_t size(name.size());
1983 char *text(name.data());
1986 if (!isdigit(text[0]))
1990 while (size != digits && isdigit(text[digits]))
1998 if (offset == 0 && zeros != 0) {
1999 memset(data, '0', zeros);
2000 memcpy(data + zeros, text, 4 - zeros);
2002 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2003 if (size <= offset - zeros)
2006 text += offset - zeros;
2007 size -= offset - zeros;
2010 memcpy(data, text, 4);
2012 memcpy(data, text, size);
2013 memset(data + size, 0, 4 - size);
2016 for (size_t i(0); i != 4; ++i)
2017 if (isalpha(data[i]))
2025 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2027 /* XXX: ntohl may be more honest */
2028 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2031 CYString &(*PackageName)(Package *self, SEL sel);
2033 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2034 _profile(PackageNameCompare)
2035 CYString &lhi(PackageName(lhs, @selector(cyname)));
2036 CYString &rhi(PackageName(rhs, @selector(cyname)));
2037 CFStringRef lhn(lhi), rhn(rhi);
2040 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2041 else if (rhn == NULL)
2042 return NSOrderedDescending;
2044 _profile(PackageNameCompare$NumbersLast)
2045 if (!lhi.empty() && !rhi.empty()) {
2046 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2047 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2048 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2049 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2050 return lha ? NSOrderedAscending : NSOrderedDescending;
2054 CFIndex length = CFStringGetLength(lhn);
2056 _profile(PackageNameCompare$Compare)
2057 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2062 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2063 return PackageNameCompare(*lhs, *rhs, context);
2066 struct PackageNameOrdering :
2067 std::binary_function<Package *, Package *, bool>
2069 _finline bool operator ()(Package *lhs, Package *rhs) const {
2070 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2074 @implementation Package
2076 - (NSString *) description {
2077 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2081 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_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2221 if (strcmp(name + 6, "enduser") == 0)
2223 else if (strcmp(name + 6, "hacker") == 0)
2225 else if (strcmp(name + 6, "developer") == 0)
2227 else if (strcmp(name + 6, "cydia") == 0)
2233 if (strncmp(name, "cydia::", 7) == 0) {
2234 if (strcmp(name + 7, "essential") == 0)
2236 else if (strcmp(name + 7, "obsolete") == 0)
2241 } while (!tag.end());
2245 _profile(Package$initWithVersion$Metadata)
2246 const char *mixed(iterator.Name());
2247 size_t size(strlen(mixed));
2248 char lower[size + 1];
2250 for (size_t i(0); i != size; ++i)
2251 lower[i] = mixed[i] | 0x20;
2254 PackageValue *metadata(PackageFind(lower, size));
2255 metadata_ = metadata;
2257 id_.set(NULL, metadata->name_, size);
2259 const char *latest(version_.VerStr());
2260 size_t length(strlen(latest));
2262 uint16_t vhash(hashlittle(latest, length));
2264 size_t capped(std::min<size_t>(8, length));
2265 latest = latest + length - capped;
2267 if (metadata->first_ == 0)
2268 metadata->first_ = now_;
2270 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2271 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2272 metadata->vhash_ = vhash;
2273 metadata->last_ = now_;
2274 } else if (metadata->last_ == 0)
2275 metadata->last_ = metadata->first_;
2278 _profile(Package$initWithVersion$Section)
2279 section_ = iterator.Section();
2282 _profile(Package$initWithVersion$Flags)
2283 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2284 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2289 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2290 pkgCache::VerIterator version;
2292 _profile(Package$packageWithIterator$GetCandidateVer)
2293 version = [database policy]->GetCandidateVer(iterator);
2301 _profile(Package$packageWithIterator$Allocate)
2302 package = [Package allocWithZone:zone];
2305 _profile(Package$packageWithIterator$Initialize)
2307 initWithVersion:version
2314 _profile(Package$packageWithIterator$Autorelease)
2315 package = [package autorelease];
2321 - (pkgCache::PkgIterator) iterator {
2325 - (NSString *) section {
2326 if (section$_ == nil) {
2327 if (section_ == NULL)
2330 _profile(Package$section$mappedSectionForPointer)
2331 section$_ = [database_ mappedSectionForPointer:section_];
2336 - (NSString *) simpleSection {
2337 if (NSString *section = [self section])
2338 return Simplify(section);
2343 - (NSString *) longSection {
2344 return LocalizeSection([self section]);
2347 - (NSString *) shortSection {
2348 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2351 - (NSString *) uri {
2354 pkgIndexFile *index;
2355 pkgCache::PkgFileIterator file(file_.File());
2356 if (![database_ list].FindIndex(file, index))
2358 return [NSString stringWithUTF8String:iterator_->Path];
2359 //return [NSString stringWithUTF8String:file.Site()];
2360 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2364 - (Address *) maintainer {
2365 @synchronized (database_) {
2366 if ([database_ era] != era_ || file_.end())
2369 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2370 const std::string &maintainer(parser->Maintainer());
2371 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2375 @synchronized (database_) {
2376 if ([database_ era] != era_ || version_.end())
2379 return version_->InstalledSize;
2382 - (NSString *) longDescription {
2383 @synchronized (database_) {
2384 if ([database_ era] != era_ || file_.end())
2387 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2388 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2390 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2391 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2392 if ([lines count] < 2)
2395 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2396 for (size_t i(1), e([lines count]); i != e; ++i) {
2397 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2398 [trimmed addObject:trim];
2401 return [trimmed componentsJoinedByString:@"\n"];
2404 - (NSString *) shortDescription {
2405 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2409 _profile(Package$index)
2410 CFStringRef name((CFStringRef) [self name]);
2411 if (CFStringGetLength(name) == 0)
2413 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2414 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2416 return toupper(character);
2420 - (PackageValue *) metadata {
2425 PackageValue *metadata([self metadata]);
2426 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2429 - (bool) subscribed {
2430 return [self metadata]->subscribed_;
2433 - (bool) setSubscribed:(bool)subscribed {
2434 PackageValue *metadata([self metadata]);
2435 if (metadata->subscribed_ == subscribed)
2437 metadata->subscribed_ = subscribed;
2445 - (NSString *) latest {
2449 - (NSString *) installed {
2453 - (BOOL) uninstalled {
2454 return installed_.empty();
2458 return !version_.end();
2461 - (BOOL) upgradableAndEssential:(BOOL)essential {
2462 _profile(Package$upgradableAndEssential)
2463 pkgCache::VerIterator current(iterator_.CurrentVer());
2465 return essential && essential_;
2467 return !version_.end() && version_ != current;
2471 - (BOOL) essential {
2476 return [database_ cache][iterator_].InstBroken();
2479 - (BOOL) unfiltered {
2480 _profile(Package$unfiltered$obsolete)
2481 if (_unlikely(obsolete_))
2485 _profile(Package$unfiltered$hasSupportingRole)
2486 if (_unlikely(![self hasSupportingRole]))
2494 if (![self unfiltered])
2499 _profile(Package$visible$section)
2500 section = [self section];
2503 _profile(Package$visible$isSectionVisible)
2504 if (section != nil && !isSectionVisible(section))
2512 unsigned char current(iterator_->CurrentState);
2513 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2516 - (BOOL) halfConfigured {
2517 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2520 - (BOOL) halfInstalled {
2521 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2525 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2526 return state.Mode != pkgDepCache::ModeKeep;
2529 - (NSString *) mode {
2530 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2532 switch (state.Mode) {
2533 case pkgDepCache::ModeDelete:
2534 if ((state.iFlags & pkgDepCache::Purge) != 0)
2538 case pkgDepCache::ModeKeep:
2539 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2540 return @"REINSTALL";
2541 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2545 case pkgDepCache::ModeInstall:
2546 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2547 return @"REINSTALL";
2548 else*/ switch (state.Status) {
2550 return @"DOWNGRADE";
2556 return @"NEW_INSTALL";
2567 - (NSString *) name {
2568 return name_.empty() ? id_ : name_;
2571 - (UIImage *) icon {
2572 NSString *section = [self simpleSection];
2575 if (parsed_ != NULL)
2576 if (NSString *href = parsed_->icon_)
2577 if ([href hasPrefix:@"file:///"])
2578 // XXX: correct escaping
2579 icon = [UIImage imageAtPath:[href substringFromIndex:7]];
2580 if (icon == nil) if (section != nil)
2581 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2582 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2583 if ([dicon hasPrefix:@"file:///"])
2584 // XXX: correct escaping
2585 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2587 icon = [UIImage applicationImageNamed:@"unknown.png"];
2591 - (NSString *) homepage {
2592 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2595 - (NSString *) depiction {
2596 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2599 - (Address *) sponsor {
2600 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [Address addressWithString:parsed_->sponsor_];
2603 - (Address *) author {
2604 return parsed_ == NULL || parsed_->author_.empty() ? nil : [Address addressWithString:parsed_->author_];
2607 - (NSString *) support {
2608 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2611 - (NSArray *) files {
2612 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2613 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2616 fin.open([path UTF8String]);
2621 while (std::getline(fin, line))
2622 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2627 - (NSArray *) warnings {
2628 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2629 const char *name(iterator_.Name());
2631 size_t length(strlen(name));
2632 if (length < 2) invalid:
2633 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2634 else for (size_t i(0); i != length; ++i)
2636 /* XXX: technically this is not allowed */
2637 (name[i] < 'A' || name[i] > 'Z') &&
2638 (name[i] < 'a' || name[i] > 'z') &&
2639 (name[i] < '0' || name[i] > '9') &&
2640 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2643 if (strcmp(name, "cydia") != 0) {
2646 bool _private = false;
2649 bool repository = [[self section] isEqualToString:@"Repositories"];
2651 if (NSArray *files = [self files])
2652 for (NSString *file in files)
2653 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2655 else if (!user && [file isEqualToString:@"/User"])
2657 else if (!_private && [file isEqualToString:@"/private"])
2659 else if (!stash && [file isEqualToString:@"/var/stash"])
2662 /* XXX: this is not sensitive enough. only some folders are valid. */
2663 if (cydia && !repository)
2664 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2666 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2668 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2670 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2673 return [warnings count] == 0 ? nil : warnings;
2676 - (NSArray *) applications {
2677 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2679 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2681 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2682 if (NSArray *files = [self files])
2683 for (NSString *file in files)
2684 if (application_r(file)) {
2685 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2686 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2687 if ([id isEqualToString:me])
2690 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2692 display = application_r[1];
2694 NSString *bundle([file stringByDeletingLastPathComponent]);
2695 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2696 if (icon == nil || [icon length] == 0)
2698 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2700 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2701 [applications addObject:application];
2703 [application addObject:id];
2704 [application addObject:display];
2705 [application addObject:url];
2708 return [applications count] == 0 ? nil : applications;
2711 - (Source *) source {
2712 if (source_ == nil) {
2713 @synchronized (database_) {
2714 if ([database_ era] != era_ || file_.end())
2715 source_ = (Source *) [NSNull null];
2717 source_ = [([database_ getSource:file_.File()] ?: (Source *) [NSNull null]) retain];
2721 return source_ == (Source *) [NSNull null] ? nil : source_;
2724 - (BOOL) matches:(NSString *)text {
2730 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2731 if (range.location != NSNotFound)
2734 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2735 if (range.location != NSNotFound)
2738 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2739 if (range.location != NSNotFound)
2745 - (bool) hasSupportingRole {
2750 if ([Role_ isEqualToString:@"User"])
2754 if ([Role_ isEqualToString:@"Hacker"])
2758 if ([Role_ isEqualToString:@"Developer"])
2763 - (BOOL) hasTag:(NSString *)tag {
2764 return tags_ == nil ? NO : [tags_ containsObject:tag];
2767 - (NSString *) primaryPurpose {
2768 for (NSString *tag in tags_)
2769 if ([tag hasPrefix:@"purpose::"])
2770 return [tag substringFromIndex:9];
2774 - (NSArray *) purposes {
2775 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2776 for (NSString *tag in tags_)
2777 if ([tag hasPrefix:@"purpose::"])
2778 [purposes addObject:[tag substringFromIndex:9]];
2779 return [purposes count] == 0 ? nil : purposes;
2782 - (bool) isCommercial {
2783 return [self hasTag:@"cydia::commercial"];
2786 - (void) setIndex:(size_t)index {
2787 if (metadata_->index_ != index)
2788 metadata_->index_ = index;
2791 - (CYString &) cyname {
2792 return name_.empty() ? id_ : name_;
2795 - (uint32_t) compareBySection:(NSArray *)sections {
2796 NSString *section([self section]);
2797 for (size_t i(0), e([sections count]); i != e; ++i) {
2798 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2802 return _not(uint32_t);
2806 @synchronized (database_) {
2807 pkgProblemResolver *resolver = [database_ resolver];
2808 resolver->Clear(iterator_);
2810 pkgCacheFile &cache([database_ cache]);
2811 cache->SetReInstall(iterator_, false);
2812 cache->MarkKeep(iterator_, false);
2816 @synchronized (database_) {
2817 pkgProblemResolver *resolver = [database_ resolver];
2818 resolver->Clear(iterator_);
2819 resolver->Protect(iterator_);
2821 pkgCacheFile &cache([database_ cache]);
2822 cache->SetReInstall(iterator_, false);
2823 cache->MarkInstall(iterator_, false);
2825 pkgDepCache::StateCache &state((*cache)[iterator_]);
2826 if (!state.Install())
2827 cache->SetReInstall(iterator_, true);
2831 @synchronized (database_) {
2832 pkgProblemResolver *resolver = [database_ resolver];
2833 resolver->Clear(iterator_);
2834 resolver->Remove(iterator_);
2835 resolver->Protect(iterator_);
2837 pkgCacheFile &cache([database_ cache]);
2838 cache->SetReInstall(iterator_, false);
2839 cache->MarkDelete(iterator_, true);
2842 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2843 _profile(Package$isUnfilteredAndSearchedForBy)
2846 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2847 value &= [self unfiltered];
2850 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2851 value &= [self matches:search];
2858 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2859 if ([search length] == 0)
2862 _profile(Package$isUnfilteredAndSelectedForBy)
2865 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2866 value &= [self unfiltered];
2869 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2870 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2877 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
2878 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
2881 - (bool) isVisibleInSection:(NSString *)name {
2882 NSString *section([self section]);
2886 section == nil && [name length] == 0 ||
2887 [name isEqualToString:section]
2888 ) && [self visible];
2891 - (bool) isVisibleInSource:(Source *)source {
2892 return [self source] == source && [self visible];
2897 /* Section Class {{{ */
2898 @interface Section : NSObject {
2903 NSString *localized_;
2906 - (NSComparisonResult) compareByLocalized:(Section *)section;
2907 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2908 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2909 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2910 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2911 - (NSString *) name;
2918 - (void) addToCount;
2920 - (void) setCount:(size_t)count;
2921 - (NSString *) localized;
2925 @implementation Section
2929 if (localized_ != nil)
2930 [localized_ release];
2934 - (NSComparisonResult) compareByLocalized:(Section *)section {
2935 NSString *lhs(localized_);
2936 NSString *rhs([section localized]);
2938 /*if ([lhs length] != 0 && [rhs length] != 0) {
2939 unichar lhc = [lhs characterAtIndex:0];
2940 unichar rhc = [rhs characterAtIndex:0];
2942 if (isalpha(lhc) && !isalpha(rhc))
2943 return NSOrderedAscending;
2944 else if (!isalpha(lhc) && isalpha(rhc))
2945 return NSOrderedDescending;
2948 return [lhs compare:rhs options:LaxCompareOptions_];
2951 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2952 if ((self = [self initWithName:name localize:NO]) != nil) {
2953 if (localized != nil)
2954 localized_ = [localized retain];
2958 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2959 return [self initWithName:name row:0 localize:localize];
2962 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2963 if ((self = [super init]) != nil) {
2964 name_ = [name retain];
2968 localized_ = [LocalizeSection(name_) retain];
2972 /* XXX: localize the index thingees */
2973 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2974 if ((self = [super init]) != nil) {
2975 name_ = [[NSString stringWithCharacters:&index length:1] retain];
2981 - (NSString *) name {
3001 - (void) addToCount {
3005 - (void) setCount:(size_t)count {
3009 - (NSString *) localized {
3016 static NSString *Colon_;
3017 static NSString *Elision_;
3018 static NSString *Error_;
3019 static NSString *Warning_;
3021 /* Database Implementation {{{ */
3022 @implementation Database
3024 + (Database *) sharedInstance {
3025 static Database *instance;
3026 if (instance == nil)
3027 instance = [[Database alloc] init];
3035 - (void) releasePackages {
3036 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3037 CFArrayRemoveAllValues(packages_);
3041 // XXX: actually implement this thing
3043 [self releasePackages];
3044 apr_pool_destroy(pool_);
3045 NSRecycleZone(zone_);
3049 - (void) _readCydia:(NSNumber *)fd { _pooled
3050 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3051 std::istream is(&ib);
3054 static Pcre finish_r("^finish:([^:]*)$");
3056 while (std::getline(is, line)) {
3057 const char *data(line.c_str());
3058 size_t size = line.size();
3059 lprintf("C:%s\n", data);
3061 if (finish_r(data, size)) {
3062 NSString *finish = finish_r[1];
3063 int index = [Finishes_ indexOfObject:finish];
3064 if (index != INT_MAX && index > Finish_)
3072 - (void) _readStatus:(NSNumber *)fd { _pooled
3073 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3074 std::istream is(&ib);
3077 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3078 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3080 while (std::getline(is, line)) {
3081 const char *data(line.c_str());
3082 size_t size(line.size());
3083 lprintf("S:%s\n", data);
3085 if (conffile_r(data, size)) {
3086 [delegate_ setConfigurationData:conffile_r[1]];
3087 } else if (strncmp(data, "status: ", 8) == 0) {
3088 NSString *string = [NSString stringWithUTF8String:(data + 8)];
3089 [delegate_ setProgressTitle:string];
3090 } else if (pmstatus_r(data, size)) {
3091 std::string type([pmstatus_r[1] UTF8String]);
3092 NSString *id = pmstatus_r[2];
3094 float percent([pmstatus_r[3] floatValue]);
3095 [delegate_ setProgressPercent:(percent / 100)];
3097 NSString *string = pmstatus_r[4];
3099 if (type == "pmerror")
3100 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3101 withObject:[NSArray arrayWithObjects:string, id, nil]
3104 else if (type == "pmstatus") {
3105 [delegate_ setProgressTitle:string];
3106 } else if (type == "pmconffile")
3107 [delegate_ setConfigurationData:string];
3109 lprintf("E:unknown pmstatus\n");
3111 lprintf("E:unknown status\n");
3117 - (void) _readOutput:(NSNumber *)fd { _pooled
3118 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3119 std::istream is(&ib);
3122 while (std::getline(is, line)) {
3123 lprintf("O:%s\n", line.c_str());
3124 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
3134 - (Package *) packageWithName:(NSString *)name {
3135 @synchronized (self) {
3136 if (static_cast<pkgDepCache *>(cache_) == NULL)
3138 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3139 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3143 if ((self = [super init]) != nil) {
3150 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3151 apr_pool_create(&pool_, NULL);
3153 size_t capacity(MetaFile_->active_);
3159 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3163 _assert(pipe(fds) != -1);
3166 _config->Set("APT::Keep-Fds::", cydiafd_);
3167 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3170 detachNewThreadSelector:@selector(_readCydia:)
3172 withObject:[NSNumber numberWithInt:fds[0]]
3175 _assert(pipe(fds) != -1);
3179 detachNewThreadSelector:@selector(_readStatus:)
3181 withObject:[NSNumber numberWithInt:fds[0]]
3184 _assert(pipe(fds) != -1);
3185 _assert(dup2(fds[0], 0) != -1);
3186 _assert(close(fds[0]) != -1);
3188 input_ = fdopen(fds[1], "a");
3190 _assert(pipe(fds) != -1);
3191 _assert(dup2(fds[1], 1) != -1);
3192 _assert(close(fds[1]) != -1);
3195 detachNewThreadSelector:@selector(_readOutput:)
3197 withObject:[NSNumber numberWithInt:fds[0]]
3202 - (pkgCacheFile &) cache {
3206 - (pkgDepCache::Policy *) policy {
3210 - (pkgRecords *) records {
3214 - (pkgProblemResolver *) resolver {
3218 - (pkgAcquire &) fetcher {
3222 - (pkgSourceList &) list {
3226 - (NSArray *) packages {
3227 return (NSArray *) packages_;
3230 - (NSArray *) sources {
3231 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3232 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3233 [sources addObject:i->second];
3237 - (NSArray *) issues {
3238 if (cache_->BrokenCount() == 0)
3241 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3243 for (Package *package in [self packages]) {
3244 if (![package broken])
3246 pkgCache::PkgIterator pkg([package iterator]);
3248 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3249 [entry addObject:[package name]];
3250 [issues addObject:entry];
3252 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3256 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3257 pkgCache::DepIterator start;
3258 pkgCache::DepIterator end;
3259 dep.GlobOr(start, end); // ++dep
3261 if (!cache_->IsImportantDep(end))
3263 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3266 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3267 [entry addObject:failure];
3268 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3270 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3271 if (Package *package = [self packageWithName:name])
3272 name = [package name];
3273 [failure addObject:name];
3275 pkgCache::PkgIterator target(start.TargetPkg());
3276 if (target->ProvidesList != 0)
3277 [failure addObject:@"?"];
3279 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3281 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3282 else if (!cache_[target].CandidateVerIter(cache_).end())
3283 [failure addObject:@"-"];
3284 else if (target->ProvidesList == 0)
3285 [failure addObject:@"!"];
3287 [failure addObject:@"%"];
3291 if (start.TargetVer() != 0)
3292 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3303 - (bool) popErrorWithTitle:(NSString *)title {
3305 std::string message;
3307 while (!_error->empty()) {
3309 bool warning(!_error->PopMessage(error));
3313 size_t size(error.size());
3314 if (size == 0 || error[size - 1] != '\n')
3316 error.resize(size - 1);
3318 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3320 if (!message.empty())
3325 if (fatal && !message.empty())
3326 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3331 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3332 return [self popErrorWithTitle:title] || !success;
3335 - (void) reloadData { CYPoolStart() {
3336 @synchronized (self) {
3339 [self releasePackages];
3360 apr_pool_clear(pool_);
3362 NSRecycleZone(zone_);
3363 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3365 int chk(creat("/tmp/cydia.chk", 0644));
3369 NSString *title(UCLocalize("DATABASE"));
3372 if (!cache_.Open(progress_, true)) { pop:
3374 bool warning(!_error->PopMessage(error));
3375 lprintf("cache_.Open():[%s]\n", error.c_str());
3377 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3378 [delegate_ repairWithSelector:@selector(configure)];
3379 else if (error == "The package lists or status file could not be parsed or opened.")
3380 [delegate_ repairWithSelector:@selector(update)];
3381 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3382 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3383 // else if (error == "The list of sources could not be read.")
3385 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3394 unlink("/tmp/cydia.chk");
3396 now_ = [[NSDate date] timeIntervalSince1970];
3398 policy_ = new pkgDepCache::Policy();
3399 records_ = new pkgRecords(cache_);
3400 resolver_ = new pkgProblemResolver(cache_);
3401 fetcher_ = new pkgAcquire(&status_);
3404 list_ = new pkgSourceList();
3405 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3408 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3409 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3413 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3416 if (cache_->BrokenCount() != 0) {
3417 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3420 if (cache_->BrokenCount() != 0) {
3421 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3425 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3429 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3430 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3431 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3432 // XXX: this could be more intelligent
3433 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3434 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3436 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3441 /*std::vector<Package *> packages;
3442 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3443 [packages_ release];
3448 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3449 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3450 //packages.push_back(package);
3451 CFArrayAppendValue(packages_, [package retain]);
3455 /*if (packages.empty())
3456 packages_ = [[NSArray alloc] init];
3458 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3461 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3462 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3463 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3471 /*if (!packages.empty())
3472 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3473 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3475 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3477 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3479 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3483 size_t count(CFArrayGetCount(packages_));
3484 MetaFile_->active_ = count;
3486 for (size_t index(0); index != count; ++index)
3487 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3491 } } CYPoolEnd() _trace(); }
3494 @synchronized (self) {
3496 resolver_ = new pkgProblemResolver(cache_);
3498 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator) {
3499 if (!cache_[iterator].Keep()) {
3500 cache_->MarkKeep(iterator, false);
3501 cache_->SetReInstall(iterator, false);
3506 - (void) configure {
3507 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3509 system([dpkg UTF8String]);
3514 // XXX: I don't remember this condition
3519 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3521 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3523 if ([self popErrorWithTitle:title])
3527 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3530 public pkgArchiveCleaner
3533 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3538 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3545 fetcher_->Shutdown();
3547 pkgRecords records(cache_);
3549 lock_ = new FileFd();
3550 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3552 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3554 if ([self popErrorWithTitle:title])
3558 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3561 manager_ = (_system->CreatePM(cache_));
3562 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3569 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3571 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3573 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3575 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3576 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3579 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3584 [CydiaApp retainNetworkActivityIndicator];
3586 bool failed = false;
3587 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3588 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3590 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3593 std::string uri = (*item)->DescURI();
3594 std::string error = (*item)->ErrorText;
3596 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3599 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3600 withObject:[NSArray arrayWithObjects:
3601 [NSString stringWithUTF8String:error.c_str()],
3607 [CydiaApp releaseNetworkActivityIndicator];
3615 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3617 if (_error->PendingError()) {
3622 if (result == pkgPackageManager::Failed) {
3627 if (result != pkgPackageManager::Completed) {
3632 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3634 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3636 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3637 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3640 if (![before isEqualToArray:after])
3645 NSString *title(UCLocalize("UPGRADE"));
3646 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3652 [self updateWithStatus:status_];
3655 - (void) updateWithStatus:(Status &)status {
3656 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3657 NSString *title(UCLocalize("REFRESHING_DATA"));
3660 if (!list.ReadMainList())
3661 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3664 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3665 if ([self popErrorWithTitle:title])
3668 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3669 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */
3670 /* XXX: why the hell is an empty if statement a clang error? */ (void) 0;
3672 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3676 - (void) setDelegate:(id)delegate {
3677 delegate_ = delegate;
3678 status_.setDelegate(delegate);
3679 progress_.setDelegate(delegate);
3682 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3683 SourceMap::const_iterator i(sources_.find(file->ID));
3684 return i == sources_.end() ? nil : i->second;
3687 - (NSString *) mappedSectionForPointer:(const char *)section {
3688 _H<NSString> *mapped;
3690 _profile(Database$mappedSectionForPointer$Cache)
3691 mapped = §ions_[section];
3694 if (*mapped == NULL) {
3695 size_t length(strlen(section));
3696 char spaced[length + 1];
3698 _profile(Database$mappedSectionForPointer$Replace)
3699 for (size_t index(0); index != length; ++index)
3700 spaced[index] = section[index] == '_' ? ' ' : section[index];
3701 spaced[length] = '\0';
3706 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3707 string = [NSString stringWithUTF8String:spaced];
3710 _profile(Database$mappedSectionForPointer$Map)
3711 string = [SectionMap_ objectForKey:string] ?: string;
3721 /* Confirmation Controller {{{ */
3722 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3723 if (!iterator.end())
3724 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3725 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3727 pkgCache::PkgIterator package(dep.TargetPkg());
3730 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3738 /* Web Scripting {{{ */
3739 @interface CydiaObject : NSObject {
3741 _transient id delegate_;
3744 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3747 @implementation CydiaObject
3750 [indirect_ release];
3754 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3755 if ((self = [super init]) != nil) {
3756 indirect_ = [indirect retain];
3760 - (void) setDelegate:(id)delegate {
3761 delegate_ = delegate;
3764 + (NSArray *) _attributeKeys {
3765 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3768 - (NSArray *) attributeKeys {
3769 return [[self class] _attributeKeys];
3772 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3773 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3776 - (NSString *) device {
3777 return [[UIDevice currentDevice] uniqueIdentifier];
3780 #if 0 // XXX: implement!
3781 - (NSString *) mac {
3782 if (![indirect_ promptForSensitive:@"Mac Address"])
3786 - (NSString *) serial {
3787 if (![indirect_ promptForSensitive:@"Serial #"])
3791 - (NSString *) firewire {
3792 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3796 - (NSString *) imei {
3797 if (![indirect_ promptForSensitive:@"IMEI"])
3802 + (NSString *) webScriptNameForSelector:(SEL)selector {
3803 if (selector == @selector(close))
3805 else if (selector == @selector(getInstalledPackages))
3806 return @"getInstalledPackages";
3807 else if (selector == @selector(getPackageById:))
3808 return @"getPackageById";
3809 else if (selector == @selector(installPackages:))
3810 return @"installPackages";
3811 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3812 return @"setButtonImage";
3813 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3814 return @"setButtonTitle";
3815 else if (selector == @selector(setPopupHook:))
3816 return @"setPopupHook";
3817 else if (selector == @selector(setSpecial:))
3818 return @"setSpecial";
3819 else if (selector == @selector(setToken:))
3821 else if (selector == @selector(setViewportWidth:))
3822 return @"setViewportWidth";
3823 else if (selector == @selector(supports:))
3825 else if (selector == @selector(stringWithFormat:arguments:))
3827 else if (selector == @selector(localizedStringForKey:value:table:))
3829 else if (selector == @selector(du:))
3831 else if (selector == @selector(statfs:))
3837 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3838 return [self webScriptNameForSelector:selector] == nil;
3841 - (BOOL) supports:(NSString *)feature {
3842 return [feature isEqualToString:@"window.open"];
3845 - (NSArray *) getInstalledPackages {
3846 NSArray *packages([[Database sharedInstance] packages]);
3847 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
3848 for (Package *package in packages)
3849 if ([package installed] != nil)
3850 [installed addObject:package];
3854 - (Package *) getPackageById:(NSString *)id {
3855 Package *package([[Database sharedInstance] packageWithName:id]);
3860 - (NSArray *) statfs:(NSString *)path {
3863 if (path == nil || statfs([path UTF8String], &stat) == -1)
3866 return [NSArray arrayWithObjects:
3867 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3868 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3869 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3873 - (NSNumber *) du:(NSString *)path {
3874 NSNumber *value(nil);
3877 _assert(pipe(fds) != -1);
3879 pid_t pid(ExecFork());
3881 _assert(dup2(fds[1], 1) != -1);
3882 _assert(close(fds[0]) != -1);
3883 _assert(close(fds[1]) != -1);
3884 /* XXX: this should probably not use du */
3885 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3890 _assert(close(fds[1]) != -1);
3892 if (FILE *du = fdopen(fds[0], "r")) {
3894 while (fgets(line, sizeof(line), du) != NULL) {
3895 size_t length(strlen(line));
3896 while (length != 0 && line[length - 1] == '\n')
3897 line[--length] = '\0';
3898 if (char *tab = strchr(line, '\t')) {
3900 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3905 } else _assert(close(fds[0]));
3909 if (waitpid(pid, &status, 0) == -1)
3912 else _assert(false);
3921 - (void) installPackages:(NSArray *)packages {
3922 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
3925 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3926 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3929 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3930 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3933 - (void) setSpecial:(id)function {
3934 [indirect_ setSpecial:function];
3937 - (void) setToken:(NSString *)token {
3940 Token_ = [token retain];
3942 [Metadata_ setObject:Token_ forKey:@"Token"];
3946 - (void) setPopupHook:(id)function {
3947 [indirect_ setPopupHook:function];
3950 - (void) setViewportWidth:(float)width {
3951 [indirect_ setViewportWidth:width];
3954 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3955 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3956 unsigned count([arguments count]);
3958 for (unsigned i(0); i != count; ++i)
3959 values[i] = [arguments objectAtIndex:i];
3960 return [[[NSString alloc] initWithFormat:format arguments:*(reinterpret_cast<va_list *>(&values))] autorelease];
3963 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3964 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3966 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3968 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3974 /* @ Loading... Indicator {{{ */
3975 @interface CYLoadingIndicator : UIView {
3976 UIActivityIndicatorView *spinner_;
3981 @property (readonly, nonatomic) UILabel *label;
3982 @property (readonly, nonatomic) UIActivityIndicatorView *activityIndicatorView;
3986 @implementation CYLoadingIndicator
3988 - (id)initWithFrame:(CGRect)frame {
3989 if ((self = [super initWithFrame:frame])) {
3990 container_ = [[[UIView alloc] init] autorelease];
3991 [container_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
3993 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
3994 [spinner_ startAnimating];
3995 [container_ addSubview:spinner_];
3997 label_ = [[[UILabel alloc] init] autorelease];
3998 [label_ setFont:[UIFont boldSystemFontOfSize:15.0f]];
3999 [label_ setBackgroundColor:[UIColor clearColor]];
4000 [label_ setTextColor:[UIColor blackColor]];
4001 [label_ setShadowColor:[UIColor whiteColor]];
4002 [label_ setShadowOffset:CGSizeMake(0, 1)];
4003 [label_ setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
4004 [container_ addSubview:label_];
4006 CGSize viewsize = frame.size;
4007 CGSize spinnersize = [spinner_ bounds].size;
4008 CGSize textsize = [[label_ text] sizeWithFont:[label_ font]];
4009 float bothwidth = spinnersize.width + textsize.width + 5.0f;
4011 CGRect containrect = {
4012 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
4013 CGSizeMake(bothwidth, spinnersize.height)
4016 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
4024 [container_ setFrame:containrect];
4025 [spinner_ setFrame:spinrect];
4026 [label_ setFrame:textrect];
4027 [self addSubview:container_];
4033 - (UILabel *)label { return label_; }
4034 - (UIActivityIndicatorView *)activityIndicatorView { return spinner_; }
4039 /* Cydia Browser Controller {{{ */
4040 @interface CYBrowserController : BrowserController {
4041 CydiaObject *cydia_;
4046 @implementation CYBrowserController
4053 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
4056 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4057 [super webView:view didClearWindowObject:window forFrame:frame];
4059 WebDataSource *source([frame dataSource]);
4060 NSURLResponse *response([source response]);
4061 NSURL *url([response URL]);
4062 NSString *scheme([url scheme]);
4064 NSHTTPURLResponse *http;
4065 if (scheme != nil && ([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"]))
4066 http = (NSHTTPURLResponse *) response;
4070 NSDictionary *headers([http allHeaderFields]);
4071 NSString *host([url host]);
4072 [self setHeaders:headers forHost:host];
4075 [host isEqualToString:@"cydia.saurik.com"] ||
4076 [host hasSuffix:@".cydia.saurik.com"] ||
4077 [scheme isEqualToString:@"file"]
4079 [window setValue:cydia_ forKey:@"cydia"];
4082 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
4083 if (System_ != NULL)
4084 [request setValue:System_ forHTTPHeaderField:@"X-System"];
4085 if (Machine_ != NULL)
4086 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4088 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4090 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
4093 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4094 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4095 [self _setMoreHeaders:copy];
4099 - (void) setDelegate:(id)delegate {
4100 [super setDelegate:delegate];
4101 [cydia_ setDelegate:delegate];
4105 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
4106 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
4108 WebView *webview([[webview_ _documentView] webView]);
4110 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
4112 NSString *application = package == nil ? @"Cydia" : [NSString
4113 stringWithFormat:@"Cydia/%@",
4118 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4120 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4121 if (Product_ != nil)
4122 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4124 [webview setApplicationNameForUserAgent:application];
4131 /* Confirmation {{{ */
4132 @protocol ConfirmationControllerDelegate
4133 - (void) cancelAndClear:(bool)clear;
4134 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4138 @interface ConfirmationController : CYBrowserController {
4139 _transient Database *database_;
4140 UIAlertView *essential_;
4147 - (id) initWithDatabase:(Database *)database;
4151 @implementation ConfirmationController
4158 if (essential_ != nil)
4159 [essential_ release];
4163 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4164 NSString *context([alert context]);
4166 if ([context isEqualToString:@"remove"]) {
4167 if (button == [alert cancelButtonIndex]) {
4168 [self dismissModalViewControllerAnimated:YES];
4169 } else if (button == [alert firstOtherButtonIndex]) {
4172 [delegate_ confirmWithNavigationController:[self navigationController]];
4175 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4176 } else if ([context isEqualToString:@"unable"]) {
4177 [self dismissModalViewControllerAnimated:YES];
4178 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4180 [super alertView:alert clickedButtonAtIndex:button];
4184 - (void) _doContinue {
4185 [self dismissModalViewControllerAnimated:YES];
4186 [delegate_ cancelAndClear:NO];
4189 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4190 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4194 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4195 [super webView:view didClearWindowObject:window forFrame:frame];
4196 [window setValue:changes_ forKey:@"changes"];
4197 [window setValue:issues_ forKey:@"issues"];
4198 [window setValue:sizes_ forKey:@"sizes"];
4199 [window setValue:self forKey:@"queue"];
4202 - (id) initWithDatabase:(Database *)database {
4203 if ((self = [super init]) != nil) {
4204 database_ = database;
4206 [[self navigationItem] setTitle:UCLocalize("CONFIRM")];
4208 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
4209 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
4210 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
4211 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
4212 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
4216 pkgDepCache::Policy *policy([database_ policy]);
4218 pkgCacheFile &cache([database_ cache]);
4219 NSArray *packages = [database_ packages];
4220 for (Package *package in packages) {
4221 pkgCache::PkgIterator iterator = [package iterator];
4222 pkgDepCache::StateCache &state(cache[iterator]);
4224 NSString *name([package name]);
4226 if (state.NewInstall())
4227 [installing addObject:name];
4228 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4229 [reinstalling addObject:name];
4230 else if (state.Upgrade())
4231 [upgrading addObject:name];
4232 else if (state.Downgrade())
4233 [downgrading addObject:name];
4234 else if (state.Delete()) {
4235 if ([package essential])
4237 [removing addObject:name];
4240 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4241 substrate_ |= DepSubstrate(iterator.CurrentVer());
4246 else if (Advanced_) {
4247 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4249 essential_ = [[UIAlertView alloc]
4250 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4251 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4253 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4254 otherButtonTitles:[NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")], nil
4257 [essential_ setContext:@"remove"];
4259 essential_ = [[UIAlertView alloc]
4260 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4261 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4263 cancelButtonTitle:UCLocalize("OKAY")
4264 otherButtonTitles:nil
4267 [essential_ setContext:@"unable"];
4270 changes_ = [[NSArray alloc] initWithObjects:
4278 issues_ = [database_ issues];
4280 issues_ = [issues_ retain];
4282 sizes_ = [[NSArray alloc] initWithObjects:
4283 SizeString([database_ fetcher].FetchNeeded()),
4284 SizeString([database_ fetcher].PartialPresent()),
4287 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
4289 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
4290 initWithTitle:UCLocalize("CANCEL")
4291 // OLD: [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")]
4292 style:UIBarButtonItemStylePlain
4294 action:@selector(cancelButtonClicked)
4299 - (void) applyRightButton {
4300 #if !AlwaysReload && !IgnoreInstall
4301 if (issues_ == nil && ![self isLoading])
4302 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4303 initWithTitle:UCLocalize("CONFIRM")
4304 style:UIBarButtonItemStylePlain
4306 action:@selector(confirmButtonClicked)
4309 [super applyRightButton];
4311 [[self navigationItem] setRightBarButtonItem:nil];
4315 - (void) cancelButtonClicked {
4316 [self dismissModalViewControllerAnimated:YES];
4317 [delegate_ cancelAndClear:YES];
4321 - (void) confirmButtonClicked {
4325 if (essential_ != nil)
4330 [delegate_ confirmWithNavigationController:[self navigationController]];
4338 /* Progress Data {{{ */
4339 @interface ProgressData : NSObject {
4341 // XXX: should these really both be _transient?
4342 _transient id target_;
4343 _transient id object_;
4346 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4353 @implementation ProgressData
4355 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4356 if ((self = [super init]) != nil) {
4357 selector_ = selector;
4377 /* Progress Controller {{{ */
4378 @interface ProgressController : CYViewController <
4379 ConfigurationDelegate,
4382 _transient Database *database_;
4383 UIProgressBar *progress_;
4384 UITextView *output_;
4385 UITextLabel *status_;
4386 UIPushButton *close_;
4388 SHA1SumValue springlist_;
4389 SHA1SumValue notifyconf_;
4393 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4395 - (void) _retachThread;
4396 - (void) _detachNewThreadData:(ProgressData *)data;
4397 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4403 @protocol ProgressControllerDelegate
4404 - (void) progressControllerIsComplete:(ProgressController *)sender;
4407 @implementation ProgressController
4410 [database_ setDelegate:nil];
4411 [progress_ release];
4420 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4421 if ((self = [super init]) != nil) {
4422 database_ = database;
4423 [database_ setDelegate:self];
4424 delegate_ = delegate;
4426 [[self view] setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
4428 progress_ = [[UIProgressBar alloc] init];
4429 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4430 [progress_ setStyle:0];
4432 status_ = [[UITextLabel alloc] init];
4433 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4434 [status_ setColor:[UIColor whiteColor]];
4435 [status_ setBackgroundColor:[UIColor clearColor]];
4436 [status_ setCentersHorizontally:YES];
4437 //[status_ setFont:font];
4439 output_ = [[UITextView alloc] init];
4441 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4442 //[output_ setTextFont:@"Courier New"];
4443 [output_ setFont:[[output_ font] fontWithSize:12]];
4444 [output_ setTextColor:[UIColor whiteColor]];
4445 [output_ setBackgroundColor:[UIColor clearColor]];
4446 [output_ setMarginTop:0];
4447 [output_ setAllowsRubberBanding:YES];
4448 [output_ setEditable:NO];
4449 [[self view] addSubview:output_];
4451 close_ = [[UIPushButton alloc] init];
4452 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4453 [close_ setAutosizesToFit:NO];
4454 [close_ setDrawsShadow:YES];
4455 [close_ setStretchBackground:YES];
4456 [close_ setEnabled:YES];
4457 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
4458 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4459 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4460 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4464 - (void) positionViews {
4465 CGRect bounds = [[self view] bounds];
4466 CGSize prgsize = [UIProgressBar defaultSize];
4469 (bounds.size.width - prgsize.width) / 2,
4470 bounds.size.height - prgsize.height - 20
4473 float closewidth = std::min(bounds.size.width - 20, 300.0f);
4475 [progress_ setFrame:prgrect];
4476 [status_ setFrame:CGRectMake(
4478 bounds.size.height - prgsize.height - 50,
4479 bounds.size.width - 20,
4482 [output_ setFrame:CGRectMake(
4485 bounds.size.width - 20,
4486 bounds.size.height - 62
4488 [close_ setFrame:CGRectMake(
4489 (bounds.size.width - closewidth) / 2,
4490 bounds.size.height - prgsize.height - 50,
4496 - (void) viewWillAppear:(BOOL)animated {
4497 [super viewDidAppear:animated];
4498 [[self navigationItem] setHidesBackButton:YES];
4499 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4501 [self positionViews];
4504 - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4505 [self positionViews];
4508 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4509 NSString *context([alert context]);
4511 if ([context isEqualToString:@"conffile"]) {
4512 FILE *input = [database_ input];
4513 if (button == [alert cancelButtonIndex])
4514 fprintf(input, "N\n");
4515 else if (button == [alert firstOtherButtonIndex])
4516 fprintf(input, "Y\n");
4521 - (void) closeButtonPushed {
4524 UpdateExternalStatus(0);
4528 [self dismissModalViewControllerAnimated:YES];
4532 [delegate_ terminateWithSuccess];
4533 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4534 [delegate_ suspendWithAnimation:YES];
4536 [delegate_ suspend];*/
4548 system("/usr/bin/sbreload");
4554 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
4555 SBReboot(SBSSpringBoardServerPort());
4557 reboot2(RB_AUTOBOOT);
4562 - (void) _retachThread {
4563 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
4565 [[self view] addSubview:close_];
4566 [progress_ removeFromSuperview];
4567 [status_ removeFromSuperview];
4569 [database_ popErrorWithTitle:title_];
4570 [delegate_ progressControllerIsComplete:self];
4574 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4577 MMap mmap(file, MMap::ReadOnly);
4579 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4580 if (!(notifyconf_ == sha1.Result()))
4587 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4590 MMap mmap(file, MMap::ReadOnly);
4592 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4593 if (!(springlist_ == sha1.Result()))
4599 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
4600 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4601 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4602 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4603 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4607 system("su -c /usr/bin/uicache mobile");
4610 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
4612 [delegate_ setStatusBarShowsProgress:NO];
4615 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4616 [[data target] performSelector:[data selector] withObject:[data object]];
4617 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4620 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4621 UpdateExternalStatus(1);
4628 title_ = [title retain];
4630 [[self navigationItem] setTitle:title_];
4632 [status_ setText:nil];
4633 [output_ setText:@""];
4634 [progress_ setProgress:0];
4636 [close_ removeFromSuperview];
4637 [[self view] addSubview:progress_];
4638 [[self view] addSubview:status_];
4640 [delegate_ setStatusBarShowsProgress:YES];
4645 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4648 MMap mmap(file, MMap::ReadOnly);
4650 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4651 notifyconf_ = sha1.Result();
4657 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4660 MMap mmap(file, MMap::ReadOnly);
4662 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4663 springlist_ = sha1.Result();
4668 detachNewThreadSelector:@selector(_detachNewThreadData:)
4670 withObject:[[[ProgressData alloc]
4671 initWithSelector:selector
4678 - (void) repairWithSelector:(SEL)selector {
4680 detachNewThreadSelector:selector
4683 title:UCLocalize("REPAIRING")
4687 - (void) setConfigurationData:(NSString *)data {
4689 performSelectorOnMainThread:@selector(_setConfigurationData:)
4695 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4696 CYActionSheet *sheet([[[CYActionSheet alloc]
4698 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4699 defaultButtonIndex:0
4702 [sheet setMessage:error];
4703 [sheet yieldToPopupAlertAnimated:YES];
4707 - (void) setProgressTitle:(NSString *)title {
4709 performSelectorOnMainThread:@selector(_setProgressTitle:)
4715 - (void) setProgressPercent:(float)percent {
4717 performSelectorOnMainThread:@selector(_setProgressPercent:)
4718 withObject:[NSNumber numberWithFloat:percent]
4723 - (void) startProgress {
4726 - (void) addProgressOutput:(NSString *)output {
4728 performSelectorOnMainThread:@selector(_addProgressOutput:)
4734 - (bool) isCancelling:(size_t)received {
4738 - (void) _setConfigurationData:(NSString *)data {
4739 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4741 if (!conffile_r(data)) {
4742 lprintf("E:invalid conffile\n");
4746 NSString *ofile = conffile_r[1];
4747 //NSString *nfile = conffile_r[2];
4749 UIAlertView *alert = [[[UIAlertView alloc]
4750 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4751 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
4753 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
4754 otherButtonTitles:UCLocalize("ACCEPT_NEW_COPY"),
4755 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4759 [alert setContext:@"conffile"];
4763 - (void) _setProgressTitle:(NSString *)title {
4764 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4765 for (size_t i(0), e([words count]); i != e; ++i) {
4766 NSString *word([words objectAtIndex:i]);
4767 if (Package *package = [database_ packageWithName:word])
4768 [words replaceObjectAtIndex:i withObject:[package name]];
4771 [status_ setText:[words componentsJoinedByString:@" "]];
4774 - (void) _setProgressPercent:(NSNumber *)percent {
4775 [progress_ setProgress:[percent floatValue]];
4778 - (void) _addProgressOutput:(NSString *)output {
4779 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4780 CGSize size = [output_ contentSize];
4781 CGPoint offset = [output_ contentOffset];
4782 if (size.height - offset.y < [output_ frame].size.height + 20.f) {
4783 CGRect rect = {{0, size.height-1}, {size.width, 1}};
4784 [output_ scrollRectToVisible:rect animated:YES];
4788 - (BOOL) isRunning {
4795 /* Cell Content View {{{ */
4796 @protocol ContentDelegate
4797 - (void) drawContentRect:(CGRect)rect;
4800 @interface ContentView : UIView {
4801 _transient id<ContentDelegate> delegate_;
4806 @implementation ContentView
4808 - (id) initWithFrame:(CGRect)frame {
4809 if ((self = [super initWithFrame:frame]) != nil) {
4810 [self setNeedsDisplayOnBoundsChange:YES];
4814 - (void) setDelegate:(id<ContentDelegate>)delegate {
4815 delegate_ = delegate;
4818 - (void) drawRect:(CGRect)rect {
4819 [super drawRect:rect];
4820 [delegate_ drawContentRect:rect];
4825 /* Cydia TableView Cell {{{ */
4826 @interface CYTableViewCell : UITableViewCell {
4827 ContentView *content_;
4833 @implementation CYTableViewCell
4840 - (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
4841 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
4843 if (view == content_) {
4844 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
4845 highlighted_ = highlighted;
4848 [super _updateHighlightColorsForView:view highlighted:highlighted];
4851 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
4852 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
4853 highlighted_ = selected;
4855 [super setSelected:selected animated:animated];
4856 [content_ setNeedsDisplay];
4861 /* Package Cell {{{ */
4862 @interface PackageCell : CYTableViewCell <
4867 NSString *description_;
4875 - (PackageCell *) init;
4876 - (void) setPackage:(Package *)package;
4878 + (int) heightForPackage:(Package *)package;
4879 - (void) drawContentRect:(CGRect)rect;
4883 @implementation PackageCell
4885 - (void) clearPackage {
4896 if (description_ != nil) {
4897 [description_ release];
4901 if (source_ != nil) {
4906 if (badge_ != nil) {
4911 if (placard_ != nil) {
4921 [self clearPackage];
4925 - (PackageCell *) init {
4926 CGRect frame(CGRectMake(0, 0, 320, 74));
4927 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4928 UIView *content([self contentView]);
4929 CGRect bounds([content bounds]);
4931 content_ = [[ContentView alloc] initWithFrame:bounds];
4932 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4933 [content addSubview:content_];
4935 [content_ setDelegate:self];
4936 [content_ setOpaque:YES];
4940 - (void) _setBackgroundColor {
4942 if (NSString *mode = [package_ mode]) {
4943 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4944 color = remove ? RemovingColor_ : InstallingColor_;
4946 color = [UIColor whiteColor];
4948 [content_ setBackgroundColor:color];
4949 [self setNeedsDisplay];
4952 - (void) setPackage:(Package *)package {
4953 [self clearPackage];
4956 Source *source = [package source];
4958 icon_ = [[package icon] retain];
4959 name_ = [[package name] retain];
4962 description_ = [package longDescription];
4963 if (description_ == nil)
4964 description_ = [package shortDescription];
4965 if (description_ != nil)
4966 description_ = [description_ retain];
4968 commercial_ = [package isCommercial];
4970 package_ = [package retain];
4972 NSString *label = nil;
4973 bool trusted = false;
4975 if (source != nil) {
4976 label = [source label];
4977 trusted = [source trusted];
4978 } else if ([[package id] isEqualToString:@"firmware"])
4979 label = UCLocalize("APPLE");
4981 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
4983 NSString *from(label);
4985 NSString *section = [package simpleSection];
4986 if (section != nil && ![section isEqualToString:label]) {
4987 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4988 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
4991 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
4992 source_ = [from retain];
4994 if (NSString *purpose = [package primaryPurpose])
4995 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4996 badge_ = [badge_ retain];
4998 if ([package installed] != nil)
4999 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/installed.png", App_]]) != nil)
5000 placard_ = [placard_ retain];
5002 [self _setBackgroundColor];
5003 [content_ setNeedsDisplay];
5006 - (void) drawContentRect:(CGRect)rect {
5007 bool highlighted(highlighted_);
5008 float width([self bounds].size.width);
5011 CGContextRef context(UIGraphicsGetCurrentContext());
5012 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
5013 CGContextFillRect(context, rect);
5018 rect.size = [icon_ size];
5020 rect.size.width /= 2;
5021 rect.size.height /= 2;
5023 rect.origin.x = 25 - rect.size.width / 2;
5024 rect.origin.y = 25 - rect.size.height / 2;
5026 [icon_ drawInRect:rect];
5029 if (badge_ != nil) {
5031 rect.size = [badge_ size];
5033 rect.size.width /= 2;
5034 rect.size.height /= 2;
5036 rect.origin.x = 36 - rect.size.width / 2;
5037 rect.origin.y = 36 - rect.size.height / 2;
5039 [badge_ drawInRect:rect];
5046 UISetColor(commercial_ ? Purple_ : Black_);
5047 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5048 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5051 UISetColor(commercial_ ? Purplish_ : Gray_);
5052 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5054 if (placard_ != nil)
5055 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5058 + (int) heightForPackage:(Package *)package {
5064 /* Section Cell {{{ */
5065 @interface SectionCell : CYTableViewCell <
5077 - (void) setSection:(Section *)section editing:(BOOL)editing;
5081 @implementation SectionCell
5083 - (void) clearSection {
5084 if (basic_ != nil) {
5089 if (section_ != nil) {
5099 if (count_ != nil) {
5106 [self clearSection];
5112 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5113 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5114 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
5115 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
5116 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5118 UIView *content([self contentView]);
5119 CGRect bounds([content bounds]);
5121 content_ = [[ContentView alloc] initWithFrame:bounds];
5122 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5123 [content addSubview:content_];
5124 [content_ setBackgroundColor:[UIColor whiteColor]];
5126 [content_ setDelegate:self];
5130 - (void) onSwitch:(id)sender {
5131 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5132 if (metadata == nil) {
5133 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5134 [Sections_ setObject:metadata forKey:basic_];
5137 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5141 - (void) setSection:(Section *)section editing:(BOOL)editing {
5142 if (editing != editing_) {
5144 [switch_ removeFromSuperview];
5146 [self addSubview:switch_];
5150 [self clearSection];
5152 if (section == nil) {
5153 name_ = [UCLocalize("ALL_PACKAGES") retain];
5156 basic_ = [section name];
5158 basic_ = [basic_ retain];
5160 section_ = [section localized];
5161 if (section_ != nil)
5162 section_ = [section_ retain];
5164 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
5165 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
5168 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5171 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5172 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5174 [content_ setNeedsDisplay];
5177 - (void) setFrame:(CGRect)frame {
5178 [super setFrame:frame];
5180 CGRect rect([switch_ frame]);
5181 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5184 - (void) drawContentRect:(CGRect)rect {
5185 bool highlighted(highlighted_ && !editing_);
5187 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5192 float width(rect.size.width);
5198 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5200 CGSize size = [count_ sizeWithFont:Font14_];
5204 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5210 /* File Table {{{ */
5211 @interface FileTable : CYViewController <
5212 UITableViewDataSource,
5215 _transient Database *database_;
5218 NSMutableArray *files_;
5222 - (id) initWithDatabase:(Database *)database;
5223 - (void) setPackage:(Package *)package;
5227 @implementation FileTable
5230 if (package_ != nil)
5239 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5240 return files_ == nil ? 0 : [files_ count];
5243 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5247 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5248 static NSString *reuseIdentifier = @"Cell";
5250 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5252 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5253 [cell setFont:[UIFont systemFontOfSize:16]];
5255 [cell setText:[files_ objectAtIndex:indexPath.row]];
5256 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5261 - (id) initWithDatabase:(Database *)database {
5262 if ((self = [super init]) != nil) {
5263 database_ = database;
5265 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5267 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5269 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5270 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5271 [list_ setRowHeight:24.0f];
5272 [[self view] addSubview:list_];
5274 [list_ setDataSource:self];
5275 [list_ setDelegate:self];
5279 - (void) setPackage:(Package *)package {
5280 if (package_ != nil) {
5281 [package_ autorelease];
5290 [files_ removeAllObjects];
5292 if (package != nil) {
5293 package_ = [package retain];
5294 name_ = [[package id] retain];
5296 if (NSArray *files = [package files])
5297 [files_ addObjectsFromArray:files];
5299 if ([files_ count] != 0) {
5300 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5301 [files_ removeObjectAtIndex:0];
5302 [files_ sortUsingSelector:@selector(compareByPath:)];
5304 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5305 [stack addObject:@"/"];
5307 for (int i(0), e([files_ count]); i != e; ++i) {
5308 NSString *file = [files_ objectAtIndex:i];
5309 while (![file hasPrefix:[stack lastObject]])
5310 [stack removeLastObject];
5311 NSString *directory = [stack lastObject];
5312 [stack addObject:[file stringByAppendingString:@"/"]];
5313 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5314 ([stack count] - 2) * 3, "",
5315 [file substringFromIndex:[directory length]]
5324 - (void) reloadData {
5325 [self setPackage:[database_ packageWithName:name_]];
5330 /* Package Controller {{{ */
5331 @interface PackageController : CYBrowserController <
5332 UIActionSheetDelegate
5334 _transient Database *database_;
5338 NSMutableArray *buttons_;
5339 UIBarButtonItem *button_;
5342 - (id) initWithDatabase:(Database *)database;
5343 - (void) setPackage:(Package *)package;
5347 @implementation PackageController
5350 if (package_ != nil)
5364 if ([self retainCount] == 1)
5365 [delegate_ setPackageController:self];
5369 /* XXX: this is not safe at all... localization of /fail/ */
5370 - (void) _clickButtonWithName:(NSString *)name {
5371 if ([name isEqualToString:UCLocalize("CLEAR")])
5372 [delegate_ clearPackage:package_];
5373 else if ([name isEqualToString:UCLocalize("INSTALL")])
5374 [delegate_ installPackage:package_];
5375 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5376 [delegate_ installPackage:package_];
5377 else if ([name isEqualToString:UCLocalize("REMOVE")])
5378 [delegate_ removePackage:package_];
5379 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5380 [delegate_ installPackage:package_];
5381 else _assert(false);
5384 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5385 NSString *context([sheet context]);
5387 if ([context isEqualToString:@"modify"]) {
5388 if (button != [sheet cancelButtonIndex]) {
5389 NSString *buttonName = [buttons_ objectAtIndex:button];
5390 [self _clickButtonWithName:buttonName];
5393 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5397 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5398 [super webView:view didClearWindowObject:window forFrame:frame];
5399 [window setValue:package_ forKey:@"package"];
5402 - (bool) _allowJavaScriptPanel {
5407 - (void) _customButtonClicked {
5408 int count([buttons_ count]);
5413 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5415 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5416 [buttons addObjectsFromArray:buttons_];
5418 UIActionSheet *sheet = [[[UIActionSheet alloc]
5421 cancelButtonTitle:nil
5422 destructiveButtonTitle:nil
5423 otherButtonTitles:nil
5426 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5428 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5429 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5431 [sheet setContext:@"modify"];
5433 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5437 // We don't want to allow non-commercial packages to do custom things to the install button,
5438 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5439 - (void) customButtonClicked {
5441 [super customButtonClicked];
5443 [self _customButtonClicked];
5446 - (void) reloadButtonClicked {
5447 // Don't reload a commerical package by tapping the loading button,
5448 // but if it's not an Install button, we should forward it on.
5449 if (![package_ uninstalled])
5450 [self _customButtonClicked];
5453 - (void) applyLoadingTitle {
5454 // Don't show "Loading" as the title. Ever.
5457 - (UIBarButtonItem *) rightButton {
5462 - (id) initWithDatabase:(Database *)database {
5463 if ((self = [super init]) != nil) {
5464 database_ = database;
5465 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5466 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
5470 - (void) setPackage:(Package *)package {
5471 if (package_ != nil) {
5472 [package_ autorelease];
5481 [buttons_ removeAllObjects];
5483 if (package != nil) {
5486 package_ = [package retain];
5487 name_ = [[package id] retain];
5488 commercial_ = [package isCommercial];
5490 if ([package_ mode] != nil)
5491 [buttons_ addObject:UCLocalize("CLEAR")];
5492 if ([package_ source] == nil);
5493 else if ([package_ upgradableAndEssential:NO])
5494 [buttons_ addObject:UCLocalize("UPGRADE")];
5495 else if ([package_ uninstalled])
5496 [buttons_ addObject:UCLocalize("INSTALL")];
5498 [buttons_ addObject:UCLocalize("REINSTALL")];
5499 if (![package_ uninstalled])
5500 [buttons_ addObject:UCLocalize("REMOVE")];
5507 switch ([buttons_ count]) {
5508 case 0: title = nil; break;
5509 case 1: title = [buttons_ objectAtIndex:0]; break;
5510 default: title = UCLocalize("MODIFY"); break;
5513 button_ = [[UIBarButtonItem alloc]
5515 style:UIBarButtonItemStylePlain
5517 action:@selector(customButtonClicked)
5523 - (bool) isLoading {
5524 return commercial_ ? [super isLoading] : false;
5527 - (void) reloadData {
5528 [self setPackage:[database_ packageWithName:name_]];
5533 /* Package Table {{{ */
5534 @interface PackageTable : UIView <
5535 UITableViewDataSource,
5538 _transient Database *database_;
5540 NSMutableArray *packages_;
5541 NSMutableArray *sections_;
5543 NSMutableArray *index_;
5544 NSMutableDictionary *indices_;
5545 // XXX: this target_ seems to be delegate_. :(
5546 _transient id target_;
5548 // XXX: why do we even have this delegate_?
5549 _transient id delegate_;
5552 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action;
5554 - (void) setDelegate:(id)delegate;
5556 - (void) reloadData;
5557 - (void) resetCursor;
5559 - (UITableView *) list;
5561 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5563 - (void) deselectWithAnimation:(BOOL)animated;
5567 @implementation PackageTable
5570 [packages_ release];
5571 [sections_ release];
5579 + (BOOL) hasIndexedCollation {
5580 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
5583 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5584 NSInteger count([sections_ count]);
5585 return count == 0 ? 1 : count;
5588 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5589 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
5591 return [[sections_ objectAtIndex:section] name];
5594 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5595 if ([sections_ count] == 0)
5597 return [[sections_ objectAtIndex:section] count];
5600 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5601 @synchronized (database_) {
5602 if ([database_ era] != era_)
5605 Section *section([sections_ objectAtIndex:[path section]]);
5606 NSInteger row([path row]);
5607 Package *package([packages_ objectAtIndex:([section row] + row)]);
5608 return [[package retain] autorelease];
5611 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5612 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5614 cell = [[[PackageCell alloc] init] autorelease];
5615 [cell setPackage:[self packageAtIndexPath:path]];
5619 - (void) deselectWithAnimation:(BOOL)animated {
5620 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5623 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
5624 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
5627 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5628 Package *package([self packageAtIndexPath:path]);
5629 package = [database_ packageWithName:[package id]];
5630 [target_ performSelector:action_ withObject:package];
5634 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5635 // XXX: is 20 the most optimal number here?
5636 return [packages_ count] > 20 ? index_ : nil;
5639 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5640 if ([[self class] hasIndexedCollation]) {
5641 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
5647 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action {
5648 if ((self = [super initWithFrame:frame]) != nil) {
5649 database_ = database;
5654 index_ = [[self class] hasIndexedCollation]
5655 ? [[[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles] retain]
5656 : [[NSMutableArray alloc] initWithCapacity:32];
5657 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5659 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5660 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5662 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
5663 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5664 [list_ setRowHeight:73.0f];
5665 [self addSubview:list_];
5667 [list_ setDataSource:self];
5668 [list_ setDelegate:self];
5672 - (void) setDelegate:(id)delegate {
5673 delegate_ = delegate;
5676 - (bool) hasPackage:(Package *)package {
5680 - (void) reloadData {
5681 era_ = [database_ era];
5682 NSArray *packages = [database_ packages];
5684 [packages_ removeAllObjects];
5685 [sections_ removeAllObjects];
5687 _profile(PackageTable$reloadData$Filter)
5688 for (Package *package in packages)
5689 if ([self hasPackage:package])
5690 [packages_ addObject:package];
5693 [indices_ removeAllObjects];
5695 Section *section = nil;
5697 if ([[self class] hasIndexedCollation]) {
5698 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
5699 NSArray *titles = [collation sectionIndexTitles];
5702 _profile(PackageTable$reloadData$Section)
5703 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5707 _profile(PackageTable$reloadData$Section$Package)
5708 package = [packages_ objectAtIndex:offset];
5709 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
5712 while (secidx < index) {
5715 _profile(PackageTable$reloadData$Section$Allocate)
5716 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
5719 _profile(PackageTable$reloadData$Section$Add)
5720 [sections_ addObject:section];
5724 [section addToCount];
5728 [index_ removeAllObjects];
5730 _profile(PackageTable$reloadData$Section)
5731 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5735 _profile(PackageTable$reloadData$Section$Package)
5736 package = [packages_ objectAtIndex:offset];
5737 index = [package index];
5740 if (section == nil || [section index] != index) {
5741 _profile(PackageTable$reloadData$Section$Allocate)
5742 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5745 [index_ addObject:[section name]];
5746 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5748 _profile(PackageTable$reloadData$Section$Add)
5749 [sections_ addObject:section];
5753 [section addToCount];
5758 _profile(PackageTable$reloadData$List)
5763 - (void) resetCursor {
5764 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5767 - (UITableView *) list {
5771 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5772 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
5777 /* Filtered Package Table {{{ */
5778 @interface FilteredPackageTable : PackageTable {
5784 - (void) setObject:(id)object;
5785 - (void) setObject:(id)object forFilter:(SEL)filter;
5787 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object;
5791 @implementation FilteredPackageTable
5799 - (void) setFilter:(SEL)filter {
5802 /* XXX: this is an unsafe optimization of doomy hell */
5803 Method method(class_getInstanceMethod([Package class], filter));
5804 _assert(method != NULL);
5805 imp_ = method_getImplementation(method);
5806 _assert(imp_ != NULL);
5809 - (void) setObject:(id)object {
5815 object_ = [object retain];
5818 - (void) setObject:(id)object forFilter:(SEL)filter {
5819 [self setFilter:filter];
5820 [self setObject:object];
5823 - (bool) hasPackage:(Package *)package {
5824 _profile(FilteredPackageTable$hasPackage)
5825 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5829 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object {
5830 if ((self = [super initWithFrame:frame database:database target:target action:action]) != nil) {
5831 [self setFilter:filter];
5832 object_ = [object retain];
5840 /* Filtered Package Controller {{{ */
5841 @interface FilteredPackageController : CYViewController {
5842 _transient Database *database_;
5843 FilteredPackageTable *packages_;
5847 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5851 @implementation FilteredPackageController
5854 [packages_ release];
5860 - (void) viewDidAppear:(BOOL)animated {
5861 [super viewDidAppear:animated];
5862 [packages_ deselectWithAnimation:animated];
5865 - (void) didSelectPackage:(Package *)package {
5866 PackageController *view([delegate_ packageController]);
5867 [view setPackage:package];
5868 [view setDelegate:delegate_];
5869 [[self navigationController] pushViewController:view animated:YES];
5872 - (NSString *) title { return title_; }
5874 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5875 if ((self = [super init]) != nil) {
5876 database_ = database;
5877 title_ = [title copy];
5878 [[self navigationItem] setTitle:title_];
5880 packages_ = [[FilteredPackageTable alloc]
5881 initWithFrame:[[self view] bounds]
5884 action:@selector(didSelectPackage:)
5889 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5890 [[self view] addSubview:packages_];
5894 - (void) reloadData {
5895 [packages_ reloadData];
5898 - (void) setDelegate:(id)delegate {
5899 [super setDelegate:delegate];
5900 [packages_ setDelegate:delegate];
5907 /* Source Cell {{{ */
5908 @interface SourceCell : CYTableViewCell <
5913 NSString *description_;
5917 - (void) setSource:(Source *)source;
5921 @implementation SourceCell
5923 - (void) clearSource {
5926 [description_ release];
5935 - (void) setSource:(Source *)source {
5939 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5941 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5942 icon_ = [icon_ retain];
5944 origin_ = [[source name] retain];
5945 label_ = [[source uri] retain];
5946 description_ = [[source description] retain];
5948 [content_ setNeedsDisplay];
5956 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5957 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5958 UIView *content([self contentView]);
5959 CGRect bounds([content bounds]);
5961 content_ = [[ContentView alloc] initWithFrame:bounds];
5962 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5963 [content_ setBackgroundColor:[UIColor whiteColor]];
5964 [content addSubview:content_];
5966 [content_ setDelegate:self];
5967 [content_ setOpaque:YES];
5971 - (void) drawContentRect:(CGRect)rect {
5972 bool highlighted(highlighted_);
5973 float width(rect.size.width);
5976 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5983 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5987 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5991 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 40) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5996 /* Source Table {{{ */
5997 @interface SourceController : CYViewController <
5998 UITableViewDataSource,
6001 _transient Database *database_;
6003 NSMutableArray *sources_;
6007 UIProgressHUD *hud_;
6010 //NSURLConnection *installer_;
6011 NSURLConnection *trivial_;
6012 NSURLConnection *trivial_bz2_;
6013 NSURLConnection *trivial_gz_;
6014 //NSURLConnection *automatic_;
6019 - (id) initWithDatabase:(Database *)database;
6021 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
6025 @implementation SourceController
6027 - (void) _releaseConnection:(NSURLConnection *)connection {
6028 if (connection != nil) {
6029 [connection cancel];
6030 //[connection setDelegate:nil];
6031 [connection release];
6043 //[self _releaseConnection:installer_];
6044 [self _releaseConnection:trivial_];
6045 [self _releaseConnection:trivial_gz_];
6046 [self _releaseConnection:trivial_bz2_];
6047 //[self _releaseConnection:automatic_];
6054 - (void) viewDidAppear:(BOOL)animated {
6055 [super viewDidAppear:animated];
6056 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6059 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
6060 return offset_ == 0 ? 1 : 2;
6063 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
6064 switch (section + (offset_ == 0 ? 1 : 0)) {
6065 case 0: return UCLocalize("ENTERED_BY_USER");
6066 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
6072 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6073 int count = [sources_ count];
6075 case 0: return (offset_ == 0 ? count : offset_);
6076 case 1: return count - offset_;
6082 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
6084 switch (indexPath.section) {
6085 case 0: idx = indexPath.row; break;
6086 case 1: idx = indexPath.row + offset_; break;
6090 return [sources_ objectAtIndex:idx];
6093 - (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6094 Source *source = [self sourceAtIndexPath:indexPath];
6095 return [source description] == nil ? 56 : 73;
6098 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6099 static NSString *cellIdentifier = @"SourceCell";
6101 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
6102 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
6103 [cell setSource:[self sourceAtIndexPath:indexPath]];
6108 - (UITableViewCellAccessoryType) tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath {
6109 return UITableViewCellAccessoryDisclosureIndicator;
6112 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6113 Source *source = [self sourceAtIndexPath:indexPath];
6115 FilteredPackageController *packages = [[[FilteredPackageController alloc]
6116 initWithDatabase:database_
6117 title:[source label]
6118 filter:@selector(isVisibleInSource:)
6122 [packages setDelegate:delegate_];
6124 [[self navigationController] pushViewController:packages animated:YES];
6127 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
6128 Source *source = [self sourceAtIndexPath:indexPath];
6129 return [source record] != nil;
6132 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
6133 Source *source = [self sourceAtIndexPath:indexPath];
6134 [Sources_ removeObjectForKey:[source key]];
6135 [delegate_ syncData];
6139 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
6142 @"./", @"Distribution",
6143 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
6145 [delegate_ syncData];
6148 - (NSString *) getWarning {
6149 NSString *href(href_);
6150 NSRange colon([href rangeOfString:@"://"]);
6151 if (colon.location != NSNotFound)
6152 href = [href substringFromIndex:(colon.location + 3)];
6153 href = [href stringByAddingPercentEscapes];
6154 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
6155 href = [href stringByCachingURLWithCurrentCDN];
6157 NSURL *url([NSURL URLWithString:href]);
6159 NSStringEncoding encoding;
6160 NSError *error(nil);
6162 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
6163 return [warning length] == 0 ? nil : warning;
6167 - (void) _endConnection:(NSURLConnection *)connection {
6168 // XXX: the memory management in this method is horribly awkward
6170 NSURLConnection **field = NULL;
6171 if (connection == trivial_)
6173 else if (connection == trivial_bz2_)
6174 field = &trivial_bz2_;
6175 else if (connection == trivial_gz_)
6176 field = &trivial_gz_;
6177 _assert(field != NULL);
6178 [connection release];
6183 trivial_bz2_ == nil &&
6189 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
6192 UIAlertView *alert = [[[UIAlertView alloc]
6193 initWithTitle:UCLocalize("SOURCE_WARNING")
6196 cancelButtonTitle:UCLocalize("CANCEL")
6197 otherButtonTitles:UCLocalize("ADD_ANYWAY"), nil
6200 [alert setContext:@"warning"];
6201 [alert setNumberOfRows:1];
6205 } else if (error_ != nil) {
6206 UIAlertView *alert = [[[UIAlertView alloc]
6207 initWithTitle:UCLocalize("VERIFICATION_ERROR")
6208 message:[error_ localizedDescription]
6210 cancelButtonTitle:UCLocalize("OK")
6211 otherButtonTitles:nil
6214 [alert setContext:@"urlerror"];
6217 UIAlertView *alert = [[[UIAlertView alloc]
6218 initWithTitle:UCLocalize("NOT_REPOSITORY")
6219 message:UCLocalize("NOT_REPOSITORY_EX")
6221 cancelButtonTitle:UCLocalize("OK")
6222 otherButtonTitles:nil
6225 [alert setContext:@"trivial"];
6229 [delegate_ setStatusBarShowsProgress:NO];
6230 [delegate_ removeProgressHUD:hud_];
6240 if (error_ != nil) {
6247 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
6248 switch ([response statusCode]) {
6254 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
6255 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
6257 error_ = [error retain];
6258 [self _endConnection:connection];
6261 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
6262 [self _endConnection:connection];
6265 - (NSString *) title { return UCLocalize("SOURCES"); }
6267 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
6268 NSMutableURLRequest *request = [NSMutableURLRequest
6269 requestWithURL:[NSURL URLWithString:href]
6270 cachePolicy:NSURLRequestUseProtocolCachePolicy
6271 timeoutInterval:120.0
6274 [request setHTTPMethod:method];
6276 if (Machine_ != NULL)
6277 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
6278 if (UniqueID_ != nil)
6279 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6281 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
6283 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
6286 - (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
6287 NSString *context([alert context]);
6289 if ([context isEqualToString:@"source"]) {
6292 NSString *href = [[alert textField] text];
6294 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
6296 if (![href hasSuffix:@"/"])
6297 href_ = [href stringByAppendingString:@"/"];
6300 href_ = [href_ retain];
6302 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
6303 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
6304 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
6305 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
6309 // XXX: this is stupid
6310 hud_ = [[delegate_ addProgressHUD] retain];
6311 [hud_ setText:UCLocalize("VERIFYING_URL")];
6320 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6321 } else if ([context isEqualToString:@"trivial"])
6322 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6323 else if ([context isEqualToString:@"urlerror"])
6324 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6325 else if ([context isEqualToString:@"warning"]) {
6340 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6344 - (id) initWithDatabase:(Database *)database {
6345 if ((self = [super init]) != nil) {
6346 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
6347 [self updateButtonsForEditingStatus:NO animated:NO];
6349 database_ = database;
6350 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
6352 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6353 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6354 [[self view] addSubview:list_];
6356 [list_ setDataSource:self];
6357 [list_ setDelegate:self];
6363 - (void) reloadData {
6365 if (!list.ReadMainList())
6368 [sources_ removeAllObjects];
6369 [sources_ addObjectsFromArray:[database_ sources]];
6371 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
6374 int count([sources_ count]);
6376 for (int i = 0; i != count; i++) {
6377 if ([[sources_ objectAtIndex:i] record] == nil)
6382 [list_ setEditing:NO];
6383 [self updateButtonsForEditingStatus:NO animated:NO];
6387 - (void) addButtonClicked {
6388 /*[book_ pushPage:[[[AddSourceController alloc]
6393 UIAlertView *alert = [[[UIAlertView alloc]
6394 initWithTitle:UCLocalize("ENTER_APT_URL")
6397 cancelButtonTitle:UCLocalize("CANCEL")
6398 otherButtonTitles:UCLocalize("ADD_SOURCE"), nil
6401 [alert setContext:@"source"];
6402 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
6404 [alert setNumberOfRows:1];
6405 [alert addTextFieldWithValue:@"http://" label:@""];
6407 UITextInputTraits *traits = [[alert textField] textInputTraits];
6408 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6409 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6410 [traits setKeyboardType:UIKeyboardTypeURL];
6411 // XXX: UIReturnKeyDone
6412 [traits setReturnKeyType:UIReturnKeyNext];
6417 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
6418 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
6419 initWithTitle:UCLocalize("ADD")
6420 style:UIBarButtonItemStylePlain
6422 action:@selector(addButtonClicked)
6423 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
6425 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6426 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
6427 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
6429 action:@selector(editButtonClicked)
6430 ] autorelease] animated:animated];
6432 if (IsWildcat_ && !editing)
6433 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6434 initWithTitle:UCLocalize("SETTINGS")
6435 style:UIBarButtonItemStylePlain
6437 action:@selector(settingsButtonClicked)
6441 - (void) settingsButtonClicked {
6442 [delegate_ showSettings];
6445 - (void) editButtonClicked {
6446 [list_ setEditing:![list_ isEditing] animated:YES];
6448 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
6454 /* Installed Controller {{{ */
6455 @interface InstalledController : FilteredPackageController {
6459 - (id) initWithDatabase:(Database *)database;
6461 - (void) updateRoleButton;
6462 - (void) queueStatusDidChange;
6466 @implementation InstalledController
6472 - (NSString *) title { return UCLocalize("INSTALLED"); }
6474 - (id) initWithDatabase:(Database *)database {
6475 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
6476 [self updateRoleButton];
6477 [self queueStatusDidChange];
6482 - (void) queueButtonClicked {
6487 - (void) queueStatusDidChange {
6491 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6492 initWithTitle:UCLocalize("QUEUE")
6493 style:UIBarButtonItemStyleDone
6495 action:@selector(queueButtonClicked)
6498 [[self navigationItem] setLeftBarButtonItem:nil];
6504 - (void) reloadData {
6505 [packages_ reloadData];
6508 - (void) updateRoleButton {
6509 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
6510 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6511 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
6512 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
6514 action:@selector(roleButtonClicked)
6518 - (void) roleButtonClicked {
6519 [packages_ setObject:[NSNumber numberWithBool:expert_]];
6520 [packages_ reloadData];
6523 [self updateRoleButton];
6526 - (void) setDelegate:(id)delegate {
6527 [super setDelegate:delegate];
6528 [packages_ setDelegate:delegate];
6534 /* Home Controller {{{ */
6535 @interface HomeController : CYBrowserController {
6540 @implementation HomeController
6542 + (BOOL)shouldHideNavigationBar {
6546 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6547 [super _setMoreHeaders:request];
6550 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6551 if (UniqueID_ != nil)
6552 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6554 [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"];
6557 - (void) aboutButtonClicked {
6558 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6560 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6561 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6562 [alert setCancelButtonIndex:0];
6565 @"Copyright (C) 2008-2010\n"
6566 "Jay Freeman (saurik)\n"
6567 "saurik@saurik.com\n"
6568 "http://www.saurik.com/"
6574 - (void) viewWillAppear:(BOOL)animated {
6575 [super viewWillAppear:animated];
6577 if ([[self class] shouldHideNavigationBar])
6578 [[self navigationController] setNavigationBarHidden:YES animated:animated];
6581 - (void) viewWillDisappear:(BOOL)animated {
6582 [super viewWillDisappear:animated];
6584 if ([[self class] shouldHideNavigationBar])
6585 [[self navigationController] setNavigationBarHidden:NO animated:animated];
6589 if ((self = [super init]) != nil) {
6590 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6591 initWithTitle:UCLocalize("ABOUT")
6592 style:UIBarButtonItemStylePlain
6594 action:@selector(aboutButtonClicked)
6601 /* Manage Controller {{{ */
6602 @interface ManageController : CYBrowserController {
6605 - (void) queueStatusDidChange;
6608 @implementation ManageController
6611 if ((self = [super init]) != nil) {
6612 [[self navigationItem] setTitle:UCLocalize("MANAGE")];
6614 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6615 initWithTitle:UCLocalize("SETTINGS")
6616 style:UIBarButtonItemStylePlain
6618 action:@selector(settingsButtonClicked)
6621 [self queueStatusDidChange];
6625 - (void) settingsButtonClicked {
6626 [delegate_ showSettings];
6630 - (void) queueButtonClicked {
6634 - (void) applyLoadingTitle {
6635 // No "Loading" title.
6638 - (void) applyRightButton {
6643 - (void) queueStatusDidChange {
6645 if (!IsWildcat_ && Queuing_) {
6646 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6647 initWithTitle:UCLocalize("QUEUE")
6648 style:UIBarButtonItemStyleDone
6650 action:@selector(queueButtonClicked)
6653 [[self navigationItem] setRightBarButtonItem:nil];
6658 - (bool) isLoading {
6665 /* Refresh Bar {{{ */
6666 @interface RefreshBar : UINavigationBar {
6667 UIProgressIndicator *indicator_;
6668 UITextLabel *prompt_;
6669 UIProgressBar *progress_;
6670 UINavigationButton *cancel_;
6675 @implementation RefreshBar
6678 [indicator_ release];
6680 [progress_ release];
6685 - (void) positionViews {
6686 CGRect frame = [cancel_ frame];
6687 frame.size = [cancel_ sizeThatFits:frame.size];
6688 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6689 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6690 [cancel_ setFrame:frame];
6692 CGSize prgsize = {75, 100};
6694 [self frame].size.width - prgsize.width - 10,
6695 ([self frame].size.height - prgsize.height) / 2
6697 [progress_ setFrame:prgrect];
6699 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6700 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6701 CGRect indrect = {{indoffset, indoffset}, indsize};
6702 [indicator_ setFrame:indrect];
6704 CGSize prmsize = {215, indsize.height + 4};
6706 indoffset * 2 + indsize.width,
6707 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6709 [prompt_ setFrame:prmrect];
6712 - (void)setFrame:(CGRect)frame {
6713 [super setFrame:frame];
6715 [self positionViews];
6718 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6719 if ((self = [super initWithFrame:frame])) {
6720 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6722 [self setBarStyle:UIBarStyleBlack];
6724 UIBarStyle barstyle([self _barStyle:NO]);
6725 bool ugly(barstyle == UIBarStyleDefault);
6727 UIProgressIndicatorStyle style = ugly ?
6728 UIProgressIndicatorStyleMediumBrown :
6729 UIProgressIndicatorStyleMediumWhite;
6731 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6732 [indicator_ setStyle:style];
6733 [indicator_ startAnimation];
6734 [self addSubview:indicator_];
6736 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6737 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6738 [prompt_ setBackgroundColor:[UIColor clearColor]];
6739 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6740 [self addSubview:prompt_];
6742 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6743 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6744 [progress_ setStyle:0];
6745 [self addSubview:progress_];
6747 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6748 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6749 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6750 [cancel_ setBarStyle:barstyle];
6752 [self positionViews];
6757 [cancel_ removeFromSuperview];
6761 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6762 [progress_ setProgress:0];
6763 [self addSubview:cancel_];
6767 [cancel_ removeFromSuperview];
6770 - (void) setPrompt:(NSString *)prompt {
6771 [prompt_ setText:prompt];
6774 - (void) setProgress:(float)progress {
6775 [progress_ setProgress:progress];
6781 @class CYNavigationController;
6783 /* Cydia Tab Bar Controller {{{ */
6784 @interface CYTabBarController : UITabBarController <
6787 _transient Database *database_;
6788 RefreshBar *refreshbar_;
6792 // XXX: ok, "updatedelegate_"?...
6793 _transient NSObject<CydiaDelegate> *updatedelegate_;
6798 - (void) dropBar:(BOOL)animated;
6799 - (void) beginUpdate;
6800 - (void) raiseBar:(BOOL)animated;
6805 @implementation CYTabBarController
6807 /* XXX: some logic should probably go here related to
6808 freeing the view controllers on tab change */
6810 - (void) reloadData {
6811 size_t count([[self viewControllers] count]);
6812 for (size_t i(0); i != count; ++i) {
6813 CYNavigationController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6818 - (id) initWithDatabase:(Database *)database {
6819 if ((self = [super init]) != nil) {
6820 database_ = database;
6822 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6823 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6825 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
6829 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
6830 return IsWildcat_ || orientation == UIInterfaceOrientationPortrait;
6833 - (void) setUpdate:(NSDate *)date {
6837 - (void) beginUpdate {
6838 [refreshbar_ start];
6841 [updatedelegate_ retainNetworkActivityIndicator];
6845 detachNewThreadSelector:@selector(performUpdate)
6851 - (void) performUpdate { _pooled
6853 status.setDelegate(self);
6854 [database_ updateWithStatus:status];
6857 performSelectorOnMainThread:@selector(completeUpdate)
6863 - (void) stopUpdateWithSelector:(SEL)selector {
6865 [updatedelegate_ releaseNetworkActivityIndicator];
6867 [self raiseBar:YES];
6870 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6873 - (void) completeUpdate {
6876 [self stopUpdateWithSelector:@selector(reloadData)];
6879 - (void) cancelUpdate {
6880 [self stopUpdateWithSelector:@selector(updateData)];
6883 - (void) cancelPressed {
6884 [self cancelUpdate];
6891 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
6892 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
6895 - (void) startProgress {
6898 - (void) setProgressTitle:(NSString *)title {
6900 performSelectorOnMainThread:@selector(_setProgressTitle:)
6906 - (bool) isCancelling:(size_t)received {
6910 - (void) setProgressPercent:(float)percent {
6912 performSelectorOnMainThread:@selector(_setProgressPercent:)
6913 withObject:[NSNumber numberWithFloat:percent]
6918 - (void) addProgressOutput:(NSString *)output {
6920 performSelectorOnMainThread:@selector(_addProgressOutput:)
6926 - (void) _setProgressTitle:(NSString *)title {
6927 [refreshbar_ setPrompt:title];
6930 - (void) _setProgressPercent:(NSNumber *)percent {
6931 [refreshbar_ setProgress:[percent floatValue]];
6934 - (void) _addProgressOutput:(NSString *)output {
6937 - (void) setUpdateDelegate:(id)delegate {
6938 updatedelegate_ = delegate;
6941 - (CGFloat) statusBarHeight {
6942 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
6943 return [[UIApplication sharedApplication] statusBarFrame].size.height;
6945 return [[UIApplication sharedApplication] statusBarFrame].size.width;
6949 - (UIView *) transitionView {
6950 if ([self respondsToSelector:@selector(_transitionView)])
6951 return [self _transitionView];
6953 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6956 - (void) dropBar:(BOOL)animated {
6961 UIView *transition([self transitionView]);
6962 [[self view] addSubview:refreshbar_];
6964 CGRect barframe([refreshbar_ frame]);
6966 if (false) // XXX: _UIApplicationLinkedOnOrAfter(4)
6967 barframe.origin.y = [self statusBarHeight];
6969 barframe.origin.y = 0;
6971 [refreshbar_ setFrame:barframe];
6974 [UIView beginAnimations:nil context:NULL];
6976 CGRect viewframe = [transition frame];
6977 viewframe.origin.y += barframe.size.height;
6978 viewframe.size.height -= barframe.size.height;
6979 [transition setFrame:viewframe];
6982 [UIView commitAnimations];
6984 // Ensure bar has the proper width for our view, it might have changed
6985 barframe.size.width = viewframe.size.width;
6986 [refreshbar_ setFrame:barframe];
6988 // XXX: fix Apple's layout bug
6989 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6992 - (void) raiseBar:(BOOL)animated {
6997 UIView *transition([self transitionView]);
6998 [refreshbar_ removeFromSuperview];
7000 CGRect barframe([refreshbar_ frame]);
7003 [UIView beginAnimations:nil context:NULL];
7005 CGRect viewframe = [transition frame];
7006 viewframe.origin.y -= barframe.size.height;
7007 viewframe.size.height += barframe.size.height;
7008 [transition setFrame:viewframe];
7011 [UIView commitAnimations];
7013 // XXX: fix Apple's layout bug
7014 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7018 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7019 // XXX: fix Apple's layout bug
7020 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7024 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7025 bool dropped(dropped_);
7030 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
7035 // XXX: fix Apple's layout bug
7036 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7039 - (void) statusBarFrameChanged:(NSNotification *)notification {
7047 [refreshbar_ release];
7048 [[NSNotificationCenter defaultCenter] removeObserver:self];
7055 /* Cydia Navigation Controller {{{ */
7056 @interface CYNavigationController : UINavigationController {
7057 _transient Database *database_;
7058 _transient id<UINavigationControllerDelegate> delegate_;
7061 - (id) initWithDatabase:(Database *)database;
7062 - (void) reloadData;
7067 @implementation CYNavigationController
7069 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7070 // Inherit autorotation settings for modal parents.
7071 if ([self parentViewController] && [[self parentViewController] modalViewController] == self) {
7072 return [[self parentViewController] shouldAutorotateToInterfaceOrientation:orientation];
7073 } else if ([self parentViewController]) {
7074 return [[self parentViewController] shouldAutorotateToInterfaceOrientation:orientation];
7076 return [super shouldAutorotateToInterfaceOrientation:orientation];
7084 - (void) reloadData {
7085 size_t count([[self viewControllers] count]);
7086 for (size_t i(0); i != count; ++i) {
7087 CYViewController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
7092 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
7093 delegate_ = delegate;
7096 - (id) initWithDatabase:(Database *)database {
7097 if ((self = [super init]) != nil) {
7098 database_ = database;
7104 /* Cydia:// Protocol {{{ */
7105 @interface CydiaURLProtocol : NSURLProtocol {
7110 @implementation CydiaURLProtocol
7112 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7113 NSURL *url([request URL]);
7116 NSString *scheme([[url scheme] lowercaseString]);
7117 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
7122 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7126 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7127 id<NSURLProtocolClient> client([self client]);
7129 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7131 NSData *data(UIImagePNGRepresentation(icon));
7133 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7134 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7135 [client URLProtocol:self didLoadData:data];
7136 [client URLProtocolDidFinishLoading:self];
7140 - (void) startLoading {
7141 id<NSURLProtocolClient> client([self client]);
7142 NSURLRequest *request([self request]);
7144 NSURL *url([request URL]);
7145 NSString *href([url absoluteString]);
7147 NSString *path([href substringFromIndex:8]);
7148 NSRange slash([path rangeOfString:@"/"]);
7151 if (slash.location == NSNotFound) {
7155 command = [path substringToIndex:slash.location];
7156 path = [path substringFromIndex:(slash.location + 1)];
7159 Database *database([Database sharedInstance]);
7161 if ([command isEqualToString:@"package-icon"]) {
7164 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7165 Package *package([database packageWithName:path]);
7168 UIImage *icon([package icon]);
7169 [self _returnPNGWithImage:icon forRequest:request];
7170 } else if ([command isEqualToString:@"source-icon"]) {
7173 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7174 NSString *source(Simplify(path));
7175 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
7177 icon = [UIImage applicationImageNamed:@"unknown.png"];
7178 [self _returnPNGWithImage:icon forRequest:request];
7179 } else if ([command isEqualToString:@"uikit-image"]) {
7182 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7183 UIImage *icon(_UIImageWithName(path));
7184 [self _returnPNGWithImage:icon forRequest:request];
7185 } else if ([command isEqualToString:@"section-icon"]) {
7188 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7189 NSString *section(Simplify(path));
7190 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
7192 icon = [UIImage applicationImageNamed:@"unknown.png"];
7193 [self _returnPNGWithImage:icon forRequest:request];
7195 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7199 - (void) stopLoading {
7205 /* Sections Controller {{{ */
7206 @interface CYSectionsController : CYViewController <
7207 UITableViewDataSource,
7210 _transient Database *database_;
7211 NSMutableArray *sections_;
7212 NSMutableArray *filtered_;
7218 - (id) initWithDatabase:(Database *)database;
7219 - (void) reloadData;
7222 - (void) editButtonClicked;
7226 @implementation CYSectionsController
7229 [list_ setDataSource:nil];
7230 [list_ setDelegate:nil];
7232 [sections_ release];
7233 [filtered_ release];
7235 [accessory_ release];
7239 - (void) setEditing:(BOOL)editing {
7240 if ((editing_ = editing))
7243 [delegate_ updateData];
7245 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7246 [[[self navigationItem] rightBarButtonItem] setTitle:[sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT")];
7247 [[[self navigationItem] rightBarButtonItem] setStyle:editing_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain];
7250 - (void) viewDidAppear:(BOOL)animated {
7251 [super viewDidAppear:animated];
7252 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7255 - (void) viewWillDisappear:(BOOL)animated {
7256 [super viewWillDisappear:animated];
7257 if (editing_) [self setEditing:NO];
7260 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7261 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
7265 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7266 return editing_ ? [sections_ count] : [filtered_ count] + 1;
7269 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7273 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7274 static NSString *reuseIdentifier = @"SectionCell";
7276 SectionCell *cell = (SectionCell *) [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7278 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7280 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
7285 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7289 Section *section = [self sectionAtIndexPath:indexPath];
7290 NSString *name = [section name];
7293 if ([indexPath row] == 0) {
7296 title = UCLocalize("ALL_PACKAGES");
7299 name = [NSString stringWithString:name];
7300 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7303 title = UCLocalize("NO_SECTION");
7307 FilteredPackageController *table = [[[FilteredPackageController alloc]
7308 initWithDatabase:database_
7310 filter:@selector(isVisibleInSection:)
7314 [table setDelegate:delegate_];
7316 [[self navigationController] pushViewController:table animated:YES];
7319 - (NSString *) title { return UCLocalize("SECTIONS"); }
7321 - (id) initWithDatabase:(Database *)database {
7322 if ((self = [super init]) != nil) {
7323 database_ = database;
7325 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7327 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7328 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
7330 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
7331 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7332 [list_ setRowHeight:45.0f];
7333 [[self view] addSubview:list_];
7335 [list_ setDataSource:self];
7336 [list_ setDelegate:self];
7342 - (void) reloadData {
7343 NSArray *packages = [database_ packages];
7345 [sections_ removeAllObjects];
7346 [filtered_ removeAllObjects];
7348 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7351 for (Package *package in packages) {
7352 NSString *name([package section]);
7353 NSString *key(name == nil ? @"" : name);
7357 _profile(SectionsView$reloadData$Section)
7358 section = [sections objectForKey:key];
7359 if (section == nil) {
7360 _profile(SectionsView$reloadData$Section$Allocate)
7361 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
7362 [sections setObject:section forKey:key];
7367 [section addToCount];
7369 _profile(SectionsView$reloadData$Filter)
7370 if (![package valid] || ![package visible])
7378 [sections_ addObjectsFromArray:[sections allValues]];
7380 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7382 for (Section *section in sections_) {
7383 size_t count([section row]);
7387 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7388 [section setCount:count];
7389 [filtered_ addObject:section];
7392 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7393 initWithTitle:([sections_ count] == 0 ? nil : UCLocalize("EDIT"))
7394 style:UIBarButtonItemStylePlain
7396 action:@selector(editButtonClicked)
7397 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7403 - (void) resetView {
7405 [self editButtonClicked];
7408 - (void)editButtonClicked {
7409 [self setEditing:!editing_];
7412 - (UIView *) accessoryView {
7418 /* Changes Controller {{{ */
7419 @interface ChangesController : CYViewController <
7420 UITableViewDataSource,
7423 _transient Database *database_;
7425 CFMutableArrayRef packages_;
7426 NSMutableArray *sections_;
7429 BOOL hasSentFirstLoad_;
7432 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
7433 - (void) reloadData;
7437 @implementation ChangesController
7440 [list_ setDelegate:nil];
7441 [list_ setDataSource:nil];
7443 CFRelease(packages_);
7445 [sections_ release];
7450 - (void) viewDidAppear:(BOOL)animated {
7451 [super viewDidAppear:animated];
7452 if (!hasSentFirstLoad_) {
7453 hasSentFirstLoad_ = YES;
7454 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
7456 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7460 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7461 NSInteger count([sections_ count]);
7462 return count == 0 ? 1 : count;
7465 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7466 if ([sections_ count] == 0)
7468 return [[sections_ objectAtIndex:section] name];
7471 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7472 if ([sections_ count] == 0)
7474 return [[sections_ objectAtIndex:section] count];
7477 - (Package *) packageAtIndex:(NSUInteger)index {
7478 return (Package *) CFArrayGetValueAtIndex(packages_, index);
7481 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7482 @synchronized (database_) {
7483 if ([database_ era] != era_)
7486 Section *section([sections_ objectAtIndex:[path section]]);
7487 NSInteger row([path row]);
7488 return [[[self packageAtIndex:([section row] + row)] retain] autorelease];
7491 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7492 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7494 cell = [[[PackageCell alloc] init] autorelease];
7495 [cell setPackage:[self packageAtIndexPath:path]];
7499 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
7500 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
7503 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7504 Package *package([self packageAtIndexPath:path]);
7505 PackageController *view([delegate_ packageController]);
7506 [view setDelegate:delegate_];
7507 [view setPackage:package];
7508 [[self navigationController] pushViewController:view animated:YES];
7512 - (void) refreshButtonClicked {
7513 [delegate_ beginUpdate];
7514 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7517 - (void) upgradeButtonClicked {
7518 [delegate_ distUpgrade];
7521 - (NSString *) title { return UCLocalize("CHANGES"); }
7523 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7524 if ((self = [super init]) != nil) {
7525 database_ = database;
7526 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7528 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7530 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7532 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7533 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7534 [list_ setRowHeight:73.0f];
7535 [[self view] addSubview:list_];
7537 [list_ setDataSource:self];
7538 [list_ setDelegate:self];
7540 delegate_ = delegate;
7544 - (void) _reloadPackages:(NSArray *)packages {
7545 CFRelease(packages_);
7546 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, [packages count], NULL);
7549 for (Package *package in packages)
7550 if ([package upgradableAndEssential:YES] || [package visible])
7551 CFArrayAppendValue(packages_, package);
7554 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7558 - (void) reloadData {
7559 @synchronized (database_) {
7560 era_ = [database_ era];
7561 NSArray *packages = [database_ packages];
7563 [sections_ removeAllObjects];
7566 UIProgressHUD *hud([delegate_ addProgressHUD]);
7567 [hud setText:UCLocalize("LOADING")];
7568 //NSLog(@"HUD:%@::%@", delegate_, hud);
7569 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7570 [delegate_ removeProgressHUD:hud];
7572 [self _reloadPackages:packages];
7575 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7576 Section *ignored = nil;
7577 Section *section = nil;
7581 bool unseens = false;
7583 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7585 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7586 Package *package = [self packageAtIndex:offset];
7588 BOOL uae = [package upgradableAndEssential:YES];
7592 time_t seen([package seen]);
7594 if (section == nil || last != seen) {
7598 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7601 _profile(ChangesController$reloadData$Allocate)
7602 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7603 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7604 [sections_ addObject:section];
7608 [section addToCount];
7609 } else if ([package ignored]) {
7610 if (ignored == nil) {
7611 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7613 [ignored addToCount];
7616 [upgradable addToCount];
7621 CFRelease(formatter);
7624 Section *last = [sections_ lastObject];
7625 size_t count = [last count];
7626 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7627 [sections_ removeLastObject];
7630 if ([ignored count] != 0)
7631 [sections_ insertObject:ignored atIndex:0];
7633 [sections_ insertObject:upgradable atIndex:0];
7638 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7639 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7640 style:UIBarButtonItemStylePlain
7642 action:@selector(upgradeButtonClicked)
7645 if (![delegate_ updating])
7646 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7647 initWithTitle:UCLocalize("REFRESH")
7648 style:UIBarButtonItemStylePlain
7650 action:@selector(refreshButtonClicked)
7656 /* Search Controller {{{ */
7657 @interface SearchController : FilteredPackageController <
7660 UISearchBar *search_;
7663 - (id) initWithDatabase:(Database *)database;
7664 - (void) reloadData;
7668 @implementation SearchController
7675 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7676 [packages_ setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7677 [search_ resignFirstResponder];
7681 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7682 [packages_ setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7686 - (NSString *) title { return nil; }
7688 - (id) initWithDatabase:(Database *)database {
7689 return [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil];
7692 - (void)viewDidAppear:(BOOL)animated {
7693 [super viewDidAppear:animated];
7695 search_ = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7696 [search_ layoutSubviews];
7697 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7699 UITextField *textField;
7700 if ([search_ respondsToSelector:@selector(searchField)])
7701 textField = [search_ searchField];
7703 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7705 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7706 [search_ setDelegate:self];
7707 [textField setEnablesReturnKeyAutomatically:NO];
7708 [[self navigationItem] setTitleView:textField];
7712 - (void) _reloadData {
7715 - (void) reloadData {
7716 _profile(SearchController$reloadData)
7717 [packages_ reloadData];
7720 [packages_ resetCursor];
7723 - (void) didSelectPackage:(Package *)package {
7724 [search_ resignFirstResponder];
7725 [super didSelectPackage:package];
7730 /* Settings Controller {{{ */
7731 @interface CYPackageSettingsController : CYViewController <
7732 UITableViewDataSource,
7735 _transient Database *database_;
7738 UITableView *table_;
7739 UISwitch *subscribedSwitch_;
7740 UISwitch *ignoredSwitch_;
7741 UITableViewCell *subscribedCell_;
7742 UITableViewCell *ignoredCell_;
7745 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7749 @implementation CYPackageSettingsController
7753 if (package_ != nil)
7756 [subscribedSwitch_ release];
7757 [ignoredSwitch_ release];
7758 [subscribedCell_ release];
7759 [ignoredCell_ release];
7764 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7765 if (package_ == nil)
7771 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7772 if (package_ == nil)
7778 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7779 return UCLocalize("SHOW_ALL_CHANGES_EX");
7782 - (void) onSubscribed:(id)control {
7783 bool value([control isOn]);
7784 if (package_ == nil)
7786 if ([package_ setSubscribed:value])
7787 [delegate_ updateData];
7790 - (void) onIgnored:(id)control {
7791 // TODO: set Held state - possibly call out to dpkg, etc.
7794 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7795 if (package_ == nil)
7798 switch ([indexPath row]) {
7799 case 0: return subscribedCell_;
7800 case 1: return ignoredCell_;
7808 - (NSString *) title { return UCLocalize("SETTINGS"); }
7810 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7811 if ((self = [super init])) {
7812 database_ = database;
7813 name_ = [package retain];
7815 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7817 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7818 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7819 [[self view] addSubview:table_];
7821 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7822 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7823 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7825 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7826 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7827 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7829 subscribedCell_ = [[UITableViewCell alloc] init];
7830 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7831 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7832 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7834 ignoredCell_ = [[UITableViewCell alloc] init];
7835 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7836 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7837 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7839 [table_ setDataSource:self];
7840 [table_ setDelegate:self];
7845 - (void) reloadData {
7846 if (package_ != nil)
7847 [package_ autorelease];
7848 package_ = [database_ packageWithName:name_];
7849 if (package_ != nil) {
7851 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7852 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7855 [table_ reloadData];
7860 /* Signature Controller {{{ */
7861 @interface SignatureController : CYBrowserController {
7862 _transient Database *database_;
7866 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7870 @implementation SignatureController
7877 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7879 [super webView:view didClearWindowObject:window forFrame:frame];
7882 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7883 if ((self = [super init]) != nil) {
7884 database_ = database;
7885 package_ = [package retain];
7890 - (void) reloadData {
7891 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7897 /* Role Controller {{{ */
7898 @interface CYSettingsController : CYViewController <
7899 UITableViewDataSource,
7902 _transient Database *database_;
7903 // XXX: ok, "roledelegate_"?...
7904 _transient id roledelegate_;
7905 UITableView *table_;
7906 UISegmentedControl *segment_;
7910 - (void) showDoneButton;
7911 - (void) resizeSegmentedControl;
7915 @implementation CYSettingsController
7919 [container_ release];
7924 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7925 if ((self = [super init])) {
7926 database_ = database;
7927 roledelegate_ = delegate;
7929 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
7931 NSArray *items = [NSArray arrayWithObjects:
7933 UCLocalize("HACKER"),
7934 UCLocalize("DEVELOPER"),
7936 segment_ = [[UISegmentedControl alloc] initWithItems:items];
7937 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
7938 [container_ addSubview:segment_];
7941 if ([Role_ isEqualToString:@"User"]) index = 0;
7942 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
7943 if ([Role_ isEqualToString:@"Developer"]) index = 2;
7945 [segment_ setSelectedSegmentIndex:index];
7946 [self showDoneButton];
7949 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
7950 [self resizeSegmentedControl];
7952 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7953 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7954 [table_ setDelegate:self];
7955 [table_ setDataSource:self];
7956 [[self view] addSubview:table_];
7957 [table_ reloadData];
7961 - (void) resizeSegmentedControl {
7962 CGFloat width = [[self view] frame].size.width;
7963 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
7966 - (void) viewWillAppear:(BOOL)animated {
7967 [super viewWillAppear:animated];
7969 [self resizeSegmentedControl];
7972 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7973 [self resizeSegmentedControl];
7976 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7977 [self resizeSegmentedControl];
7981 NSString *role(nil);
7983 switch ([segment_ selectedSegmentIndex]) {
7984 case 0: role = @"User"; break;
7985 case 1: role = @"Hacker"; break;
7986 case 2: role = @"Developer"; break;
7991 if (![role isEqualToString:Role_]) {
7992 bool rolling(Role_ == nil);
7995 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7999 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8003 [roledelegate_ loadData];
8005 [roledelegate_ updateData];
8009 - (void) segmentChanged:(UISegmentedControl *)control {
8010 [self showDoneButton];
8013 - (void) saveAndClose {
8016 [[self navigationItem] setRightBarButtonItem:nil];
8017 [[self navigationController] dismissModalViewControllerAnimated:YES];
8020 - (void) doneButtonClicked {
8021 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8022 [spinner startAnimating];
8023 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8024 [[self navigationItem] setRightBarButtonItem:spinItem];
8026 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8029 - (void) showDoneButton {
8030 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8031 initWithTitle:UCLocalize("DONE")
8032 style:UIBarButtonItemStyleDone
8034 action:@selector(doneButtonClicked)
8035 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8038 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8039 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8043 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8047 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8048 return nil; // This method is required by the protocol.
8051 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8053 return UCLocalize("ROLE_EX");
8055 return [NSString stringWithFormat:
8056 @"%@: %@\n%@: %@\n%@: %@",
8057 UCLocalize("USER"), UCLocalize("USER_EX"),
8058 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8059 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8064 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8065 return section == 3 ? 44.0f : 0;
8068 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8069 return section == 3 ? container_ : nil;
8074 /* Stash Controller {{{ */
8075 @interface CYStashController : CYViewController {
8076 // XXX: just delete these things
8077 _transient UIActivityIndicatorView *spinner_;
8078 _transient UILabel *status_;
8079 _transient UILabel *caption_;
8083 @implementation CYStashController
8085 if ((self = [super init])) {
8086 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8088 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8089 CGRect spinrect = [spinner_ frame];
8090 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8091 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8092 [spinner_ setFrame:spinrect];
8093 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8094 [[self view] addSubview:spinner_];
8095 [spinner_ startAnimating];
8098 captrect.size.width = [[self view] frame].size.width;
8099 captrect.size.height = 40.0f;
8100 captrect.origin.x = 0;
8101 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8102 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8103 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8104 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8105 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8106 [caption_ setTextColor:[UIColor whiteColor]];
8107 [caption_ setBackgroundColor:[UIColor clearColor]];
8108 [caption_ setShadowColor:[UIColor blackColor]];
8109 [caption_ setTextAlignment:UITextAlignmentCenter];
8110 [[self view] addSubview:caption_];
8113 statusrect.size.width = [[self view] frame].size.width;
8114 statusrect.size.height = 30.0f;
8115 statusrect.origin.x = 0;
8116 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8117 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8118 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8119 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8120 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8121 [status_ setTextColor:[UIColor whiteColor]];
8122 [status_ setBackgroundColor:[UIColor clearColor]];
8123 [status_ setShadowColor:[UIColor blackColor]];
8124 [status_ setTextAlignment:UITextAlignmentCenter];
8125 [[self view] addSubview:status_];
8129 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
8130 return IsWildcat_ || orientation == UIInterfaceOrientationPortrait;
8145 @interface Cydia : UIApplication <
8146 ConfirmationControllerDelegate,
8147 ProgressControllerDelegate,
8149 UINavigationControllerDelegate,
8150 UITabBarControllerDelegate
8152 // XXX: evaluate all fields for _transient
8155 CYTabBarController *tabbar_;
8157 NSMutableArray *essential_;
8158 NSMutableArray *broken_;
8160 Database *database_;
8168 CYSectionsController *sections_;
8169 ChangesController *changes_;
8170 ManageController *manage_;
8171 SearchController *search_;
8172 SourceController *sources_;
8173 InstalledController *installed_;
8176 CYStashController *stash_;
8181 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class;
8182 - (void) setPage:(CYViewController *)page;
8185 // XXX: I hate prototypes
8186 - (id) queueBadgeController;
8190 static _finline void _setHomePage(Cydia *self) {
8191 [self setPage:[self _pageForURL:[NSURL URLWithString:CydiaURL(@"")] withClass:[HomeController class]]];
8194 @implementation Cydia
8196 - (void) beginUpdate {
8197 [tabbar_ beginUpdate];
8201 return [tabbar_ updating];
8205 if ([broken_ count] != 0) {
8206 int count = [broken_ count];
8208 UIAlertView *alert = [[[UIAlertView alloc]
8209 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8210 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8212 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8213 otherButtonTitles:UCLocalize("TEMPORARY_IGNORE"), nil
8216 [alert setContext:@"fixhalf"];
8218 } else if (!Ignored_ && [essential_ count] != 0) {
8219 int count = [essential_ count];
8221 UIAlertView *alert = [[[UIAlertView alloc]
8222 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8223 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8225 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8226 otherButtonTitles:UCLocalize("UPGRADE_ESSENTIAL"), UCLocalize("COMPLETE_UPGRADE"), nil
8229 [alert setContext:@"upgrade"];
8234 - (void) _saveConfig {
8240 NSString *error(nil);
8242 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8244 NSError *error(nil);
8245 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8246 NSLog(@"failure to save metadata data: %@", error);
8251 NSLog(@"failure to serialize metadata: %@", error);
8256 - (void) _updateData {
8259 NSMutableSet *tabs([[[NSMutableSet alloc] initWithCapacity:10] autorelease]);
8261 [tabs addObject:[tabbar_ selectedViewController]];
8263 if (sections_ != nil)
8264 [tabs addObject:sections_];
8265 if (changes_ != nil)
8266 [tabs addObject:changes_];
8268 [tabs addObject:manage_];
8270 [tabs addObject:search_];
8271 if (sources_ != nil)
8272 [tabs addObject:sources_];
8273 if (installed_ != nil)
8274 [tabs addObject:installed_];
8276 for (CYNavigationController *tab in tabs)
8279 [queueDelegate_ queueStatusDidChange];
8280 [[[self queueBadgeController] tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8283 - (int)indexOfTabWithTag:(int)tag {
8285 for (UINavigationController *controller in [tabbar_ viewControllers]) {
8286 if ([[controller tabBarItem] tag] == tag)
8294 - (void) _refreshIfPossible {
8295 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8297 bool recently = false;
8298 NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
8299 if (update != nil) {
8300 NSTimeInterval interval([update timeIntervalSinceNow]);
8301 if (interval <= 0 && interval > -(15*60))
8305 // Don't automatic refresh if:
8306 // - We already refreshed recently.
8307 // - We already auto-refreshed this launch.
8308 // - Auto-refresh is disabled.
8309 if (recently || loaded_ || ManualRefresh) {
8310 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8312 // If we are cancelling due to ManualRefresh or a recent refresh
8313 // we need to make sure it knows it's already loaded.
8317 // We are going to load, so remember that.
8321 SCNetworkReachabilityFlags flags; {
8322 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8323 SCNetworkReachabilityGetFlags(reachability, &flags);
8324 CFRelease(reachability);
8327 // XXX: this elaborate mess is what Apple is using to determine this? :(
8328 // XXX: do we care if the user has to intervene? maybe that's ok?
8330 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8331 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8332 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8333 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8334 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8335 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8339 // If we can reach the server, auto-refresh!
8341 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8346 - (void) refreshIfPossible {
8347 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
8350 - (void) _reloadData {
8351 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8352 [hud setText:UCLocalize("RELOADING_DATA")];
8354 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
8357 [self removeProgressHUD:hud];
8361 [essential_ removeAllObjects];
8362 [broken_ removeAllObjects];
8364 NSArray *packages([database_ packages]);
8365 for (Package *package in packages) {
8367 [broken_ addObject:package];
8368 if ([package upgradableAndEssential:NO]) {
8369 if ([package essential])
8370 [essential_ addObject:package];
8375 NSLog(@"changes:#%u", changes);
8377 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem];
8380 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8381 [changesItem setBadgeValue:badge];
8382 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8383 [self setApplicationIconBadgeNumber:changes];
8386 [changesItem setBadgeValue:nil];
8387 [changesItem setAnimatedBadge:NO];
8388 [self setApplicationIconBadgeNumber:0];
8393 [self refreshIfPossible];
8396 - (void) updateData {
8405 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8406 _assert(file != NULL);
8408 for (NSString *key in [Sources_ allKeys]) {
8409 NSDictionary *source([Sources_ objectForKey:key]);
8411 fprintf(file, "%s %s %s\n",
8412 [[source objectForKey:@"Type"] UTF8String],
8413 [[source objectForKey:@"URI"] UTF8String],
8414 [[source objectForKey:@"Distribution"] UTF8String]
8422 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8423 CYNavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8425 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8426 [tabbar_ presentModalViewController:navigation animated:YES];
8429 detachNewThreadSelector:@selector(update_)
8432 title:UCLocalize("UPDATING_SOURCES")
8436 - (void) reloadData {
8437 @synchronized (self) {
8443 pkgProblemResolver *resolver = [database_ resolver];
8445 resolver->InstallProtect();
8446 if (!resolver->Resolve(true))
8451 if (![database_ prepare])
8454 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8455 [page setDelegate:self];
8456 CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]);
8457 [confirm_ setDelegate:self];
8460 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8461 [tabbar_ presentModalViewController:confirm_ animated:YES];
8467 @synchronized (self) {
8472 - (void) clearPackage:(Package *)package {
8473 @synchronized (self) {
8480 - (void) installPackages:(NSArray *)packages {
8481 @synchronized (self) {
8482 for (Package *package in packages)
8489 - (void) installPackage:(Package *)package {
8490 @synchronized (self) {
8497 - (void) removePackage:(Package *)package {
8498 @synchronized (self) {
8505 - (void) distUpgrade {
8506 @synchronized (self) {
8507 if (![database_ upgrade])
8514 @synchronized (self) {
8519 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8522 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8524 if (navigation != nil) {
8525 [navigation pushViewController:progress animated:YES];
8527 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8529 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8530 [tabbar_ presentModalViewController:navigation animated:YES];
8534 detachNewThreadSelector:@selector(perform)
8537 title:UCLocalize("RUNNING")
8543 - (void) progressControllerIsComplete:(ProgressController *)progress {
8548 - (void) setPage:(CYViewController *)page {
8549 [page setDelegate:self];
8551 CYNavigationController *navController = (CYNavigationController *) [tabbar_ selectedViewController];
8552 [navController setViewControllers:[NSArray arrayWithObject:page]];
8553 for (CYNavigationController *page in [tabbar_ viewControllers])
8554 if (page != navController)
8555 [page setViewControllers:nil];
8558 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class {
8559 CYBrowserController *browser = [[[_class alloc] init] autorelease];
8560 [browser loadURL:url];
8564 - (CYSectionsController *) sectionsController {
8565 if (sections_ == nil)
8566 sections_ = [[CYSectionsController alloc] initWithDatabase:database_];
8570 - (ChangesController *) changesController {
8571 if (changes_ == nil)
8572 changes_ = [[ChangesController alloc] initWithDatabase:database_ delegate:self];
8576 - (ManageController *) manageController {
8577 if (manage_ == nil) {
8578 manage_ = (ManageController *) [[self
8579 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
8580 withClass:[ManageController class]
8583 queueDelegate_ = manage_;
8588 - (SearchController *) searchController {
8590 search_ = [[SearchController alloc] initWithDatabase:database_];
8594 - (SourceController *) sourcesController {
8595 if (sources_ == nil)
8596 sources_ = [[SourceController alloc] initWithDatabase:database_];
8600 - (InstalledController *) installedController {
8601 if (installed_ == nil) {
8602 installed_ = [[InstalledController alloc] initWithDatabase:database_];
8604 queueDelegate_ = installed_;
8609 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
8610 int tag = [[viewController tabBarItem] tag];
8612 [(CYNavigationController *)[tabbar_ selectedViewController] popToRootViewControllerAnimated:YES];
8614 } else if (tag_ == 1) {
8615 [[self sectionsController] resetView];
8619 case kCydiaTag: _setHomePage(self); break;
8621 case kSectionsTag: [self setPage:[self sectionsController]]; break;
8622 case kChangesTag: [self setPage:[self changesController]]; break;
8623 case kManageTag: [self setPage:[self manageController]]; break;
8624 case kInstalledTag: [self setPage:[self installedController]]; break;
8625 case kSourcesTag: [self setPage:[self sourcesController]]; break;
8626 case kSearchTag: [self setPage:[self searchController]]; break;
8634 - (void) showSettings {
8635 CYSettingsController *role = [[[CYSettingsController alloc] initWithDatabase:database_ delegate:self] autorelease];
8636 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
8638 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
8639 [tabbar_ presentModalViewController:nav animated:YES];
8642 - (void) retainNetworkActivityIndicator {
8643 if (activity_++ == 0)
8644 [self setNetworkActivityIndicatorVisible:YES];
8647 - (void) releaseNetworkActivityIndicator {
8648 if (--activity_ == 0)
8649 [self setNetworkActivityIndicatorVisible:NO];
8652 - (void) setPackageController:(PackageController *)view {
8654 [view setPackage:nil];
8658 - (PackageController *) _packageController {
8659 return [[[PackageController alloc] initWithDatabase:database_] autorelease];
8662 - (PackageController *) packageController {
8663 return [self _packageController];
8666 // Returns the navigation controller for the queuing badge.
8667 - (id) queueBadgeController {
8668 int index = [self indexOfTabWithTag:kManageTag];
8670 index = [self indexOfTabWithTag:kInstalledTag];
8672 return [[tabbar_ viewControllers] objectAtIndex:index];
8675 - (void) cancelAndClear:(bool)clear {
8676 @synchronized (self) {
8688 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8689 NSString *context([alert context]);
8691 if ([context isEqualToString:@"fixhalf"]) {
8692 if (button == [alert firstOtherButtonIndex]) {
8693 @synchronized (self) {
8694 for (Package *broken in broken_) {
8697 NSString *id = [broken id];
8698 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8699 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8700 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8701 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8707 } else if (button == [alert cancelButtonIndex]) {
8708 [broken_ removeAllObjects];
8712 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8713 } else if ([context isEqualToString:@"upgrade"]) {
8714 if (button == [alert firstOtherButtonIndex]) {
8715 @synchronized (self) {
8716 for (Package *essential in essential_)
8717 [essential install];
8722 } else if (button == [alert firstOtherButtonIndex] + 1) {
8724 } else if (button == [alert cancelButtonIndex]) {
8728 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8732 - (void) system:(NSString *)command { _pooled
8734 system([command UTF8String]);
8738 - (void) applicationWillSuspend {
8740 [super applicationWillSuspend];
8743 - (BOOL) isSafeToSuspend {
8744 // Use external process status API internally.
8745 // This is probably a really bad idea.
8746 // XXX: what is the point of this? does this solve anything at all?
8747 uint64_t status = 0;
8749 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
8750 notify_get_state(notify_token, &status);
8751 notify_cancel(notify_token);
8754 return locked_ == 0 && status == 0;
8757 - (void) applicationSuspend:(__GSEvent *)event {
8758 if ([self isSafeToSuspend])
8759 [super applicationSuspend:event];
8762 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8763 if ([self isSafeToSuspend])
8764 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8767 - (void) _setSuspended:(BOOL)value {
8768 if ([self isSafeToSuspend])
8769 [super _setSuspended:value];
8772 - (UIProgressHUD *) addProgressHUD {
8773 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8774 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8776 [window_ setUserInteractionEnabled:NO];
8779 UIViewController *target = tabbar_;
8780 while ([target modalViewController] != nil) target = [target modalViewController];
8781 [[target view] addSubview:hud];
8787 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8789 [hud removeFromSuperview];
8790 [window_ setUserInteractionEnabled:YES];
8794 - (CYViewController *) pageForPackage:(NSString *)name {
8795 if (Package *package = [database_ packageWithName:name]) {
8796 PackageController *view([self packageController]);
8797 [view setPackage:package];
8800 NSURL *url([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"unknown" ofType:@"html"]]);
8801 url = [NSURL URLWithString:[[url absoluteString] stringByAppendingString:[NSString stringWithFormat:@"?%@", name]]];
8802 return [self _pageForURL:url withClass:[CYBrowserController class]];
8806 - (CYViewController *) pageForURL:(NSURL *)url hasTag:(int *)tag {
8810 NSString *href([url absoluteString]);
8811 if ([href hasPrefix:@"apptapp://package/"])
8812 return [self pageForPackage:[href substringFromIndex:18]];
8814 NSString *scheme([[url scheme] lowercaseString]);
8815 if (![scheme isEqualToString:@"cydia"])
8817 NSString *path([url absoluteString]);
8818 if ([path length] < 8)
8820 path = [path substringFromIndex:8];
8821 if (![path hasPrefix:@"/"])
8822 path = [@"/" stringByAppendingString:path];
8824 if ([path isEqualToString:@"/storage"])
8825 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CYBrowserController class]];
8826 /*else if ([path isEqualToString:@"/add-source"])
8827 return [[[AddSourceController alloc] initWithDatabase:database_] autorelease];*/
8828 else if ([path isEqualToString:@"/sources"])
8829 return [[[SourceController alloc] initWithDatabase:database_] autorelease];
8830 else if ([path isEqualToString:@"/packages"])
8831 return [[[InstalledController alloc] initWithDatabase:database_] autorelease];
8832 else if ([path hasPrefix:@"/url/"])
8833 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[CYBrowserController class]];
8834 else if ([path hasPrefix:@"/launch/"])
8835 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8836 else if ([path hasPrefix:@"/package-settings/"])
8837 return [[[CYPackageSettingsController alloc] initWithDatabase:database_ package:[path substringFromIndex:18]] autorelease];
8838 else if ([path hasPrefix:@"/package-signature/"])
8839 return [[[SignatureController alloc] initWithDatabase:database_ package:[path substringFromIndex:19]] autorelease];
8840 else if ([path hasPrefix:@"/package/"])
8841 return [self pageForPackage:[path substringFromIndex:9]];
8842 else if ([path hasPrefix:@"/files/"]) {
8843 NSString *name = [path substringFromIndex:7];
8845 if (Package *package = [database_ packageWithName:name]) {
8846 FileTable *files = [[[FileTable alloc] initWithDatabase:database_] autorelease];
8847 [files setPackage:package];
8855 - (BOOL) openCydiaURL:(NSURL *)url {
8856 CYViewController *page = nil;
8859 if ((page = [self pageForURL:url hasTag:&tag])) {
8860 [self setPage:page];
8862 [tabbar_ setSelectedViewController:(tag_ == -1 ? nil : [[tabbar_ viewControllers] objectAtIndex:tag_])];
8868 - (void) applicationOpenURL:(NSURL *)url {
8869 [super applicationOpenURL:url];
8871 if (!loaded_) starturl_ = [url retain];
8872 else [self openCydiaURL:url];
8875 - (void) applicationWillResignActive:(UIApplication *)application {
8876 // Stop refreshing if you get a phone call or lock the device.
8877 if ([tabbar_ updating])
8878 [tabbar_ cancelUpdate];
8880 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
8881 [super applicationWillResignActive:application];
8884 - (void) addStashController {
8886 stash_ = [[CYStashController alloc] init];
8887 [window_ addSubview:[stash_ view]];
8890 - (void) removeStashController {
8891 [[stash_ view] removeFromSuperview];
8897 [self setIdleTimerDisabled:YES];
8899 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
8900 [self setStatusBarShowsProgress:YES];
8901 UpdateExternalStatus(1);
8903 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
8905 UpdateExternalStatus(0);
8906 [self setStatusBarShowsProgress:NO];
8908 [self removeStashController];
8910 if (ExecFork() == 0) {
8911 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
8912 perror("launchctl stop");
8916 - (void) setupTabBarController {
8917 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
8918 [tabbar_ setDelegate:self];
8920 NSMutableArray *items([NSMutableArray arrayWithObjects:
8921 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:kCydiaTag] autorelease],
8922 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:kSectionsTag] autorelease],
8923 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:kChangesTag] autorelease],
8924 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:kSearchTag] autorelease],
8928 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:kSourcesTag] autorelease] atIndex:3];
8929 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:kInstalledTag] autorelease] atIndex:3];
8931 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:kManageTag] autorelease] atIndex:3];
8934 NSMutableArray *controllers([NSMutableArray array]);
8936 for (UITabBarItem *item in items) {
8937 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
8938 [controller setTabBarItem:item];
8939 [controllers addObject:controller];
8942 [tabbar_ setViewControllers:controllers];
8945 - (void)showFakeTabBarInView:(UIView *)view {
8946 static UITabBar *fake = [[UITabBar alloc] initWithFrame:CGRectMake(0, 0, 0, 49.0f)];
8948 CGRect frame = [fake frame];
8949 frame.origin.y = [view frame].size.height - frame.size.height;
8950 frame.size.width = [view frame].size.width;
8951 [fake setFrame:frame];
8952 [fake setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
8953 [view addSubview:fake];
8955 [fake removeFromSuperview];
8959 - (void) applicationDidFinishLaunching:(id)unused {
8963 [NSURLCache setSharedURLCache:[[[SDURLCache alloc]
8964 initWithMemoryCapacity:524288
8965 diskCapacity:10485760
8966 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
8969 [CYBrowserController _initialize];
8971 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8973 Font12_ = [[UIFont systemFontOfSize:12] retain];
8974 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8975 Font14_ = [[UIFont systemFontOfSize:14] retain];
8976 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8977 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8981 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8982 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8984 window_ = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
8985 [window_ orderFront:self];
8986 [window_ makeKey:self];
8987 [window_ setHidden:NO];
8990 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8991 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8992 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8993 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
8994 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8995 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8996 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8997 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
8998 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9001 [self addStashController];
9002 // XXX: this would be much cleaner as a yieldToSelector:
9003 // that way the removeStashController could happen right here inline
9004 // we also could no longer require the useless stash_ field anymore
9005 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9009 database_ = [Database sharedInstance];
9011 [self setupTabBarController];
9012 [tabbar_ setUpdateDelegate:self];
9013 [window_ addSubview:[tabbar_ view]];
9015 // Show pinstripes while loading data.
9016 [[tabbar_ view] setBackgroundColor:[UIColor pinStripeColor]];
9017 [self showFakeTabBarInView:[tabbar_ tabBar]];
9019 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9026 [self showSettings];
9030 CGRect fixframe = [[tabbar_ view] frame];
9031 if (UIInterfaceOrientationIsLandscape([[UIApplication sharedApplication] statusBarOrientation]))
9032 fixframe.size = CGSizeMake(fixframe.size.height, fixframe.size.width);
9033 CYLoadingIndicator *loading = [[[CYLoadingIndicator alloc] initWithFrame:fixframe] autorelease];
9034 [loading setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9035 [[tabbar_ view] addSubview:loading];
9036 [window_ setUserInteractionEnabled:NO];
9041 // Show the initial page
9042 if (starturl_ == nil || ![self openCydiaURL:starturl_]) {
9043 [tabbar_ setSelectedIndex:0];
9047 [self showFakeTabBarInView:nil];
9049 [starturl_ release];
9052 [window_ setUserInteractionEnabled:YES];
9054 // XXX: does this actually slow anything down?
9055 [[tabbar_ view] setBackgroundColor:[UIColor clearColor]];
9056 [loading removeFromSuperview];
9059 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9060 if (item != nil && IsWildcat_) {
9061 [sheet showFromBarButtonItem:item animated:YES];
9063 [sheet showInView:window_];
9070 id Alloc_(id self, SEL selector) {
9071 id object = alloc_(self, selector);
9072 lprintf("[%s]A-%p\n", self->isa->name, object);
9077 id Dealloc_(id self, SEL selector) {
9078 id object = dealloc_(self, selector);
9079 lprintf("[%s]D-%p\n", self->isa->name, object);
9083 Class $WebDefaultUIKitDelegate;
9085 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9086 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9087 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9088 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9091 static NSNumber *shouldPlayKeyboardSounds;
9095 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
9097 case 1104: // Keyboard Button Clicked
9098 case 1105: // Keyboard Delete Repeated
9099 if (shouldPlayKeyboardSounds == nil) {
9100 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
9101 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
9104 if (![shouldPlayKeyboardSounds boolValue])
9108 _UIHardware$_playSystemSound$(self, _cmd, sound);
9112 int main(int argc, char *argv[]) { _pooled
9115 if (Class $UIDevice = objc_getClass("UIDevice")) {
9116 UIDevice *device([$UIDevice currentDevice]);
9117 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
9121 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9123 /* Library Hacks {{{ */
9124 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
9126 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
9127 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
9128 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
9129 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
9130 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
9133 $UIHardware = objc_getClass("UIHardware");
9134 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
9135 if (UIHardware$_playSystemSound$ != NULL) {
9136 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
9137 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
9140 /* Set Locale {{{ */
9141 Locale_ = CFLocaleCopyCurrent();
9142 Languages_ = [NSLocale preferredLanguages];
9143 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
9144 //NSLog(@"%@", [Languages_ description]);
9147 if (Languages_ == nil || [Languages_ count] == 0)
9148 // XXX: consider just setting to C and then falling through?
9151 lang = [[Languages_ objectAtIndex:0] UTF8String];
9152 setenv("LANG", lang, true);
9155 //std::setlocale(LC_ALL, lang);
9156 NSLog(@"Setting Language: %s", lang);
9159 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
9161 /* Parse Arguments {{{ */
9162 bool substrate(false);
9168 for (int argi(1); argi != argc; ++argi)
9169 if (strcmp(argv[argi], "--") == 0) {
9171 argv[argi] = argv[0];
9177 for (int argi(1); argi != arge; ++argi)
9178 if (strcmp(args[argi], "--substrate") == 0)
9181 fprintf(stderr, "unknown argument: %s\n", args[argi]);
9185 App_ = [[NSBundle mainBundle] bundlePath];
9186 Home_ = NSHomeDirectory();
9192 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
9193 alloc_ = alloc->method_imp;
9194 alloc->method_imp = (IMP) &Alloc_;*/
9196 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
9197 dealloc_ = dealloc->method_imp;
9198 dealloc->method_imp = (IMP) &Dealloc_;*/
9200 /* System Information {{{ */
9204 size = sizeof(maxproc);
9205 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9206 perror("sysctlbyname(\"kern.maxproc\", ?)");
9207 else if (maxproc < 64) {
9209 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9210 perror("sysctlbyname(\"kern.maxproc\", #)");
9213 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
9214 char *osversion = new char[size];
9215 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
9216 perror("sysctlbyname(\"kern.osversion\", ?)");
9218 System_ = [NSString stringWithUTF8String:osversion];
9220 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
9221 char *machine = new char[size];
9222 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
9223 perror("sysctlbyname(\"hw.machine\", ?)");
9227 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
9228 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
9229 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
9230 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
9234 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
9235 NSData *data((NSData *) ecid);
9236 size_t length([data length]);
9237 uint8_t bytes[length];
9238 [data getBytes:bytes];
9239 char string[length * 2 + 1];
9240 for (size_t i(0); i != length; ++i)
9241 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
9242 ChipID_ = [NSString stringWithUTF8String:string];
9246 IOObjectRelease(service);
9250 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
9252 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
9253 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9254 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
9256 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
9257 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9258 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
9260 if (mcc != NULL && mnc != NULL)
9261 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9268 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9269 Build_ = [system objectForKey:@"ProductBuildVersion"];
9270 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9271 Product_ = [info objectForKey:@"SafariProductVersion"];
9272 Safari_ = [info objectForKey:@"CFBundleVersion"];
9275 /* Load Database {{{ */
9277 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9279 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9281 if (Metadata_ == NULL)
9282 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9284 Settings_ = [Metadata_ objectForKey:@"Settings"];
9286 Packages_ = [Metadata_ objectForKey:@"Packages"];
9287 Sections_ = [Metadata_ objectForKey:@"Sections"];
9288 Sources_ = [Metadata_ objectForKey:@"Sources"];
9290 Token_ = [Metadata_ objectForKey:@"Token"];
9293 if (Settings_ != nil)
9294 Role_ = [Settings_ objectForKey:@"Role"];
9296 if (Sections_ == nil) {
9297 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9298 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9301 if (Sources_ == nil) {
9302 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9303 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9308 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
9311 if (Packages_ != nil) {
9312 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, NULL);
9314 [Metadata_ removeObjectForKey:@"Packages"];
9319 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9321 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", F_OK) == 0)
9322 dlopen("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", RTLD_LAZY | RTLD_GLOBAL);
9323 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
9324 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
9325 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9326 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9328 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9330 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9331 unlink("/tmp/.cydia.fw");
9333 } else if (access("/User", F_OK) != 0 || version < 2) {
9336 system("/usr/libexec/cydia/firmware.sh");
9340 _assert([[NSFileManager defaultManager]
9341 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9342 withIntermediateDirectories:YES
9347 if (access("/tmp/cydia.chk", F_OK) == 0) {
9348 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9349 _assert(errno == ENOENT);
9350 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9351 _assert(errno == ENOENT);
9354 /* APT Initialization {{{ */
9355 _assert(pkgInitConfig(*_config));
9356 _assert(pkgInitSystem(*_config, _system));
9359 _config->Set("APT::Acquire::Translation", lang);
9361 // XXX: this timeout might be important :(
9362 //_config->Set("Acquire::http::Timeout", 15);
9364 _config->Set("Acquire::http::MaxParallel", 3);
9366 /* Color Choices {{{ */
9367 space_ = CGColorSpaceCreateDeviceRGB();
9369 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9370 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9371 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9372 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9373 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9374 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9375 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9376 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9377 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9379 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9380 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9382 /* UIKit Configuration {{{ */
9383 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9384 if ($GSFontSetUseLegacyFontMetrics != NULL)
9385 $GSFontSetUseLegacyFontMetrics(YES);
9387 // XXX: I have a feeling this was important
9388 //UIKeyboardDisableAutomaticAppearance();
9391 Colon_ = UCLocalize("COLON_DELIMITED");
9392 Elision_ = UCLocalize("ELISION");
9393 Error_ = UCLocalize("ERROR");
9394 Warning_ = UCLocalize("WARNING");
9397 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9399 CGColorSpaceRelease(space_);