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_;
1360 + (Database *) sharedInstance;
1363 - (void) _readCydia:(NSNumber *)fd;
1364 - (void) _readStatus:(NSNumber *)fd;
1365 - (void) _readOutput:(NSNumber *)fd;
1369 - (Package *) packageWithName:(NSString *)name;
1371 - (pkgCacheFile &) cache;
1372 - (pkgDepCache::Policy *) policy;
1373 - (pkgRecords *) records;
1374 - (pkgProblemResolver *) resolver;
1375 - (pkgAcquire &) fetcher;
1376 - (pkgSourceList &) list;
1377 - (NSArray *) packages;
1378 - (NSArray *) sources;
1379 - (void) reloadData;
1387 - (void) updateWithStatus:(Status &)status;
1389 - (void) setDelegate:(id)delegate;
1390 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1393 /* Delegate Helpers {{{ */
1394 @implementation NSObject (ProgressDelegate)
1396 - (void) _setProgressErrorPackage:(NSArray *)args {
1397 [self performSelector:@selector(setProgressError:forPackage:)
1398 withObject:[args objectAtIndex:0]
1399 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1403 - (void) _setProgressErrorTitle:(NSArray *)args {
1404 [self performSelector:@selector(setProgressError:withTitle:)
1405 withObject:[args objectAtIndex:0]
1406 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1410 - (void) _setProgressError:(NSString *)error withTitle:(NSString *)title {
1411 [self performSelectorOnMainThread:@selector(_setProgressErrorTitle:)
1412 withObject:[NSArray arrayWithObjects:error, title, nil]
1417 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
1418 Package *package = id == nil ? nil : [[Database sharedInstance] packageWithName:id];
1420 [self performSelector:@selector(setProgressError:withTitle:)
1422 withObject:(package == nil ? id : [package name])
1429 // Cytore Definitions {{{
1430 struct PackageValue :
1433 Cytore::Offset<PackageValue> next_;
1435 uint32_t index_ : 23;
1436 uint32_t subscribed_ : 1;
1453 Cytore::Offset<PackageValue> packages_[1 << 16];
1456 static Cytore::File<MetaValue> MetaFile_;
1458 // Cytore Helper Functions {{{
1459 static PackageValue *PackageFind(const char *name, size_t length) {
1460 SplitHash nhash = { hashlittle(name, length) };
1462 PackageValue *metadata;
1464 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1465 offset: if (offset->IsNull()) {
1466 *offset = MetaFile_.New<PackageValue>(length + 1);
1467 metadata = &MetaFile_.Get(*offset);
1469 memcpy(metadata->name_, name, length + 1);
1470 metadata->nhash_ = nhash.u16[1];
1472 metadata = &MetaFile_.Get(*offset);
1474 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1475 offset = &metadata->next_;
1483 static void PackageImport(const void *key, const void *value, void *context) {
1485 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1486 NSLog(@"failed to import package %@", key);
1490 PackageValue *metadata(PackageFind(buffer, strlen(buffer)));
1491 NSDictionary *package((NSDictionary *) value);
1493 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1494 if ([subscribed boolValue] && !metadata->subscribed_)
1495 metadata->subscribed_ = true;
1497 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1498 time_t time([date timeIntervalSince1970]);
1499 if (metadata->first_ > time || metadata->first_ == 0)
1500 metadata->first_ = time;
1503 NSDate *date([package objectForKey:@"LastSeen"]);
1504 NSString *version([package objectForKey:@"LastVersion"]);
1506 if (date != nil && version != nil) {
1507 time_t time([date timeIntervalSince1970]);
1508 if (metadata->last_ < time || metadata->last_ == 0)
1509 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1510 size_t length(strlen(buffer));
1511 uint16_t vhash(hashlittle(buffer, length));
1513 size_t capped(std::min<size_t>(8, length));
1514 char *latest(buffer + length - capped);
1516 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1517 metadata->vhash_ = vhash;
1519 metadata->last_ = time;
1525 /* Source Class {{{ */
1526 @interface Source : NSObject {
1527 CYString depiction_;
1528 CYString description_;
1534 CYString distribution_;
1539 NSString *authority_;
1541 CYString defaultIcon_;
1543 NSDictionary *record_;
1547 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1549 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1551 - (NSString *) depictionForPackage:(NSString *)package;
1552 - (NSString *) supportForPackage:(NSString *)package;
1554 - (NSDictionary *) record;
1558 - (NSString *) distribution;
1559 - (NSString *) type;
1561 - (NSString *) host;
1563 - (NSString *) name;
1564 - (NSString *) description;
1565 - (NSString *) label;
1566 - (NSString *) origin;
1567 - (NSString *) version;
1569 - (NSString *) defaultIcon;
1573 @implementation Source
1577 distribution_.clear();
1580 description_.clear();
1586 defaultIcon_.clear();
1588 if (record_ != nil) {
1598 if (authority_ != nil) {
1599 [authority_ release];
1605 // XXX: this is a very inefficient way to call these deconstructors
1610 + (NSArray *) _attributeKeys {
1611 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1614 - (NSArray *) attributeKeys {
1615 return [[self class] _attributeKeys];
1618 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1619 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1622 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1625 trusted_ = index->IsTrusted();
1627 uri_.set(pool, index->GetURI());
1628 distribution_.set(pool, index->GetDist());
1629 type_.set(pool, index->GetType());
1631 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1632 if (dindex != NULL) {
1634 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1637 pkgTagFile tags(&fd);
1639 pkgTagSection section;
1646 {"default-icon", &defaultIcon_},
1647 {"depiction", &depiction_},
1648 {"description", &description_},
1650 {"origin", &origin_},
1651 {"support", &support_},
1652 {"version", &version_},
1655 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1656 const char *start, *end;
1658 if (section.Find(names[i].name_, start, end)) {
1659 CYString &value(*names[i].value_);
1660 value.set(pool, start, end - start);
1666 record_ = [Sources_ objectForKey:[self key]];
1668 record_ = [record_ retain];
1670 NSURL *url([NSURL URLWithString:uri_]);
1674 host_ = [[host_ lowercaseString] retain];
1679 authority_ = [url path];
1681 if (authority_ != nil)
1682 authority_ = [authority_ retain];
1685 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1686 if ((self = [super init]) != nil) {
1687 [self setMetaIndex:index inPool:pool];
1691 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1692 NSDictionary *lhr = [self record];
1693 NSDictionary *rhr = [source record];
1696 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1698 NSString *lhs = [self name];
1699 NSString *rhs = [source name];
1701 if ([lhs length] != 0 && [rhs length] != 0) {
1702 unichar lhc = [lhs characterAtIndex:0];
1703 unichar rhc = [rhs characterAtIndex:0];
1705 if (isalpha(lhc) && !isalpha(rhc))
1706 return NSOrderedAscending;
1707 else if (!isalpha(lhc) && isalpha(rhc))
1708 return NSOrderedDescending;
1711 return [lhs compare:rhs options:LaxCompareOptions_];
1714 - (NSString *) depictionForPackage:(NSString *)package {
1715 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1718 - (NSString *) supportForPackage:(NSString *)package {
1719 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1722 - (NSDictionary *) record {
1730 - (NSString *) uri {
1734 - (NSString *) distribution {
1735 return distribution_;
1738 - (NSString *) type {
1742 - (NSString *) key {
1743 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1746 - (NSString *) host {
1750 - (NSString *) name {
1751 return origin_.empty() ? authority_ : origin_;
1754 - (NSString *) description {
1755 return description_;
1758 - (NSString *) label {
1759 return label_.empty() ? authority_ : label_;
1762 - (NSString *) origin {
1766 - (NSString *) version {
1770 - (NSString *) defaultIcon {
1771 return defaultIcon_;
1776 /* Relationship Class {{{ */
1777 @interface Relationship : NSObject {
1782 - (NSString *) type;
1784 - (NSString *) name;
1788 @implementation Relationship
1796 - (NSString *) type {
1804 - (NSString *) name {
1811 /* Package Class {{{ */
1812 struct ParsedPackage {
1817 CYString depiction_;
1827 @interface Package : NSObject {
1829 uint32_t essential_ : 1;
1830 uint32_t obsolete_ : 1;
1831 uint32_t ignored_ : 1;
1835 _transient Database *database_;
1837 pkgCache::VerIterator version_;
1838 pkgCache::PkgIterator iterator_;
1839 pkgCache::VerFileIterator file_;
1845 CYString installed_;
1848 _transient NSString *section$_;
1852 PackageValue *metadata_;
1853 ParsedPackage *parsed_;
1855 NSMutableArray *tags_;
1859 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1860 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1862 - (pkgCache::PkgIterator) iterator;
1865 - (NSString *) section;
1866 - (NSString *) simpleSection;
1868 - (NSString *) longSection;
1869 - (NSString *) shortSection;
1873 - (Address *) maintainer;
1875 - (NSString *) longDescription;
1876 - (NSString *) shortDescription;
1879 - (PackageValue *) metadata;
1882 - (bool) subscribed;
1883 - (bool) setSubscribed:(bool)subscribed;
1887 - (NSString *) latest;
1888 - (NSString *) installed;
1889 - (BOOL) uninstalled;
1892 - (BOOL) upgradableAndEssential:(BOOL)essential;
1895 - (BOOL) unfiltered;
1899 - (BOOL) halfConfigured;
1900 - (BOOL) halfInstalled;
1902 - (NSString *) mode;
1905 - (NSString *) name;
1907 - (NSString *) homepage;
1908 - (NSString *) depiction;
1909 - (Address *) author;
1911 - (NSString *) support;
1913 - (NSArray *) files;
1914 - (NSArray *) warnings;
1915 - (NSArray *) applications;
1917 - (Source *) source;
1918 - (NSString *) role;
1920 - (BOOL) matches:(NSString *)text;
1922 - (bool) hasSupportingRole;
1923 - (BOOL) hasTag:(NSString *)tag;
1924 - (NSString *) primaryPurpose;
1925 - (NSArray *) purposes;
1926 - (bool) isCommercial;
1928 - (void) setIndex:(size_t)index;
1930 - (CYString &) cyname;
1932 - (uint32_t) compareBySection:(NSArray *)sections;
1937 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1938 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1939 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1940 - (bool) isVisibleInSection:(NSString *)section;
1941 - (bool) isVisibleInSource:(Source *)source;
1945 uint32_t PackageChangesRadix(Package *self, void *) {
1950 uint32_t timestamp : 30;
1951 uint32_t ignored : 1;
1952 uint32_t upgradable : 1;
1956 bool upgradable([self upgradableAndEssential:YES]);
1957 value.bits.upgradable = upgradable ? 1 : 0;
1960 value.bits.timestamp = 0;
1961 value.bits.ignored = [self ignored] ? 0 : 1;
1962 value.bits.upgradable = 1;
1964 value.bits.timestamp = [self seen] >> 2;
1965 value.bits.ignored = 0;
1966 value.bits.upgradable = 0;
1969 return _not(uint32_t) - value.key;
1972 uint32_t PackagePrefixRadix(Package *self, void *context) {
1973 size_t offset(reinterpret_cast<size_t>(context));
1974 CYString &name([self cyname]);
1976 size_t size(name.size());
1979 char *text(name.data());
1982 if (!isdigit(text[0]))
1986 while (size != digits && isdigit(text[digits]))
1994 if (offset == 0 && zeros != 0) {
1995 memset(data, '0', zeros);
1996 memcpy(data + zeros, text, 4 - zeros);
1998 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1999 if (size <= offset - zeros)
2002 text += offset - zeros;
2003 size -= offset - zeros;
2006 memcpy(data, text, 4);
2008 memcpy(data, text, size);
2009 memset(data + size, 0, 4 - size);
2012 for (size_t i(0); i != 4; ++i)
2013 if (isalpha(data[i]))
2021 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2023 /* XXX: ntohl may be more honest */
2024 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2027 CYString &(*PackageName)(Package *self, SEL sel);
2029 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2030 _profile(PackageNameCompare)
2031 CYString &lhi(PackageName(lhs, @selector(cyname)));
2032 CYString &rhi(PackageName(rhs, @selector(cyname)));
2033 CFStringRef lhn(lhi), rhn(rhi);
2036 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2037 else if (rhn == NULL)
2038 return NSOrderedDescending;
2040 _profile(PackageNameCompare$NumbersLast)
2041 if (!lhi.empty() && !rhi.empty()) {
2042 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2043 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2044 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2045 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2046 return lha ? NSOrderedAscending : NSOrderedDescending;
2050 CFIndex length = CFStringGetLength(lhn);
2052 _profile(PackageNameCompare$Compare)
2053 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2058 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2059 return PackageNameCompare(*lhs, *rhs, context);
2062 struct PackageNameOrdering :
2063 std::binary_function<Package *, Package *, bool>
2065 _finline bool operator ()(Package *lhs, Package *rhs) const {
2066 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2070 @implementation Package
2072 - (NSString *) description {
2073 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2077 if (parsed_ != NULL)
2091 + (NSString *) webScriptNameForSelector:(SEL)selector {
2092 if (selector == @selector(hasTag:))
2098 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2099 return [self webScriptNameForSelector:selector] == nil;
2102 + (NSArray *) _attributeKeys {
2103 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];
2106 - (NSArray *) attributeKeys {
2107 return [[self class] _attributeKeys];
2110 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2111 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2115 if (parsed_ != NULL)
2117 @synchronized (database_) {
2118 if ([database_ era] != era_ || file_.end())
2121 ParsedPackage *parsed(new ParsedPackage);
2124 _profile(Package$parse)
2125 pkgRecords::Parser *parser;
2127 _profile(Package$parse$Lookup)
2128 parser = &[database_ records]->Lookup(file_);
2133 _profile(Package$parse$Find)
2138 {"icon", &parsed->icon_},
2139 {"depiction", &parsed->depiction_},
2140 {"homepage", &parsed->homepage_},
2141 {"website", &website},
2142 {"bugs", &parsed->bugs_},
2143 {"support", &parsed->support_},
2144 {"sponsor", &parsed->sponsor_},
2145 {"author", &parsed->author_},
2148 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2149 const char *start, *end;
2151 if (parser->Find(names[i].name_, start, end)) {
2152 CYString &value(*names[i].value_);
2153 _profile(Package$parse$Value)
2154 value.set(pool_, start, end - start);
2160 _profile(Package$parse$Tagline)
2161 const char *start, *end;
2162 if (parser->ShortDesc(start, end)) {
2163 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2166 while (stop != start && stop[-1] == '\r')
2168 parsed->tagline_.set(pool_, start, stop - start);
2172 _profile(Package$parse$Retain)
2173 if (parsed->homepage_.empty())
2174 parsed->homepage_ = website;
2175 if (parsed->homepage_ == parsed->depiction_)
2176 parsed->homepage_.clear();
2181 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2182 if ((self = [super init]) != nil) {
2183 _profile(Package$initWithVersion)
2186 database_ = database;
2187 era_ = [database era];
2191 pkgCache::PkgIterator iterator(version.ParentPkg());
2192 iterator_ = iterator;
2194 _profile(Package$initWithVersion$Version)
2195 if (!version_.end())
2196 file_ = version_.FileList();
2198 pkgCache &cache([database_ cache]);
2199 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2203 _profile(Package$initWithVersion$Cache)
2204 name_.set(NULL, iterator.Display());
2206 latest_.set(NULL, StripVersion_(version_.VerStr()));
2208 pkgCache::VerIterator current(iterator.CurrentVer());
2210 installed_.set(NULL, StripVersion_(current.VerStr()));
2213 _profile(Package$initWithVersion$Tags)
2214 pkgCache::TagIterator tag(iterator.TagList());
2216 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2218 const char *name(tag.Name());
2219 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2221 if (role_ == nil && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/)
2222 role_ = (NSString *) CYStringCreate(name + 6);
2224 if (strncmp(name, "cydia::", 7) == 0) {
2225 if (strcmp(name + 7, "essential") == 0)
2227 else if (strcmp(name + 7, "obsolete") == 0)
2232 } while (!tag.end());
2236 _profile(Package$initWithVersion$Metadata)
2237 const char *mixed(iterator.Name());
2238 size_t size(strlen(mixed));
2239 char lower[size + 1];
2241 for (size_t i(0); i != size; ++i)
2242 lower[i] = mixed[i] | 0x20;
2245 PackageValue *metadata(PackageFind(lower, size));
2246 metadata_ = metadata;
2248 id_.set(NULL, metadata->name_, size);
2250 const char *latest(version_.VerStr());
2251 size_t length(strlen(latest));
2253 uint16_t vhash(hashlittle(latest, length));
2255 size_t capped(std::min<size_t>(8, length));
2256 latest = latest + length - capped;
2258 if (metadata->first_ == 0)
2259 metadata->first_ = now_;
2261 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2262 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2263 metadata->vhash_ = vhash;
2264 metadata->last_ = now_;
2265 } else if (metadata->last_ == 0)
2266 metadata->last_ = metadata->first_;
2269 _profile(Package$initWithVersion$Section)
2270 section_.set(NULL, iterator.Section());
2273 _profile(Package$initWithVersion$Flags)
2274 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2275 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2280 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2281 pkgCache::VerIterator version;
2283 _profile(Package$packageWithIterator$GetCandidateVer)
2284 version = [database policy]->GetCandidateVer(iterator);
2292 _profile(Package$packageWithIterator$Allocate)
2293 package = [Package allocWithZone:zone];
2296 _profile(Package$packageWithIterator$Initialize)
2298 initWithVersion:version
2305 _profile(Package$packageWithIterator$Autorelease)
2306 package = [package autorelease];
2312 - (pkgCache::PkgIterator) iterator {
2316 - (NSString *) section {
2317 if (section$_ == nil) {
2318 if (section_.empty())
2321 _profile(Package$section)
2322 std::replace(section_.data(), section_.data() + section_.size(), '_', ' ');
2323 NSString *name(section_);
2324 section$_ = [SectionMap_ objectForKey:name] ?: name;
2329 - (NSString *) simpleSection {
2330 if (NSString *section = [self section])
2331 return Simplify(section);
2336 - (NSString *) longSection {
2337 return LocalizeSection([self section]);
2340 - (NSString *) shortSection {
2341 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2344 - (NSString *) uri {
2347 pkgIndexFile *index;
2348 pkgCache::PkgFileIterator file(file_.File());
2349 if (![database_ list].FindIndex(file, index))
2351 return [NSString stringWithUTF8String:iterator_->Path];
2352 //return [NSString stringWithUTF8String:file.Site()];
2353 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2357 - (Address *) maintainer {
2358 @synchronized (database_) {
2359 if ([database_ era] != era_ || file_.end())
2362 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2363 const std::string &maintainer(parser->Maintainer());
2364 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2368 @synchronized (database_) {
2369 if ([database_ era] != era_ || version_.end())
2372 return version_->InstalledSize;
2375 - (NSString *) longDescription {
2376 @synchronized (database_) {
2377 if ([database_ era] != era_ || file_.end())
2380 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2381 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2383 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2384 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2385 if ([lines count] < 2)
2388 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2389 for (size_t i(1), e([lines count]); i != e; ++i) {
2390 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2391 [trimmed addObject:trim];
2394 return [trimmed componentsJoinedByString:@"\n"];
2397 - (NSString *) shortDescription {
2398 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2402 _profile(Package$index)
2403 CFStringRef name((CFStringRef) [self name]);
2404 if (CFStringGetLength(name) == 0)
2406 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2407 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2409 return toupper(character);
2413 - (PackageValue *) metadata {
2418 PackageValue *metadata([self metadata]);
2419 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2422 - (bool) subscribed {
2423 return [self metadata]->subscribed_;
2426 - (bool) setSubscribed:(bool)subscribed {
2427 PackageValue *metadata([self metadata]);
2428 if (metadata->subscribed_ == subscribed)
2430 metadata->subscribed_ = subscribed;
2438 - (NSString *) latest {
2442 - (NSString *) installed {
2446 - (BOOL) uninstalled {
2447 return installed_.empty();
2451 return !version_.end();
2454 - (BOOL) upgradableAndEssential:(BOOL)essential {
2455 _profile(Package$upgradableAndEssential)
2456 pkgCache::VerIterator current(iterator_.CurrentVer());
2458 return essential && essential_;
2460 return !version_.end() && version_ != current;
2464 - (BOOL) essential {
2469 return [database_ cache][iterator_].InstBroken();
2472 - (BOOL) unfiltered {
2473 _profile(Package$unfiltered$obsolete)
2478 _profile(Package$unfiltered$hasSupportingRole)
2479 if (![self hasSupportingRole])
2487 if (![self unfiltered])
2490 NSString *section([self section]);
2492 _profile(Package$visible$isSectionVisible)
2493 if (section != nil && !isSectionVisible(section))
2501 unsigned char current(iterator_->CurrentState);
2502 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2505 - (BOOL) halfConfigured {
2506 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2509 - (BOOL) halfInstalled {
2510 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2514 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2515 return state.Mode != pkgDepCache::ModeKeep;
2518 - (NSString *) mode {
2519 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2521 switch (state.Mode) {
2522 case pkgDepCache::ModeDelete:
2523 if ((state.iFlags & pkgDepCache::Purge) != 0)
2527 case pkgDepCache::ModeKeep:
2528 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2529 return @"REINSTALL";
2530 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2534 case pkgDepCache::ModeInstall:
2535 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2536 return @"REINSTALL";
2537 else*/ switch (state.Status) {
2539 return @"DOWNGRADE";
2545 return @"NEW_INSTALL";
2556 - (NSString *) name {
2557 return name_.empty() ? id_ : name_;
2560 - (UIImage *) icon {
2561 NSString *section = [self simpleSection];
2564 if (parsed_ != NULL)
2565 if (NSString *href = parsed_->icon_)
2566 if ([href hasPrefix:@"file:///"])
2567 // XXX: correct escaping
2568 icon = [UIImage imageAtPath:[href substringFromIndex:7]];
2569 if (icon == nil) if (section != nil)
2570 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2571 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2572 if ([dicon hasPrefix:@"file:///"])
2573 // XXX: correct escaping
2574 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2576 icon = [UIImage applicationImageNamed:@"unknown.png"];
2580 - (NSString *) homepage {
2581 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2584 - (NSString *) depiction {
2585 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2588 - (Address *) sponsor {
2589 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [Address addressWithString:parsed_->sponsor_];
2592 - (Address *) author {
2593 return parsed_ == NULL || parsed_->author_.empty() ? nil : [Address addressWithString:parsed_->author_];
2596 - (NSString *) support {
2597 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2600 - (NSArray *) files {
2601 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2602 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2605 fin.open([path UTF8String]);
2610 while (std::getline(fin, line))
2611 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2616 - (NSArray *) warnings {
2617 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2618 const char *name(iterator_.Name());
2620 size_t length(strlen(name));
2621 if (length < 2) invalid:
2622 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2623 else for (size_t i(0); i != length; ++i)
2625 /* XXX: technically this is not allowed */
2626 (name[i] < 'A' || name[i] > 'Z') &&
2627 (name[i] < 'a' || name[i] > 'z') &&
2628 (name[i] < '0' || name[i] > '9') &&
2629 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2632 if (strcmp(name, "cydia") != 0) {
2635 bool _private = false;
2638 bool repository = [[self section] isEqualToString:@"Repositories"];
2640 if (NSArray *files = [self files])
2641 for (NSString *file in files)
2642 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2644 else if (!user && [file isEqualToString:@"/User"])
2646 else if (!_private && [file isEqualToString:@"/private"])
2648 else if (!stash && [file isEqualToString:@"/var/stash"])
2651 /* XXX: this is not sensitive enough. only some folders are valid. */
2652 if (cydia && !repository)
2653 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2655 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2657 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2659 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2662 return [warnings count] == 0 ? nil : warnings;
2665 - (NSArray *) applications {
2666 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2668 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2670 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2671 if (NSArray *files = [self files])
2672 for (NSString *file in files)
2673 if (application_r(file)) {
2674 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2675 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2676 if ([id isEqualToString:me])
2679 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2681 display = application_r[1];
2683 NSString *bundle([file stringByDeletingLastPathComponent]);
2684 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2685 if (icon == nil || [icon length] == 0)
2687 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2689 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2690 [applications addObject:application];
2692 [application addObject:id];
2693 [application addObject:display];
2694 [application addObject:url];
2697 return [applications count] == 0 ? nil : applications;
2700 - (Source *) source {
2701 if (source_ == nil) {
2702 @synchronized (database_) {
2703 if ([database_ era] != era_ || file_.end())
2704 source_ = (Source *) [NSNull null];
2706 source_ = [([database_ getSource:file_.File()] ?: (Source *) [NSNull null]) retain];
2710 return source_ == (Source *) [NSNull null] ? nil : source_;
2713 - (NSString *) role {
2717 - (BOOL) matches:(NSString *)text {
2723 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2724 if (range.location != NSNotFound)
2727 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2728 if (range.location != NSNotFound)
2731 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2732 if (range.location != NSNotFound)
2738 - (bool) hasSupportingRole {
2741 if ([role_ isEqualToString:@"enduser"])
2743 if ([Role_ isEqualToString:@"User"])
2745 if ([role_ isEqualToString:@"hacker"])
2747 if ([Role_ isEqualToString:@"Hacker"])
2749 if ([role_ isEqualToString:@"developer"])
2751 if ([Role_ isEqualToString:@"Developer"])
2756 - (BOOL) hasTag:(NSString *)tag {
2757 return tags_ == nil ? NO : [tags_ containsObject:tag];
2760 - (NSString *) primaryPurpose {
2761 for (NSString *tag in tags_)
2762 if ([tag hasPrefix:@"purpose::"])
2763 return [tag substringFromIndex:9];
2767 - (NSArray *) purposes {
2768 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2769 for (NSString *tag in tags_)
2770 if ([tag hasPrefix:@"purpose::"])
2771 [purposes addObject:[tag substringFromIndex:9]];
2772 return [purposes count] == 0 ? nil : purposes;
2775 - (bool) isCommercial {
2776 return [self hasTag:@"cydia::commercial"];
2779 - (void) setIndex:(size_t)index {
2780 if (metadata_->index_ != index)
2781 metadata_->index_ = index;
2784 - (CYString &) cyname {
2785 return name_.empty() ? id_ : name_;
2788 - (uint32_t) compareBySection:(NSArray *)sections {
2789 NSString *section([self section]);
2790 for (size_t i(0), e([sections count]); i != e; ++i) {
2791 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2795 return _not(uint32_t);
2799 @synchronized (database_) {
2800 pkgProblemResolver *resolver = [database_ resolver];
2801 resolver->Clear(iterator_);
2803 pkgCacheFile &cache([database_ cache]);
2804 cache->SetReInstall(iterator_, false);
2805 cache->MarkKeep(iterator_, false);
2809 @synchronized (database_) {
2810 pkgProblemResolver *resolver = [database_ resolver];
2811 resolver->Clear(iterator_);
2812 resolver->Protect(iterator_);
2814 pkgCacheFile &cache([database_ cache]);
2815 cache->SetReInstall(iterator_, false);
2816 cache->MarkInstall(iterator_, false);
2818 pkgDepCache::StateCache &state((*cache)[iterator_]);
2819 if (!state.Install())
2820 cache->SetReInstall(iterator_, true);
2824 @synchronized (database_) {
2825 pkgProblemResolver *resolver = [database_ resolver];
2826 resolver->Clear(iterator_);
2827 resolver->Remove(iterator_);
2828 resolver->Protect(iterator_);
2830 pkgCacheFile &cache([database_ cache]);
2831 cache->SetReInstall(iterator_, false);
2832 cache->MarkDelete(iterator_, true);
2835 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2836 _profile(Package$isUnfilteredAndSearchedForBy)
2839 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2840 value &= [self unfiltered];
2843 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2844 value &= [self matches:search];
2851 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2852 if ([search length] == 0)
2855 _profile(Package$isUnfilteredAndSelectedForBy)
2858 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2859 value &= [self unfiltered];
2862 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2863 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2870 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
2871 return ![self uninstalled] && (![number boolValue] && ![role_ isEqualToString:@"cydia"] || [self unfiltered]);
2874 - (bool) isVisibleInSection:(NSString *)name {
2875 NSString *section([self section]);
2879 section == nil && [name length] == 0 ||
2880 [name isEqualToString:section]
2881 ) && [self visible];
2884 - (bool) isVisibleInSource:(Source *)source {
2885 return [self source] == source && [self visible];
2890 /* Section Class {{{ */
2891 @interface Section : NSObject {
2896 NSString *localized_;
2899 - (NSComparisonResult) compareByLocalized:(Section *)section;
2900 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2901 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2902 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2903 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2904 - (NSString *) name;
2911 - (void) addToCount;
2913 - (void) setCount:(size_t)count;
2914 - (NSString *) localized;
2918 @implementation Section
2922 if (localized_ != nil)
2923 [localized_ release];
2927 - (NSComparisonResult) compareByLocalized:(Section *)section {
2928 NSString *lhs(localized_);
2929 NSString *rhs([section localized]);
2931 /*if ([lhs length] != 0 && [rhs length] != 0) {
2932 unichar lhc = [lhs characterAtIndex:0];
2933 unichar rhc = [rhs characterAtIndex:0];
2935 if (isalpha(lhc) && !isalpha(rhc))
2936 return NSOrderedAscending;
2937 else if (!isalpha(lhc) && isalpha(rhc))
2938 return NSOrderedDescending;
2941 return [lhs compare:rhs options:LaxCompareOptions_];
2944 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2945 if ((self = [self initWithName:name localize:NO]) != nil) {
2946 if (localized != nil)
2947 localized_ = [localized retain];
2951 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2952 return [self initWithName:name row:0 localize:localize];
2955 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2956 if ((self = [super init]) != nil) {
2957 name_ = [name retain];
2961 localized_ = [LocalizeSection(name_) retain];
2965 /* XXX: localize the index thingees */
2966 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2967 if ((self = [super init]) != nil) {
2968 name_ = [[NSString stringWithCharacters:&index length:1] retain];
2974 - (NSString *) name {
2994 - (void) addToCount {
2998 - (void) setCount:(size_t)count {
3002 - (NSString *) localized {
3009 static NSString *Colon_;
3010 static NSString *Elision_;
3011 static NSString *Error_;
3012 static NSString *Warning_;
3014 /* Database Implementation {{{ */
3015 @implementation Database
3017 + (Database *) sharedInstance {
3018 static Database *instance;
3019 if (instance == nil)
3020 instance = [[Database alloc] init];
3028 - (void) releasePackages {
3029 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3030 CFArrayRemoveAllValues(packages_);
3034 // XXX: actually implement this thing
3036 [self releasePackages];
3037 apr_pool_destroy(pool_);
3038 NSRecycleZone(zone_);
3042 - (void) _readCydia:(NSNumber *)fd { _pooled
3043 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3044 std::istream is(&ib);
3047 static Pcre finish_r("^finish:([^:]*)$");
3049 while (std::getline(is, line)) {
3050 const char *data(line.c_str());
3051 size_t size = line.size();
3052 lprintf("C:%s\n", data);
3054 if (finish_r(data, size)) {
3055 NSString *finish = finish_r[1];
3056 int index = [Finishes_ indexOfObject:finish];
3057 if (index != INT_MAX && index > Finish_)
3065 - (void) _readStatus:(NSNumber *)fd { _pooled
3066 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3067 std::istream is(&ib);
3070 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3071 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3073 while (std::getline(is, line)) {
3074 const char *data(line.c_str());
3075 size_t size(line.size());
3076 lprintf("S:%s\n", data);
3078 if (conffile_r(data, size)) {
3079 [delegate_ setConfigurationData:conffile_r[1]];
3080 } else if (strncmp(data, "status: ", 8) == 0) {
3081 NSString *string = [NSString stringWithUTF8String:(data + 8)];
3082 [delegate_ setProgressTitle:string];
3083 } else if (pmstatus_r(data, size)) {
3084 std::string type([pmstatus_r[1] UTF8String]);
3085 NSString *id = pmstatus_r[2];
3087 float percent([pmstatus_r[3] floatValue]);
3088 [delegate_ setProgressPercent:(percent / 100)];
3090 NSString *string = pmstatus_r[4];
3092 if (type == "pmerror")
3093 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3094 withObject:[NSArray arrayWithObjects:string, id, nil]
3097 else if (type == "pmstatus") {
3098 [delegate_ setProgressTitle:string];
3099 } else if (type == "pmconffile")
3100 [delegate_ setConfigurationData:string];
3102 lprintf("E:unknown pmstatus\n");
3104 lprintf("E:unknown status\n");
3110 - (void) _readOutput:(NSNumber *)fd { _pooled
3111 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3112 std::istream is(&ib);
3115 while (std::getline(is, line)) {
3116 lprintf("O:%s\n", line.c_str());
3117 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
3127 - (Package *) packageWithName:(NSString *)name {
3128 @synchronized (self) {
3129 if (static_cast<pkgDepCache *>(cache_) == NULL)
3131 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3132 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3136 if ((self = [super init]) != nil) {
3143 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3144 apr_pool_create(&pool_, NULL);
3146 size_t capacity(MetaFile_->active_);
3152 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3156 _assert(pipe(fds) != -1);
3159 _config->Set("APT::Keep-Fds::", cydiafd_);
3160 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3163 detachNewThreadSelector:@selector(_readCydia:)
3165 withObject:[NSNumber numberWithInt:fds[0]]
3168 _assert(pipe(fds) != -1);
3172 detachNewThreadSelector:@selector(_readStatus:)
3174 withObject:[NSNumber numberWithInt:fds[0]]
3177 _assert(pipe(fds) != -1);
3178 _assert(dup2(fds[0], 0) != -1);
3179 _assert(close(fds[0]) != -1);
3181 input_ = fdopen(fds[1], "a");
3183 _assert(pipe(fds) != -1);
3184 _assert(dup2(fds[1], 1) != -1);
3185 _assert(close(fds[1]) != -1);
3188 detachNewThreadSelector:@selector(_readOutput:)
3190 withObject:[NSNumber numberWithInt:fds[0]]
3195 - (pkgCacheFile &) cache {
3199 - (pkgDepCache::Policy *) policy {
3203 - (pkgRecords *) records {
3207 - (pkgProblemResolver *) resolver {
3211 - (pkgAcquire &) fetcher {
3215 - (pkgSourceList &) list {
3219 - (NSArray *) packages {
3220 return (NSArray *) packages_;
3223 - (NSArray *) sources {
3224 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3225 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3226 [sources addObject:i->second];
3230 - (NSArray *) issues {
3231 if (cache_->BrokenCount() == 0)
3234 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3236 for (Package *package in [self packages]) {
3237 if (![package broken])
3239 pkgCache::PkgIterator pkg([package iterator]);
3241 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3242 [entry addObject:[package name]];
3243 [issues addObject:entry];
3245 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3249 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3250 pkgCache::DepIterator start;
3251 pkgCache::DepIterator end;
3252 dep.GlobOr(start, end); // ++dep
3254 if (!cache_->IsImportantDep(end))
3256 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3259 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3260 [entry addObject:failure];
3261 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3263 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3264 if (Package *package = [self packageWithName:name])
3265 name = [package name];
3266 [failure addObject:name];
3268 pkgCache::PkgIterator target(start.TargetPkg());
3269 if (target->ProvidesList != 0)
3270 [failure addObject:@"?"];
3272 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3274 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3275 else if (!cache_[target].CandidateVerIter(cache_).end())
3276 [failure addObject:@"-"];
3277 else if (target->ProvidesList == 0)
3278 [failure addObject:@"!"];
3280 [failure addObject:@"%"];
3284 if (start.TargetVer() != 0)
3285 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3296 - (bool) popErrorWithTitle:(NSString *)title {
3298 std::string message;
3300 while (!_error->empty()) {
3302 bool warning(!_error->PopMessage(error));
3306 size_t size(error.size());
3307 if (size == 0 || error[size - 1] != '\n')
3309 error.resize(size - 1);
3311 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3313 if (!message.empty())
3318 if (fatal && !message.empty())
3319 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3324 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3325 return [self popErrorWithTitle:title] || !success;
3328 - (void) reloadData { CYPoolStart() {
3329 @synchronized (self) {
3332 [self releasePackages];
3353 apr_pool_clear(pool_);
3355 NSRecycleZone(zone_);
3356 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3358 int chk(creat("/tmp/cydia.chk", 0644));
3362 NSString *title(UCLocalize("DATABASE"));
3365 if (!cache_.Open(progress_, true)) { pop:
3367 bool warning(!_error->PopMessage(error));
3368 lprintf("cache_.Open():[%s]\n", error.c_str());
3370 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3371 [delegate_ repairWithSelector:@selector(configure)];
3372 else if (error == "The package lists or status file could not be parsed or opened.")
3373 [delegate_ repairWithSelector:@selector(update)];
3374 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3375 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3376 // else if (error == "The list of sources could not be read.")
3378 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3387 unlink("/tmp/cydia.chk");
3389 now_ = [[NSDate date] timeIntervalSince1970];
3391 policy_ = new pkgDepCache::Policy();
3392 records_ = new pkgRecords(cache_);
3393 resolver_ = new pkgProblemResolver(cache_);
3394 fetcher_ = new pkgAcquire(&status_);
3397 list_ = new pkgSourceList();
3398 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3401 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3402 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3406 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3409 if (cache_->BrokenCount() != 0) {
3410 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3413 if (cache_->BrokenCount() != 0) {
3414 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3418 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3422 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3423 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3424 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3425 // XXX: this could be more intelligent
3426 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3427 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3429 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3434 /*std::vector<Package *> packages;
3435 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3436 [packages_ release];
3441 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3442 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3443 //packages.push_back(package);
3444 CFArrayAppendValue(packages_, [package retain]);
3448 /*if (packages.empty())
3449 packages_ = [[NSArray alloc] init];
3451 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3454 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3455 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3456 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3464 /*if (!packages.empty())
3465 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3466 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3468 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3470 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3472 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3476 size_t count(CFArrayGetCount(packages_));
3477 MetaFile_->active_ = count;
3479 for (size_t index(0); index != count; ++index)
3480 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3484 } } CYPoolEnd() _trace(); }
3487 @synchronized (self) {
3489 resolver_ = new pkgProblemResolver(cache_);
3491 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator) {
3492 if (!cache_[iterator].Keep()) {
3493 cache_->MarkKeep(iterator, false);
3494 cache_->SetReInstall(iterator, false);
3499 - (void) configure {
3500 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3502 system([dpkg UTF8String]);
3507 // XXX: I don't remember this condition
3512 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3514 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3516 if ([self popErrorWithTitle:title])
3520 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3523 public pkgArchiveCleaner
3526 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3531 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3538 fetcher_->Shutdown();
3540 pkgRecords records(cache_);
3542 lock_ = new FileFd();
3543 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3545 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3547 if ([self popErrorWithTitle:title])
3551 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3554 manager_ = (_system->CreatePM(cache_));
3555 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3562 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3564 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3566 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3568 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3569 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3572 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3577 [CydiaApp retainNetworkActivityIndicator];
3579 bool failed = false;
3580 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3581 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3583 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3586 std::string uri = (*item)->DescURI();
3587 std::string error = (*item)->ErrorText;
3589 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3592 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3593 withObject:[NSArray arrayWithObjects:
3594 [NSString stringWithUTF8String:error.c_str()],
3600 [CydiaApp releaseNetworkActivityIndicator];
3608 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3610 if (_error->PendingError()) {
3615 if (result == pkgPackageManager::Failed) {
3620 if (result != pkgPackageManager::Completed) {
3625 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3627 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3629 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3630 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3633 if (![before isEqualToArray:after])
3638 NSString *title(UCLocalize("UPGRADE"));
3639 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3645 [self updateWithStatus:status_];
3648 - (void) updateWithStatus:(Status &)status {
3649 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3650 NSString *title(UCLocalize("REFRESHING_DATA"));
3653 if (!list.ReadMainList())
3654 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3657 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3658 if ([self popErrorWithTitle:title])
3661 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3662 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */
3663 /* XXX: why the hell is an empty if statement a clang error? */ (void) 0;
3665 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3669 - (void) setDelegate:(id)delegate {
3670 delegate_ = delegate;
3671 status_.setDelegate(delegate);
3672 progress_.setDelegate(delegate);
3675 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3676 SourceMap::const_iterator i(sources_.find(file->ID));
3677 return i == sources_.end() ? nil : i->second;
3683 /* Confirmation Controller {{{ */
3684 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3685 if (!iterator.end())
3686 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3687 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3689 pkgCache::PkgIterator package(dep.TargetPkg());
3692 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3700 /* Web Scripting {{{ */
3701 @interface CydiaObject : NSObject {
3703 _transient id delegate_;
3706 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3709 @implementation CydiaObject
3712 [indirect_ release];
3716 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3717 if ((self = [super init]) != nil) {
3718 indirect_ = [indirect retain];
3722 - (void) setDelegate:(id)delegate {
3723 delegate_ = delegate;
3726 + (NSArray *) _attributeKeys {
3727 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3730 - (NSArray *) attributeKeys {
3731 return [[self class] _attributeKeys];
3734 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3735 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3738 - (NSString *) device {
3739 return [[UIDevice currentDevice] uniqueIdentifier];
3742 #if 0 // XXX: implement!
3743 - (NSString *) mac {
3744 if (![indirect_ promptForSensitive:@"Mac Address"])
3748 - (NSString *) serial {
3749 if (![indirect_ promptForSensitive:@"Serial #"])
3753 - (NSString *) firewire {
3754 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3758 - (NSString *) imei {
3759 if (![indirect_ promptForSensitive:@"IMEI"])
3764 + (NSString *) webScriptNameForSelector:(SEL)selector {
3765 if (selector == @selector(close))
3767 else if (selector == @selector(getInstalledPackages))
3768 return @"getInstalledPackages";
3769 else if (selector == @selector(getPackageById:))
3770 return @"getPackageById";
3771 else if (selector == @selector(installPackages:))
3772 return @"installPackages";
3773 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3774 return @"setButtonImage";
3775 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3776 return @"setButtonTitle";
3777 else if (selector == @selector(setPopupHook:))
3778 return @"setPopupHook";
3779 else if (selector == @selector(setSpecial:))
3780 return @"setSpecial";
3781 else if (selector == @selector(setToken:))
3783 else if (selector == @selector(setViewportWidth:))
3784 return @"setViewportWidth";
3785 else if (selector == @selector(supports:))
3787 else if (selector == @selector(stringWithFormat:arguments:))
3789 else if (selector == @selector(localizedStringForKey:value:table:))
3791 else if (selector == @selector(du:))
3793 else if (selector == @selector(statfs:))
3799 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3800 return [self webScriptNameForSelector:selector] == nil;
3803 - (BOOL) supports:(NSString *)feature {
3804 return [feature isEqualToString:@"window.open"];
3807 - (NSArray *) getInstalledPackages {
3808 NSArray *packages([[Database sharedInstance] packages]);
3809 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
3810 for (Package *package in packages)
3811 if ([package installed] != nil)
3812 [installed addObject:package];
3816 - (Package *) getPackageById:(NSString *)id {
3817 Package *package([[Database sharedInstance] packageWithName:id]);
3822 - (NSArray *) statfs:(NSString *)path {
3825 if (path == nil || statfs([path UTF8String], &stat) == -1)
3828 return [NSArray arrayWithObjects:
3829 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3830 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3831 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3835 - (NSNumber *) du:(NSString *)path {
3836 NSNumber *value(nil);
3839 _assert(pipe(fds) != -1);
3841 pid_t pid(ExecFork());
3843 _assert(dup2(fds[1], 1) != -1);
3844 _assert(close(fds[0]) != -1);
3845 _assert(close(fds[1]) != -1);
3846 /* XXX: this should probably not use du */
3847 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3852 _assert(close(fds[1]) != -1);
3854 if (FILE *du = fdopen(fds[0], "r")) {
3856 while (fgets(line, sizeof(line), du) != NULL) {
3857 size_t length(strlen(line));
3858 while (length != 0 && line[length - 1] == '\n')
3859 line[--length] = '\0';
3860 if (char *tab = strchr(line, '\t')) {
3862 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3867 } else _assert(close(fds[0]));
3871 if (waitpid(pid, &status, 0) == -1)
3874 else _assert(false);
3883 - (void) installPackages:(NSArray *)packages {
3884 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
3887 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3888 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3891 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3892 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3895 - (void) setSpecial:(id)function {
3896 [indirect_ setSpecial:function];
3899 - (void) setToken:(NSString *)token {
3902 Token_ = [token retain];
3904 [Metadata_ setObject:Token_ forKey:@"Token"];
3908 - (void) setPopupHook:(id)function {
3909 [indirect_ setPopupHook:function];
3912 - (void) setViewportWidth:(float)width {
3913 [indirect_ setViewportWidth:width];
3916 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3917 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3918 unsigned count([arguments count]);
3920 for (unsigned i(0); i != count; ++i)
3921 values[i] = [arguments objectAtIndex:i];
3922 return [[[NSString alloc] initWithFormat:format arguments:*(reinterpret_cast<va_list *>(&values))] autorelease];
3925 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3926 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3928 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3930 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3936 /* @ Loading... Indicator {{{ */
3937 @interface CYLoadingIndicator : UIView {
3938 UIActivityIndicatorView *spinner_;
3943 @property (readonly, nonatomic) UILabel *label;
3944 @property (readonly, nonatomic) UIActivityIndicatorView *activityIndicatorView;
3948 @implementation CYLoadingIndicator
3950 - (id)initWithFrame:(CGRect)frame {
3951 if ((self = [super initWithFrame:frame])) {
3952 container_ = [[[UIView alloc] init] autorelease];
3953 [container_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
3955 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
3956 [spinner_ startAnimating];
3957 [container_ addSubview:spinner_];
3959 label_ = [[[UILabel alloc] init] autorelease];
3960 [label_ setFont:[UIFont boldSystemFontOfSize:15.0f]];
3961 [label_ setBackgroundColor:[UIColor clearColor]];
3962 [label_ setTextColor:[UIColor blackColor]];
3963 [label_ setShadowColor:[UIColor whiteColor]];
3964 [label_ setShadowOffset:CGSizeMake(0, 1)];
3965 [label_ setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
3966 [container_ addSubview:label_];
3968 CGSize viewsize = frame.size;
3969 CGSize spinnersize = [spinner_ bounds].size;
3970 CGSize textsize = [[label_ text] sizeWithFont:[label_ font]];
3971 float bothwidth = spinnersize.width + textsize.width + 5.0f;
3973 CGRect containrect = {
3974 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
3975 CGSizeMake(bothwidth, spinnersize.height)
3978 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
3986 [container_ setFrame:containrect];
3987 [spinner_ setFrame:spinrect];
3988 [label_ setFrame:textrect];
3989 [self addSubview:container_];
3995 - (UILabel *)label { return label_; }
3996 - (UIActivityIndicatorView *)activityIndicatorView { return spinner_; }
4001 /* Cydia Browser Controller {{{ */
4002 @interface CYBrowserController : BrowserController {
4003 CydiaObject *cydia_;
4008 @implementation CYBrowserController
4015 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
4018 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4019 [super webView:view didClearWindowObject:window forFrame:frame];
4021 WebDataSource *source([frame dataSource]);
4022 NSURLResponse *response([source response]);
4023 NSURL *url([response URL]);
4024 NSString *scheme([url scheme]);
4026 NSHTTPURLResponse *http;
4027 if (scheme != nil && ([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"]))
4028 http = (NSHTTPURLResponse *) response;
4032 NSDictionary *headers([http allHeaderFields]);
4033 NSString *host([url host]);
4034 [self setHeaders:headers forHost:host];
4037 [host isEqualToString:@"cydia.saurik.com"] ||
4038 [host hasSuffix:@".cydia.saurik.com"] ||
4039 [scheme isEqualToString:@"file"]
4041 [window setValue:cydia_ forKey:@"cydia"];
4044 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
4045 if (System_ != NULL)
4046 [request setValue:System_ forHTTPHeaderField:@"X-System"];
4047 if (Machine_ != NULL)
4048 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4050 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4052 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
4055 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4056 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4057 [self _setMoreHeaders:copy];
4061 - (void) setDelegate:(id)delegate {
4062 [super setDelegate:delegate];
4063 [cydia_ setDelegate:delegate];
4067 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
4068 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
4070 WebView *webview([[webview_ _documentView] webView]);
4072 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
4074 NSString *application = package == nil ? @"Cydia" : [NSString
4075 stringWithFormat:@"Cydia/%@",
4080 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4082 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4083 if (Product_ != nil)
4084 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4086 [webview setApplicationNameForUserAgent:application];
4093 /* Confirmation {{{ */
4094 @protocol ConfirmationControllerDelegate
4095 - (void) cancelAndClear:(bool)clear;
4096 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4100 @interface ConfirmationController : CYBrowserController {
4101 _transient Database *database_;
4102 UIAlertView *essential_;
4109 - (id) initWithDatabase:(Database *)database;
4113 @implementation ConfirmationController
4120 if (essential_ != nil)
4121 [essential_ release];
4125 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4126 NSString *context([alert context]);
4128 if ([context isEqualToString:@"remove"]) {
4129 if (button == [alert cancelButtonIndex]) {
4130 [self dismissModalViewControllerAnimated:YES];
4131 } else if (button == [alert firstOtherButtonIndex]) {
4134 [delegate_ confirmWithNavigationController:[self navigationController]];
4137 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4138 } else if ([context isEqualToString:@"unable"]) {
4139 [self dismissModalViewControllerAnimated:YES];
4140 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4142 [super alertView:alert clickedButtonAtIndex:button];
4146 - (void) _doContinue {
4147 [self dismissModalViewControllerAnimated:YES];
4148 [delegate_ cancelAndClear:NO];
4151 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4152 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4156 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4157 [super webView:view didClearWindowObject:window forFrame:frame];
4158 [window setValue:changes_ forKey:@"changes"];
4159 [window setValue:issues_ forKey:@"issues"];
4160 [window setValue:sizes_ forKey:@"sizes"];
4161 [window setValue:self forKey:@"queue"];
4164 - (id) initWithDatabase:(Database *)database {
4165 if ((self = [super init]) != nil) {
4166 database_ = database;
4168 [[self navigationItem] setTitle:UCLocalize("CONFIRM")];
4170 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
4171 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
4172 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
4173 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
4174 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
4178 pkgDepCache::Policy *policy([database_ policy]);
4180 pkgCacheFile &cache([database_ cache]);
4181 NSArray *packages = [database_ packages];
4182 for (Package *package in packages) {
4183 pkgCache::PkgIterator iterator = [package iterator];
4184 pkgDepCache::StateCache &state(cache[iterator]);
4186 NSString *name([package name]);
4188 if (state.NewInstall())
4189 [installing addObject:name];
4190 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4191 [reinstalling addObject:name];
4192 else if (state.Upgrade())
4193 [upgrading addObject:name];
4194 else if (state.Downgrade())
4195 [downgrading addObject:name];
4196 else if (state.Delete()) {
4197 if ([package essential])
4199 [removing addObject:name];
4202 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4203 substrate_ |= DepSubstrate(iterator.CurrentVer());
4208 else if (Advanced_) {
4209 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4211 essential_ = [[UIAlertView alloc]
4212 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4213 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4215 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4216 otherButtonTitles:[NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")], nil
4219 [essential_ setContext:@"remove"];
4221 essential_ = [[UIAlertView alloc]
4222 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4223 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4225 cancelButtonTitle:UCLocalize("OKAY")
4226 otherButtonTitles:nil
4229 [essential_ setContext:@"unable"];
4232 changes_ = [[NSArray alloc] initWithObjects:
4240 issues_ = [database_ issues];
4242 issues_ = [issues_ retain];
4244 sizes_ = [[NSArray alloc] initWithObjects:
4245 SizeString([database_ fetcher].FetchNeeded()),
4246 SizeString([database_ fetcher].PartialPresent()),
4249 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
4251 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
4252 initWithTitle:UCLocalize("CANCEL")
4253 // OLD: [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")]
4254 style:UIBarButtonItemStylePlain
4256 action:@selector(cancelButtonClicked)
4261 - (void) applyRightButton {
4262 #if !AlwaysReload && !IgnoreInstall
4263 if (issues_ == nil && ![self isLoading])
4264 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4265 initWithTitle:UCLocalize("CONFIRM")
4266 style:UIBarButtonItemStylePlain
4268 action:@selector(confirmButtonClicked)
4271 [super applyRightButton];
4273 [[self navigationItem] setRightBarButtonItem:nil];
4277 - (void) cancelButtonClicked {
4278 [self dismissModalViewControllerAnimated:YES];
4279 [delegate_ cancelAndClear:YES];
4283 - (void) confirmButtonClicked {
4287 if (essential_ != nil)
4292 [delegate_ confirmWithNavigationController:[self navigationController]];
4300 /* Progress Data {{{ */
4301 @interface ProgressData : NSObject {
4303 // XXX: should these really both be _transient?
4304 _transient id target_;
4305 _transient id object_;
4308 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4315 @implementation ProgressData
4317 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4318 if ((self = [super init]) != nil) {
4319 selector_ = selector;
4339 /* Progress Controller {{{ */
4340 @interface ProgressController : CYViewController <
4341 ConfigurationDelegate,
4344 _transient Database *database_;
4345 UIProgressBar *progress_;
4346 UITextView *output_;
4347 UITextLabel *status_;
4348 UIPushButton *close_;
4350 SHA1SumValue springlist_;
4351 SHA1SumValue notifyconf_;
4355 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4357 - (void) _retachThread;
4358 - (void) _detachNewThreadData:(ProgressData *)data;
4359 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4365 @protocol ProgressControllerDelegate
4366 - (void) progressControllerIsComplete:(ProgressController *)sender;
4369 @implementation ProgressController
4372 [database_ setDelegate:nil];
4373 [progress_ release];
4382 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4383 if ((self = [super init]) != nil) {
4384 database_ = database;
4385 [database_ setDelegate:self];
4386 delegate_ = delegate;
4388 [[self view] setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
4390 progress_ = [[UIProgressBar alloc] init];
4391 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4392 [progress_ setStyle:0];
4394 status_ = [[UITextLabel alloc] init];
4395 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4396 [status_ setColor:[UIColor whiteColor]];
4397 [status_ setBackgroundColor:[UIColor clearColor]];
4398 [status_ setCentersHorizontally:YES];
4399 //[status_ setFont:font];
4401 output_ = [[UITextView alloc] init];
4403 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4404 //[output_ setTextFont:@"Courier New"];
4405 [output_ setFont:[[output_ font] fontWithSize:12]];
4406 [output_ setTextColor:[UIColor whiteColor]];
4407 [output_ setBackgroundColor:[UIColor clearColor]];
4408 [output_ setMarginTop:0];
4409 [output_ setAllowsRubberBanding:YES];
4410 [output_ setEditable:NO];
4411 [[self view] addSubview:output_];
4413 close_ = [[UIPushButton alloc] init];
4414 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4415 [close_ setAutosizesToFit:NO];
4416 [close_ setDrawsShadow:YES];
4417 [close_ setStretchBackground:YES];
4418 [close_ setEnabled:YES];
4419 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
4420 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4421 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4422 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4426 - (void) positionViews {
4427 CGRect bounds = [[self view] bounds];
4428 CGSize prgsize = [UIProgressBar defaultSize];
4431 (bounds.size.width - prgsize.width) / 2,
4432 bounds.size.height - prgsize.height - 20
4435 float closewidth = std::min(bounds.size.width - 20, 300.0f);
4437 [progress_ setFrame:prgrect];
4438 [status_ setFrame:CGRectMake(
4440 bounds.size.height - prgsize.height - 50,
4441 bounds.size.width - 20,
4444 [output_ setFrame:CGRectMake(
4447 bounds.size.width - 20,
4448 bounds.size.height - 62
4450 [close_ setFrame:CGRectMake(
4451 (bounds.size.width - closewidth) / 2,
4452 bounds.size.height - prgsize.height - 50,
4458 - (void) viewWillAppear:(BOOL)animated {
4459 [super viewDidAppear:animated];
4460 [[self navigationItem] setHidesBackButton:YES];
4461 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4463 [self positionViews];
4466 - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4467 [self positionViews];
4470 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4471 NSString *context([alert context]);
4473 if ([context isEqualToString:@"conffile"]) {
4474 FILE *input = [database_ input];
4475 if (button == [alert cancelButtonIndex])
4476 fprintf(input, "N\n");
4477 else if (button == [alert firstOtherButtonIndex])
4478 fprintf(input, "Y\n");
4483 - (void) closeButtonPushed {
4486 UpdateExternalStatus(0);
4490 [self dismissModalViewControllerAnimated:YES];
4494 [delegate_ terminateWithSuccess];
4495 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4496 [delegate_ suspendWithAnimation:YES];
4498 [delegate_ suspend];*/
4510 system("/usr/bin/sbreload");
4516 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
4517 SBReboot(SBSSpringBoardServerPort());
4519 reboot2(RB_AUTOBOOT);
4524 - (void) _retachThread {
4525 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
4527 [[self view] addSubview:close_];
4528 [progress_ removeFromSuperview];
4529 [status_ removeFromSuperview];
4531 [database_ popErrorWithTitle:title_];
4532 [delegate_ progressControllerIsComplete:self];
4536 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4539 MMap mmap(file, MMap::ReadOnly);
4541 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4542 if (!(notifyconf_ == sha1.Result()))
4549 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4552 MMap mmap(file, MMap::ReadOnly);
4554 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4555 if (!(springlist_ == sha1.Result()))
4561 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
4562 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4563 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4564 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4565 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4569 system("su -c /usr/bin/uicache mobile");
4572 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
4574 [delegate_ setStatusBarShowsProgress:NO];
4577 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4578 [[data target] performSelector:[data selector] withObject:[data object]];
4579 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4582 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4583 UpdateExternalStatus(1);
4590 title_ = [title retain];
4592 [[self navigationItem] setTitle:title_];
4594 [status_ setText:nil];
4595 [output_ setText:@""];
4596 [progress_ setProgress:0];
4598 [close_ removeFromSuperview];
4599 [[self view] addSubview:progress_];
4600 [[self view] addSubview:status_];
4602 [delegate_ setStatusBarShowsProgress:YES];
4607 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4610 MMap mmap(file, MMap::ReadOnly);
4612 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4613 notifyconf_ = sha1.Result();
4619 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4622 MMap mmap(file, MMap::ReadOnly);
4624 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4625 springlist_ = sha1.Result();
4630 detachNewThreadSelector:@selector(_detachNewThreadData:)
4632 withObject:[[[ProgressData alloc]
4633 initWithSelector:selector
4640 - (void) repairWithSelector:(SEL)selector {
4642 detachNewThreadSelector:selector
4645 title:UCLocalize("REPAIRING")
4649 - (void) setConfigurationData:(NSString *)data {
4651 performSelectorOnMainThread:@selector(_setConfigurationData:)
4657 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4658 CYActionSheet *sheet([[[CYActionSheet alloc]
4660 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4661 defaultButtonIndex:0
4664 [sheet setMessage:error];
4665 [sheet yieldToPopupAlertAnimated:YES];
4669 - (void) setProgressTitle:(NSString *)title {
4671 performSelectorOnMainThread:@selector(_setProgressTitle:)
4677 - (void) setProgressPercent:(float)percent {
4679 performSelectorOnMainThread:@selector(_setProgressPercent:)
4680 withObject:[NSNumber numberWithFloat:percent]
4685 - (void) startProgress {
4688 - (void) addProgressOutput:(NSString *)output {
4690 performSelectorOnMainThread:@selector(_addProgressOutput:)
4696 - (bool) isCancelling:(size_t)received {
4700 - (void) _setConfigurationData:(NSString *)data {
4701 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4703 if (!conffile_r(data)) {
4704 lprintf("E:invalid conffile\n");
4708 NSString *ofile = conffile_r[1];
4709 //NSString *nfile = conffile_r[2];
4711 UIAlertView *alert = [[[UIAlertView alloc]
4712 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4713 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
4715 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
4716 otherButtonTitles:UCLocalize("ACCEPT_NEW_COPY"),
4717 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4721 [alert setContext:@"conffile"];
4725 - (void) _setProgressTitle:(NSString *)title {
4726 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4727 for (size_t i(0), e([words count]); i != e; ++i) {
4728 NSString *word([words objectAtIndex:i]);
4729 if (Package *package = [database_ packageWithName:word])
4730 [words replaceObjectAtIndex:i withObject:[package name]];
4733 [status_ setText:[words componentsJoinedByString:@" "]];
4736 - (void) _setProgressPercent:(NSNumber *)percent {
4737 [progress_ setProgress:[percent floatValue]];
4740 - (void) _addProgressOutput:(NSString *)output {
4741 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4742 CGSize size = [output_ contentSize];
4743 CGPoint offset = [output_ contentOffset];
4744 if (size.height - offset.y < [output_ frame].size.height + 20.f) {
4745 CGRect rect = {{0, size.height-1}, {size.width, 1}};
4746 [output_ scrollRectToVisible:rect animated:YES];
4750 - (BOOL) isRunning {
4757 /* Cell Content View {{{ */
4758 @protocol ContentDelegate
4759 - (void) drawContentRect:(CGRect)rect;
4762 @interface ContentView : UIView {
4763 _transient id<ContentDelegate> delegate_;
4768 @implementation ContentView
4770 - (id) initWithFrame:(CGRect)frame {
4771 if ((self = [super initWithFrame:frame]) != nil) {
4772 [self setNeedsDisplayOnBoundsChange:YES];
4776 - (void) setDelegate:(id<ContentDelegate>)delegate {
4777 delegate_ = delegate;
4780 - (void) drawRect:(CGRect)rect {
4781 [super drawRect:rect];
4782 [delegate_ drawContentRect:rect];
4787 /* Cydia TableView Cell {{{ */
4788 @interface CYTableViewCell : UITableViewCell {
4789 ContentView *content_;
4795 @implementation CYTableViewCell
4802 - (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
4803 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
4805 if (view == content_) {
4806 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
4807 highlighted_ = highlighted;
4810 [super _updateHighlightColorsForView:view highlighted:highlighted];
4813 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
4814 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
4815 highlighted_ = selected;
4817 [super setSelected:selected animated:animated];
4818 [content_ setNeedsDisplay];
4823 /* Package Cell {{{ */
4824 @interface PackageCell : CYTableViewCell <
4829 NSString *description_;
4837 - (PackageCell *) init;
4838 - (void) setPackage:(Package *)package;
4840 + (int) heightForPackage:(Package *)package;
4841 - (void) drawContentRect:(CGRect)rect;
4845 @implementation PackageCell
4847 - (void) clearPackage {
4858 if (description_ != nil) {
4859 [description_ release];
4863 if (source_ != nil) {
4868 if (badge_ != nil) {
4873 if (placard_ != nil) {
4883 [self clearPackage];
4887 - (PackageCell *) init {
4888 CGRect frame(CGRectMake(0, 0, 320, 74));
4889 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4890 UIView *content([self contentView]);
4891 CGRect bounds([content bounds]);
4893 content_ = [[ContentView alloc] initWithFrame:bounds];
4894 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4895 [content addSubview:content_];
4897 [content_ setDelegate:self];
4898 [content_ setOpaque:YES];
4902 - (void) _setBackgroundColor {
4904 if (NSString *mode = [package_ mode]) {
4905 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4906 color = remove ? RemovingColor_ : InstallingColor_;
4908 color = [UIColor whiteColor];
4910 [content_ setBackgroundColor:color];
4911 [self setNeedsDisplay];
4914 - (void) setPackage:(Package *)package {
4915 [self clearPackage];
4918 Source *source = [package source];
4920 icon_ = [[package icon] retain];
4921 name_ = [[package name] retain];
4924 description_ = [package longDescription];
4925 if (description_ == nil)
4926 description_ = [package shortDescription];
4927 if (description_ != nil)
4928 description_ = [description_ retain];
4930 commercial_ = [package isCommercial];
4932 package_ = [package retain];
4934 NSString *label = nil;
4935 bool trusted = false;
4937 if (source != nil) {
4938 label = [source label];
4939 trusted = [source trusted];
4940 } else if ([[package id] isEqualToString:@"firmware"])
4941 label = UCLocalize("APPLE");
4943 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
4945 NSString *from(label);
4947 NSString *section = [package simpleSection];
4948 if (section != nil && ![section isEqualToString:label]) {
4949 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4950 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
4953 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
4954 source_ = [from retain];
4956 if (NSString *purpose = [package primaryPurpose])
4957 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4958 badge_ = [badge_ retain];
4960 if ([package installed] != nil)
4961 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/installed.png", App_]]) != nil)
4962 placard_ = [placard_ retain];
4964 [self _setBackgroundColor];
4965 [content_ setNeedsDisplay];
4968 - (void) drawContentRect:(CGRect)rect {
4969 bool highlighted(highlighted_);
4970 float width([self bounds].size.width);
4973 CGContextRef context(UIGraphicsGetCurrentContext());
4974 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
4975 CGContextFillRect(context, rect);
4980 rect.size = [icon_ size];
4982 rect.size.width /= 2;
4983 rect.size.height /= 2;
4985 rect.origin.x = 25 - rect.size.width / 2;
4986 rect.origin.y = 25 - rect.size.height / 2;
4988 [icon_ drawInRect:rect];
4991 if (badge_ != nil) {
4993 rect.size = [badge_ size];
4995 rect.size.width /= 2;
4996 rect.size.height /= 2;
4998 rect.origin.x = 36 - rect.size.width / 2;
4999 rect.origin.y = 36 - rect.size.height / 2;
5001 [badge_ drawInRect:rect];
5008 UISetColor(commercial_ ? Purple_ : Black_);
5009 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5010 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5013 UISetColor(commercial_ ? Purplish_ : Gray_);
5014 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5016 if (placard_ != nil)
5017 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5020 + (int) heightForPackage:(Package *)package {
5026 /* Section Cell {{{ */
5027 @interface SectionCell : CYTableViewCell <
5039 - (void) setSection:(Section *)section editing:(BOOL)editing;
5043 @implementation SectionCell
5045 - (void) clearSection {
5046 if (basic_ != nil) {
5051 if (section_ != nil) {
5061 if (count_ != nil) {
5068 [self clearSection];
5074 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5075 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5076 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
5077 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
5078 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5080 UIView *content([self contentView]);
5081 CGRect bounds([content bounds]);
5083 content_ = [[ContentView alloc] initWithFrame:bounds];
5084 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5085 [content addSubview:content_];
5086 [content_ setBackgroundColor:[UIColor whiteColor]];
5088 [content_ setDelegate:self];
5092 - (void) onSwitch:(id)sender {
5093 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5094 if (metadata == nil) {
5095 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5096 [Sections_ setObject:metadata forKey:basic_];
5099 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5103 - (void) setSection:(Section *)section editing:(BOOL)editing {
5104 if (editing != editing_) {
5106 [switch_ removeFromSuperview];
5108 [self addSubview:switch_];
5112 [self clearSection];
5114 if (section == nil) {
5115 name_ = [UCLocalize("ALL_PACKAGES") retain];
5118 basic_ = [section name];
5120 basic_ = [basic_ retain];
5122 section_ = [section localized];
5123 if (section_ != nil)
5124 section_ = [section_ retain];
5126 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
5127 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
5130 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5133 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5134 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5136 [content_ setNeedsDisplay];
5139 - (void) setFrame:(CGRect)frame {
5140 [super setFrame:frame];
5142 CGRect rect([switch_ frame]);
5143 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5146 - (void) drawContentRect:(CGRect)rect {
5147 bool highlighted(highlighted_);
5149 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5154 float width(rect.size.width);
5160 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5162 CGSize size = [count_ sizeWithFont:Font14_];
5166 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5172 /* File Table {{{ */
5173 @interface FileTable : CYViewController <
5174 UITableViewDataSource,
5177 _transient Database *database_;
5180 NSMutableArray *files_;
5184 - (id) initWithDatabase:(Database *)database;
5185 - (void) setPackage:(Package *)package;
5189 @implementation FileTable
5192 if (package_ != nil)
5201 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5202 return files_ == nil ? 0 : [files_ count];
5205 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5209 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5210 static NSString *reuseIdentifier = @"Cell";
5212 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5214 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5215 [cell setFont:[UIFont systemFontOfSize:16]];
5217 [cell setText:[files_ objectAtIndex:indexPath.row]];
5218 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5223 - (id) initWithDatabase:(Database *)database {
5224 if ((self = [super init]) != nil) {
5225 database_ = database;
5227 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5229 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5231 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5232 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5233 [list_ setRowHeight:24.0f];
5234 [[self view] addSubview:list_];
5236 [list_ setDataSource:self];
5237 [list_ setDelegate:self];
5241 - (void) setPackage:(Package *)package {
5242 if (package_ != nil) {
5243 [package_ autorelease];
5252 [files_ removeAllObjects];
5254 if (package != nil) {
5255 package_ = [package retain];
5256 name_ = [[package id] retain];
5258 if (NSArray *files = [package files])
5259 [files_ addObjectsFromArray:files];
5261 if ([files_ count] != 0) {
5262 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5263 [files_ removeObjectAtIndex:0];
5264 [files_ sortUsingSelector:@selector(compareByPath:)];
5266 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5267 [stack addObject:@"/"];
5269 for (int i(0), e([files_ count]); i != e; ++i) {
5270 NSString *file = [files_ objectAtIndex:i];
5271 while (![file hasPrefix:[stack lastObject]])
5272 [stack removeLastObject];
5273 NSString *directory = [stack lastObject];
5274 [stack addObject:[file stringByAppendingString:@"/"]];
5275 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5276 ([stack count] - 2) * 3, "",
5277 [file substringFromIndex:[directory length]]
5286 - (void) reloadData {
5287 [self setPackage:[database_ packageWithName:name_]];
5292 /* Package Controller {{{ */
5293 @interface PackageController : CYBrowserController <
5294 UIActionSheetDelegate
5296 _transient Database *database_;
5300 NSMutableArray *buttons_;
5301 UIBarButtonItem *button_;
5304 - (id) initWithDatabase:(Database *)database;
5305 - (void) setPackage:(Package *)package;
5309 @implementation PackageController
5312 if (package_ != nil)
5326 if ([self retainCount] == 1)
5327 [delegate_ setPackageController:self];
5331 /* XXX: this is not safe at all... localization of /fail/ */
5332 - (void) _clickButtonWithName:(NSString *)name {
5333 if ([name isEqualToString:UCLocalize("CLEAR")])
5334 [delegate_ clearPackage:package_];
5335 else if ([name isEqualToString:UCLocalize("INSTALL")])
5336 [delegate_ installPackage:package_];
5337 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5338 [delegate_ installPackage:package_];
5339 else if ([name isEqualToString:UCLocalize("REMOVE")])
5340 [delegate_ removePackage:package_];
5341 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5342 [delegate_ installPackage:package_];
5343 else _assert(false);
5346 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5347 NSString *context([sheet context]);
5349 if ([context isEqualToString:@"modify"]) {
5350 if (button != [sheet cancelButtonIndex]) {
5351 NSString *buttonName = [buttons_ objectAtIndex:button];
5352 [self _clickButtonWithName:buttonName];
5355 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5359 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5360 [super webView:view didClearWindowObject:window forFrame:frame];
5361 [window setValue:package_ forKey:@"package"];
5364 - (bool) _allowJavaScriptPanel {
5369 - (void) _customButtonClicked {
5370 int count([buttons_ count]);
5375 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5377 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5378 [buttons addObjectsFromArray:buttons_];
5380 UIActionSheet *sheet = [[[UIActionSheet alloc]
5383 cancelButtonTitle:nil
5384 destructiveButtonTitle:nil
5385 otherButtonTitles:nil
5388 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5390 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5391 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5393 [sheet setContext:@"modify"];
5395 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5399 // We don't want to allow non-commercial packages to do custom things to the install button,
5400 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5401 - (void) customButtonClicked {
5403 [super customButtonClicked];
5405 [self _customButtonClicked];
5408 - (void) reloadButtonClicked {
5409 // Don't reload a package view by clicking the button.
5412 - (void) applyLoadingTitle {
5413 // Don't show "Loading" as the title. Ever.
5416 - (UIBarButtonItem *) rightButton {
5421 - (id) initWithDatabase:(Database *)database {
5422 if ((self = [super init]) != nil) {
5423 database_ = database;
5424 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5425 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
5429 - (void) setPackage:(Package *)package {
5430 if (package_ != nil) {
5431 [package_ autorelease];
5440 [buttons_ removeAllObjects];
5442 if (package != nil) {
5445 package_ = [package retain];
5446 name_ = [[package id] retain];
5447 commercial_ = [package isCommercial];
5449 if ([package_ mode] != nil)
5450 [buttons_ addObject:UCLocalize("CLEAR")];
5451 if ([package_ source] == nil);
5452 else if ([package_ upgradableAndEssential:NO])
5453 [buttons_ addObject:UCLocalize("UPGRADE")];
5454 else if ([package_ uninstalled])
5455 [buttons_ addObject:UCLocalize("INSTALL")];
5457 [buttons_ addObject:UCLocalize("REINSTALL")];
5458 if (![package_ uninstalled])
5459 [buttons_ addObject:UCLocalize("REMOVE")];
5466 switch ([buttons_ count]) {
5467 case 0: title = nil; break;
5468 case 1: title = [buttons_ objectAtIndex:0]; break;
5469 default: title = UCLocalize("MODIFY"); break;
5472 button_ = [[UIBarButtonItem alloc]
5474 style:UIBarButtonItemStylePlain
5476 action:@selector(customButtonClicked)
5482 - (bool) isLoading {
5483 return commercial_ ? [super isLoading] : false;
5486 - (void) reloadData {
5487 [self setPackage:[database_ packageWithName:name_]];
5492 /* Package Table {{{ */
5493 @interface PackageTable : UIView <
5494 UITableViewDataSource,
5497 _transient Database *database_;
5499 NSMutableArray *packages_;
5500 NSMutableArray *sections_;
5502 NSMutableArray *index_;
5503 NSMutableDictionary *indices_;
5504 // XXX: this target_ seems to be delegate_. :(
5505 _transient id target_;
5507 // XXX: why do we even have this delegate_?
5508 _transient id delegate_;
5511 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action;
5513 - (void) setDelegate:(id)delegate;
5515 - (void) reloadData;
5516 - (void) resetCursor;
5518 - (UITableView *) list;
5520 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5522 - (void) deselectWithAnimation:(BOOL)animated;
5526 @implementation PackageTable
5529 [packages_ release];
5530 [sections_ release];
5538 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5539 NSInteger count([sections_ count]);
5540 return count == 0 ? 1 : count;
5543 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5544 if ([sections_ count] == 0)
5546 return [[sections_ objectAtIndex:section] name];
5549 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5550 if ([sections_ count] == 0)
5552 return [[sections_ objectAtIndex:section] count];
5555 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5556 @synchronized (database_) {
5557 if ([database_ era] != era_)
5560 Section *section([sections_ objectAtIndex:[path section]]);
5561 NSInteger row([path row]);
5562 Package *package([packages_ objectAtIndex:([section row] + row)]);
5563 return [[package retain] autorelease];
5566 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5567 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5569 cell = [[[PackageCell alloc] init] autorelease];
5570 [cell setPackage:[self packageAtIndexPath:path]];
5574 - (void) deselectWithAnimation:(BOOL)animated {
5575 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5578 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
5579 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
5582 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5583 Package *package([self packageAtIndexPath:path]);
5584 package = [database_ packageWithName:[package id]];
5585 [target_ performSelector:action_ withObject:package];
5589 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5590 return [packages_ count] > 20 ? index_ : nil;
5593 - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5597 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action {
5598 if ((self = [super initWithFrame:frame]) != nil) {
5599 database_ = database;
5604 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5605 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5607 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5608 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5610 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
5611 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5612 [list_ setRowHeight:73.0f];
5613 [self addSubview:list_];
5615 [list_ setDataSource:self];
5616 [list_ setDelegate:self];
5620 - (void) setDelegate:(id)delegate {
5621 delegate_ = delegate;
5624 - (bool) hasPackage:(Package *)package {
5628 - (void) reloadData {
5629 era_ = [database_ era];
5630 NSArray *packages = [database_ packages];
5632 [packages_ removeAllObjects];
5633 [sections_ removeAllObjects];
5635 _profile(PackageTable$reloadData$Filter)
5636 for (Package *package in packages)
5637 if ([self hasPackage:package])
5638 [packages_ addObject:package];
5641 [index_ removeAllObjects];
5642 [indices_ removeAllObjects];
5644 Section *section = nil;
5646 _profile(PackageTable$reloadData$Section)
5647 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5651 _profile(PackageTable$reloadData$Section$Package)
5652 package = [packages_ objectAtIndex:offset];
5653 index = [package index];
5656 if (section == nil || [section index] != index) {
5657 _profile(PackageTable$reloadData$Section$Allocate)
5658 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5661 [index_ addObject:[section name]];
5662 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5664 _profile(PackageTable$reloadData$Section$Add)
5665 [sections_ addObject:section];
5669 [section addToCount];
5673 _profile(PackageTable$reloadData$List)
5678 - (void) resetCursor {
5679 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5682 - (UITableView *) list {
5686 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5687 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
5692 /* Filtered Package Table {{{ */
5693 @interface FilteredPackageTable : PackageTable {
5699 - (void) setObject:(id)object;
5700 - (void) setObject:(id)object forFilter:(SEL)filter;
5702 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object;
5706 @implementation FilteredPackageTable
5714 - (void) setFilter:(SEL)filter {
5717 /* XXX: this is an unsafe optimization of doomy hell */
5718 Method method(class_getInstanceMethod([Package class], filter));
5719 _assert(method != NULL);
5720 imp_ = method_getImplementation(method);
5721 _assert(imp_ != NULL);
5724 - (void) setObject:(id)object {
5730 object_ = [object retain];
5733 - (void) setObject:(id)object forFilter:(SEL)filter {
5734 [self setFilter:filter];
5735 [self setObject:object];
5738 - (bool) hasPackage:(Package *)package {
5739 _profile(FilteredPackageTable$hasPackage)
5740 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5744 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object {
5745 if ((self = [super initWithFrame:frame database:database target:target action:action]) != nil) {
5746 [self setFilter:filter];
5747 object_ = [object retain];
5755 /* Filtered Package Controller {{{ */
5756 @interface FilteredPackageController : CYViewController {
5757 _transient Database *database_;
5758 FilteredPackageTable *packages_;
5762 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5766 @implementation FilteredPackageController
5769 [packages_ release];
5775 - (void) viewDidAppear:(BOOL)animated {
5776 [super viewDidAppear:animated];
5777 [packages_ deselectWithAnimation:animated];
5780 - (void) didSelectPackage:(Package *)package {
5781 PackageController *view([delegate_ packageController]);
5782 [view setPackage:package];
5783 [view setDelegate:delegate_];
5784 [[self navigationController] pushViewController:view animated:YES];
5787 - (NSString *) title { return title_; }
5789 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5790 if ((self = [super init]) != nil) {
5791 database_ = database;
5792 title_ = [title copy];
5793 [[self navigationItem] setTitle:title_];
5795 packages_ = [[FilteredPackageTable alloc]
5796 initWithFrame:[[self view] bounds]
5799 action:@selector(didSelectPackage:)
5804 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5805 [[self view] addSubview:packages_];
5809 - (void) reloadData {
5810 [packages_ reloadData];
5813 - (void) setDelegate:(id)delegate {
5814 [super setDelegate:delegate];
5815 [packages_ setDelegate:delegate];
5822 /* Source Cell {{{ */
5823 @interface SourceCell : CYTableViewCell <
5828 NSString *description_;
5832 - (void) setSource:(Source *)source;
5836 @implementation SourceCell
5838 - (void) clearSource {
5841 [description_ release];
5850 - (void) setSource:(Source *)source {
5854 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5856 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5857 icon_ = [icon_ retain];
5859 origin_ = [[source name] retain];
5860 label_ = [[source uri] retain];
5861 description_ = [[source description] retain];
5863 [content_ setNeedsDisplay];
5871 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5872 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5873 UIView *content([self contentView]);
5874 CGRect bounds([content bounds]);
5876 content_ = [[ContentView alloc] initWithFrame:bounds];
5877 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5878 [content_ setBackgroundColor:[UIColor whiteColor]];
5879 [content addSubview:content_];
5881 [content_ setDelegate:self];
5882 [content_ setOpaque:YES];
5886 - (void) drawContentRect:(CGRect)rect {
5887 bool highlighted(highlighted_);
5888 float width(rect.size.width);
5891 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5898 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5902 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5906 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 40) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5911 /* Source Table {{{ */
5912 @interface SourceController : CYViewController <
5913 UITableViewDataSource,
5916 _transient Database *database_;
5918 NSMutableArray *sources_;
5922 UIProgressHUD *hud_;
5925 //NSURLConnection *installer_;
5926 NSURLConnection *trivial_;
5927 NSURLConnection *trivial_bz2_;
5928 NSURLConnection *trivial_gz_;
5929 //NSURLConnection *automatic_;
5934 - (id) initWithDatabase:(Database *)database;
5936 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
5940 @implementation SourceController
5942 - (void) _releaseConnection:(NSURLConnection *)connection {
5943 if (connection != nil) {
5944 [connection cancel];
5945 //[connection setDelegate:nil];
5946 [connection release];
5958 //[self _releaseConnection:installer_];
5959 [self _releaseConnection:trivial_];
5960 [self _releaseConnection:trivial_gz_];
5961 [self _releaseConnection:trivial_bz2_];
5962 //[self _releaseConnection:automatic_];
5969 - (void) viewDidAppear:(BOOL)animated {
5970 [super viewDidAppear:animated];
5971 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5974 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
5975 return offset_ == 0 ? 1 : 2;
5978 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
5979 switch (section + (offset_ == 0 ? 1 : 0)) {
5980 case 0: return UCLocalize("ENTERED_BY_USER");
5981 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
5987 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5988 int count = [sources_ count];
5990 case 0: return (offset_ == 0 ? count : offset_);
5991 case 1: return count - offset_;
5997 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
5999 switch (indexPath.section) {
6000 case 0: idx = indexPath.row; break;
6001 case 1: idx = indexPath.row + offset_; break;
6005 return [sources_ objectAtIndex:idx];
6008 - (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6009 Source *source = [self sourceAtIndexPath:indexPath];
6010 return [source description] == nil ? 56 : 73;
6013 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6014 static NSString *cellIdentifier = @"SourceCell";
6016 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
6017 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
6018 [cell setSource:[self sourceAtIndexPath:indexPath]];
6023 - (UITableViewCellAccessoryType) tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath {
6024 return UITableViewCellAccessoryDisclosureIndicator;
6027 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6028 Source *source = [self sourceAtIndexPath:indexPath];
6030 FilteredPackageController *packages = [[[FilteredPackageController alloc]
6031 initWithDatabase:database_
6032 title:[source label]
6033 filter:@selector(isVisibleInSource:)
6037 [packages setDelegate:delegate_];
6039 [[self navigationController] pushViewController:packages animated:YES];
6042 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
6043 Source *source = [self sourceAtIndexPath:indexPath];
6044 return [source record] != nil;
6047 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
6048 Source *source = [self sourceAtIndexPath:indexPath];
6049 [Sources_ removeObjectForKey:[source key]];
6050 [delegate_ syncData];
6054 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
6057 @"./", @"Distribution",
6058 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
6060 [delegate_ syncData];
6063 - (NSString *) getWarning {
6064 NSString *href(href_);
6065 NSRange colon([href rangeOfString:@"://"]);
6066 if (colon.location != NSNotFound)
6067 href = [href substringFromIndex:(colon.location + 3)];
6068 href = [href stringByAddingPercentEscapes];
6069 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
6070 href = [href stringByCachingURLWithCurrentCDN];
6072 NSURL *url([NSURL URLWithString:href]);
6074 NSStringEncoding encoding;
6075 NSError *error(nil);
6077 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
6078 return [warning length] == 0 ? nil : warning;
6082 - (void) _endConnection:(NSURLConnection *)connection {
6083 // XXX: the memory management in this method is horribly awkward
6085 NSURLConnection **field = NULL;
6086 if (connection == trivial_)
6088 else if (connection == trivial_bz2_)
6089 field = &trivial_bz2_;
6090 else if (connection == trivial_gz_)
6091 field = &trivial_gz_;
6092 _assert(field != NULL);
6093 [connection release];
6098 trivial_bz2_ == nil &&
6104 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
6107 UIAlertView *alert = [[[UIAlertView alloc]
6108 initWithTitle:UCLocalize("SOURCE_WARNING")
6111 cancelButtonTitle:UCLocalize("CANCEL")
6112 otherButtonTitles:UCLocalize("ADD_ANYWAY"), nil
6115 [alert setContext:@"warning"];
6116 [alert setNumberOfRows:1];
6120 } else if (error_ != nil) {
6121 UIAlertView *alert = [[[UIAlertView alloc]
6122 initWithTitle:UCLocalize("VERIFICATION_ERROR")
6123 message:[error_ localizedDescription]
6125 cancelButtonTitle:UCLocalize("OK")
6126 otherButtonTitles:nil
6129 [alert setContext:@"urlerror"];
6132 UIAlertView *alert = [[[UIAlertView alloc]
6133 initWithTitle:UCLocalize("NOT_REPOSITORY")
6134 message:UCLocalize("NOT_REPOSITORY_EX")
6136 cancelButtonTitle:UCLocalize("OK")
6137 otherButtonTitles:nil
6140 [alert setContext:@"trivial"];
6144 [delegate_ setStatusBarShowsProgress:NO];
6145 [delegate_ removeProgressHUD:hud_];
6155 if (error_ != nil) {
6162 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
6163 switch ([response statusCode]) {
6169 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
6170 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
6172 error_ = [error retain];
6173 [self _endConnection:connection];
6176 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
6177 [self _endConnection:connection];
6180 - (NSString *) title { return UCLocalize("SOURCES"); }
6182 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
6183 NSMutableURLRequest *request = [NSMutableURLRequest
6184 requestWithURL:[NSURL URLWithString:href]
6185 cachePolicy:NSURLRequestUseProtocolCachePolicy
6186 timeoutInterval:120.0
6189 [request setHTTPMethod:method];
6191 if (Machine_ != NULL)
6192 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
6193 if (UniqueID_ != nil)
6194 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6196 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
6198 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
6201 - (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
6202 NSString *context([alert context]);
6204 if ([context isEqualToString:@"source"]) {
6207 NSString *href = [[alert textField] text];
6209 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
6211 if (![href hasSuffix:@"/"])
6212 href_ = [href stringByAppendingString:@"/"];
6215 href_ = [href_ retain];
6217 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
6218 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
6219 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
6220 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
6224 // XXX: this is stupid
6225 hud_ = [[delegate_ addProgressHUD] retain];
6226 [hud_ setText:UCLocalize("VERIFYING_URL")];
6235 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6236 } else if ([context isEqualToString:@"trivial"])
6237 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6238 else if ([context isEqualToString:@"urlerror"])
6239 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6240 else if ([context isEqualToString:@"warning"]) {
6255 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6259 - (id) initWithDatabase:(Database *)database {
6260 if ((self = [super init]) != nil) {
6261 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
6262 [self updateButtonsForEditingStatus:NO animated:NO];
6264 database_ = database;
6265 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
6267 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6268 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6269 [[self view] addSubview:list_];
6271 [list_ setDataSource:self];
6272 [list_ setDelegate:self];
6278 - (void) reloadData {
6280 if (!list.ReadMainList())
6283 [sources_ removeAllObjects];
6284 [sources_ addObjectsFromArray:[database_ sources]];
6286 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
6289 int count([sources_ count]);
6291 for (int i = 0; i != count; i++) {
6292 if ([[sources_ objectAtIndex:i] record] == nil)
6297 [list_ setEditing:NO];
6298 [self updateButtonsForEditingStatus:NO animated:NO];
6302 - (void) addButtonClicked {
6303 /*[book_ pushPage:[[[AddSourceController alloc]
6308 UIAlertView *alert = [[[UIAlertView alloc]
6309 initWithTitle:UCLocalize("ENTER_APT_URL")
6312 cancelButtonTitle:UCLocalize("CANCEL")
6313 otherButtonTitles:UCLocalize("ADD_SOURCE"), nil
6316 [alert setContext:@"source"];
6317 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
6319 [alert setNumberOfRows:1];
6320 [alert addTextFieldWithValue:@"http://" label:@""];
6322 UITextInputTraits *traits = [[alert textField] textInputTraits];
6323 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6324 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6325 [traits setKeyboardType:UIKeyboardTypeURL];
6326 // XXX: UIReturnKeyDone
6327 [traits setReturnKeyType:UIReturnKeyNext];
6332 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
6333 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
6334 initWithTitle:UCLocalize("ADD")
6335 style:UIBarButtonItemStylePlain
6337 action:@selector(addButtonClicked)
6338 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
6340 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6341 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
6342 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
6344 action:@selector(editButtonClicked)
6345 ] autorelease] animated:animated];
6347 if (IsWildcat_ && !editing)
6348 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6349 initWithTitle:UCLocalize("SETTINGS")
6350 style:UIBarButtonItemStylePlain
6352 action:@selector(settingsButtonClicked)
6356 - (void) settingsButtonClicked {
6357 [delegate_ showSettings];
6360 - (void) editButtonClicked {
6361 [list_ setEditing:![list_ isEditing] animated:YES];
6363 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
6369 /* Installed Controller {{{ */
6370 @interface InstalledController : FilteredPackageController {
6374 - (id) initWithDatabase:(Database *)database;
6376 - (void) updateRoleButton;
6377 - (void) queueStatusDidChange;
6381 @implementation InstalledController
6387 - (NSString *) title { return UCLocalize("INSTALLED"); }
6389 - (id) initWithDatabase:(Database *)database {
6390 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
6391 [self updateRoleButton];
6392 [self queueStatusDidChange];
6397 - (void) queueButtonClicked {
6402 - (void) queueStatusDidChange {
6406 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6407 initWithTitle:UCLocalize("QUEUE")
6408 style:UIBarButtonItemStyleDone
6410 action:@selector(queueButtonClicked)
6413 [[self navigationItem] setLeftBarButtonItem:nil];
6419 - (void) reloadData {
6420 [packages_ reloadData];
6423 - (void) updateRoleButton {
6424 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
6425 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6426 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
6427 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
6429 action:@selector(roleButtonClicked)
6433 - (void) roleButtonClicked {
6434 [packages_ setObject:[NSNumber numberWithBool:expert_]];
6435 [packages_ reloadData];
6438 [self updateRoleButton];
6441 - (void) setDelegate:(id)delegate {
6442 [super setDelegate:delegate];
6443 [packages_ setDelegate:delegate];
6449 /* Home Controller {{{ */
6450 @interface HomeController : CYBrowserController {
6455 @implementation HomeController
6457 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6458 [super _setMoreHeaders:request];
6461 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6462 if (UniqueID_ != nil)
6463 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6465 [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"];
6468 - (void) aboutButtonClicked {
6469 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6471 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6472 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6473 [alert setCancelButtonIndex:0];
6476 @"Copyright (C) 2008-2010\n"
6477 "Jay Freeman (saurik)\n"
6478 "saurik@saurik.com\n"
6479 "http://www.saurik.com/"
6485 - (void) viewWillAppear:(BOOL)animated {
6486 [super viewWillAppear:animated];
6487 //[[self navigationController] setNavigationBarHidden:YES animated:animated];
6490 - (void) viewWillDisappear:(BOOL)animated {
6491 [super viewWillDisappear:animated];
6492 //[[self navigationController] setNavigationBarHidden:NO animated:animated];
6496 if ((self = [super init]) != nil) {
6497 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6498 initWithTitle:UCLocalize("ABOUT")
6499 style:UIBarButtonItemStylePlain
6501 action:@selector(aboutButtonClicked)
6508 /* Manage Controller {{{ */
6509 @interface ManageController : CYBrowserController {
6512 - (void) queueStatusDidChange;
6515 @implementation ManageController
6518 if ((self = [super init]) != nil) {
6519 [[self navigationItem] setTitle:UCLocalize("MANAGE")];
6521 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6522 initWithTitle:UCLocalize("SETTINGS")
6523 style:UIBarButtonItemStylePlain
6525 action:@selector(settingsButtonClicked)
6528 [self queueStatusDidChange];
6532 - (void) settingsButtonClicked {
6533 [delegate_ showSettings];
6537 - (void) queueButtonClicked {
6541 - (void) applyLoadingTitle {
6542 // No "Loading" title.
6545 - (void) applyRightButton {
6550 - (void) queueStatusDidChange {
6552 if (!IsWildcat_ && Queuing_) {
6553 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6554 initWithTitle:UCLocalize("QUEUE")
6555 style:UIBarButtonItemStyleDone
6557 action:@selector(queueButtonClicked)
6560 [[self navigationItem] setRightBarButtonItem:nil];
6565 - (bool) isLoading {
6572 /* Refresh Bar {{{ */
6573 @interface RefreshBar : UINavigationBar {
6574 UIProgressIndicator *indicator_;
6575 UITextLabel *prompt_;
6576 UIProgressBar *progress_;
6577 UINavigationButton *cancel_;
6582 @implementation RefreshBar
6585 [indicator_ release];
6587 [progress_ release];
6592 - (void) positionViews {
6593 CGRect frame = [cancel_ frame];
6594 frame.size = [cancel_ sizeThatFits:frame.size];
6595 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6596 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6597 [cancel_ setFrame:frame];
6599 CGSize prgsize = {75, 100};
6601 [self frame].size.width - prgsize.width - 10,
6602 ([self frame].size.height - prgsize.height) / 2
6604 [progress_ setFrame:prgrect];
6606 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6607 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6608 CGRect indrect = {{indoffset, indoffset}, indsize};
6609 [indicator_ setFrame:indrect];
6611 CGSize prmsize = {215, indsize.height + 4};
6613 indoffset * 2 + indsize.width,
6614 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6616 [prompt_ setFrame:prmrect];
6619 - (void)setFrame:(CGRect)frame {
6620 [super setFrame:frame];
6622 [self positionViews];
6625 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6626 if ((self = [super initWithFrame:frame])) {
6627 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6629 [self setBarStyle:UIBarStyleBlack];
6631 UIBarStyle barstyle([self _barStyle:NO]);
6632 bool ugly(barstyle == UIBarStyleDefault);
6634 UIProgressIndicatorStyle style = ugly ?
6635 UIProgressIndicatorStyleMediumBrown :
6636 UIProgressIndicatorStyleMediumWhite;
6638 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6639 [indicator_ setStyle:style];
6640 [indicator_ startAnimation];
6641 [self addSubview:indicator_];
6643 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6644 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6645 [prompt_ setBackgroundColor:[UIColor clearColor]];
6646 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6647 [self addSubview:prompt_];
6649 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6650 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6651 [progress_ setStyle:0];
6652 [self addSubview:progress_];
6654 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6655 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6656 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6657 [cancel_ setBarStyle:barstyle];
6659 [self positionViews];
6664 [cancel_ removeFromSuperview];
6668 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6669 [progress_ setProgress:0];
6670 [self addSubview:cancel_];
6674 [cancel_ removeFromSuperview];
6677 - (void) setPrompt:(NSString *)prompt {
6678 [prompt_ setText:prompt];
6681 - (void) setProgress:(float)progress {
6682 [progress_ setProgress:progress];
6688 @class CYNavigationController;
6690 /* Cydia Tab Bar Controller {{{ */
6691 @interface CYTabBarController : UITabBarController <
6694 _transient Database *database_;
6695 RefreshBar *refreshbar_;
6699 // XXX: ok, "updatedelegate_"?...
6700 _transient NSObject<CydiaDelegate> *updatedelegate_;
6705 - (void) dropBar:(BOOL)animated;
6706 - (void) beginUpdate;
6707 - (void) raiseBar:(BOOL)animated;
6712 @implementation CYTabBarController
6714 /* XXX: some logic should probably go here related to
6715 freeing the view controllers on tab change */
6717 - (void) reloadData {
6718 size_t count([[self viewControllers] count]);
6719 for (size_t i(0); i != count; ++i) {
6720 CYNavigationController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6725 - (id) initWithDatabase:(Database *)database {
6726 if ((self = [super init]) != nil) {
6727 database_ = database;
6729 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6730 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6732 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
6736 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
6737 return IsWildcat_ || orientation == UIInterfaceOrientationPortrait;
6740 - (void) setUpdate:(NSDate *)date {
6744 - (void) beginUpdate {
6745 [refreshbar_ start];
6748 [updatedelegate_ retainNetworkActivityIndicator];
6752 detachNewThreadSelector:@selector(performUpdate)
6758 - (void) performUpdate { _pooled
6760 status.setDelegate(self);
6761 [database_ updateWithStatus:status];
6764 performSelectorOnMainThread:@selector(completeUpdate)
6770 - (void) stopUpdateWithSelector:(SEL)selector {
6772 [updatedelegate_ releaseNetworkActivityIndicator];
6774 [self raiseBar:YES];
6777 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6780 - (void) completeUpdate {
6783 [self stopUpdateWithSelector:@selector(reloadData)];
6786 - (void) cancelUpdate {
6787 [self stopUpdateWithSelector:@selector(updateData)];
6790 - (void) cancelPressed {
6791 [self cancelUpdate];
6798 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
6799 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
6802 - (void) startProgress {
6805 - (void) setProgressTitle:(NSString *)title {
6807 performSelectorOnMainThread:@selector(_setProgressTitle:)
6813 - (bool) isCancelling:(size_t)received {
6817 - (void) setProgressPercent:(float)percent {
6819 performSelectorOnMainThread:@selector(_setProgressPercent:)
6820 withObject:[NSNumber numberWithFloat:percent]
6825 - (void) addProgressOutput:(NSString *)output {
6827 performSelectorOnMainThread:@selector(_addProgressOutput:)
6833 - (void) _setProgressTitle:(NSString *)title {
6834 [refreshbar_ setPrompt:title];
6837 - (void) _setProgressPercent:(NSNumber *)percent {
6838 [refreshbar_ setProgress:[percent floatValue]];
6841 - (void) _addProgressOutput:(NSString *)output {
6844 - (void) setUpdateDelegate:(id)delegate {
6845 updatedelegate_ = delegate;
6848 - (CGFloat) statusBarHeight {
6849 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
6850 return [[UIApplication sharedApplication] statusBarFrame].size.height;
6852 return [[UIApplication sharedApplication] statusBarFrame].size.width;
6856 - (UIView *) transitionView {
6857 if ([self respondsToSelector:@selector(_transitionView)])
6858 return [self _transitionView];
6860 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6863 - (void) dropBar:(BOOL)animated {
6868 UIView *transition([self transitionView]);
6869 [[self view] addSubview:refreshbar_];
6871 CGRect barframe([refreshbar_ frame]);
6873 if (false) // XXX: _UIApplicationLinkedOnOrAfter(4)
6874 barframe.origin.y = [self statusBarHeight];
6876 barframe.origin.y = 0;
6878 [refreshbar_ setFrame:barframe];
6881 [UIView beginAnimations:nil context:NULL];
6883 CGRect viewframe = [transition frame];
6884 viewframe.origin.y += barframe.size.height;
6885 viewframe.size.height -= barframe.size.height;
6886 [transition setFrame:viewframe];
6889 [UIView commitAnimations];
6891 // Ensure bar has the proper width for our view, it might have changed
6892 barframe.size.width = viewframe.size.width;
6893 [refreshbar_ setFrame:barframe];
6895 // XXX: fix Apple's layout bug
6896 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6899 - (void) raiseBar:(BOOL)animated {
6904 UIView *transition([self transitionView]);
6905 [refreshbar_ removeFromSuperview];
6907 CGRect barframe([refreshbar_ frame]);
6910 [UIView beginAnimations:nil context:NULL];
6912 CGRect viewframe = [transition frame];
6913 viewframe.origin.y -= barframe.size.height;
6914 viewframe.size.height += barframe.size.height;
6915 [transition setFrame:viewframe];
6918 [UIView commitAnimations];
6920 // XXX: fix Apple's layout bug
6921 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6925 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
6926 // XXX: fix Apple's layout bug
6927 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6931 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6932 bool dropped(dropped_);
6937 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6942 // XXX: fix Apple's layout bug
6943 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6946 - (void) statusBarFrameChanged:(NSNotification *)notification {
6954 [refreshbar_ release];
6955 [[NSNotificationCenter defaultCenter] removeObserver:self];
6962 /* Cydia Navigation Controller {{{ */
6963 @interface CYNavigationController : UINavigationController {
6964 _transient Database *database_;
6965 _transient id<UINavigationControllerDelegate> delegate_;
6968 - (id) initWithDatabase:(Database *)database;
6969 - (void) reloadData;
6974 @implementation CYNavigationController
6976 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
6977 // Inherit autorotation settings for modal parents.
6978 if ([self parentViewController] && [[self parentViewController] modalViewController] == self) {
6979 return [[self parentViewController] shouldAutorotateToInterfaceOrientation:orientation];
6981 return [super shouldAutorotateToInterfaceOrientation:orientation];
6989 - (void) reloadData {
6990 size_t count([[self viewControllers] count]);
6991 for (size_t i(0); i != count; ++i) {
6992 CYViewController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6997 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
6998 delegate_ = delegate;
7001 - (id) initWithDatabase:(Database *)database {
7002 if ((self = [super init]) != nil) {
7003 database_ = database;
7009 /* Cydia:// Protocol {{{ */
7010 @interface CydiaURLProtocol : NSURLProtocol {
7015 @implementation CydiaURLProtocol
7017 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7018 NSURL *url([request URL]);
7021 NSString *scheme([[url scheme] lowercaseString]);
7022 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
7027 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7031 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7032 id<NSURLProtocolClient> client([self client]);
7034 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7036 NSData *data(UIImagePNGRepresentation(icon));
7038 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7039 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7040 [client URLProtocol:self didLoadData:data];
7041 [client URLProtocolDidFinishLoading:self];
7045 - (void) startLoading {
7046 id<NSURLProtocolClient> client([self client]);
7047 NSURLRequest *request([self request]);
7049 NSURL *url([request URL]);
7050 NSString *href([url absoluteString]);
7052 NSString *path([href substringFromIndex:8]);
7053 NSRange slash([path rangeOfString:@"/"]);
7056 if (slash.location == NSNotFound) {
7060 command = [path substringToIndex:slash.location];
7061 path = [path substringFromIndex:(slash.location + 1)];
7064 Database *database([Database sharedInstance]);
7066 if ([command isEqualToString:@"package-icon"]) {
7069 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7070 Package *package([database packageWithName:path]);
7073 UIImage *icon([package icon]);
7074 [self _returnPNGWithImage:icon forRequest:request];
7075 } else if ([command isEqualToString:@"source-icon"]) {
7078 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7079 NSString *source(Simplify(path));
7080 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
7082 icon = [UIImage applicationImageNamed:@"unknown.png"];
7083 [self _returnPNGWithImage:icon forRequest:request];
7084 } else if ([command isEqualToString:@"uikit-image"]) {
7087 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7088 UIImage *icon(_UIImageWithName(path));
7089 [self _returnPNGWithImage:icon forRequest:request];
7090 } else if ([command isEqualToString:@"section-icon"]) {
7093 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7094 NSString *section(Simplify(path));
7095 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
7097 icon = [UIImage applicationImageNamed:@"unknown.png"];
7098 [self _returnPNGWithImage:icon forRequest:request];
7100 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7104 - (void) stopLoading {
7110 /* Sections Controller {{{ */
7111 @interface CYSectionsController : CYViewController <
7112 UITableViewDataSource,
7115 _transient Database *database_;
7116 NSMutableArray *sections_;
7117 NSMutableArray *filtered_;
7123 - (id) initWithDatabase:(Database *)database;
7124 - (void) reloadData;
7127 - (void) editButtonClicked;
7131 @implementation CYSectionsController
7134 [list_ setDataSource:nil];
7135 [list_ setDelegate:nil];
7137 [sections_ release];
7138 [filtered_ release];
7140 [accessory_ release];
7144 - (void) setEditing:(BOOL)editing {
7145 if ((editing_ = editing))
7148 [delegate_ updateData];
7150 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7151 [[[self navigationItem] rightBarButtonItem] setTitle:[sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT")];
7152 [[[self navigationItem] rightBarButtonItem] setStyle:editing_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain];
7155 - (void) viewDidAppear:(BOOL)animated {
7156 [super viewDidAppear:animated];
7157 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7160 - (void) viewWillDisappear:(BOOL)animated {
7161 [super viewWillDisappear:animated];
7162 if (editing_) [self setEditing:NO];
7165 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7166 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
7170 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7171 return editing_ ? [sections_ count] : [filtered_ count] + 1;
7174 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7178 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7179 static NSString *reuseIdentifier = @"SectionCell";
7181 SectionCell *cell = (SectionCell *) [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7183 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7185 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
7190 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7194 Section *section = [self sectionAtIndexPath:indexPath];
7195 NSString *name = [section name];
7198 if ([indexPath row] == 0) {
7201 title = UCLocalize("ALL_PACKAGES");
7204 name = [NSString stringWithString:name];
7205 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7208 title = UCLocalize("NO_SECTION");
7212 FilteredPackageController *table = [[[FilteredPackageController alloc]
7213 initWithDatabase:database_
7215 filter:@selector(isVisibleInSection:)
7219 [table setDelegate:delegate_];
7221 [[self navigationController] pushViewController:table animated:YES];
7224 - (NSString *) title { return UCLocalize("SECTIONS"); }
7226 - (id) initWithDatabase:(Database *)database {
7227 if ((self = [super init]) != nil) {
7228 database_ = database;
7230 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7232 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7233 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
7235 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
7236 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7237 [list_ setRowHeight:45.0f];
7238 [[self view] addSubview:list_];
7240 [list_ setDataSource:self];
7241 [list_ setDelegate:self];
7247 - (void) reloadData {
7248 NSArray *packages = [database_ packages];
7250 [sections_ removeAllObjects];
7251 [filtered_ removeAllObjects];
7253 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7256 for (Package *package in packages) {
7257 NSString *name([package section]);
7258 NSString *key(name == nil ? @"" : name);
7262 _profile(SectionsView$reloadData$Section)
7263 section = [sections objectForKey:key];
7264 if (section == nil) {
7265 _profile(SectionsView$reloadData$Section$Allocate)
7266 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
7267 [sections setObject:section forKey:key];
7272 [section addToCount];
7274 _profile(SectionsView$reloadData$Filter)
7275 if (![package valid] || ![package visible])
7283 [sections_ addObjectsFromArray:[sections allValues]];
7285 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7287 for (Section *section in sections_) {
7288 size_t count([section row]);
7292 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7293 [section setCount:count];
7294 [filtered_ addObject:section];
7297 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7298 initWithTitle:([sections_ count] == 0 ? nil : UCLocalize("EDIT"))
7299 style:UIBarButtonItemStylePlain
7301 action:@selector(editButtonClicked)
7302 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7308 - (void) resetView {
7310 [self editButtonClicked];
7313 - (void)editButtonClicked {
7314 [self setEditing:!editing_];
7317 - (UIView *) accessoryView {
7323 /* Changes Controller {{{ */
7324 @interface ChangesController : CYViewController <
7325 UITableViewDataSource,
7328 _transient Database *database_;
7330 CFMutableArrayRef packages_;
7331 NSMutableArray *sections_;
7334 BOOL hasSentFirstLoad_;
7337 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
7338 - (void) reloadData;
7342 @implementation ChangesController
7345 [list_ setDelegate:nil];
7346 [list_ setDataSource:nil];
7348 CFRelease(packages_);
7350 [sections_ release];
7355 - (void) viewDidAppear:(BOOL)animated {
7356 [super viewDidAppear:animated];
7357 if (!hasSentFirstLoad_) {
7358 hasSentFirstLoad_ = YES;
7359 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
7361 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7365 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7366 NSInteger count([sections_ count]);
7367 return count == 0 ? 1 : count;
7370 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7371 if ([sections_ count] == 0)
7373 return [[sections_ objectAtIndex:section] name];
7376 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7377 if ([sections_ count] == 0)
7379 return [[sections_ objectAtIndex:section] count];
7382 - (Package *) packageAtIndex:(NSUInteger)index {
7383 return (Package *) CFArrayGetValueAtIndex(packages_, index);
7386 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7387 @synchronized (database_) {
7388 if ([database_ era] != era_)
7391 Section *section([sections_ objectAtIndex:[path section]]);
7392 NSInteger row([path row]);
7393 return [[[self packageAtIndex:([section row] + row)] retain] autorelease];
7396 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7397 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7399 cell = [[[PackageCell alloc] init] autorelease];
7400 [cell setPackage:[self packageAtIndexPath:path]];
7404 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
7405 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
7408 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7409 Package *package([self packageAtIndexPath:path]);
7410 PackageController *view([delegate_ packageController]);
7411 [view setDelegate:delegate_];
7412 [view setPackage:package];
7413 [[self navigationController] pushViewController:view animated:YES];
7417 - (void) refreshButtonClicked {
7418 [delegate_ beginUpdate];
7419 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7422 - (void) upgradeButtonClicked {
7423 [delegate_ distUpgrade];
7426 - (NSString *) title { return UCLocalize("CHANGES"); }
7428 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7429 if ((self = [super init]) != nil) {
7430 database_ = database;
7431 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7433 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7435 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7437 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7438 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7439 [list_ setRowHeight:73.0f];
7440 [[self view] addSubview:list_];
7442 [list_ setDataSource:self];
7443 [list_ setDelegate:self];
7445 delegate_ = delegate;
7449 - (void) _reloadPackages:(NSArray *)packages {
7451 for (Package *package in packages)
7452 if ([package upgradableAndEssential:YES] || [package visible])
7453 CFArrayAppendValue(packages_, package);
7456 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7460 - (void) reloadData {
7461 era_ = [database_ era];
7462 NSArray *packages = [database_ packages];
7464 CFArrayRemoveAllValues(packages_);
7466 [sections_ removeAllObjects];
7469 UIProgressHUD *hud([delegate_ addProgressHUD]);
7470 [hud setText:UCLocalize("LOADING")];
7471 //NSLog(@"HUD:%@::%@", delegate_, hud);
7472 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7473 [delegate_ removeProgressHUD:hud];
7475 [self _reloadPackages:packages];
7478 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7479 Section *ignored = nil;
7480 Section *section = nil;
7484 bool unseens = false;
7486 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7488 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7489 Package *package = [self packageAtIndex:offset];
7491 BOOL uae = [package upgradableAndEssential:YES];
7495 time_t seen([package seen]);
7497 if (section == nil || last != seen) {
7501 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7504 _profile(ChangesController$reloadData$Allocate)
7505 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7506 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7507 [sections_ addObject:section];
7511 [section addToCount];
7512 } else if ([package ignored]) {
7513 if (ignored == nil) {
7514 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7516 [ignored addToCount];
7519 [upgradable addToCount];
7524 CFRelease(formatter);
7527 Section *last = [sections_ lastObject];
7528 size_t count = [last count];
7529 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7530 [sections_ removeLastObject];
7533 if ([ignored count] != 0)
7534 [sections_ insertObject:ignored atIndex:0];
7536 [sections_ insertObject:upgradable atIndex:0];
7541 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7542 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7543 style:UIBarButtonItemStylePlain
7545 action:@selector(upgradeButtonClicked)
7548 if (![delegate_ updating])
7549 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7550 initWithTitle:UCLocalize("REFRESH")
7551 style:UIBarButtonItemStylePlain
7553 action:@selector(refreshButtonClicked)
7559 /* Search Controller {{{ */
7560 @interface SearchController : FilteredPackageController <
7563 UISearchBar *search_;
7566 - (id) initWithDatabase:(Database *)database;
7567 - (void) reloadData;
7571 @implementation SearchController
7578 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7579 [packages_ setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7580 [search_ resignFirstResponder];
7584 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7585 [packages_ setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7589 - (NSString *) title { return nil; }
7591 - (id) initWithDatabase:(Database *)database {
7592 return [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil];
7595 - (void)viewDidAppear:(BOOL)animated {
7596 [super viewDidAppear:animated];
7598 search_ = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7599 [search_ layoutSubviews];
7600 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7602 UITextField *textField;
7603 if ([search_ respondsToSelector:@selector(searchField)])
7604 textField = [search_ searchField];
7606 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7608 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7609 [search_ setDelegate:self];
7610 [textField setEnablesReturnKeyAutomatically:NO];
7611 [[self navigationItem] setTitleView:textField];
7615 - (void) _reloadData {
7618 - (void) reloadData {
7619 _profile(SearchController$reloadData)
7620 [packages_ reloadData];
7623 [packages_ resetCursor];
7626 - (void) didSelectPackage:(Package *)package {
7627 [search_ resignFirstResponder];
7628 [super didSelectPackage:package];
7633 /* Settings Controller {{{ */
7634 @interface CYPackageSettingsController : CYViewController <
7635 UITableViewDataSource,
7638 _transient Database *database_;
7641 UITableView *table_;
7642 UISwitch *subscribedSwitch_;
7643 UISwitch *ignoredSwitch_;
7644 UITableViewCell *subscribedCell_;
7645 UITableViewCell *ignoredCell_;
7648 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7652 @implementation CYPackageSettingsController
7656 if (package_ != nil)
7659 [subscribedSwitch_ release];
7660 [ignoredSwitch_ release];
7661 [subscribedCell_ release];
7662 [ignoredCell_ release];
7667 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7668 if (package_ == nil)
7674 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7675 if (package_ == nil)
7681 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7682 return UCLocalize("SHOW_ALL_CHANGES_EX");
7685 - (void) onSubscribed:(id)control {
7686 bool value([control isOn]);
7687 if (package_ == nil)
7689 if ([package_ setSubscribed:value])
7690 [delegate_ updateData];
7693 - (void) onIgnored:(id)control {
7694 // TODO: set Held state - possibly call out to dpkg, etc.
7697 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7698 if (package_ == nil)
7701 switch ([indexPath row]) {
7702 case 0: return subscribedCell_;
7703 case 1: return ignoredCell_;
7711 - (NSString *) title { return UCLocalize("SETTINGS"); }
7713 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7714 if ((self = [super init])) {
7715 database_ = database;
7716 name_ = [package retain];
7718 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7720 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7721 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7722 [[self view] addSubview:table_];
7724 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7725 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7726 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7728 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7729 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7730 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7732 subscribedCell_ = [[UITableViewCell alloc] init];
7733 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7734 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7735 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7737 ignoredCell_ = [[UITableViewCell alloc] init];
7738 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7739 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7740 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7742 [table_ setDataSource:self];
7743 [table_ setDelegate:self];
7748 - (void) reloadData {
7749 if (package_ != nil)
7750 [package_ autorelease];
7751 package_ = [database_ packageWithName:name_];
7752 if (package_ != nil) {
7754 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7755 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7758 [table_ reloadData];
7763 /* Signature Controller {{{ */
7764 @interface SignatureController : CYBrowserController {
7765 _transient Database *database_;
7769 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7773 @implementation SignatureController
7780 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7782 [super webView:view didClearWindowObject:window forFrame:frame];
7785 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7786 if ((self = [super init]) != nil) {
7787 database_ = database;
7788 package_ = [package retain];
7793 - (void) reloadData {
7794 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7800 /* Role Controller {{{ */
7801 @interface CYSettingsController : CYViewController <
7802 UITableViewDataSource,
7805 _transient Database *database_;
7806 // XXX: ok, "roledelegate_"?...
7807 _transient id roledelegate_;
7808 UITableView *table_;
7809 UISegmentedControl *segment_;
7813 - (void) showDoneButton;
7814 - (void) resizeSegmentedControl;
7818 @implementation CYSettingsController
7822 [container_ release];
7827 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7828 if ((self = [super init])) {
7829 database_ = database;
7830 roledelegate_ = delegate;
7832 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
7834 NSArray *items = [NSArray arrayWithObjects:
7836 UCLocalize("HACKER"),
7837 UCLocalize("DEVELOPER"),
7839 segment_ = [[UISegmentedControl alloc] initWithItems:items];
7840 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
7841 [container_ addSubview:segment_];
7844 if ([Role_ isEqualToString:@"User"]) index = 0;
7845 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
7846 if ([Role_ isEqualToString:@"Developer"]) index = 2;
7848 [segment_ setSelectedSegmentIndex:index];
7849 [self showDoneButton];
7852 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
7853 [self resizeSegmentedControl];
7855 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7856 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7857 [table_ setDelegate:self];
7858 [table_ setDataSource:self];
7859 [[self view] addSubview:table_];
7860 [table_ reloadData];
7864 - (void) resizeSegmentedControl {
7865 CGFloat width = [[self view] frame].size.width;
7866 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
7869 - (void) viewWillAppear:(BOOL)animated {
7870 [super viewWillAppear:animated];
7872 [self resizeSegmentedControl];
7875 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7876 [self resizeSegmentedControl];
7879 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7880 [self resizeSegmentedControl];
7884 NSString *role(nil);
7886 switch ([segment_ selectedSegmentIndex]) {
7887 case 0: role = @"User"; break;
7888 case 1: role = @"Hacker"; break;
7889 case 2: role = @"Developer"; break;
7894 if (![role isEqualToString:Role_]) {
7895 bool rolling(Role_ == nil);
7898 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7902 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7906 [roledelegate_ loadData];
7908 [roledelegate_ updateData];
7912 - (void) segmentChanged:(UISegmentedControl *)control {
7913 [self showDoneButton];
7916 - (void) saveAndClose {
7919 [[self navigationItem] setRightBarButtonItem:nil];
7920 [[self navigationController] dismissModalViewControllerAnimated:YES];
7923 - (void) doneButtonClicked {
7924 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
7925 [spinner startAnimating];
7926 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
7927 [[self navigationItem] setRightBarButtonItem:spinItem];
7929 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
7932 - (void) showDoneButton {
7933 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7934 initWithTitle:UCLocalize("DONE")
7935 style:UIBarButtonItemStyleDone
7937 action:@selector(doneButtonClicked)
7938 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
7941 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7942 // XXX: For not having a single cell in the table, this sure is a lot of sections.
7946 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7950 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7951 return nil; // This method is required by the protocol.
7954 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7956 return UCLocalize("ROLE_EX");
7958 return [NSString stringWithFormat:
7959 @"%@: %@\n%@: %@\n%@: %@",
7960 UCLocalize("USER"), UCLocalize("USER_EX"),
7961 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
7962 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
7967 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
7968 return section == 3 ? 44.0f : 0;
7971 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
7972 return section == 3 ? container_ : nil;
7977 /* Stash Controller {{{ */
7978 @interface CYStashController : CYViewController {
7979 // XXX: just delete these things
7980 _transient UIActivityIndicatorView *spinner_;
7981 _transient UILabel *status_;
7982 _transient UILabel *caption_;
7986 @implementation CYStashController
7988 if ((self = [super init])) {
7989 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
7991 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
7992 CGRect spinrect = [spinner_ frame];
7993 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
7994 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
7995 [spinner_ setFrame:spinrect];
7996 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
7997 [[self view] addSubview:spinner_];
7998 [spinner_ startAnimating];
8001 captrect.size.width = [[self view] frame].size.width;
8002 captrect.size.height = 40.0f;
8003 captrect.origin.x = 0;
8004 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8005 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8006 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8007 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8008 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8009 [caption_ setTextColor:[UIColor whiteColor]];
8010 [caption_ setBackgroundColor:[UIColor clearColor]];
8011 [caption_ setShadowColor:[UIColor blackColor]];
8012 [caption_ setTextAlignment:UITextAlignmentCenter];
8013 [[self view] addSubview:caption_];
8016 statusrect.size.width = [[self view] frame].size.width;
8017 statusrect.size.height = 30.0f;
8018 statusrect.origin.x = 0;
8019 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8020 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8021 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8022 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8023 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8024 [status_ setTextColor:[UIColor whiteColor]];
8025 [status_ setBackgroundColor:[UIColor clearColor]];
8026 [status_ setShadowColor:[UIColor blackColor]];
8027 [status_ setTextAlignment:UITextAlignmentCenter];
8028 [[self view] addSubview:status_];
8032 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
8033 return IsWildcat_ || orientation == UIInterfaceOrientationPortrait;
8048 @interface Cydia : UIApplication <
8049 ConfirmationControllerDelegate,
8050 ProgressControllerDelegate,
8052 UINavigationControllerDelegate,
8053 UITabBarControllerDelegate
8055 // XXX: evaluate all fields for _transient
8058 CYTabBarController *tabbar_;
8060 NSMutableArray *essential_;
8061 NSMutableArray *broken_;
8063 Database *database_;
8071 CYSectionsController *sections_;
8072 ChangesController *changes_;
8073 ManageController *manage_;
8074 SearchController *search_;
8075 SourceController *sources_;
8076 InstalledController *installed_;
8079 CYStashController *stash_;
8084 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class;
8085 - (void) setPage:(CYViewController *)page;
8088 // XXX: I hate prototypes
8089 - (id) queueBadgeController;
8093 static _finline void _setHomePage(Cydia *self) {
8094 [self setPage:[self _pageForURL:[NSURL URLWithString:CydiaURL(@"")] withClass:[HomeController class]]];
8097 @implementation Cydia
8099 - (void) beginUpdate {
8100 [tabbar_ beginUpdate];
8104 return [tabbar_ updating];
8108 if ([broken_ count] != 0) {
8109 int count = [broken_ count];
8111 UIAlertView *alert = [[[UIAlertView alloc]
8112 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8113 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8115 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8116 otherButtonTitles:UCLocalize("TEMPORARY_IGNORE"), nil
8119 [alert setContext:@"fixhalf"];
8121 } else if (!Ignored_ && [essential_ count] != 0) {
8122 int count = [essential_ count];
8124 UIAlertView *alert = [[[UIAlertView alloc]
8125 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8126 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8128 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8129 otherButtonTitles:UCLocalize("UPGRADE_ESSENTIAL"), UCLocalize("COMPLETE_UPGRADE"), nil
8132 [alert setContext:@"upgrade"];
8137 - (void) _saveConfig {
8143 NSString *error(nil);
8145 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8147 NSError *error(nil);
8148 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8149 NSLog(@"failure to save metadata data: %@", error);
8154 NSLog(@"failure to serialize metadata: %@", error);
8159 - (void) _updateData {
8162 NSMutableSet *tabs([[[NSMutableSet alloc] initWithCapacity:10] autorelease]);
8164 [tabs addObject:[tabbar_ selectedViewController]];
8166 if (sections_ != nil)
8167 [tabs addObject:sections_];
8168 if (changes_ != nil)
8169 [tabs addObject:changes_];
8171 [tabs addObject:manage_];
8173 [tabs addObject:search_];
8174 if (sources_ != nil)
8175 [tabs addObject:sources_];
8176 if (installed_ != nil)
8177 [tabs addObject:installed_];
8179 for (CYNavigationController *tab in tabs)
8182 [queueDelegate_ queueStatusDidChange];
8183 [[[self queueBadgeController] tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8186 - (int)indexOfTabWithTag:(int)tag {
8188 for (UINavigationController *controller in [tabbar_ viewControllers]) {
8189 if ([[controller tabBarItem] tag] == tag)
8197 - (void) _refreshIfPossible {
8198 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8200 bool recently = false;
8201 NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
8202 if (update != nil) {
8203 NSTimeInterval interval([update timeIntervalSinceNow]);
8204 if (interval <= 0 && interval > -(15*60))
8208 // Don't automatic refresh if:
8209 // - We already refreshed recently.
8210 // - We already auto-refreshed this launch.
8211 // - Auto-refresh is disabled.
8212 if (recently || loaded_ || ManualRefresh) {
8213 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8215 // If we are cancelling due to ManualRefresh or a recent refresh
8216 // we need to make sure it knows it's already loaded.
8220 // We are going to load, so remember that.
8224 SCNetworkReachabilityFlags flags; {
8225 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8226 SCNetworkReachabilityGetFlags(reachability, &flags);
8227 CFRelease(reachability);
8230 // XXX: this elaborate mess is what Apple is using to determine this? :(
8231 // XXX: do we care if the user has to intervene? maybe that's ok?
8233 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8234 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8235 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8236 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8237 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8238 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8242 // If we can reach the server, auto-refresh!
8244 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8249 - (void) refreshIfPossible {
8250 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
8253 - (void) _reloadData {
8254 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8255 [hud setText:UCLocalize("RELOADING_DATA")];
8257 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
8260 [self removeProgressHUD:hud];
8264 [essential_ removeAllObjects];
8265 [broken_ removeAllObjects];
8267 NSArray *packages([database_ packages]);
8268 for (Package *package in packages) {
8270 [broken_ addObject:package];
8271 if ([package upgradableAndEssential:NO]) {
8272 if ([package essential])
8273 [essential_ addObject:package];
8278 NSLog(@"changes:#%u", changes);
8280 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem];
8283 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8284 [changesItem setBadgeValue:badge];
8285 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8286 [self setApplicationIconBadgeNumber:changes];
8289 [changesItem setBadgeValue:nil];
8290 [changesItem setAnimatedBadge:NO];
8291 [self setApplicationIconBadgeNumber:0];
8296 [self refreshIfPossible];
8299 - (void) updateData {
8308 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8309 _assert(file != NULL);
8311 for (NSString *key in [Sources_ allKeys]) {
8312 NSDictionary *source([Sources_ objectForKey:key]);
8314 fprintf(file, "%s %s %s\n",
8315 [[source objectForKey:@"Type"] UTF8String],
8316 [[source objectForKey:@"URI"] UTF8String],
8317 [[source objectForKey:@"Distribution"] UTF8String]
8325 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8326 CYNavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8328 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8329 [tabbar_ presentModalViewController:navigation animated:YES];
8332 detachNewThreadSelector:@selector(update_)
8335 title:UCLocalize("UPDATING_SOURCES")
8339 - (void) reloadData {
8340 @synchronized (self) {
8346 pkgProblemResolver *resolver = [database_ resolver];
8348 resolver->InstallProtect();
8349 if (!resolver->Resolve(true))
8354 if (![database_ prepare])
8357 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8358 [page setDelegate:self];
8359 CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]);
8360 [confirm_ setDelegate:self];
8363 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8364 [tabbar_ presentModalViewController:confirm_ animated:YES];
8370 @synchronized (self) {
8375 - (void) clearPackage:(Package *)package {
8376 @synchronized (self) {
8383 - (void) installPackages:(NSArray *)packages {
8384 @synchronized (self) {
8385 for (Package *package in packages)
8392 - (void) installPackage:(Package *)package {
8393 @synchronized (self) {
8400 - (void) removePackage:(Package *)package {
8401 @synchronized (self) {
8408 - (void) distUpgrade {
8409 @synchronized (self) {
8410 if (![database_ upgrade])
8417 @synchronized (self) {
8422 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8425 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8427 if (navigation != nil) {
8428 [navigation pushViewController:progress animated:YES];
8430 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8432 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8433 [tabbar_ presentModalViewController:navigation animated:YES];
8437 detachNewThreadSelector:@selector(perform)
8440 title:UCLocalize("RUNNING")
8446 - (void) progressControllerIsComplete:(ProgressController *)progress {
8451 - (void) setPage:(CYViewController *)page {
8452 [page setDelegate:self];
8454 CYNavigationController *navController = (CYNavigationController *) [tabbar_ selectedViewController];
8455 [navController setViewControllers:[NSArray arrayWithObject:page]];
8456 for (CYNavigationController *page in [tabbar_ viewControllers])
8457 if (page != navController)
8458 [page setViewControllers:nil];
8461 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class {
8462 CYBrowserController *browser = [[[_class alloc] init] autorelease];
8463 [browser loadURL:url];
8467 - (CYSectionsController *) sectionsController {
8468 if (sections_ == nil)
8469 sections_ = [[CYSectionsController alloc] initWithDatabase:database_];
8473 - (ChangesController *) changesController {
8474 if (changes_ == nil)
8475 changes_ = [[ChangesController alloc] initWithDatabase:database_ delegate:self];
8479 - (ManageController *) manageController {
8480 if (manage_ == nil) {
8481 manage_ = (ManageController *) [[self
8482 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
8483 withClass:[ManageController class]
8486 queueDelegate_ = manage_;
8491 - (SearchController *) searchController {
8493 search_ = [[SearchController alloc] initWithDatabase:database_];
8497 - (SourceController *) sourcesController {
8498 if (sources_ == nil)
8499 sources_ = [[SourceController alloc] initWithDatabase:database_];
8503 - (InstalledController *) installedController {
8504 if (installed_ == nil) {
8505 installed_ = [[InstalledController alloc] initWithDatabase:database_];
8507 queueDelegate_ = installed_;
8512 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
8513 int tag = [[viewController tabBarItem] tag];
8515 [(CYNavigationController *)[tabbar_ selectedViewController] popToRootViewControllerAnimated:YES];
8517 } else if (tag_ == 1) {
8518 [[self sectionsController] resetView];
8522 case kCydiaTag: _setHomePage(self); break;
8524 case kSectionsTag: [self setPage:[self sectionsController]]; break;
8525 case kChangesTag: [self setPage:[self changesController]]; break;
8526 case kManageTag: [self setPage:[self manageController]]; break;
8527 case kInstalledTag: [self setPage:[self installedController]]; break;
8528 case kSourcesTag: [self setPage:[self sourcesController]]; break;
8529 case kSearchTag: [self setPage:[self searchController]]; break;
8537 - (void) showSettings {
8538 CYSettingsController *role = [[[CYSettingsController alloc] initWithDatabase:database_ delegate:self] autorelease];
8539 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
8541 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
8542 [tabbar_ presentModalViewController:nav animated:YES];
8545 - (void) retainNetworkActivityIndicator {
8546 if (activity_++ == 0)
8547 [self setNetworkActivityIndicatorVisible:YES];
8550 - (void) releaseNetworkActivityIndicator {
8551 if (--activity_ == 0)
8552 [self setNetworkActivityIndicatorVisible:NO];
8555 - (void) setPackageController:(PackageController *)view {
8557 [view setPackage:nil];
8561 - (PackageController *) _packageController {
8562 return [[[PackageController alloc] initWithDatabase:database_] autorelease];
8565 - (PackageController *) packageController {
8566 return [self _packageController];
8569 // Returns the navigation controller for the queuing badge.
8570 - (id) queueBadgeController {
8571 int index = [self indexOfTabWithTag:kManageTag];
8573 index = [self indexOfTabWithTag:kInstalledTag];
8575 return [[tabbar_ viewControllers] objectAtIndex:index];
8578 - (void) cancelAndClear:(bool)clear {
8579 @synchronized (self) {
8591 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8592 NSString *context([alert context]);
8594 if ([context isEqualToString:@"fixhalf"]) {
8595 if (button == [alert firstOtherButtonIndex]) {
8596 @synchronized (self) {
8597 for (Package *broken in broken_) {
8600 NSString *id = [broken id];
8601 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8602 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8603 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8604 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8610 } else if (button == [alert cancelButtonIndex]) {
8611 [broken_ removeAllObjects];
8615 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8616 } else if ([context isEqualToString:@"upgrade"]) {
8617 if (button == [alert firstOtherButtonIndex]) {
8618 @synchronized (self) {
8619 for (Package *essential in essential_)
8620 [essential install];
8625 } else if (button == [alert firstOtherButtonIndex] + 1) {
8627 } else if (button == [alert cancelButtonIndex]) {
8631 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8635 - (void) system:(NSString *)command { _pooled
8637 system([command UTF8String]);
8641 - (void) applicationWillSuspend {
8643 [super applicationWillSuspend];
8646 - (BOOL) isSafeToSuspend {
8647 // Use external process status API internally.
8648 // This is probably a really bad idea.
8649 // XXX: what is the point of this? does this solve anything at all?
8650 uint64_t status = 0;
8652 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
8653 notify_get_state(notify_token, &status);
8654 notify_cancel(notify_token);
8657 return locked_ == 0 && status == 0;
8660 - (void) applicationSuspend:(__GSEvent *)event {
8661 if ([self isSafeToSuspend])
8662 [super applicationSuspend:event];
8665 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8666 if ([self isSafeToSuspend])
8667 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8670 - (void) _setSuspended:(BOOL)value {
8671 if ([self isSafeToSuspend])
8672 [super _setSuspended:value];
8675 - (UIProgressHUD *) addProgressHUD {
8676 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8677 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8679 [window_ setUserInteractionEnabled:NO];
8682 UIViewController *target = tabbar_;
8683 while ([target modalViewController] != nil) target = [target modalViewController];
8684 [[target view] addSubview:hud];
8690 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8692 [hud removeFromSuperview];
8693 [window_ setUserInteractionEnabled:YES];
8697 - (CYViewController *) pageForPackage:(NSString *)name {
8698 if (Package *package = [database_ packageWithName:name]) {
8699 PackageController *view([self packageController]);
8700 [view setPackage:package];
8703 NSURL *url([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"unknown" ofType:@"html"]]);
8704 url = [NSURL URLWithString:[[url absoluteString] stringByAppendingString:[NSString stringWithFormat:@"?%@", name]]];
8705 return [self _pageForURL:url withClass:[CYBrowserController class]];
8709 - (CYViewController *) pageForURL:(NSURL *)url hasTag:(int *)tag {
8713 NSString *href([url absoluteString]);
8714 if ([href hasPrefix:@"apptapp://package/"])
8715 return [self pageForPackage:[href substringFromIndex:18]];
8717 NSString *scheme([[url scheme] lowercaseString]);
8718 if (![scheme isEqualToString:@"cydia"])
8720 NSString *path([url absoluteString]);
8721 if ([path length] < 8)
8723 path = [path substringFromIndex:8];
8724 if (![path hasPrefix:@"/"])
8725 path = [@"/" stringByAppendingString:path];
8727 if ([path isEqualToString:@"/storage"])
8728 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CYBrowserController class]];
8729 /*else if ([path isEqualToString:@"/add-source"])
8730 return [[[AddSourceController alloc] initWithDatabase:database_] autorelease];*/
8731 else if ([path isEqualToString:@"/sources"])
8732 return [[[SourceController alloc] initWithDatabase:database_] autorelease];
8733 else if ([path isEqualToString:@"/packages"])
8734 return [[[InstalledController alloc] initWithDatabase:database_] autorelease];
8735 else if ([path hasPrefix:@"/url/"])
8736 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[CYBrowserController class]];
8737 else if ([path hasPrefix:@"/launch/"])
8738 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8739 else if ([path hasPrefix:@"/package-settings/"])
8740 return [[[CYPackageSettingsController alloc] initWithDatabase:database_ package:[path substringFromIndex:18]] autorelease];
8741 else if ([path hasPrefix:@"/package-signature/"])
8742 return [[[SignatureController alloc] initWithDatabase:database_ package:[path substringFromIndex:19]] autorelease];
8743 else if ([path hasPrefix:@"/package/"])
8744 return [self pageForPackage:[path substringFromIndex:9]];
8745 else if ([path hasPrefix:@"/files/"]) {
8746 NSString *name = [path substringFromIndex:7];
8748 if (Package *package = [database_ packageWithName:name]) {
8749 FileTable *files = [[[FileTable alloc] initWithDatabase:database_] autorelease];
8750 [files setPackage:package];
8758 - (BOOL) openCydiaURL:(NSURL *)url {
8759 CYViewController *page = nil;
8762 NSLog(@"open url: %@", url);
8764 if ((page = [self pageForURL:url hasTag:&tag])) {
8765 [self setPage:page];
8767 [tabbar_ setSelectedViewController:(tag_ == -1 ? nil : [[tabbar_ viewControllers] objectAtIndex:tag_])];
8773 - (void) applicationOpenURL:(NSURL *)url {
8774 [super applicationOpenURL:url];
8775 NSLog(@"first: %@", url);
8776 if (!loaded_) starturl_ = [url retain];
8777 else [self openCydiaURL:url];
8780 - (void) applicationWillResignActive:(UIApplication *)application {
8781 // Stop refreshing if you get a phone call or lock the device.
8782 if ([tabbar_ updating])
8783 [tabbar_ cancelUpdate];
8785 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
8786 [super applicationWillResignActive:application];
8789 - (void) addStashController {
8791 stash_ = [[CYStashController alloc] init];
8792 [window_ addSubview:[stash_ view]];
8795 - (void) removeStashController {
8796 [[stash_ view] removeFromSuperview];
8802 [self setIdleTimerDisabled:YES];
8804 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
8805 [self setStatusBarShowsProgress:YES];
8806 UpdateExternalStatus(1);
8808 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
8810 UpdateExternalStatus(0);
8811 [self setStatusBarShowsProgress:NO];
8813 [self removeStashController];
8815 if (ExecFork() == 0) {
8816 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
8817 perror("launchctl stop");
8821 - (void) setupTabBarController {
8822 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
8823 [tabbar_ setDelegate:self];
8825 NSMutableArray *items([NSMutableArray arrayWithObjects:
8826 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:kCydiaTag] autorelease],
8827 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:kSectionsTag] autorelease],
8828 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:kChangesTag] autorelease],
8829 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:kSearchTag] autorelease],
8833 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:kSourcesTag] autorelease] atIndex:3];
8834 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:kInstalledTag] autorelease] atIndex:3];
8836 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:kManageTag] autorelease] atIndex:3];
8839 NSMutableArray *controllers([NSMutableArray array]);
8841 for (UITabBarItem *item in items) {
8842 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
8843 [controller setTabBarItem:item];
8844 [controllers addObject:controller];
8847 [tabbar_ setViewControllers:controllers];
8850 - (void)showFakeTabBarInView:(UIView *)view {
8851 static UITabBar *fake = [[UITabBar alloc] initWithFrame:CGRectMake(0, 0, 0, 49.0f)];
8853 CGRect frame = [fake frame];
8854 frame.origin.y = [view frame].size.height - frame.size.height;
8855 frame.size.width = [view frame].size.width;
8856 [fake setFrame:frame];
8857 [fake setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
8858 [view addSubview:fake];
8860 [fake removeFromSuperview];
8864 - (void) applicationDidFinishLaunching:(id)unused {
8868 [NSURLCache setSharedURLCache:[[[SDURLCache alloc]
8869 initWithMemoryCapacity:524288
8870 diskCapacity:10485760
8871 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
8874 [CYBrowserController _initialize];
8876 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8878 Font12_ = [[UIFont systemFontOfSize:12] retain];
8879 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8880 Font14_ = [[UIFont systemFontOfSize:14] retain];
8881 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8882 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8886 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8887 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8889 window_ = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
8890 [window_ orderFront:self];
8891 [window_ makeKey:self];
8892 [window_ setHidden:NO];
8895 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8896 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8897 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8898 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
8899 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8900 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8901 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8902 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
8903 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
8906 [self addStashController];
8907 // XXX: this would be much cleaner as a yieldToSelector:
8908 // that way the removeStashController could happen right here inline
8909 // we also could no longer require the useless stash_ field anymore
8910 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
8914 database_ = [Database sharedInstance];
8916 [self setupTabBarController];
8917 [tabbar_ setUpdateDelegate:self];
8918 [window_ addSubview:[tabbar_ view]];
8920 // Show pinstripes while loading data.
8921 [[tabbar_ view] setBackgroundColor:[UIColor pinStripeColor]];
8922 [self showFakeTabBarInView:[tabbar_ tabBar]];
8924 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
8931 [self showSettings];
8935 CGRect fixframe = [[tabbar_ view] frame];
8936 if (UIInterfaceOrientationIsLandscape([[UIApplication sharedApplication] statusBarOrientation]))
8937 fixframe.size = CGSizeMake(fixframe.size.height, fixframe.size.width);
8938 CYLoadingIndicator *loading = [[[CYLoadingIndicator alloc] initWithFrame:fixframe] autorelease];
8939 [loading setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8940 [[tabbar_ view] addSubview:loading];
8941 [window_ setUserInteractionEnabled:NO];
8946 // Show the initial page
8947 if (starturl_ == nil || ![self openCydiaURL:starturl_]) {
8948 [tabbar_ setSelectedIndex:0];
8952 [self showFakeTabBarInView:nil];
8954 [starturl_ release];
8957 [window_ setUserInteractionEnabled:YES];
8959 // XXX: does this actually slow anything down?
8960 [[tabbar_ view] setBackgroundColor:[UIColor clearColor]];
8961 [loading removeFromSuperview];
8964 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
8965 if (item != nil && IsWildcat_) {
8966 [sheet showFromBarButtonItem:item animated:YES];
8968 [sheet showInView:window_];
8975 id Alloc_(id self, SEL selector) {
8976 id object = alloc_(self, selector);
8977 lprintf("[%s]A-%p\n", self->isa->name, object);
8982 id Dealloc_(id self, SEL selector) {
8983 id object = dealloc_(self, selector);
8984 lprintf("[%s]D-%p\n", self->isa->name, object);
8988 Class $WebDefaultUIKitDelegate;
8990 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
8991 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8992 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8993 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
8996 static NSNumber *shouldPlayKeyboardSounds;
9000 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
9002 case 1104: // Keyboard Button Clicked
9003 case 1105: // Keyboard Delete Repeated
9004 if (shouldPlayKeyboardSounds == nil) {
9005 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
9006 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
9009 if (![shouldPlayKeyboardSounds boolValue])
9013 _UIHardware$_playSystemSound$(self, _cmd, sound);
9017 int main(int argc, char *argv[]) { _pooled
9020 if (Class $UIDevice = objc_getClass("UIDevice")) {
9021 UIDevice *device([$UIDevice currentDevice]);
9022 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
9026 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9028 /* Library Hacks {{{ */
9029 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
9031 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
9032 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
9033 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
9034 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
9035 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
9038 $UIHardware = objc_getClass("UIHardware");
9039 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
9040 if (UIHardware$_playSystemSound$ != NULL) {
9041 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
9042 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
9045 /* Set Locale {{{ */
9046 Locale_ = CFLocaleCopyCurrent();
9047 Languages_ = [NSLocale preferredLanguages];
9048 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
9049 //NSLog(@"%@", [Languages_ description]);
9052 if (Languages_ == nil || [Languages_ count] == 0)
9053 // XXX: consider just setting to C and then falling through?
9056 lang = [[Languages_ objectAtIndex:0] UTF8String];
9057 setenv("LANG", lang, true);
9060 //std::setlocale(LC_ALL, lang);
9061 NSLog(@"Setting Language: %s", lang);
9064 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
9066 /* Parse Arguments {{{ */
9067 bool substrate(false);
9073 for (int argi(1); argi != argc; ++argi)
9074 if (strcmp(argv[argi], "--") == 0) {
9076 argv[argi] = argv[0];
9082 for (int argi(1); argi != arge; ++argi)
9083 if (strcmp(args[argi], "--substrate") == 0)
9086 fprintf(stderr, "unknown argument: %s\n", args[argi]);
9090 App_ = [[NSBundle mainBundle] bundlePath];
9091 Home_ = NSHomeDirectory();
9097 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
9098 alloc_ = alloc->method_imp;
9099 alloc->method_imp = (IMP) &Alloc_;*/
9101 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
9102 dealloc_ = dealloc->method_imp;
9103 dealloc->method_imp = (IMP) &Dealloc_;*/
9105 /* System Information {{{ */
9109 size = sizeof(maxproc);
9110 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9111 perror("sysctlbyname(\"kern.maxproc\", ?)");
9112 else if (maxproc < 64) {
9114 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9115 perror("sysctlbyname(\"kern.maxproc\", #)");
9118 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
9119 char *osversion = new char[size];
9120 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
9121 perror("sysctlbyname(\"kern.osversion\", ?)");
9123 System_ = [NSString stringWithUTF8String:osversion];
9125 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
9126 char *machine = new char[size];
9127 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
9128 perror("sysctlbyname(\"hw.machine\", ?)");
9132 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
9133 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
9134 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
9135 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
9139 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
9140 NSData *data((NSData *) ecid);
9141 size_t length([data length]);
9142 uint8_t bytes[length];
9143 [data getBytes:bytes];
9144 char string[length * 2 + 1];
9145 for (size_t i(0); i != length; ++i)
9146 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
9147 ChipID_ = [NSString stringWithUTF8String:string];
9151 IOObjectRelease(service);
9155 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
9157 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
9158 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9159 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
9161 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
9162 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9163 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
9165 if (mcc != NULL && mnc != NULL)
9166 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9173 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9174 Build_ = [system objectForKey:@"ProductBuildVersion"];
9175 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9176 Product_ = [info objectForKey:@"SafariProductVersion"];
9177 Safari_ = [info objectForKey:@"CFBundleVersion"];
9180 /* Load Database {{{ */
9182 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9184 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9186 if (Metadata_ == NULL)
9187 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9189 Settings_ = [Metadata_ objectForKey:@"Settings"];
9191 Packages_ = [Metadata_ objectForKey:@"Packages"];
9192 Sections_ = [Metadata_ objectForKey:@"Sections"];
9193 Sources_ = [Metadata_ objectForKey:@"Sources"];
9195 Token_ = [Metadata_ objectForKey:@"Token"];
9198 if (Settings_ != nil)
9199 Role_ = [Settings_ objectForKey:@"Role"];
9201 if (Sections_ == nil) {
9202 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9203 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9206 if (Sources_ == nil) {
9207 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9208 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9213 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
9216 if (Packages_ != nil) {
9217 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, NULL);
9219 [Metadata_ removeObjectForKey:@"Packages"];
9224 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9226 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", F_OK) == 0)
9227 dlopen("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", RTLD_LAZY | RTLD_GLOBAL);
9228 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
9229 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
9230 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9231 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9233 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9235 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9236 unlink("/tmp/.cydia.fw");
9238 } else if (access("/User", F_OK) != 0 || version < 2) {
9241 system("/usr/libexec/cydia/firmware.sh");
9245 _assert([[NSFileManager defaultManager]
9246 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9247 withIntermediateDirectories:YES
9252 if (access("/tmp/cydia.chk", F_OK) == 0) {
9253 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9254 _assert(errno == ENOENT);
9255 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9256 _assert(errno == ENOENT);
9259 /* APT Initialization {{{ */
9260 _assert(pkgInitConfig(*_config));
9261 _assert(pkgInitSystem(*_config, _system));
9264 _config->Set("APT::Acquire::Translation", lang);
9266 // XXX: this timeout might be important :(
9267 //_config->Set("Acquire::http::Timeout", 15);
9269 _config->Set("Acquire::http::MaxParallel", 3);
9271 /* Color Choices {{{ */
9272 space_ = CGColorSpaceCreateDeviceRGB();
9274 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9275 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9276 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9277 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9278 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9279 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9280 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9281 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9282 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9284 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9285 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9287 /* UIKit Configuration {{{ */
9288 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9289 if ($GSFontSetUseLegacyFontMetrics != NULL)
9290 $GSFontSetUseLegacyFontMetrics(YES);
9292 // XXX: I have a feeling this was important
9293 //UIKeyboardDisableAutomaticAppearance();
9296 Colon_ = UCLocalize("COLON_DELIMITED");
9297 Elision_ = UCLocalize("ELISION");
9298 Error_ = UCLocalize("ERROR");
9299 Warning_ = UCLocalize("WARNING");
9302 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9304 CGColorSpaceRelease(space_);