1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2010 Jay Freeman (saurik)
5 /* Modified BSD License {{{ */
7 * Redistribution and use in source and binary
8 * forms, with or without modification, are permitted
9 * provided that the following conditions are met:
11 * 1. Redistributions of source code must retain the
12 * above copyright notice, this list of conditions
13 * and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the
15 * above copyright notice, this list of conditions
16 * and the following disclaimer in the documentation
17 * and/or other materials provided with the
19 * 3. The name of the author may not be used to endorse
20 * or promote products derived from this software
21 * without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
24 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
25 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
26 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
28 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
34 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
36 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 // XXX: wtf/FastMalloc.h... wtf?
41 #define USE_SYSTEM_MALLOC 1
43 /* #include Directives {{{ */
44 #include "UICaboodle/UCPlatform.h"
45 #include "UICaboodle/UCLocalize.h"
47 #include <objc/objc.h>
48 #include <objc/runtime.h>
50 #include <CoreGraphics/CoreGraphics.h>
51 #include <Foundation/Foundation.h>
54 #define DEPLOYMENT_TARGET_MACOSX 1
55 #define CF_BUILDING_CF 1
56 #include <CoreFoundation/CFInternal.h>
59 #include <CoreFoundation/CFPriv.h>
60 #include <CoreFoundation/CFUniChar.h>
62 #include <SystemConfiguration/SystemConfiguration.h>
64 #include <UIKit/UIKit.h>
65 #include "iPhonePrivate.h"
67 #include <IOKit/IOKitLib.h>
69 #include <WebCore/WebCoreThread.h>
76 #include <ext/stdio_filebuf.h>
80 #include <apt-pkg/acquire.h>
81 #include <apt-pkg/acquire-item.h>
82 #include <apt-pkg/algorithms.h>
83 #include <apt-pkg/cachefile.h>
84 #include <apt-pkg/clean.h>
85 #include <apt-pkg/configuration.h>
86 #include <apt-pkg/debindexfile.h>
87 #include <apt-pkg/debmetaindex.h>
88 #include <apt-pkg/error.h>
89 #include <apt-pkg/init.h>
90 #include <apt-pkg/mmap.h>
91 #include <apt-pkg/pkgrecords.h>
92 #include <apt-pkg/sha1.h>
93 #include <apt-pkg/sourcelist.h>
94 #include <apt-pkg/sptr.h>
95 #include <apt-pkg/strutl.h>
96 #include <apt-pkg/tagfile.h>
98 #include <apr-1/apr_pools.h>
100 #include <sys/types.h>
101 #include <sys/stat.h>
102 #include <sys/sysctl.h>
103 #include <sys/param.h>
104 #include <sys/mount.h>
111 #include <mach-o/nlist.h>
121 #include <Cytore.hpp>
123 #include "UICaboodle/BrowserView.h"
125 #include "substrate.h"
132 #define _timestamp ({ \
134 gettimeofday(&tv, NULL); \
135 tv.tv_sec * 1000000 + tv.tv_usec; \
138 typedef std::vector<class ProfileTime *> TimeList;
148 ProfileTime(const char *name) :
152 times_.push_back(this);
155 void AddTime(uint64_t time) {
162 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
174 ProfileTimer(ProfileTime &time) :
181 time_.AddTime(_timestamp - start_);
186 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
188 std::cerr << "========" << std::endl;
191 #define _profile(name) { \
192 static ProfileTime name(#name); \
193 ProfileTimer _ ## name(name);
198 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
200 #define CYPoolStart() \
201 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
203 #define CYPoolEnd() \
207 // Hash Functions/Structures {{{
208 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
216 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
218 void NSLogPoint(const char *fix, const CGPoint &point) {
219 NSLog(@"%s(%g,%g)", fix, point.x, point.y);
222 void NSLogRect(const char *fix, const CGRect &rect) {
223 NSLog(@"%s(%g,%g)+(%g,%g)", fix, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
226 static _finline NSString *CydiaURL(NSString *path) {
228 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = ':';
229 page[5] = '/'; page[6] = '/'; page[7] = 'c'; page[8] = 'y'; page[9] = 'd';
230 page[10] = 'i'; page[11] = 'a'; page[12] = '.'; page[13] = 's'; page[14] = 'a';
231 page[15] = 'u'; page[16] = 'r'; page[17] = 'i'; page[18] = 'k'; page[19] = '.';
232 page[20] = 'c'; page[21] = 'o'; page[22] = 'm'; page[23] = '/'; page[24] = '\0';
233 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
236 static _finline void UpdateExternalStatus(uint64_t newStatus) {
238 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
239 notify_set_state(notify_token, newStatus);
240 notify_cancel(notify_token);
242 notify_post("com.saurik.Cydia.status");
245 /* [NSObject yieldToSelector:(withObject:)] {{{*/
246 @interface NSObject (Cydia)
247 - (id) yieldToSelector:(SEL)selector withObject:(id)object;
248 - (id) yieldToSelector:(SEL)selector;
251 @implementation NSObject (Cydia)
256 - (void) _yieldToContext:(NSMutableArray *)context { _pooled
257 SEL selector(reinterpret_cast<SEL>([[context objectAtIndex:0] pointerValue]));
258 id object([[context objectAtIndex:1] nonretainedObjectValue]);
259 volatile bool &stopped(*reinterpret_cast<bool *>([[context objectAtIndex:2] pointerValue]));
261 /* XXX: deal with exceptions */
262 id value([self performSelector:selector withObject:object]);
264 NSMethodSignature *signature([self methodSignatureForSelector:selector]);
265 [context removeAllObjects];
266 if ([signature methodReturnLength] != 0 && value != nil)
267 [context addObject:value];
272 performSelectorOnMainThread:@selector(doNothing)
278 - (id) yieldToSelector:(SEL)selector withObject:(id)object {
279 /*return [self performSelector:selector withObject: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;
1015 static const int ButtonBarWidth_ = 60;
1016 static const int ButtonBarHeight_ = 48;
1017 static const float KeyboardTime_ = 0.3f;
1020 static NSArray *Finishes_;
1022 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
1023 #define NotifyConfig_ "/etc/notify.conf"
1025 static bool Queuing_;
1027 static CYColor Blue_;
1028 static CYColor Blueish_;
1029 static CYColor Black_;
1030 static CYColor Off_;
1031 static CYColor White_;
1032 static CYColor Gray_;
1033 static CYColor Green_;
1034 static CYColor Purple_;
1035 static CYColor Purplish_;
1037 static UIColor *InstallingColor_;
1038 static UIColor *RemovingColor_;
1040 static NSString *App_;
1041 static NSString *Home_;
1043 static BOOL Advanced_;
1044 static BOOL Ignored_;
1046 static UIFont *Font12_;
1047 static UIFont *Font12Bold_;
1048 static UIFont *Font14_;
1049 static UIFont *Font18Bold_;
1050 static UIFont *Font22Bold_;
1052 static const char *Machine_ = NULL;
1053 static NSString *System_ = nil;
1054 static NSString *SerialNumber_ = nil;
1055 static NSString *ChipID_ = nil;
1056 static NSString *Token_ = nil;
1057 static NSString *UniqueID_ = nil;
1058 static NSString *PLMN_ = nil;
1059 static NSString *Build_ = nil;
1060 static NSString *Product_ = nil;
1061 static NSString *Safari_ = nil;
1063 static CFLocaleRef Locale_;
1064 static NSArray *Languages_;
1065 static CGColorSpaceRef space_;
1067 static NSDictionary *SectionMap_;
1068 static NSMutableDictionary *Metadata_;
1069 static _transient NSMutableDictionary *Settings_;
1070 static _transient NSString *Role_;
1071 static _transient NSMutableDictionary *Packages_;
1072 static _transient NSMutableDictionary *Sections_;
1073 static _transient NSMutableDictionary *Sources_;
1074 static bool Changed_;
1077 static bool IsWildcat_;
1080 /* Display Helpers {{{ */
1081 inline float Interpolate(float begin, float end, float fraction) {
1082 return (end - begin) * fraction + begin;
1085 /* XXX: localize this! */
1086 NSString *SizeString(double size) {
1087 bool negative = size < 0;
1092 while (size > 1024) {
1097 static const char *powers_[] = {"B", "kB", "MB", "GB"};
1099 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
1102 static _finline const char *StripVersion_(const char *version) {
1103 const char *colon(strchr(version, ':'));
1104 return colon == NULL ? version : colon + 1;
1107 NSString *LocalizeSection(NSString *section) {
1108 static Pcre title_r("^(.*?) \\((.*)\\)$");
1109 if (title_r(section)) {
1110 NSString *parent(title_r[1]);
1111 NSString *child(title_r[2]);
1113 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1114 LocalizeSection(parent),
1115 LocalizeSection(child)
1119 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1122 NSString *Simplify(NSString *title) {
1123 const char *data = [title UTF8String];
1124 size_t size = [title length];
1126 static Pcre square_r("^\\[(.*)\\]$");
1127 if (square_r(data, size))
1128 return Simplify(square_r[1]);
1130 static Pcre paren_r("^\\((.*)\\)$");
1131 if (paren_r(data, size))
1132 return Simplify(paren_r[1]);
1134 static Pcre title_r("^(.*?) \\((.*)\\)$");
1135 if (title_r(data, size))
1136 return Simplify(title_r[1]);
1142 NSString *GetLastUpdate() {
1143 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1146 return UCLocalize("NEVER_OR_UNKNOWN");
1148 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1149 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1151 CFRelease(formatter);
1153 return [(NSString *) formatted autorelease];
1156 bool isSectionVisible(NSString *section) {
1157 NSDictionary *metadata([Sections_ objectForKey:section]);
1158 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1159 return hidden == nil || ![hidden boolValue];
1164 /* Delegate Prototypes {{{ */
1168 @interface NSObject (ProgressDelegate)
1171 @protocol ProgressDelegate
1172 - (void) setProgressError:(NSString *)error withTitle:(NSString *)id;
1173 - (void) setProgressTitle:(NSString *)title;
1174 - (void) setProgressPercent:(float)percent;
1175 - (void) startProgress;
1176 - (void) addProgressOutput:(NSString *)output;
1177 - (bool) isCancelling:(size_t)received;
1180 @protocol ConfigurationDelegate
1181 - (void) repairWithSelector:(SEL)selector;
1182 - (void) setConfigurationData:(NSString *)data;
1185 @class PackageController;
1187 @protocol CydiaDelegate
1188 - (void) setPackageController:(PackageController *)view;
1189 - (void) clearPackage:(Package *)package;
1190 - (void) installPackage:(Package *)package;
1191 - (void) installPackages:(NSArray *)packages;
1192 - (void) removePackage:(Package *)package;
1193 - (void) beginUpdate;
1195 - (void) distUpgrade;
1197 - (void) updateData;
1199 - (void) showSettings;
1200 - (UIProgressHUD *) addProgressHUD;
1201 - (BOOL) hudIsShowing;
1202 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1203 - (CYViewController *) pageForPackage:(NSString *)name;
1204 - (PackageController *) packageController;
1205 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
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<void> reserved_;
1434 Cytore::Offset<PackageValue> next_;
1436 uint32_t index_ : 23;
1437 uint32_t subscribed_ : 1;
1453 Cytore::Offset<void> reserved_;
1454 Cytore::Offset<PackageValue> packages_[1 << 16];
1457 static Cytore::File<MetaValue> MetaFile_;
1459 // Cytore Helper Functions {{{
1460 static PackageValue *PackageFind(const char *name, size_t length) {
1461 SplitHash nhash = { hashlittle(name, length) };
1463 PackageValue *metadata;
1465 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1466 offset: if (offset->IsNull()) {
1467 *offset = MetaFile_.New<PackageValue>(length + 1);
1468 metadata = &MetaFile_.Get(*offset);
1470 memcpy(metadata->name_, name, length + 1);
1471 metadata->nhash_ = nhash.u16[1];
1473 metadata = &MetaFile_.Get(*offset);
1475 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1476 offset = &metadata->next_;
1484 static void PackageImport(const void *key, const void *value, void *context) {
1486 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1487 NSLog(@"failed to import package %@", key);
1491 PackageValue *metadata(PackageFind(buffer, strlen(buffer)));
1492 NSDictionary *package((NSDictionary *) value);
1494 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1495 if ([subscribed boolValue])
1496 metadata->subscribed_ = true;
1498 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1499 time_t time([date timeIntervalSince1970]);
1500 if (metadata->first_ > time || metadata->first_ == 0)
1501 metadata->first_ = time;
1504 if (NSDate *date = [package objectForKey:@"LastSeen"]) {
1505 time_t time([date timeIntervalSince1970]);
1506 if (metadata->last_ < time || metadata->last_ == 0) {
1507 metadata->last_ = time;
1510 } else if (metadata->last_ == 0) last: {
1511 NSString *version([package objectForKey:@"LastVersion"]);
1512 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1513 size_t length(strlen(buffer));
1514 uint16_t vhash(hashlittle(buffer, length));
1516 size_t capped(std::min<size_t>(8, length));
1517 char *latest(buffer + length - capped);
1519 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1520 metadata->vhash_ = vhash;
1526 /* Source Class {{{ */
1527 @interface Source : NSObject {
1528 CYString depiction_;
1529 CYString description_;
1535 CYString distribution_;
1540 NSString *authority_;
1542 CYString defaultIcon_;
1544 NSDictionary *record_;
1548 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1550 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1552 - (NSString *) depictionForPackage:(NSString *)package;
1553 - (NSString *) supportForPackage:(NSString *)package;
1555 - (NSDictionary *) record;
1559 - (NSString *) distribution;
1560 - (NSString *) type;
1562 - (NSString *) host;
1564 - (NSString *) name;
1565 - (NSString *) description;
1566 - (NSString *) label;
1567 - (NSString *) origin;
1568 - (NSString *) version;
1570 - (NSString *) defaultIcon;
1574 @implementation Source
1578 distribution_.clear();
1581 description_.clear();
1587 defaultIcon_.clear();
1589 if (record_ != nil) {
1599 if (authority_ != nil) {
1600 [authority_ release];
1606 // XXX: this is a very inefficient way to call these deconstructors
1611 + (NSArray *) _attributeKeys {
1612 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1615 - (NSArray *) attributeKeys {
1616 return [[self class] _attributeKeys];
1619 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1620 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1623 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1626 trusted_ = index->IsTrusted();
1628 uri_.set(pool, index->GetURI());
1629 distribution_.set(pool, index->GetDist());
1630 type_.set(pool, index->GetType());
1632 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1633 if (dindex != NULL) {
1635 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1638 pkgTagFile tags(&fd);
1640 pkgTagSection section;
1647 {"default-icon", &defaultIcon_},
1648 {"depiction", &depiction_},
1649 {"description", &description_},
1651 {"origin", &origin_},
1652 {"support", &support_},
1653 {"version", &version_},
1656 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1657 const char *start, *end;
1659 if (section.Find(names[i].name_, start, end)) {
1660 CYString &value(*names[i].value_);
1661 value.set(pool, start, end - start);
1667 record_ = [Sources_ objectForKey:[self key]];
1669 record_ = [record_ retain];
1671 NSURL *url([NSURL URLWithString:uri_]);
1675 host_ = [[host_ lowercaseString] retain];
1680 authority_ = [url path];
1682 if (authority_ != nil)
1683 authority_ = [authority_ retain];
1686 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1687 if ((self = [super init]) != nil) {
1688 [self setMetaIndex:index inPool:pool];
1692 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1693 NSDictionary *lhr = [self record];
1694 NSDictionary *rhr = [source record];
1697 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1699 NSString *lhs = [self name];
1700 NSString *rhs = [source name];
1702 if ([lhs length] != 0 && [rhs length] != 0) {
1703 unichar lhc = [lhs characterAtIndex:0];
1704 unichar rhc = [rhs characterAtIndex:0];
1706 if (isalpha(lhc) && !isalpha(rhc))
1707 return NSOrderedAscending;
1708 else if (!isalpha(lhc) && isalpha(rhc))
1709 return NSOrderedDescending;
1712 return [lhs compare:rhs options:LaxCompareOptions_];
1715 - (NSString *) depictionForPackage:(NSString *)package {
1716 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1719 - (NSString *) supportForPackage:(NSString *)package {
1720 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1723 - (NSDictionary *) record {
1731 - (NSString *) uri {
1735 - (NSString *) distribution {
1736 return distribution_;
1739 - (NSString *) type {
1743 - (NSString *) key {
1744 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1747 - (NSString *) host {
1751 - (NSString *) name {
1752 return origin_.empty() ? authority_ : origin_;
1755 - (NSString *) description {
1756 return description_;
1759 - (NSString *) label {
1760 return label_.empty() ? authority_ : label_;
1763 - (NSString *) origin {
1767 - (NSString *) version {
1771 - (NSString *) defaultIcon {
1772 return defaultIcon_;
1777 /* Relationship Class {{{ */
1778 @interface Relationship : NSObject {
1783 - (NSString *) type;
1785 - (NSString *) name;
1789 @implementation Relationship
1797 - (NSString *) type {
1805 - (NSString *) name {
1812 /* Package Class {{{ */
1813 struct ParsedPackage {
1818 CYString depiction_;
1828 @interface Package : NSObject {
1830 uint32_t essential_ : 1;
1831 uint32_t obsolete_ : 1;
1832 uint32_t ignored_ : 1;
1836 _transient Database *database_;
1838 pkgCache::VerIterator version_;
1839 pkgCache::PkgIterator iterator_;
1840 pkgCache::VerFileIterator file_;
1846 CYString installed_;
1849 _transient NSString *section$_;
1853 PackageValue *metadata_;
1854 ParsedPackage *parsed_;
1856 NSMutableArray *tags_;
1860 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1861 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1863 - (pkgCache::PkgIterator) iterator;
1866 - (NSString *) section;
1867 - (NSString *) simpleSection;
1869 - (NSString *) longSection;
1870 - (NSString *) shortSection;
1874 - (Address *) maintainer;
1876 - (NSString *) longDescription;
1877 - (NSString *) shortDescription;
1880 - (PackageValue *) metadata;
1883 - (bool) subscribed;
1884 - (bool) setSubscribed:(bool)subscribed;
1888 - (NSString *) latest;
1889 - (NSString *) installed;
1890 - (BOOL) uninstalled;
1893 - (BOOL) upgradableAndEssential:(BOOL)essential;
1896 - (BOOL) unfiltered;
1900 - (BOOL) halfConfigured;
1901 - (BOOL) halfInstalled;
1903 - (NSString *) mode;
1906 - (NSString *) name;
1908 - (NSString *) homepage;
1909 - (NSString *) depiction;
1910 - (Address *) author;
1912 - (NSString *) support;
1914 - (NSArray *) files;
1915 - (NSArray *) warnings;
1916 - (NSArray *) applications;
1918 - (Source *) source;
1919 - (NSString *) role;
1921 - (BOOL) matches:(NSString *)text;
1923 - (bool) hasSupportingRole;
1924 - (BOOL) hasTag:(NSString *)tag;
1925 - (NSString *) primaryPurpose;
1926 - (NSArray *) purposes;
1927 - (bool) isCommercial;
1929 - (void) setIndex:(size_t)index;
1931 - (CYString &) cyname;
1933 - (uint32_t) compareBySection:(NSArray *)sections;
1938 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1939 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1940 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1941 - (bool) isVisibleInSection:(NSString *)section;
1942 - (bool) isVisibleInSource:(Source *)source;
1946 uint32_t PackageChangesRadix(Package *self, void *) {
1951 uint32_t timestamp : 30;
1952 uint32_t ignored : 1;
1953 uint32_t upgradable : 1;
1957 bool upgradable([self upgradableAndEssential:YES]);
1958 value.bits.upgradable = upgradable ? 1 : 0;
1961 value.bits.timestamp = 0;
1962 value.bits.ignored = [self ignored] ? 0 : 1;
1963 value.bits.upgradable = 1;
1965 value.bits.timestamp = [self seen] >> 2;
1966 value.bits.ignored = 0;
1967 value.bits.upgradable = 0;
1970 return _not(uint32_t) - value.key;
1973 _finline static void Stifle(uint8_t &value) {
1976 uint32_t PackagePrefixRadix(Package *self, void *context) {
1977 size_t offset(reinterpret_cast<size_t>(context));
1978 CYString &name([self cyname]);
1980 size_t size(name.size());
1983 char *text(name.data());
1986 if (!isdigit(text[0]))
1990 while (size != digits && isdigit(text[digits]))
2000 if (offset == 0 && zeros != 0) {
2001 memset(data, '0', zeros);
2002 memcpy(data + zeros, text, 4 - zeros);
2004 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2005 if (size <= offset - zeros)
2008 text += offset - zeros;
2009 size -= offset - zeros;
2012 memcpy(data, text, 4);
2014 memcpy(data, text, size);
2015 memset(data + size, 0, 4 - size);
2018 for (size_t i(0); i != 4; ++i)
2019 if (isalpha(data[i]))
2027 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2029 /* XXX: ntohl may be more honest */
2030 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2033 CYString &(*PackageName)(Package *self, SEL sel);
2035 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2036 _profile(PackageNameCompare)
2037 CYString &lhi(PackageName(lhs, @selector(cyname)));
2038 CYString &rhi(PackageName(rhs, @selector(cyname)));
2039 CFStringRef lhn(lhi), rhn(rhi);
2042 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2043 else if (rhn == NULL)
2044 return NSOrderedDescending;
2046 _profile(PackageNameCompare$NumbersLast)
2047 if (!lhi.empty() && !rhi.empty()) {
2048 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2049 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2050 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2051 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2052 return lha ? NSOrderedAscending : NSOrderedDescending;
2056 CFIndex length = CFStringGetLength(lhn);
2058 _profile(PackageNameCompare$Compare)
2059 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2064 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2065 return PackageNameCompare(*lhs, *rhs, context);
2068 struct PackageNameOrdering :
2069 std::binary_function<Package *, Package *, bool>
2071 _finline bool operator ()(Package *lhs, Package *rhs) const {
2072 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2076 @implementation Package
2078 - (NSString *) description {
2079 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2083 if (parsed_ != NULL)
2097 + (NSString *) webScriptNameForSelector:(SEL)selector {
2098 if (selector == @selector(hasTag:))
2104 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2105 return [self webScriptNameForSelector:selector] == nil;
2108 + (NSArray *) _attributeKeys {
2109 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];
2112 - (NSArray *) attributeKeys {
2113 return [[self class] _attributeKeys];
2116 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2117 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2121 if (parsed_ != NULL)
2123 @synchronized (database_) {
2124 if ([database_ era] != era_ || file_.end())
2127 ParsedPackage *parsed(new ParsedPackage);
2130 _profile(Package$parse)
2131 pkgRecords::Parser *parser;
2133 _profile(Package$parse$Lookup)
2134 parser = &[database_ records]->Lookup(file_);
2139 _profile(Package$parse$Find)
2144 {"icon", &parsed->icon_},
2145 {"depiction", &parsed->depiction_},
2146 {"homepage", &parsed->homepage_},
2147 {"website", &website},
2148 {"bugs", &parsed->bugs_},
2149 {"support", &parsed->support_},
2150 {"sponsor", &parsed->sponsor_},
2151 {"author", &parsed->author_},
2154 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2155 const char *start, *end;
2157 if (parser->Find(names[i].name_, start, end)) {
2158 CYString &value(*names[i].value_);
2159 _profile(Package$parse$Value)
2160 value.set(pool_, start, end - start);
2166 _profile(Package$parse$Tagline)
2167 const char *start, *end;
2168 if (parser->ShortDesc(start, end)) {
2169 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2172 while (stop != start && stop[-1] == '\r')
2174 parsed->tagline_.set(pool_, start, stop - start);
2178 _profile(Package$parse$Retain)
2179 if (parsed->homepage_.empty())
2180 parsed->homepage_ = website;
2181 if (parsed->homepage_ == parsed->depiction_)
2182 parsed->homepage_.clear();
2187 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2188 if ((self = [super init]) != nil) {
2189 _profile(Package$initWithVersion)
2192 database_ = database;
2193 era_ = [database era];
2197 pkgCache::PkgIterator iterator(version.ParentPkg());
2198 iterator_ = iterator;
2200 _profile(Package$initWithVersion$Version)
2201 if (!version_.end())
2202 file_ = version_.FileList();
2204 pkgCache &cache([database_ cache]);
2205 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2209 _profile(Package$initWithVersion$Cache)
2210 id_.set(NULL, iterator.Name());
2211 name_.set(NULL, iterator.Display());
2213 latest_.set(NULL, StripVersion_(version_.VerStr()));
2215 pkgCache::VerIterator current(iterator.CurrentVer());
2217 installed_.set(NULL, StripVersion_(current.VerStr()));
2220 _profile(Package$initWithVersion$Lower)
2221 // XXX: do not use tolower() as this is not locale-specific? :(
2222 char *data(id_.data());
2223 for (size_t i(0), e(id_.size()); i != e; ++i)
2224 if ((data[i] & 0x20) == 0) {
2233 _profile(Package$initWithVersion$Tags)
2234 pkgCache::TagIterator tag(iterator.TagList());
2236 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2238 const char *name(tag.Name());
2239 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2241 if (role_ == nil && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/)
2242 role_ = (NSString *) CYStringCreate(name + 6);
2244 if (strncmp(name, "cydia::", 7) == 0) {
2245 if (strcmp(name + 7, "essential") == 0)
2247 else if (strcmp(name + 7, "obsolete") == 0)
2252 } while (!tag.end());
2256 _profile(Package$initWithVersion$Metadata)
2257 PackageValue *metadata(PackageFind(id_.data(), id_.size()));
2258 metadata_ = metadata;
2260 const char *latest(version_.VerStr());
2261 size_t length(strlen(latest));
2263 uint16_t vhash(hashlittle(latest, length));
2265 size_t capped(std::min<size_t>(8, length));
2266 latest = latest + length - capped;
2268 if (metadata->first_ == 0)
2269 metadata->first_ = now_;
2271 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2272 metadata->last_ = now_;
2273 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2274 metadata->vhash_ = vhash;
2275 } else if (metadata->last_ == 0)
2276 metadata->last_ = metadata->first_;
2279 _profile(Package$initWithVersion$Section)
2280 section_.set(NULL, iterator.Section());
2283 _profile(Package$initWithVersion$Flags)
2284 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2285 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2290 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2291 pkgCache::VerIterator version;
2293 _profile(Package$packageWithIterator$GetCandidateVer)
2294 version = [database policy]->GetCandidateVer(iterator);
2302 _profile(Package$packageWithIterator$Allocate)
2303 package = [Package allocWithZone:zone];
2306 _profile(Package$packageWithIterator$Initialize)
2308 initWithVersion:version
2315 _profile(Package$packageWithIterator$Autorelease)
2316 package = [package autorelease];
2322 - (pkgCache::PkgIterator) iterator {
2326 - (NSString *) section {
2327 if (section$_ == nil) {
2328 if (section_.empty())
2331 _profile(Package$section)
2332 std::replace(section_.data(), section_.data() + section_.size(), '_', ' ');
2333 NSString *name(section_);
2334 section$_ = [SectionMap_ objectForKey:name] ?: name;
2339 - (NSString *) simpleSection {
2340 if (NSString *section = [self section])
2341 return Simplify(section);
2346 - (NSString *) longSection {
2347 return LocalizeSection([self section]);
2350 - (NSString *) shortSection {
2351 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2354 - (NSString *) uri {
2357 pkgIndexFile *index;
2358 pkgCache::PkgFileIterator file(file_.File());
2359 if (![database_ list].FindIndex(file, index))
2361 return [NSString stringWithUTF8String:iterator_->Path];
2362 //return [NSString stringWithUTF8String:file.Site()];
2363 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2367 - (Address *) maintainer {
2368 @synchronized (database_) {
2369 if ([database_ era] != era_ || file_.end())
2372 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2373 const std::string &maintainer(parser->Maintainer());
2374 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2378 @synchronized (database_) {
2379 if ([database_ era] != era_ || version_.end())
2382 return version_->InstalledSize;
2385 - (NSString *) longDescription {
2386 @synchronized (database_) {
2387 if ([database_ era] != era_ || file_.end())
2390 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2391 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2393 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2394 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2395 if ([lines count] < 2)
2398 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2399 for (size_t i(1), e([lines count]); i != e; ++i) {
2400 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2401 [trimmed addObject:trim];
2404 return [trimmed componentsJoinedByString:@"\n"];
2407 - (NSString *) shortDescription {
2408 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2412 _profile(Package$index)
2413 CFStringRef name((CFStringRef) [self name]);
2414 if (CFStringGetLength(name) == 0)
2416 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2417 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2419 return toupper(character);
2423 - (PackageValue *) metadata {
2428 PackageValue *metadata([self metadata]);
2429 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2432 - (bool) subscribed {
2433 return [self metadata]->subscribed_;
2436 - (bool) setSubscribed:(bool)subscribed {
2437 PackageValue *metadata([self metadata]);
2438 if (metadata->subscribed_ == subscribed)
2440 metadata->subscribed_ = subscribed;
2448 - (NSString *) latest {
2452 - (NSString *) installed {
2456 - (BOOL) uninstalled {
2457 return installed_.empty();
2461 return !version_.end();
2464 - (BOOL) upgradableAndEssential:(BOOL)essential {
2465 _profile(Package$upgradableAndEssential)
2466 pkgCache::VerIterator current(iterator_.CurrentVer());
2468 return essential && essential_;
2470 return !version_.end() && version_ != current;
2474 - (BOOL) essential {
2479 return [database_ cache][iterator_].InstBroken();
2482 - (BOOL) unfiltered {
2483 _profile(Package$unfiltered$obsolete)
2488 _profile(Package$unfiltered$hasSupportingRole)
2489 if (![self hasSupportingRole])
2497 if (![self unfiltered])
2500 NSString *section([self section]);
2502 _profile(Package$visible$isSectionVisible)
2503 if (section != nil && !isSectionVisible(section))
2511 unsigned char current(iterator_->CurrentState);
2512 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2515 - (BOOL) halfConfigured {
2516 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2519 - (BOOL) halfInstalled {
2520 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2524 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2525 return state.Mode != pkgDepCache::ModeKeep;
2528 - (NSString *) mode {
2529 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2531 switch (state.Mode) {
2532 case pkgDepCache::ModeDelete:
2533 if ((state.iFlags & pkgDepCache::Purge) != 0)
2537 case pkgDepCache::ModeKeep:
2538 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2539 return @"REINSTALL";
2540 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2544 case pkgDepCache::ModeInstall:
2545 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2546 return @"REINSTALL";
2547 else*/ switch (state.Status) {
2549 return @"DOWNGRADE";
2555 return @"NEW_INSTALL";
2566 - (NSString *) name {
2567 return name_.empty() ? id_ : name_;
2570 - (UIImage *) icon {
2571 NSString *section = [self simpleSection];
2574 if (parsed_ != NULL)
2575 if (NSString *href = parsed_->icon_)
2576 if ([href hasPrefix:@"file:///"])
2577 // XXX: correct escaping
2578 icon = [UIImage imageAtPath:[href substringFromIndex:7]];
2579 if (icon == nil) if (section != nil)
2580 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2581 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2582 if ([dicon hasPrefix:@"file:///"])
2583 // XXX: correct escaping
2584 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2586 icon = [UIImage applicationImageNamed:@"unknown.png"];
2590 - (NSString *) homepage {
2591 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2594 - (NSString *) depiction {
2595 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2598 - (Address *) sponsor {
2599 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [Address addressWithString:parsed_->sponsor_];
2602 - (Address *) author {
2603 return parsed_ == NULL || parsed_->author_.empty() ? nil : [Address addressWithString:parsed_->author_];
2606 - (NSString *) support {
2607 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2610 - (NSArray *) files {
2611 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2612 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2615 fin.open([path UTF8String]);
2620 while (std::getline(fin, line))
2621 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2626 - (NSArray *) warnings {
2627 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2628 const char *name(iterator_.Name());
2630 size_t length(strlen(name));
2631 if (length < 2) invalid:
2632 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2633 else for (size_t i(0); i != length; ++i)
2635 /* XXX: technically this is not allowed */
2636 (name[i] < 'A' || name[i] > 'Z') &&
2637 (name[i] < 'a' || name[i] > 'z') &&
2638 (name[i] < '0' || name[i] > '9') &&
2639 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2642 if (strcmp(name, "cydia") != 0) {
2645 bool _private = false;
2648 bool repository = [[self section] isEqualToString:@"Repositories"];
2650 if (NSArray *files = [self files])
2651 for (NSString *file in files)
2652 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2654 else if (!user && [file isEqualToString:@"/User"])
2656 else if (!_private && [file isEqualToString:@"/private"])
2658 else if (!stash && [file isEqualToString:@"/var/stash"])
2661 /* XXX: this is not sensitive enough. only some folders are valid. */
2662 if (cydia && !repository)
2663 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2665 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2667 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2669 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2672 return [warnings count] == 0 ? nil : warnings;
2675 - (NSArray *) applications {
2676 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2678 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2680 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2681 if (NSArray *files = [self files])
2682 for (NSString *file in files)
2683 if (application_r(file)) {
2684 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2685 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2686 if ([id isEqualToString:me])
2689 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2691 display = application_r[1];
2693 NSString *bundle([file stringByDeletingLastPathComponent]);
2694 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2695 if (icon == nil || [icon length] == 0)
2697 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2699 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2700 [applications addObject:application];
2702 [application addObject:id];
2703 [application addObject:display];
2704 [application addObject:url];
2707 return [applications count] == 0 ? nil : applications;
2710 - (Source *) source {
2711 if (source_ == nil) {
2712 @synchronized (database_) {
2713 if ([database_ era] != era_ || file_.end())
2714 source_ = (Source *) [NSNull null];
2716 source_ = [([database_ getSource:file_.File()] ?: (Source *) [NSNull null]) retain];
2720 return source_ == (Source *) [NSNull null] ? nil : source_;
2723 - (NSString *) role {
2727 - (BOOL) matches:(NSString *)text {
2733 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2734 if (range.location != NSNotFound)
2737 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2738 if (range.location != NSNotFound)
2741 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2742 if (range.location != NSNotFound)
2748 - (bool) hasSupportingRole {
2751 if ([role_ isEqualToString:@"enduser"])
2753 if ([Role_ isEqualToString:@"User"])
2755 if ([role_ isEqualToString:@"hacker"])
2757 if ([Role_ isEqualToString:@"Hacker"])
2759 if ([role_ isEqualToString:@"developer"])
2761 if ([Role_ isEqualToString:@"Developer"])
2766 - (BOOL) hasTag:(NSString *)tag {
2767 return tags_ == nil ? NO : [tags_ containsObject:tag];
2770 - (NSString *) primaryPurpose {
2771 for (NSString *tag in tags_)
2772 if ([tag hasPrefix:@"purpose::"])
2773 return [tag substringFromIndex:9];
2777 - (NSArray *) purposes {
2778 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2779 for (NSString *tag in tags_)
2780 if ([tag hasPrefix:@"purpose::"])
2781 [purposes addObject:[tag substringFromIndex:9]];
2782 return [purposes count] == 0 ? nil : purposes;
2785 - (bool) isCommercial {
2786 return [self hasTag:@"cydia::commercial"];
2789 - (void) setIndex:(size_t)index {
2790 if (metadata_->index_ != index)
2791 metadata_->index_ = index;
2794 - (CYString &) cyname {
2795 return name_.empty() ? id_ : name_;
2798 - (uint32_t) compareBySection:(NSArray *)sections {
2799 NSString *section([self section]);
2800 for (size_t i(0), e([sections count]); i != e; ++i) {
2801 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2805 return _not(uint32_t);
2809 @synchronized (database_) {
2810 pkgProblemResolver *resolver = [database_ resolver];
2811 resolver->Clear(iterator_);
2813 pkgCacheFile &cache([database_ cache]);
2814 cache->SetReInstall(iterator_, false);
2815 cache->MarkKeep(iterator_, false);
2819 @synchronized (database_) {
2820 pkgProblemResolver *resolver = [database_ resolver];
2821 resolver->Clear(iterator_);
2822 resolver->Protect(iterator_);
2824 pkgCacheFile &cache([database_ cache]);
2825 cache->SetReInstall(iterator_, false);
2826 cache->MarkInstall(iterator_, false);
2828 pkgDepCache::StateCache &state((*cache)[iterator_]);
2829 if (!state.Install())
2830 cache->SetReInstall(iterator_, true);
2834 @synchronized (database_) {
2835 pkgProblemResolver *resolver = [database_ resolver];
2836 resolver->Clear(iterator_);
2837 resolver->Remove(iterator_);
2838 resolver->Protect(iterator_);
2840 pkgCacheFile &cache([database_ cache]);
2841 cache->SetReInstall(iterator_, false);
2842 cache->MarkDelete(iterator_, true);
2845 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2846 _profile(Package$isUnfilteredAndSearchedForBy)
2849 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2850 value &= [self unfiltered];
2853 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2854 value &= [self matches:search];
2861 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2862 if ([search length] == 0)
2865 _profile(Package$isUnfilteredAndSelectedForBy)
2868 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2869 value &= [self unfiltered];
2872 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2873 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2880 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
2881 return ![self uninstalled] && (![number boolValue] && ![role_ isEqualToString:@"cydia"] || [self unfiltered]);
2884 - (bool) isVisibleInSection:(NSString *)name {
2885 NSString *section([self section]);
2889 section == nil && [name length] == 0 ||
2890 [name isEqualToString:section]
2891 ) && [self visible];
2894 - (bool) isVisibleInSource:(Source *)source {
2895 return [self source] == source && [self visible];
2900 /* Section Class {{{ */
2901 @interface Section : NSObject {
2906 NSString *localized_;
2909 - (NSComparisonResult) compareByLocalized:(Section *)section;
2910 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2911 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2912 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2913 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2914 - (NSString *) name;
2921 - (void) addToCount;
2923 - (void) setCount:(size_t)count;
2924 - (NSString *) localized;
2928 @implementation Section
2932 if (localized_ != nil)
2933 [localized_ release];
2937 - (NSComparisonResult) compareByLocalized:(Section *)section {
2938 NSString *lhs(localized_);
2939 NSString *rhs([section localized]);
2941 /*if ([lhs length] != 0 && [rhs length] != 0) {
2942 unichar lhc = [lhs characterAtIndex:0];
2943 unichar rhc = [rhs characterAtIndex:0];
2945 if (isalpha(lhc) && !isalpha(rhc))
2946 return NSOrderedAscending;
2947 else if (!isalpha(lhc) && isalpha(rhc))
2948 return NSOrderedDescending;
2951 return [lhs compare:rhs options:LaxCompareOptions_];
2954 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2955 if ((self = [self initWithName:name localize:NO]) != nil) {
2956 if (localized != nil)
2957 localized_ = [localized retain];
2961 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2962 return [self initWithName:name row:0 localize:localize];
2965 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2966 if ((self = [super init]) != nil) {
2967 name_ = [name retain];
2971 localized_ = [LocalizeSection(name_) retain];
2975 /* XXX: localize the index thingees */
2976 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2977 if ((self = [super init]) != nil) {
2978 name_ = [[NSString stringWithCharacters:&index length:1] retain];
2984 - (NSString *) name {
3004 - (void) addToCount {
3008 - (void) setCount:(size_t)count {
3012 - (NSString *) localized {
3019 static NSString *Colon_;
3020 static NSString *Elision_;
3021 static NSString *Error_;
3022 static NSString *Warning_;
3024 /* Database Implementation {{{ */
3025 @implementation Database
3027 + (Database *) sharedInstance {
3028 static Database *instance;
3029 if (instance == nil)
3030 instance = [[Database alloc] init];
3038 - (void) releasePackages {
3039 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3040 CFArrayRemoveAllValues(packages_);
3044 // XXX: actually implement this thing
3046 [self releasePackages];
3047 apr_pool_destroy(pool_);
3048 NSRecycleZone(zone_);
3052 - (void) _readCydia:(NSNumber *)fd { _pooled
3053 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3054 std::istream is(&ib);
3057 static Pcre finish_r("^finish:([^:]*)$");
3059 while (std::getline(is, line)) {
3060 const char *data(line.c_str());
3061 size_t size = line.size();
3062 lprintf("C:%s\n", data);
3064 if (finish_r(data, size)) {
3065 NSString *finish = finish_r[1];
3066 int index = [Finishes_ indexOfObject:finish];
3067 if (index != INT_MAX && index > Finish_)
3075 - (void) _readStatus:(NSNumber *)fd { _pooled
3076 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3077 std::istream is(&ib);
3080 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3081 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3083 while (std::getline(is, line)) {
3084 const char *data(line.c_str());
3085 size_t size(line.size());
3086 lprintf("S:%s\n", data);
3088 if (conffile_r(data, size)) {
3089 [delegate_ setConfigurationData:conffile_r[1]];
3090 } else if (strncmp(data, "status: ", 8) == 0) {
3091 NSString *string = [NSString stringWithUTF8String:(data + 8)];
3092 [delegate_ setProgressTitle:string];
3093 } else if (pmstatus_r(data, size)) {
3094 std::string type([pmstatus_r[1] UTF8String]);
3095 NSString *id = pmstatus_r[2];
3097 float percent([pmstatus_r[3] floatValue]);
3098 [delegate_ setProgressPercent:(percent / 100)];
3100 NSString *string = pmstatus_r[4];
3102 if (type == "pmerror")
3103 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3104 withObject:[NSArray arrayWithObjects:string, id, nil]
3107 else if (type == "pmstatus") {
3108 [delegate_ setProgressTitle:string];
3109 } else if (type == "pmconffile")
3110 [delegate_ setConfigurationData:string];
3112 lprintf("E:unknown pmstatus\n");
3114 lprintf("E:unknown status\n");
3120 - (void) _readOutput:(NSNumber *)fd { _pooled
3121 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3122 std::istream is(&ib);
3125 while (std::getline(is, line)) {
3126 lprintf("O:%s\n", line.c_str());
3127 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
3137 - (Package *) packageWithName:(NSString *)name {
3138 @synchronized (self) {
3139 if (static_cast<pkgDepCache *>(cache_) == NULL)
3141 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3142 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3146 if ((self = [super init]) != nil) {
3153 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3154 apr_pool_create(&pool_, NULL);
3156 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
3160 _assert(pipe(fds) != -1);
3163 _config->Set("APT::Keep-Fds::", cydiafd_);
3164 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3167 detachNewThreadSelector:@selector(_readCydia:)
3169 withObject:[NSNumber numberWithInt:fds[0]]
3172 _assert(pipe(fds) != -1);
3176 detachNewThreadSelector:@selector(_readStatus:)
3178 withObject:[NSNumber numberWithInt:fds[0]]
3181 _assert(pipe(fds) != -1);
3182 _assert(dup2(fds[0], 0) != -1);
3183 _assert(close(fds[0]) != -1);
3185 input_ = fdopen(fds[1], "a");
3187 _assert(pipe(fds) != -1);
3188 _assert(dup2(fds[1], 1) != -1);
3189 _assert(close(fds[1]) != -1);
3192 detachNewThreadSelector:@selector(_readOutput:)
3194 withObject:[NSNumber numberWithInt:fds[0]]
3199 - (pkgCacheFile &) cache {
3203 - (pkgDepCache::Policy *) policy {
3207 - (pkgRecords *) records {
3211 - (pkgProblemResolver *) resolver {
3215 - (pkgAcquire &) fetcher {
3219 - (pkgSourceList &) list {
3223 - (NSArray *) packages {
3224 return (NSArray *) packages_;
3227 - (NSArray *) sources {
3228 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3229 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3230 [sources addObject:i->second];
3234 - (NSArray *) issues {
3235 if (cache_->BrokenCount() == 0)
3238 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3240 for (Package *package in [self packages]) {
3241 if (![package broken])
3243 pkgCache::PkgIterator pkg([package iterator]);
3245 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3246 [entry addObject:[package name]];
3247 [issues addObject:entry];
3249 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3253 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3254 pkgCache::DepIterator start;
3255 pkgCache::DepIterator end;
3256 dep.GlobOr(start, end); // ++dep
3258 if (!cache_->IsImportantDep(end))
3260 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3263 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3264 [entry addObject:failure];
3265 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3267 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3268 if (Package *package = [self packageWithName:name])
3269 name = [package name];
3270 [failure addObject:name];
3272 pkgCache::PkgIterator target(start.TargetPkg());
3273 if (target->ProvidesList != 0)
3274 [failure addObject:@"?"];
3276 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3278 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3279 else if (!cache_[target].CandidateVerIter(cache_).end())
3280 [failure addObject:@"-"];
3281 else if (target->ProvidesList == 0)
3282 [failure addObject:@"!"];
3284 [failure addObject:@"%"];
3288 if (start.TargetVer() != 0)
3289 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3300 - (bool) popErrorWithTitle:(NSString *)title {
3302 std::string message;
3304 while (!_error->empty()) {
3306 bool warning(!_error->PopMessage(error));
3310 size_t size(error.size());
3311 if (size == 0 || error[size - 1] != '\n')
3313 error.resize(size - 1);
3315 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3317 if (!message.empty())
3322 if (fatal && !message.empty())
3323 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3328 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3329 return [self popErrorWithTitle:title] || !success;
3332 - (void) reloadData { CYPoolStart() {
3333 @synchronized (self) {
3336 [self releasePackages];
3357 apr_pool_clear(pool_);
3358 NSRecycleZone(zone_);
3360 int chk(creat("/tmp/cydia.chk", 0644));
3364 NSString *title(UCLocalize("DATABASE"));
3367 if (!cache_.Open(progress_, true)) { pop:
3369 bool warning(!_error->PopMessage(error));
3370 lprintf("cache_.Open():[%s]\n", error.c_str());
3372 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3373 [delegate_ repairWithSelector:@selector(configure)];
3374 else if (error == "The package lists or status file could not be parsed or opened.")
3375 [delegate_ repairWithSelector:@selector(update)];
3376 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3377 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3378 // else if (error == "The list of sources could not be read.")
3380 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3389 unlink("/tmp/cydia.chk");
3391 now_ = [[NSDate date] timeIntervalSince1970];
3393 policy_ = new pkgDepCache::Policy();
3394 records_ = new pkgRecords(cache_);
3395 resolver_ = new pkgProblemResolver(cache_);
3396 fetcher_ = new pkgAcquire(&status_);
3399 list_ = new pkgSourceList();
3400 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3403 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3404 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3408 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3411 if (cache_->BrokenCount() != 0) {
3412 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3415 if (cache_->BrokenCount() != 0) {
3416 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3420 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3424 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3425 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3426 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3427 // XXX: this could be more intelligent
3428 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3429 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3431 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3436 /*std::vector<Package *> packages;
3437 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3438 [packages_ release];
3443 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3444 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3445 //packages.push_back(package);
3446 CFArrayAppendValue(packages_, [package retain]);
3450 /*if (packages.empty())
3451 packages_ = [[NSArray alloc] init];
3453 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3456 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3457 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3458 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3466 /*if (!packages.empty())
3467 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3468 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3470 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3472 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3474 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3478 size_t count(CFArrayGetCount(packages_));
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_];
3501 system([dpkg UTF8String]);
3505 // XXX: I don't remember this condition
3510 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3512 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3514 if ([self popErrorWithTitle:title])
3518 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3521 public pkgArchiveCleaner
3524 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3529 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3536 fetcher_->Shutdown();
3538 pkgRecords records(cache_);
3540 lock_ = new FileFd();
3541 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3543 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3545 if ([self popErrorWithTitle:title])
3549 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3552 manager_ = (_system->CreatePM(cache_));
3553 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3560 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3562 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3564 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3566 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3567 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3570 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3575 bool failed = false;
3576 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3577 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3579 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3582 std::string uri = (*item)->DescURI();
3583 std::string error = (*item)->ErrorText;
3585 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3588 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3589 withObject:[NSArray arrayWithObjects:
3590 [NSString stringWithUTF8String:error.c_str()],
3602 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3604 if (_error->PendingError()) {
3609 if (result == pkgPackageManager::Failed) {
3614 if (result != pkgPackageManager::Completed) {
3619 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3621 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3623 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3624 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3627 if (![before isEqualToArray:after])
3632 NSString *title(UCLocalize("UPGRADE"));
3633 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3639 [self updateWithStatus:status_];
3642 - (void) updateWithStatus:(Status &)status {
3643 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3644 NSString *title(UCLocalize("REFRESHING_DATA"));
3647 if (!list.ReadMainList())
3648 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3651 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3652 if ([self popErrorWithTitle:title])
3655 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3656 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */
3657 /* XXX: why the hell is an empty if statement a clang error? */ (void) 0;
3659 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3663 - (void) setDelegate:(id)delegate {
3664 delegate_ = delegate;
3665 status_.setDelegate(delegate);
3666 progress_.setDelegate(delegate);
3669 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3670 SourceMap::const_iterator i(sources_.find(file->ID));
3671 return i == sources_.end() ? nil : i->second;
3677 /* Confirmation Controller {{{ */
3678 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3679 if (!iterator.end())
3680 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3681 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3683 pkgCache::PkgIterator package(dep.TargetPkg());
3686 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3694 /* Web Scripting {{{ */
3695 @interface CydiaObject : NSObject {
3697 _transient id delegate_;
3700 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3703 @implementation CydiaObject
3706 [indirect_ release];
3710 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3711 if ((self = [super init]) != nil) {
3712 indirect_ = [indirect retain];
3716 - (void) setDelegate:(id)delegate {
3717 delegate_ = delegate;
3720 + (NSArray *) _attributeKeys {
3721 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3724 - (NSArray *) attributeKeys {
3725 return [[self class] _attributeKeys];
3728 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3729 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3732 - (NSString *) device {
3733 return [[UIDevice currentDevice] uniqueIdentifier];
3736 #if 0 // XXX: implement!
3737 - (NSString *) mac {
3738 if (![indirect_ promptForSensitive:@"Mac Address"])
3742 - (NSString *) serial {
3743 if (![indirect_ promptForSensitive:@"Serial #"])
3747 - (NSString *) firewire {
3748 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3752 - (NSString *) imei {
3753 if (![indirect_ promptForSensitive:@"IMEI"])
3758 + (NSString *) webScriptNameForSelector:(SEL)selector {
3759 if (selector == @selector(close))
3761 else if (selector == @selector(getInstalledPackages))
3762 return @"getInstalledPackages";
3763 else if (selector == @selector(getPackageById:))
3764 return @"getPackageById";
3765 else if (selector == @selector(installPackages:))
3766 return @"installPackages";
3767 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3768 return @"setButtonImage";
3769 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3770 return @"setButtonTitle";
3771 else if (selector == @selector(setPopupHook:))
3772 return @"setPopupHook";
3773 else if (selector == @selector(setSpecial:))
3774 return @"setSpecial";
3775 else if (selector == @selector(setToken:))
3777 else if (selector == @selector(setViewportWidth:))
3778 return @"setViewportWidth";
3779 else if (selector == @selector(supports:))
3781 else if (selector == @selector(stringWithFormat:arguments:))
3783 else if (selector == @selector(localizedStringForKey:value:table:))
3785 else if (selector == @selector(du:))
3787 else if (selector == @selector(statfs:))
3793 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3794 return [self webScriptNameForSelector:selector] == nil;
3797 - (BOOL) supports:(NSString *)feature {
3798 return [feature isEqualToString:@"window.open"];
3801 - (NSArray *) getInstalledPackages {
3802 NSArray *packages([[Database sharedInstance] packages]);
3803 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
3804 for (Package *package in packages)
3805 if ([package installed] != nil)
3806 [installed addObject:package];
3810 - (Package *) getPackageById:(NSString *)id {
3811 Package *package([[Database sharedInstance] packageWithName:id]);
3816 - (NSArray *) statfs:(NSString *)path {
3819 if (path == nil || statfs([path UTF8String], &stat) == -1)
3822 return [NSArray arrayWithObjects:
3823 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3824 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3825 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3829 - (NSNumber *) du:(NSString *)path {
3830 NSNumber *value(nil);
3833 _assert(pipe(fds) != -1);
3835 pid_t pid(ExecFork());
3837 _assert(dup2(fds[1], 1) != -1);
3838 _assert(close(fds[0]) != -1);
3839 _assert(close(fds[1]) != -1);
3840 /* XXX: this should probably not use du */
3841 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3846 _assert(close(fds[1]) != -1);
3848 if (FILE *du = fdopen(fds[0], "r")) {
3850 while (fgets(line, sizeof(line), du) != NULL) {
3851 size_t length(strlen(line));
3852 while (length != 0 && line[length - 1] == '\n')
3853 line[--length] = '\0';
3854 if (char *tab = strchr(line, '\t')) {
3856 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3861 } else _assert(close(fds[0]));
3865 if (waitpid(pid, &status, 0) == -1)
3868 else _assert(false);
3877 - (void) installPackages:(NSArray *)packages {
3878 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
3881 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3882 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3885 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3886 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3889 - (void) setSpecial:(id)function {
3890 [indirect_ setSpecial:function];
3893 - (void) setToken:(NSString *)token {
3896 Token_ = [token retain];
3898 [Metadata_ setObject:Token_ forKey:@"Token"];
3902 - (void) setPopupHook:(id)function {
3903 [indirect_ setPopupHook:function];
3906 - (void) setViewportWidth:(float)width {
3907 [indirect_ setViewportWidth:width];
3910 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3911 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3912 unsigned count([arguments count]);
3914 for (unsigned i(0); i != count; ++i)
3915 values[i] = [arguments objectAtIndex:i];
3916 return [[[NSString alloc] initWithFormat:format arguments:*(reinterpret_cast<va_list *>(&values))] autorelease];
3919 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3920 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3922 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3924 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3930 /* Cydia Browser Controller {{{ */
3931 @interface CYBrowserController : BrowserController {
3932 CydiaObject *cydia_;
3937 @implementation CYBrowserController
3944 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
3947 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3948 [super webView:view didClearWindowObject:window forFrame:frame];
3950 WebDataSource *source([frame dataSource]);
3951 NSURLResponse *response([source response]);
3952 NSURL *url([response URL]);
3953 NSString *scheme([url scheme]);
3955 NSHTTPURLResponse *http;
3956 if (scheme != nil && ([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"]))
3957 http = (NSHTTPURLResponse *) response;
3961 NSDictionary *headers([http allHeaderFields]);
3962 NSString *host([url host]);
3963 [self setHeaders:headers forHost:host];
3966 [host isEqualToString:@"cydia.saurik.com"] ||
3967 [host hasSuffix:@".cydia.saurik.com"] ||
3968 [scheme isEqualToString:@"file"]
3970 [window setValue:cydia_ forKey:@"cydia"];
3973 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
3974 if (System_ != NULL)
3975 [request setValue:System_ forHTTPHeaderField:@"X-System"];
3976 if (Machine_ != NULL)
3977 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
3979 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
3981 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
3984 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
3985 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
3986 [self _setMoreHeaders:copy];
3990 - (void) setDelegate:(id)delegate {
3991 [super setDelegate:delegate];
3992 [cydia_ setDelegate:delegate];
3996 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
3997 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
3999 WebView *webview([[webview_ _documentView] webView]);
4001 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
4003 NSString *application = package == nil ? @"Cydia" : [NSString
4004 stringWithFormat:@"Cydia/%@",
4009 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4011 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4012 if (Product_ != nil)
4013 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4015 [webview setApplicationNameForUserAgent:application];
4022 /* Confirmation {{{ */
4023 @protocol ConfirmationControllerDelegate
4024 - (void) cancelAndClear:(bool)clear;
4025 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4029 @interface ConfirmationController : CYBrowserController {
4030 _transient Database *database_;
4031 UIAlertView *essential_;
4038 - (id) initWithDatabase:(Database *)database;
4042 @implementation ConfirmationController
4049 if (essential_ != nil)
4050 [essential_ release];
4054 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4055 NSString *context([alert context]);
4057 if ([context isEqualToString:@"remove"]) {
4058 if (button == [alert cancelButtonIndex]) {
4059 [self dismissModalViewControllerAnimated:YES];
4060 } else if (button == [alert firstOtherButtonIndex]) {
4063 [delegate_ confirmWithNavigationController:[self navigationController]];
4066 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4067 } else if ([context isEqualToString:@"unable"]) {
4068 [self dismissModalViewControllerAnimated:YES];
4069 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4071 [super alertView:alert clickedButtonAtIndex:button];
4075 - (void) _doContinue {
4076 [self dismissModalViewControllerAnimated:YES];
4077 [delegate_ cancelAndClear:NO];
4080 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4081 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4085 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4086 [super webView:view didClearWindowObject:window forFrame:frame];
4087 [window setValue:changes_ forKey:@"changes"];
4088 [window setValue:issues_ forKey:@"issues"];
4089 [window setValue:sizes_ forKey:@"sizes"];
4090 [window setValue:self forKey:@"queue"];
4093 - (id) initWithDatabase:(Database *)database {
4094 if ((self = [super init]) != nil) {
4095 database_ = database;
4097 [[self navigationItem] setTitle:UCLocalize("CONFIRM")];
4099 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
4100 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
4101 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
4102 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
4103 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
4107 pkgDepCache::Policy *policy([database_ policy]);
4109 pkgCacheFile &cache([database_ cache]);
4110 NSArray *packages = [database_ packages];
4111 for (Package *package in packages) {
4112 pkgCache::PkgIterator iterator = [package iterator];
4113 pkgDepCache::StateCache &state(cache[iterator]);
4115 NSString *name([package name]);
4117 if (state.NewInstall())
4118 [installing addObject:name];
4119 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4120 [reinstalling addObject:name];
4121 else if (state.Upgrade())
4122 [upgrading addObject:name];
4123 else if (state.Downgrade())
4124 [downgrading addObject:name];
4125 else if (state.Delete()) {
4126 if ([package essential])
4128 [removing addObject:name];
4131 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4132 substrate_ |= DepSubstrate(iterator.CurrentVer());
4137 else if (Advanced_) {
4138 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4140 essential_ = [[UIAlertView alloc]
4141 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4142 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4144 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4145 otherButtonTitles:[NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")], nil
4148 [essential_ setContext:@"remove"];
4150 essential_ = [[UIAlertView alloc]
4151 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4152 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4154 cancelButtonTitle:UCLocalize("OKAY")
4155 otherButtonTitles:nil
4158 [essential_ setContext:@"unable"];
4161 changes_ = [[NSArray alloc] initWithObjects:
4169 issues_ = [database_ issues];
4171 issues_ = [issues_ retain];
4173 sizes_ = [[NSArray alloc] initWithObjects:
4174 SizeString([database_ fetcher].FetchNeeded()),
4175 SizeString([database_ fetcher].PartialPresent()),
4178 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
4180 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
4181 initWithTitle:UCLocalize("CANCEL")
4182 // OLD: [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")]
4183 style:UIBarButtonItemStylePlain
4185 action:@selector(cancelButtonClicked)
4190 - (void) applyRightButton {
4191 #if !AlwaysReload && !IgnoreInstall
4192 if (issues_ == nil && ![self isLoading])
4193 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4194 initWithTitle:UCLocalize("CONFIRM")
4195 style:UIBarButtonItemStylePlain
4197 action:@selector(confirmButtonClicked)
4200 [super applyRightButton];
4202 [[self navigationItem] setRightBarButtonItem:nil];
4206 - (void) cancelButtonClicked {
4207 [self dismissModalViewControllerAnimated:YES];
4208 [delegate_ cancelAndClear:YES];
4212 - (void) confirmButtonClicked {
4216 if (essential_ != nil)
4221 [delegate_ confirmWithNavigationController:[self navigationController]];
4229 /* Progress Data {{{ */
4230 @interface ProgressData : NSObject {
4232 // XXX: should these really both be _transient?
4233 _transient id target_;
4234 _transient id object_;
4237 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4244 @implementation ProgressData
4246 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4247 if ((self = [super init]) != nil) {
4248 selector_ = selector;
4268 /* Progress Controller {{{ */
4269 @interface ProgressController : CYViewController <
4270 ConfigurationDelegate,
4273 _transient Database *database_;
4274 UIProgressBar *progress_;
4275 UITextView *output_;
4276 UITextLabel *status_;
4277 UIPushButton *close_;
4279 SHA1SumValue springlist_;
4280 SHA1SumValue notifyconf_;
4284 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4286 - (void) _retachThread;
4287 - (void) _detachNewThreadData:(ProgressData *)data;
4288 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4294 @protocol ProgressControllerDelegate
4295 - (void) progressControllerIsComplete:(ProgressController *)sender;
4298 @implementation ProgressController
4301 [database_ setDelegate:nil];
4302 [progress_ release];
4311 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4312 if ((self = [super init]) != nil) {
4313 database_ = database;
4314 [database_ setDelegate:self];
4315 delegate_ = delegate;
4317 [[self view] setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
4319 progress_ = [[UIProgressBar alloc] init];
4320 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4321 [progress_ setStyle:0];
4323 status_ = [[UITextLabel alloc] init];
4324 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4325 [status_ setColor:[UIColor whiteColor]];
4326 [status_ setBackgroundColor:[UIColor clearColor]];
4327 [status_ setCentersHorizontally:YES];
4328 //[status_ setFont:font];
4330 output_ = [[UITextView alloc] init];
4332 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4333 //[output_ setTextFont:@"Courier New"];
4334 [output_ setFont:[[output_ font] fontWithSize:12]];
4335 [output_ setTextColor:[UIColor whiteColor]];
4336 [output_ setBackgroundColor:[UIColor clearColor]];
4337 [output_ setMarginTop:0];
4338 [output_ setAllowsRubberBanding:YES];
4339 [output_ setEditable:NO];
4340 [[self view] addSubview:output_];
4342 close_ = [[UIPushButton alloc] init];
4343 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4344 [close_ setAutosizesToFit:NO];
4345 [close_ setDrawsShadow:YES];
4346 [close_ setStretchBackground:YES];
4347 [close_ setEnabled:YES];
4348 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
4349 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4350 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4351 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4355 - (void) positionViews {
4356 CGRect bounds = [[self view] bounds];
4357 CGSize prgsize = [UIProgressBar defaultSize];
4360 (bounds.size.width - prgsize.width) / 2,
4361 bounds.size.height - prgsize.height - 20
4364 float closewidth = std::min(bounds.size.width - 20, 300.0f);
4366 [progress_ setFrame:prgrect];
4367 [status_ setFrame:CGRectMake(
4369 bounds.size.height - prgsize.height - 50,
4370 bounds.size.width - 20,
4373 [output_ setFrame:CGRectMake(
4376 bounds.size.width - 20,
4377 bounds.size.height - 62
4379 [close_ setFrame:CGRectMake(
4380 (bounds.size.width - closewidth) / 2,
4381 bounds.size.height - prgsize.height - 50,
4387 - (void) viewWillAppear:(BOOL)animated {
4388 [super viewDidAppear:animated];
4389 [[self navigationItem] setHidesBackButton:YES];
4390 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4392 [self positionViews];
4395 - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4396 [self positionViews];
4399 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4400 NSString *context([alert context]);
4402 if ([context isEqualToString:@"conffile"]) {
4403 FILE *input = [database_ input];
4404 if (button == [alert cancelButtonIndex])
4405 fprintf(input, "N\n");
4406 else if (button == [alert firstOtherButtonIndex])
4407 fprintf(input, "Y\n");
4412 - (void) closeButtonPushed {
4415 UpdateExternalStatus(0);
4419 [self dismissModalViewControllerAnimated:YES];
4423 [delegate_ terminateWithSuccess];
4424 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4425 [delegate_ suspendWithAnimation:YES];
4427 [delegate_ suspend];*/
4431 system("launchctl stop com.apple.SpringBoard");
4435 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
4444 - (void) _retachThread {
4445 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
4447 [[self view] addSubview:close_];
4448 [progress_ removeFromSuperview];
4449 [status_ removeFromSuperview];
4451 [database_ popErrorWithTitle:title_];
4452 [delegate_ progressControllerIsComplete:self];
4456 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4459 MMap mmap(file, MMap::ReadOnly);
4461 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4462 if (!(notifyconf_ == sha1.Result()))
4469 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4472 MMap mmap(file, MMap::ReadOnly);
4474 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4475 if (!(springlist_ == sha1.Result()))
4481 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
4482 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4483 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4484 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4485 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4488 system("su -c /usr/bin/uicache mobile");
4490 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
4492 [delegate_ setStatusBarShowsProgress:NO];
4495 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4496 [[data target] performSelector:[data selector] withObject:[data object]];
4497 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4500 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4501 UpdateExternalStatus(1);
4508 title_ = [title retain];
4510 [[self navigationItem] setTitle:title_];
4512 [status_ setText:nil];
4513 [output_ setText:@""];
4514 [progress_ setProgress:0];
4516 [close_ removeFromSuperview];
4517 [[self view] addSubview:progress_];
4518 [[self view] addSubview:status_];
4520 [delegate_ setStatusBarShowsProgress:YES];
4525 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4528 MMap mmap(file, MMap::ReadOnly);
4530 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4531 notifyconf_ = sha1.Result();
4537 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4540 MMap mmap(file, MMap::ReadOnly);
4542 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4543 springlist_ = sha1.Result();
4548 detachNewThreadSelector:@selector(_detachNewThreadData:)
4550 withObject:[[[ProgressData alloc]
4551 initWithSelector:selector
4558 - (void) repairWithSelector:(SEL)selector {
4560 detachNewThreadSelector:selector
4563 title:UCLocalize("REPAIRING")
4567 - (void) setConfigurationData:(NSString *)data {
4569 performSelectorOnMainThread:@selector(_setConfigurationData:)
4575 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4576 CYActionSheet *sheet([[[CYActionSheet alloc]
4578 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4579 defaultButtonIndex:0
4582 [sheet setMessage:error];
4583 [sheet yieldToPopupAlertAnimated:YES];
4587 - (void) setProgressTitle:(NSString *)title {
4589 performSelectorOnMainThread:@selector(_setProgressTitle:)
4595 - (void) setProgressPercent:(float)percent {
4597 performSelectorOnMainThread:@selector(_setProgressPercent:)
4598 withObject:[NSNumber numberWithFloat:percent]
4603 - (void) startProgress {
4606 - (void) addProgressOutput:(NSString *)output {
4608 performSelectorOnMainThread:@selector(_addProgressOutput:)
4614 - (bool) isCancelling:(size_t)received {
4618 - (void) _setConfigurationData:(NSString *)data {
4619 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4621 if (!conffile_r(data)) {
4622 lprintf("E:invalid conffile\n");
4626 NSString *ofile = conffile_r[1];
4627 //NSString *nfile = conffile_r[2];
4629 UIAlertView *alert = [[[UIAlertView alloc]
4630 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4631 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
4633 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
4634 otherButtonTitles:UCLocalize("ACCEPT_NEW_COPY"),
4635 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4639 [alert setContext:@"conffile"];
4643 - (void) _setProgressTitle:(NSString *)title {
4644 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4645 for (size_t i(0), e([words count]); i != e; ++i) {
4646 NSString *word([words objectAtIndex:i]);
4647 if (Package *package = [database_ packageWithName:word])
4648 [words replaceObjectAtIndex:i withObject:[package name]];
4651 [status_ setText:[words componentsJoinedByString:@" "]];
4654 - (void) _setProgressPercent:(NSNumber *)percent {
4655 [progress_ setProgress:[percent floatValue]];
4658 - (void) _addProgressOutput:(NSString *)output {
4659 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4660 CGSize size = [output_ contentSize];
4661 CGRect rect = {{0, size.height}, {size.width, 0}};
4662 [output_ scrollRectToVisible:rect animated:YES];
4665 - (BOOL) isRunning {
4672 /* Cell Content View {{{ */
4673 @protocol ContentDelegate
4674 - (void) drawContentRect:(CGRect)rect;
4677 @interface ContentView : UIView {
4678 _transient id<ContentDelegate> delegate_;
4683 @implementation ContentView
4685 - (id) initWithFrame:(CGRect)frame {
4686 if ((self = [super initWithFrame:frame]) != nil) {
4687 [self setNeedsDisplayOnBoundsChange:YES];
4691 - (void) setDelegate:(id<ContentDelegate>)delegate {
4692 delegate_ = delegate;
4695 - (void) drawRect:(CGRect)rect {
4696 [super drawRect:rect];
4697 [delegate_ drawContentRect:rect];
4702 /* Cydia TableView Cell {{{ */
4703 @interface CYTableViewCell : UITableViewCell {
4704 ContentView *content_;
4710 @implementation CYTableViewCell
4717 - (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
4718 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
4720 if (view == content_) {
4721 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
4722 highlighted_ = highlighted;
4725 [super _updateHighlightColorsForView:view highlighted:highlighted];
4728 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
4729 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
4730 highlighted_ = selected;
4732 [super setSelected:selected animated:animated];
4733 [content_ setNeedsDisplay];
4738 /* Package Cell {{{ */
4739 @interface PackageCell : CYTableViewCell <
4744 NSString *description_;
4752 - (PackageCell *) init;
4753 - (void) setPackage:(Package *)package;
4755 + (int) heightForPackage:(Package *)package;
4756 - (void) drawContentRect:(CGRect)rect;
4760 @implementation PackageCell
4762 - (void) clearPackage {
4773 if (description_ != nil) {
4774 [description_ release];
4778 if (source_ != nil) {
4783 if (badge_ != nil) {
4788 if (placard_ != nil) {
4798 [self clearPackage];
4802 - (PackageCell *) init {
4803 CGRect frame(CGRectMake(0, 0, 320, 74));
4804 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4805 UIView *content([self contentView]);
4806 CGRect bounds([content bounds]);
4808 content_ = [[ContentView alloc] initWithFrame:bounds];
4809 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4810 [content addSubview:content_];
4812 [content_ setDelegate:self];
4813 [content_ setOpaque:YES];
4817 - (void) _setBackgroundColor {
4819 if (NSString *mode = [package_ mode]) {
4820 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4821 color = remove ? RemovingColor_ : InstallingColor_;
4823 color = [UIColor whiteColor];
4825 [content_ setBackgroundColor:color];
4826 [self setNeedsDisplay];
4829 - (void) setPackage:(Package *)package {
4830 [self clearPackage];
4833 Source *source = [package source];
4835 icon_ = [[package icon] retain];
4836 name_ = [[package name] retain];
4839 description_ = [package longDescription];
4840 if (description_ == nil)
4841 description_ = [package shortDescription];
4842 if (description_ != nil)
4843 description_ = [description_ retain];
4845 commercial_ = [package isCommercial];
4847 package_ = [package retain];
4849 NSString *label = nil;
4850 bool trusted = false;
4852 if (source != nil) {
4853 label = [source label];
4854 trusted = [source trusted];
4855 } else if ([[package id] isEqualToString:@"firmware"])
4856 label = UCLocalize("APPLE");
4858 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
4860 NSString *from(label);
4862 NSString *section = [package simpleSection];
4863 if (section != nil && ![section isEqualToString:label]) {
4864 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4865 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
4868 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
4869 source_ = [from retain];
4871 if (NSString *purpose = [package primaryPurpose])
4872 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4873 badge_ = [badge_ retain];
4875 if ([package installed] != nil)
4876 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/installed.png", App_]]) != nil)
4877 placard_ = [placard_ retain];
4879 [self _setBackgroundColor];
4880 [content_ setNeedsDisplay];
4883 - (void) drawContentRect:(CGRect)rect {
4884 bool highlighted(highlighted_);
4885 float width([self bounds].size.width);
4888 CGContextRef context(UIGraphicsGetCurrentContext());
4889 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
4890 CGContextFillRect(context, rect);
4895 rect.size = [icon_ size];
4897 rect.size.width /= 2;
4898 rect.size.height /= 2;
4900 rect.origin.x = 25 - rect.size.width / 2;
4901 rect.origin.y = 25 - rect.size.height / 2;
4903 [icon_ drawInRect:rect];
4906 if (badge_ != nil) {
4907 CGSize size = [badge_ size];
4909 [badge_ drawAtPoint:CGPointMake(
4910 36 - size.width / 2,
4911 36 - size.height / 2
4919 UISetColor(commercial_ ? Purple_ : Black_);
4920 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
4921 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
4924 UISetColor(commercial_ ? Purplish_ : Gray_);
4925 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
4927 if (placard_ != nil)
4928 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
4931 + (int) heightForPackage:(Package *)package {
4937 /* Section Cell {{{ */
4938 @interface SectionCell : CYTableViewCell <
4950 - (void) setSection:(Section *)section editing:(BOOL)editing;
4954 @implementation SectionCell
4956 - (void) clearSection {
4957 if (basic_ != nil) {
4962 if (section_ != nil) {
4972 if (count_ != nil) {
4979 [self clearSection];
4985 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
4986 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
4987 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4988 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4989 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
4991 UIView *content([self contentView]);
4992 CGRect bounds([content bounds]);
4994 content_ = [[ContentView alloc] initWithFrame:bounds];
4995 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4996 [content addSubview:content_];
4997 [content_ setBackgroundColor:[UIColor whiteColor]];
4999 [content_ setDelegate:self];
5003 - (void) onSwitch:(id)sender {
5004 NSMutableDictionary *metadata = [Sections_ objectForKey:basic_];
5005 if (metadata == nil) {
5006 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5007 [Sections_ setObject:metadata forKey:basic_];
5011 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5014 - (void) setSection:(Section *)section editing:(BOOL)editing {
5015 if (editing != editing_) {
5017 [switch_ removeFromSuperview];
5019 [self addSubview:switch_];
5023 [self clearSection];
5025 if (section == nil) {
5026 name_ = [UCLocalize("ALL_PACKAGES") retain];
5029 basic_ = [section name];
5031 basic_ = [basic_ retain];
5033 section_ = [section localized];
5034 if (section_ != nil)
5035 section_ = [section_ retain];
5037 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
5038 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
5041 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5044 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5045 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5047 [content_ setNeedsDisplay];
5050 - (void) setFrame:(CGRect)frame {
5051 [super setFrame:frame];
5053 CGRect rect([switch_ frame]);
5054 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5057 - (void) drawContentRect:(CGRect)rect {
5058 bool highlighted(highlighted_);
5060 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5065 float width(rect.size.width);
5071 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5073 CGSize size = [count_ sizeWithFont:Font14_];
5077 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5083 /* File Table {{{ */
5084 @interface FileTable : CYViewController <
5085 UITableViewDataSource,
5088 _transient Database *database_;
5091 NSMutableArray *files_;
5095 - (id) initWithDatabase:(Database *)database;
5096 - (void) setPackage:(Package *)package;
5100 @implementation FileTable
5103 if (package_ != nil)
5112 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5113 return files_ == nil ? 0 : [files_ count];
5116 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5120 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5121 static NSString *reuseIdentifier = @"Cell";
5123 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5125 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5126 [cell setFont:[UIFont systemFontOfSize:16]];
5128 [cell setText:[files_ objectAtIndex:indexPath.row]];
5129 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5134 - (id) initWithDatabase:(Database *)database {
5135 if ((self = [super init]) != nil) {
5136 database_ = database;
5138 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5140 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5142 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5143 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5144 [list_ setRowHeight:24.0f];
5145 [[self view] addSubview:list_];
5147 [list_ setDataSource:self];
5148 [list_ setDelegate:self];
5152 - (void) setPackage:(Package *)package {
5153 if (package_ != nil) {
5154 [package_ autorelease];
5163 [files_ removeAllObjects];
5165 if (package != nil) {
5166 package_ = [package retain];
5167 name_ = [[package id] retain];
5169 if (NSArray *files = [package files])
5170 [files_ addObjectsFromArray:files];
5172 if ([files_ count] != 0) {
5173 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5174 [files_ removeObjectAtIndex:0];
5175 [files_ sortUsingSelector:@selector(compareByPath:)];
5177 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5178 [stack addObject:@"/"];
5180 for (int i(0), e([files_ count]); i != e; ++i) {
5181 NSString *file = [files_ objectAtIndex:i];
5182 while (![file hasPrefix:[stack lastObject]])
5183 [stack removeLastObject];
5184 NSString *directory = [stack lastObject];
5185 [stack addObject:[file stringByAppendingString:@"/"]];
5186 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5187 ([stack count] - 2) * 3, "",
5188 [file substringFromIndex:[directory length]]
5197 - (void) reloadData {
5198 [self setPackage:[database_ packageWithName:name_]];
5203 /* Package Controller {{{ */
5204 @interface PackageController : CYBrowserController <
5205 UIActionSheetDelegate
5207 _transient Database *database_;
5211 NSMutableArray *buttons_;
5212 UIBarButtonItem *button_;
5215 - (id) initWithDatabase:(Database *)database;
5216 - (void) setPackage:(Package *)package;
5220 @implementation PackageController
5223 if (package_ != nil)
5237 if ([self retainCount] == 1)
5238 [delegate_ setPackageController:self];
5242 /* XXX: this is not safe at all... localization of /fail/ */
5243 - (void) _clickButtonWithName:(NSString *)name {
5244 if ([name isEqualToString:UCLocalize("CLEAR")])
5245 [delegate_ clearPackage:package_];
5246 else if ([name isEqualToString:UCLocalize("INSTALL")])
5247 [delegate_ installPackage:package_];
5248 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5249 [delegate_ installPackage:package_];
5250 else if ([name isEqualToString:UCLocalize("REMOVE")])
5251 [delegate_ removePackage:package_];
5252 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5253 [delegate_ installPackage:package_];
5254 else _assert(false);
5257 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5258 NSString *context([sheet context]);
5260 if ([context isEqualToString:@"modify"]) {
5261 if (button != [sheet cancelButtonIndex]) {
5262 NSString *buttonName = [buttons_ objectAtIndex:button];
5263 [self _clickButtonWithName:buttonName];
5266 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5270 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5271 [super webView:view didClearWindowObject:window forFrame:frame];
5272 [window setValue:package_ forKey:@"package"];
5275 - (bool) _allowJavaScriptPanel {
5280 - (void) _customButtonClicked {
5281 int count([buttons_ count]);
5286 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5288 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5289 [buttons addObjectsFromArray:buttons_];
5291 UIActionSheet *sheet = [[[UIActionSheet alloc]
5294 cancelButtonTitle:nil
5295 destructiveButtonTitle:nil
5296 otherButtonTitles:nil
5299 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5301 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5302 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5304 [sheet setContext:@"modify"];
5306 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5310 // We don't want to allow non-commercial packages to do custom things to the install button,
5311 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5312 - (void) customButtonClicked {
5314 [super customButtonClicked];
5316 [self _customButtonClicked];
5319 - (void) reloadButtonClicked {
5320 // Don't reload a package view by clicking the button.
5323 - (void) applyLoadingTitle {
5324 // Don't show "Loading" as the title. Ever.
5327 - (UIBarButtonItem *) rightButton {
5332 - (id) initWithDatabase:(Database *)database {
5333 if ((self = [super init]) != nil) {
5334 database_ = database;
5335 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5336 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
5340 - (void) setPackage:(Package *)package {
5341 if (package_ != nil) {
5342 [package_ autorelease];
5351 [buttons_ removeAllObjects];
5353 if (package != nil) {
5356 package_ = [package retain];
5357 name_ = [[package id] retain];
5358 commercial_ = [package isCommercial];
5360 if ([package_ mode] != nil)
5361 [buttons_ addObject:UCLocalize("CLEAR")];
5362 if ([package_ source] == nil);
5363 else if ([package_ upgradableAndEssential:NO])
5364 [buttons_ addObject:UCLocalize("UPGRADE")];
5365 else if ([package_ uninstalled])
5366 [buttons_ addObject:UCLocalize("INSTALL")];
5368 [buttons_ addObject:UCLocalize("REINSTALL")];
5369 if (![package_ uninstalled])
5370 [buttons_ addObject:UCLocalize("REMOVE")];
5377 switch ([buttons_ count]) {
5378 case 0: title = nil; break;
5379 case 1: title = [buttons_ objectAtIndex:0]; break;
5380 default: title = UCLocalize("MODIFY"); break;
5383 button_ = [[UIBarButtonItem alloc]
5385 style:UIBarButtonItemStylePlain
5387 action:@selector(customButtonClicked)
5393 - (bool) isLoading {
5394 return commercial_ ? [super isLoading] : false;
5397 - (void) reloadData {
5398 [self setPackage:[database_ packageWithName:name_]];
5403 /* Package Table {{{ */
5404 @interface PackageTable : UIView <
5405 UITableViewDataSource,
5408 _transient Database *database_;
5409 NSMutableArray *packages_;
5410 NSMutableArray *sections_;
5412 NSMutableArray *index_;
5413 NSMutableDictionary *indices_;
5414 // XXX: this target_ seems to be delegate_. :(
5415 _transient id target_;
5417 // XXX: why do we even have this delegate_?
5418 _transient id delegate_;
5421 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action;
5423 - (void) setDelegate:(id)delegate;
5425 - (void) reloadData;
5426 - (void) resetCursor;
5428 - (UITableView *) list;
5430 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5432 - (void) deselectWithAnimation:(BOOL)animated;
5436 @implementation PackageTable
5439 [packages_ release];
5440 [sections_ release];
5448 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5449 NSInteger count([sections_ count]);
5450 return count == 0 ? 1 : count;
5453 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5454 if ([sections_ count] == 0)
5456 return [[sections_ objectAtIndex:section] name];
5459 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5460 if ([sections_ count] == 0)
5462 return [[sections_ objectAtIndex:section] count];
5465 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5466 Section *section([sections_ objectAtIndex:[path section]]);
5467 NSInteger row([path row]);
5468 Package *package([packages_ objectAtIndex:([section row] + row)]);
5472 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5473 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5475 cell = [[[PackageCell alloc] init] autorelease];
5476 [cell setPackage:[self packageAtIndexPath:path]];
5480 - (void) deselectWithAnimation:(BOOL)animated {
5481 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5484 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
5485 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
5488 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5489 Package *package([self packageAtIndexPath:path]);
5490 package = [database_ packageWithName:[package id]];
5491 [target_ performSelector:action_ withObject:package];
5495 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5496 return [packages_ count] > 20 ? index_ : nil;
5499 - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5503 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action {
5504 if ((self = [super initWithFrame:frame]) != nil) {
5505 database_ = database;
5510 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5511 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5513 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5514 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5516 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
5517 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5518 [list_ setRowHeight:73.0f];
5519 [self addSubview:list_];
5521 [list_ setDataSource:self];
5522 [list_ setDelegate:self];
5526 - (void) setDelegate:(id)delegate {
5527 delegate_ = delegate;
5530 - (bool) hasPackage:(Package *)package {
5534 - (void) reloadData {
5535 NSArray *packages = [database_ packages];
5537 [packages_ removeAllObjects];
5538 [sections_ removeAllObjects];
5540 _profile(PackageTable$reloadData$Filter)
5541 for (Package *package in packages)
5542 if ([self hasPackage:package])
5543 [packages_ addObject:package];
5546 [index_ removeAllObjects];
5547 [indices_ removeAllObjects];
5549 Section *section = nil;
5551 _profile(PackageTable$reloadData$Section)
5552 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5556 _profile(PackageTable$reloadData$Section$Package)
5557 package = [packages_ objectAtIndex:offset];
5558 index = [package index];
5561 if (section == nil || [section index] != index) {
5562 _profile(PackageTable$reloadData$Section$Allocate)
5563 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5566 [index_ addObject:[section name]];
5567 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5569 _profile(PackageTable$reloadData$Section$Add)
5570 [sections_ addObject:section];
5574 [section addToCount];
5578 _profile(PackageTable$reloadData$List)
5583 - (void) resetCursor {
5584 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5587 - (UITableView *) list {
5591 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5592 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
5597 /* Filtered Package Table {{{ */
5598 @interface FilteredPackageTable : PackageTable {
5604 - (void) setObject:(id)object;
5605 - (void) setObject:(id)object forFilter:(SEL)filter;
5607 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object;
5611 @implementation FilteredPackageTable
5619 - (void) setFilter:(SEL)filter {
5622 /* XXX: this is an unsafe optimization of doomy hell */
5623 Method method(class_getInstanceMethod([Package class], filter));
5624 _assert(method != NULL);
5625 imp_ = method_getImplementation(method);
5626 _assert(imp_ != NULL);
5629 - (void) setObject:(id)object {
5635 object_ = [object retain];
5638 - (void) setObject:(id)object forFilter:(SEL)filter {
5639 [self setFilter:filter];
5640 [self setObject:object];
5643 - (bool) hasPackage:(Package *)package {
5644 _profile(FilteredPackageTable$hasPackage)
5645 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5649 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object {
5650 if ((self = [super initWithFrame:frame database:database target:target action:action]) != nil) {
5651 [self setFilter:filter];
5652 object_ = [object retain];
5660 /* Filtered Package Controller {{{ */
5661 @interface FilteredPackageController : CYViewController {
5662 _transient Database *database_;
5663 FilteredPackageTable *packages_;
5667 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5671 @implementation FilteredPackageController
5674 [packages_ release];
5680 - (void) viewDidAppear:(BOOL)animated {
5681 [super viewDidAppear:animated];
5682 [packages_ deselectWithAnimation:animated];
5685 - (void) didSelectPackage:(Package *)package {
5686 PackageController *view([delegate_ packageController]);
5687 [view setPackage:package];
5688 [view setDelegate:delegate_];
5689 [[self navigationController] pushViewController:view animated:YES];
5692 - (NSString *) title { return title_; }
5694 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5695 if ((self = [super init]) != nil) {
5696 database_ = database;
5697 title_ = [title copy];
5698 [[self navigationItem] setTitle:title_];
5700 packages_ = [[FilteredPackageTable alloc]
5701 initWithFrame:[[self view] bounds]
5704 action:@selector(didSelectPackage:)
5709 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5710 [[self view] addSubview:packages_];
5714 - (void) reloadData {
5715 [packages_ reloadData];
5718 - (void) setDelegate:(id)delegate {
5719 [super setDelegate:delegate];
5720 [packages_ setDelegate:delegate];
5727 /* Add Source Controller {{{ */
5728 @interface AddSourceController : CYViewController {
5729 _transient Database *database_;
5732 - (id) initWithDatabase:(Database *)database;
5736 @implementation AddSourceController
5738 - (id) initWithDatabase:(Database *)database {
5739 if ((self = [super init]) != nil) {
5740 database_ = database;
5746 /* Source Cell {{{ */
5747 @interface SourceCell : CYTableViewCell <
5752 NSString *description_;
5756 - (void) setSource:(Source *)source;
5760 @implementation SourceCell
5762 - (void) clearSource {
5765 [description_ release];
5774 - (void) setSource:(Source *)source {
5778 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5780 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5781 icon_ = [icon_ retain];
5783 origin_ = [[source name] retain];
5784 label_ = [[source uri] retain];
5785 description_ = [[source description] retain];
5787 [content_ setNeedsDisplay];
5795 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5796 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5797 UIView *content([self contentView]);
5798 CGRect bounds([content bounds]);
5800 content_ = [[ContentView alloc] initWithFrame:bounds];
5801 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5802 [content_ setBackgroundColor:[UIColor whiteColor]];
5803 [content addSubview:content_];
5805 [content_ setDelegate:self];
5806 [content_ setOpaque:YES];
5810 - (void) drawContentRect:(CGRect)rect {
5811 bool highlighted(highlighted_);
5812 float width(rect.size.width);
5815 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5822 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5826 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5830 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 40) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5835 /* Source Table {{{ */
5836 @interface SourceTable : CYViewController <
5837 UITableViewDataSource,
5840 _transient Database *database_;
5842 NSMutableArray *sources_;
5846 UIProgressHUD *hud_;
5849 //NSURLConnection *installer_;
5850 NSURLConnection *trivial_;
5851 NSURLConnection *trivial_bz2_;
5852 NSURLConnection *trivial_gz_;
5853 //NSURLConnection *automatic_;
5858 - (id) initWithDatabase:(Database *)database;
5860 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
5864 @implementation SourceTable
5866 - (void) _releaseConnection:(NSURLConnection *)connection {
5867 if (connection != nil) {
5868 [connection cancel];
5869 //[connection setDelegate:nil];
5870 [connection release];
5882 //[self _releaseConnection:installer_];
5883 [self _releaseConnection:trivial_];
5884 [self _releaseConnection:trivial_gz_];
5885 [self _releaseConnection:trivial_bz2_];
5886 //[self _releaseConnection:automatic_];
5893 - (void) viewDidAppear:(BOOL)animated {
5894 [super viewDidAppear:animated];
5895 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5898 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
5899 return offset_ == 0 ? 1 : 2;
5902 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
5903 switch (section + (offset_ == 0 ? 1 : 0)) {
5904 case 0: return UCLocalize("ENTERED_BY_USER");
5905 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
5911 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5912 int count = [sources_ count];
5914 case 0: return (offset_ == 0 ? count : offset_);
5915 case 1: return count - offset_;
5921 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
5923 switch (indexPath.section) {
5924 case 0: idx = indexPath.row; break;
5925 case 1: idx = indexPath.row + offset_; break;
5929 return [sources_ objectAtIndex:idx];
5932 - (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5933 Source *source = [self sourceAtIndexPath:indexPath];
5934 return [source description] == nil ? 56 : 73;
5937 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5938 static NSString *cellIdentifier = @"SourceCell";
5940 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
5941 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
5942 [cell setSource:[self sourceAtIndexPath:indexPath]];
5947 - (UITableViewCellAccessoryType) tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath {
5948 return UITableViewCellAccessoryDisclosureIndicator;
5951 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
5952 Source *source = [self sourceAtIndexPath:indexPath];
5954 FilteredPackageController *packages = [[[FilteredPackageController alloc]
5955 initWithDatabase:database_
5956 title:[source label]
5957 filter:@selector(isVisibleInSource:)
5961 [packages setDelegate:delegate_];
5963 [[self navigationController] pushViewController:packages animated:YES];
5966 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
5967 Source *source = [self sourceAtIndexPath:indexPath];
5968 return [source record] != nil;
5971 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
5972 Source *source = [self sourceAtIndexPath:indexPath];
5973 [Sources_ removeObjectForKey:[source key]];
5974 [delegate_ syncData];
5978 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5981 @"./", @"Distribution",
5982 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5984 [delegate_ syncData];
5987 - (NSString *) getWarning {
5988 NSString *href(href_);
5989 NSRange colon([href rangeOfString:@"://"]);
5990 if (colon.location != NSNotFound)
5991 href = [href substringFromIndex:(colon.location + 3)];
5992 href = [href stringByAddingPercentEscapes];
5993 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
5994 href = [href stringByCachingURLWithCurrentCDN];
5996 NSURL *url([NSURL URLWithString:href]);
5998 NSStringEncoding encoding;
5999 NSError *error(nil);
6001 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
6002 return [warning length] == 0 ? nil : warning;
6006 - (void) _endConnection:(NSURLConnection *)connection {
6007 // XXX: the memory management in this method is horribly awkward
6009 NSURLConnection **field = NULL;
6010 if (connection == trivial_)
6012 else if (connection == trivial_bz2_)
6013 field = &trivial_bz2_;
6014 else if (connection == trivial_gz_)
6015 field = &trivial_gz_;
6016 _assert(field != NULL);
6017 [connection release];
6022 trivial_bz2_ == nil &&
6028 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
6031 UIAlertView *alert = [[[UIAlertView alloc]
6032 initWithTitle:UCLocalize("SOURCE_WARNING")
6035 cancelButtonTitle:UCLocalize("CANCEL")
6036 otherButtonTitles:UCLocalize("ADD_ANYWAY"), nil
6039 [alert setContext:@"warning"];
6040 [alert setNumberOfRows:1];
6044 } else if (error_ != nil) {
6045 UIAlertView *alert = [[[UIAlertView alloc]
6046 initWithTitle:UCLocalize("VERIFICATION_ERROR")
6047 message:[error_ localizedDescription]
6049 cancelButtonTitle:UCLocalize("OK")
6050 otherButtonTitles:nil
6053 [alert setContext:@"urlerror"];
6056 UIAlertView *alert = [[[UIAlertView alloc]
6057 initWithTitle:UCLocalize("NOT_REPOSITORY")
6058 message:UCLocalize("NOT_REPOSITORY_EX")
6060 cancelButtonTitle:UCLocalize("OK")
6061 otherButtonTitles:nil
6064 [alert setContext:@"trivial"];
6068 [delegate_ setStatusBarShowsProgress:NO];
6069 [delegate_ removeProgressHUD:hud_];
6079 if (error_ != nil) {
6086 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
6087 switch ([response statusCode]) {
6093 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
6094 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
6096 error_ = [error retain];
6097 [self _endConnection:connection];
6100 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
6101 [self _endConnection:connection];
6104 - (NSString *) title { return UCLocalize("SOURCES"); }
6106 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
6107 NSMutableURLRequest *request = [NSMutableURLRequest
6108 requestWithURL:[NSURL URLWithString:href]
6109 cachePolicy:NSURLRequestUseProtocolCachePolicy
6110 timeoutInterval:120.0
6113 [request setHTTPMethod:method];
6115 if (Machine_ != NULL)
6116 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
6117 if (UniqueID_ != nil)
6118 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6120 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
6122 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
6125 - (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
6126 NSString *context([alert context]);
6128 if ([context isEqualToString:@"source"]) {
6131 NSString *href = [[alert textField] text];
6133 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
6135 if (![href hasSuffix:@"/"])
6136 href_ = [href stringByAppendingString:@"/"];
6139 href_ = [href_ retain];
6141 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
6142 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
6143 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
6144 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
6148 // XXX: this is stupid
6149 hud_ = [[delegate_ addProgressHUD] retain];
6150 [hud_ setText:UCLocalize("VERIFYING_URL")];
6159 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6160 } else if ([context isEqualToString:@"trivial"])
6161 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6162 else if ([context isEqualToString:@"urlerror"])
6163 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6164 else if ([context isEqualToString:@"warning"]) {
6179 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6183 - (id) initWithDatabase:(Database *)database {
6184 if ((self = [super init]) != nil) {
6185 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
6186 [self updateButtonsForEditingStatus:NO animated:NO];
6188 database_ = database;
6189 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
6191 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6192 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6193 [[self view] addSubview:list_];
6195 [list_ setDataSource:self];
6196 [list_ setDelegate:self];
6202 - (void) reloadData {
6204 if (!list.ReadMainList())
6207 [sources_ removeAllObjects];
6208 [sources_ addObjectsFromArray:[database_ sources]];
6210 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
6213 int count([sources_ count]);
6215 for (int i = 0; i != count; i++) {
6216 if ([[sources_ objectAtIndex:i] record] == nil)
6221 [list_ setEditing:NO];
6222 [self updateButtonsForEditingStatus:NO animated:NO];
6226 - (void) addButtonClicked {
6227 /*[book_ pushPage:[[[AddSourceController alloc]
6232 UIAlertView *alert = [[[UIAlertView alloc]
6233 initWithTitle:UCLocalize("ENTER_APT_URL")
6236 cancelButtonTitle:UCLocalize("CANCEL")
6237 otherButtonTitles:UCLocalize("ADD_SOURCE"), nil
6240 [alert setContext:@"source"];
6241 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
6243 [alert setNumberOfRows:1];
6244 [alert addTextFieldWithValue:@"http://" label:@""];
6246 UITextInputTraits *traits = [[alert textField] textInputTraits];
6247 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6248 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6249 [traits setKeyboardType:UIKeyboardTypeURL];
6250 // XXX: UIReturnKeyDone
6251 [traits setReturnKeyType:UIReturnKeyNext];
6256 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
6257 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
6258 initWithTitle:UCLocalize("ADD")
6259 style:UIBarButtonItemStylePlain
6261 action:@selector(addButtonClicked)
6262 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
6264 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6265 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
6266 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
6268 action:@selector(editButtonClicked)
6269 ] autorelease] animated:animated];
6271 if (IsWildcat_ && !editing)
6272 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6273 initWithTitle:UCLocalize("SETTINGS")
6274 style:UIBarButtonItemStylePlain
6276 action:@selector(settingsButtonClicked)
6280 - (void) settingsButtonClicked {
6281 [delegate_ showSettings];
6284 - (void) editButtonClicked {
6285 [list_ setEditing:![list_ isEditing] animated:YES];
6287 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
6293 /* Installed Controller {{{ */
6294 @interface InstalledController : FilteredPackageController {
6298 - (id) initWithDatabase:(Database *)database;
6300 - (void) updateRoleButton;
6301 - (void) queueStatusDidChange;
6305 @implementation InstalledController
6311 - (NSString *) title { return UCLocalize("INSTALLED"); }
6313 - (id) initWithDatabase:(Database *)database {
6314 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
6315 [self updateRoleButton];
6316 [self queueStatusDidChange];
6321 - (void) queueButtonClicked {
6326 - (void) queueStatusDidChange {
6330 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6331 initWithTitle:UCLocalize("QUEUE")
6332 style:UIBarButtonItemStyleDone
6334 action:@selector(queueButtonClicked)
6337 [[self navigationItem] setLeftBarButtonItem:nil];
6343 - (void) reloadData {
6344 [packages_ reloadData];
6347 - (void) updateRoleButton {
6348 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
6349 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6350 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
6351 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
6353 action:@selector(roleButtonClicked)
6357 - (void) roleButtonClicked {
6358 [packages_ setObject:[NSNumber numberWithBool:expert_]];
6359 [packages_ reloadData];
6362 [self updateRoleButton];
6365 - (void) setDelegate:(id)delegate {
6366 [super setDelegate:delegate];
6367 [packages_ setDelegate:delegate];
6373 /* Home Controller {{{ */
6374 @interface HomeController : CYBrowserController {
6379 @implementation HomeController
6381 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6382 [super _setMoreHeaders:request];
6385 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6386 if (UniqueID_ != nil)
6387 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6389 [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"];
6392 - (void) aboutButtonClicked {
6393 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6395 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6396 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6397 [alert setCancelButtonIndex:0];
6400 @"Copyright (C) 2008-2010\n"
6401 "Jay Freeman (saurik)\n"
6402 "saurik@saurik.com\n"
6403 "http://www.saurik.com/"
6409 - (void) viewWillAppear:(BOOL)animated {
6410 [super viewWillAppear:animated];
6411 //[[self navigationController] setNavigationBarHidden:YES animated:animated];
6414 - (void) viewWillDisappear:(BOOL)animated {
6415 [super viewWillDisappear:animated];
6416 //[[self navigationController] setNavigationBarHidden:NO animated:animated];
6420 if ((self = [super init]) != nil) {
6421 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6422 initWithTitle:UCLocalize("ABOUT")
6423 style:UIBarButtonItemStylePlain
6425 action:@selector(aboutButtonClicked)
6432 /* Manage Controller {{{ */
6433 @interface ManageController : CYBrowserController {
6436 - (void) queueStatusDidChange;
6439 @implementation ManageController
6442 if ((self = [super init]) != nil) {
6443 [[self navigationItem] setTitle:UCLocalize("MANAGE")];
6445 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6446 initWithTitle:UCLocalize("SETTINGS")
6447 style:UIBarButtonItemStylePlain
6449 action:@selector(settingsButtonClicked)
6452 [self queueStatusDidChange];
6456 - (void) settingsButtonClicked {
6457 [delegate_ showSettings];
6461 - (void) queueButtonClicked {
6465 - (void) applyLoadingTitle {
6466 // No "Loading" title.
6469 - (void) applyRightButton {
6474 - (void) queueStatusDidChange {
6476 if (!IsWildcat_ && Queuing_) {
6477 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6478 initWithTitle:UCLocalize("QUEUE")
6479 style:UIBarButtonItemStyleDone
6481 action:@selector(queueButtonClicked)
6484 [[self navigationItem] setRightBarButtonItem:nil];
6489 - (bool) isLoading {
6496 /* Refresh Bar {{{ */
6497 @interface RefreshBar : UINavigationBar {
6498 UIProgressIndicator *indicator_;
6499 UITextLabel *prompt_;
6500 UIProgressBar *progress_;
6501 UINavigationButton *cancel_;
6506 @implementation RefreshBar
6509 [indicator_ release];
6511 [progress_ release];
6516 - (void) positionViews {
6517 CGRect frame = [cancel_ frame];
6518 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6519 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6520 [cancel_ setFrame:frame];
6522 CGSize prgsize = {75, 100};
6524 [self frame].size.width - prgsize.width - 10,
6525 ([self frame].size.height - prgsize.height) / 2
6527 [progress_ setFrame:prgrect];
6529 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6530 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6531 CGRect indrect = {{indoffset, indoffset}, indsize};
6532 [indicator_ setFrame:indrect];
6534 CGSize prmsize = {215, indsize.height + 4};
6536 indoffset * 2 + indsize.width,
6537 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6539 [prompt_ setFrame:prmrect];
6542 - (void)setFrame:(CGRect)frame {
6543 [super setFrame:frame];
6545 [self positionViews];
6548 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6549 if ((self = [super initWithFrame:frame])) {
6550 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6552 [self setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
6553 [self setBarStyle:UIBarStyleBlack];
6555 UIBarStyle barstyle([self _barStyle:NO]);
6556 bool ugly(barstyle == UIBarStyleDefault);
6558 UIProgressIndicatorStyle style = ugly ?
6559 UIProgressIndicatorStyleMediumBrown :
6560 UIProgressIndicatorStyleMediumWhite;
6562 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6563 [indicator_ setStyle:style];
6564 [indicator_ startAnimation];
6565 [self addSubview:indicator_];
6567 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6568 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6569 [prompt_ setBackgroundColor:[UIColor clearColor]];
6570 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6571 [self addSubview:prompt_];
6573 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6574 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6575 [progress_ setStyle:0];
6576 [self addSubview:progress_];
6578 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6579 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6580 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6581 [cancel_ setBarStyle:barstyle];
6583 [self positionViews];
6588 [cancel_ removeFromSuperview];
6592 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6593 [progress_ setProgress:0];
6594 [self addSubview:cancel_];
6598 [cancel_ removeFromSuperview];
6601 - (void) setPrompt:(NSString *)prompt {
6602 [prompt_ setText:prompt];
6605 - (void) setProgress:(float)progress {
6606 [progress_ setProgress:progress];
6612 @class CYNavigationController;
6614 /* Cydia Tab Bar Controller {{{ */
6615 @interface CYTabBarController : UITabBarController {
6616 _transient Database *database_;
6621 @implementation CYTabBarController
6623 /* XXX: some logic should probably go here related to
6624 freeing the view controllers on tab change */
6626 - (void) reloadData {
6627 size_t count([[self viewControllers] count]);
6628 for (size_t i(0); i != count; ++i) {
6629 CYNavigationController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6634 - (id) initWithDatabase:(Database *)database {
6635 if ((self = [super init]) != nil) {
6636 database_ = database;
6643 /* Cydia Navigation Controller {{{ */
6644 @interface CYNavigationController : UINavigationController {
6645 _transient Database *database_;
6646 _transient id<UINavigationControllerDelegate> delegate_;
6649 - (id) initWithDatabase:(Database *)database;
6650 - (void) reloadData;
6655 @implementation CYNavigationController
6657 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
6658 // Inherit autorotation settings for modal parents.
6659 if ([self parentViewController] && [[self parentViewController] modalViewController] == self) {
6660 return [[self parentViewController] shouldAutorotateToInterfaceOrientation:orientation];
6662 return [super shouldAutorotateToInterfaceOrientation:orientation];
6670 - (void) reloadData {
6671 size_t count([[self viewControllers] count]);
6672 for (size_t i(0); i != count; ++i) {
6673 CYViewController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6678 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
6679 delegate_ = delegate;
6682 - (id) initWithDatabase:(Database *)database {
6683 if ((self = [super init]) != nil) {
6684 database_ = database;
6690 /* Cydia:// Protocol {{{ */
6691 @interface CydiaURLProtocol : NSURLProtocol {
6696 @implementation CydiaURLProtocol
6698 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6699 NSURL *url([request URL]);
6702 NSString *scheme([[url scheme] lowercaseString]);
6703 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6708 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6712 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6713 id<NSURLProtocolClient> client([self client]);
6715 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6717 NSData *data(UIImagePNGRepresentation(icon));
6719 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6720 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6721 [client URLProtocol:self didLoadData:data];
6722 [client URLProtocolDidFinishLoading:self];
6726 - (void) startLoading {
6727 id<NSURLProtocolClient> client([self client]);
6728 NSURLRequest *request([self request]);
6730 NSURL *url([request URL]);
6731 NSString *href([url absoluteString]);
6733 NSString *path([href substringFromIndex:8]);
6734 NSRange slash([path rangeOfString:@"/"]);
6737 if (slash.location == NSNotFound) {
6741 command = [path substringToIndex:slash.location];
6742 path = [path substringFromIndex:(slash.location + 1)];
6745 Database *database([Database sharedInstance]);
6747 if ([command isEqualToString:@"package-icon"]) {
6750 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6751 Package *package([database packageWithName:path]);
6754 UIImage *icon([package icon]);
6755 [self _returnPNGWithImage:icon forRequest:request];
6756 } else if ([command isEqualToString:@"source-icon"]) {
6759 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6760 NSString *source(Simplify(path));
6761 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6763 icon = [UIImage applicationImageNamed:@"unknown.png"];
6764 [self _returnPNGWithImage:icon forRequest:request];
6765 } else if ([command isEqualToString:@"uikit-image"]) {
6768 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6769 UIImage *icon(_UIImageWithName(path));
6770 [self _returnPNGWithImage:icon forRequest:request];
6771 } else if ([command isEqualToString:@"section-icon"]) {
6774 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6775 NSString *section(Simplify(path));
6776 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6778 icon = [UIImage applicationImageNamed:@"unknown.png"];
6779 [self _returnPNGWithImage:icon forRequest:request];
6781 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6785 - (void) stopLoading {
6791 /* Sections Controller {{{ */
6792 @interface SectionsController : CYViewController <
6793 UITableViewDataSource,
6796 _transient Database *database_;
6797 NSMutableArray *sections_;
6798 NSMutableArray *filtered_;
6804 - (id) initWithDatabase:(Database *)database;
6805 - (void) reloadData;
6808 - (void) editButtonClicked;
6812 @implementation SectionsController
6815 [list_ setDataSource:nil];
6816 [list_ setDelegate:nil];
6818 [sections_ release];
6819 [filtered_ release];
6821 [accessory_ release];
6825 - (void) viewDidAppear:(BOOL)animated {
6826 [super viewDidAppear:animated];
6827 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6830 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
6831 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
6835 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6836 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6839 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6843 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6844 static NSString *reuseIdentifier = @"SectionCell";
6846 SectionCell *cell = (SectionCell *) [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6848 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6850 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
6855 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6859 Section *section = [self sectionAtIndexPath:indexPath];
6860 NSString *name = [section name];
6863 if ([indexPath row] == 0) {
6866 title = UCLocalize("ALL_PACKAGES");
6869 name = [NSString stringWithString:name];
6870 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6873 title = UCLocalize("NO_SECTION");
6877 FilteredPackageController *table = [[[FilteredPackageController alloc]
6878 initWithDatabase:database_
6880 filter:@selector(isVisibleInSection:)
6884 [table setDelegate:delegate_];
6886 [[self navigationController] pushViewController:table animated:YES];
6889 - (NSString *) title { return UCLocalize("SECTIONS"); }
6891 - (id) initWithDatabase:(Database *)database {
6892 if ((self = [super init]) != nil) {
6893 database_ = database;
6895 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
6897 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6898 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6900 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
6901 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6902 [list_ setRowHeight:45.0f];
6903 [[self view] addSubview:list_];
6905 [list_ setDataSource:self];
6906 [list_ setDelegate:self];
6912 - (void) reloadData {
6913 NSArray *packages = [database_ packages];
6915 [sections_ removeAllObjects];
6916 [filtered_ removeAllObjects];
6918 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6921 for (Package *package in packages) {
6922 NSString *name([package section]);
6923 NSString *key(name == nil ? @"" : name);
6927 _profile(SectionsView$reloadData$Section)
6928 section = [sections objectForKey:key];
6929 if (section == nil) {
6930 _profile(SectionsView$reloadData$Section$Allocate)
6931 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6932 [sections setObject:section forKey:key];
6937 [section addToCount];
6939 _profile(SectionsView$reloadData$Filter)
6940 if (![package valid] || ![package visible])
6948 [sections_ addObjectsFromArray:[sections allValues]];
6950 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6952 for (Section *section in sections_) {
6953 size_t count([section row]);
6957 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6958 [section setCount:count];
6959 [filtered_ addObject:section];
6962 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6963 initWithTitle:([sections_ count] == 0 ? nil : UCLocalize("EDIT"))
6964 style:UIBarButtonItemStylePlain
6966 action:@selector(editButtonClicked)
6967 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] != nil)];
6973 - (void) resetView {
6975 [self editButtonClicked];
6978 - (void) editButtonClicked {
6979 if ((editing_ = !editing_))
6982 [delegate_ updateData];
6984 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6985 [[[self navigationItem] rightBarButtonItem] setTitle:[sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT")];
6986 [[[self navigationItem] rightBarButtonItem] setStyle:editing_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain];
6989 - (UIView *) accessoryView {
6995 /* Changes Controller {{{ */
6996 @interface ChangesController : CYViewController <
6997 UITableViewDataSource,
7000 _transient Database *database_;
7001 CFMutableArrayRef packages_;
7002 NSMutableArray *sections_;
7005 BOOL hasSentFirstLoad_;
7008 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
7009 - (void) reloadData;
7013 @implementation ChangesController
7016 [list_ setDelegate:nil];
7017 [list_ setDataSource:nil];
7019 CFRelease(packages_);
7021 [sections_ release];
7026 - (void) viewDidAppear:(BOOL)animated {
7027 [super viewDidAppear:animated];
7028 if (!hasSentFirstLoad_) {
7029 hasSentFirstLoad_ = YES;
7030 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
7032 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7036 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7037 NSInteger count([sections_ count]);
7038 return count == 0 ? 1 : count;
7041 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7042 if ([sections_ count] == 0)
7044 return [[sections_ objectAtIndex:section] name];
7047 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7048 if ([sections_ count] == 0)
7050 return [[sections_ objectAtIndex:section] count];
7053 - (Package *) packageAtIndex:(NSUInteger)index {
7054 return (Package *) CFArrayGetValueAtIndex(packages_, index);
7057 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7058 Section *section([sections_ objectAtIndex:[path section]]);
7059 NSInteger row([path row]);
7060 return [self packageAtIndex:([section row] + row)];
7063 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7064 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7066 cell = [[[PackageCell alloc] init] autorelease];
7067 [cell setPackage:[self packageAtIndexPath:path]];
7071 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
7072 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
7075 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7076 Package *package([self packageAtIndexPath:path]);
7077 PackageController *view([delegate_ packageController]);
7078 [view setDelegate:delegate_];
7079 [view setPackage:package];
7080 [[self navigationController] pushViewController:view animated:YES];
7084 - (void) refreshButtonClicked {
7085 [delegate_ beginUpdate];
7086 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7089 - (void) upgradeButtonClicked {
7090 [delegate_ distUpgrade];
7093 - (NSString *) title { return UCLocalize("CHANGES"); }
7095 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7096 if ((self = [super init]) != nil) {
7097 database_ = database;
7098 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7100 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7102 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7104 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7105 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7106 [list_ setRowHeight:73.0f];
7107 [[self view] addSubview:list_];
7109 [list_ setDataSource:self];
7110 [list_ setDelegate:self];
7112 delegate_ = delegate;
7116 - (void) _reloadPackages:(NSArray *)packages {
7118 for (Package *package in packages)
7119 if ([package upgradableAndEssential:YES] || [package visible])
7120 CFArrayAppendValue(packages_, package);
7123 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7127 - (void) reloadData {
7128 NSArray *packages = [database_ packages];
7130 CFArrayRemoveAllValues(packages_);
7132 [sections_ removeAllObjects];
7135 UIProgressHUD *hud([delegate_ addProgressHUD]);
7136 [hud setText:UCLocalize("LOADING")];
7137 //NSLog(@"HUD:%@::%@", delegate_, hud);
7138 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7139 [delegate_ removeProgressHUD:hud];
7141 [self _reloadPackages:packages];
7144 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7145 Section *ignored = nil;
7146 Section *section = nil;
7150 bool unseens = false;
7152 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7154 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7155 Package *package = [self packageAtIndex:offset];
7157 BOOL uae = [package upgradableAndEssential:YES];
7161 time_t seen([package seen]);
7163 if (section == nil || last != seen) {
7167 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7170 _profile(ChangesController$reloadData$Allocate)
7171 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7172 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7173 [sections_ addObject:section];
7177 [section addToCount];
7178 } else if ([package ignored]) {
7179 if (ignored == nil) {
7180 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7182 [ignored addToCount];
7185 [upgradable addToCount];
7190 CFRelease(formatter);
7193 Section *last = [sections_ lastObject];
7194 size_t count = [last count];
7195 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7196 [sections_ removeLastObject];
7199 if ([ignored count] != 0)
7200 [sections_ insertObject:ignored atIndex:0];
7202 [sections_ insertObject:upgradable atIndex:0];
7207 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7208 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7209 style:UIBarButtonItemStylePlain
7211 action:@selector(upgradeButtonClicked)
7214 if (![delegate_ updating])
7215 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7216 initWithTitle:UCLocalize("REFRESH")
7217 style:UIBarButtonItemStylePlain
7219 action:@selector(refreshButtonClicked)
7225 /* Search Controller {{{ */
7226 @interface SearchController : FilteredPackageController <
7229 UISearchBar *search_;
7232 - (id) initWithDatabase:(Database *)database;
7233 - (void) reloadData;
7237 @implementation SearchController
7244 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7245 [packages_ setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7246 [search_ resignFirstResponder];
7250 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7251 [packages_ setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7255 - (NSString *) title { return nil; }
7257 - (id) initWithDatabase:(Database *)database {
7258 return [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil];
7261 - (void)viewDidAppear:(BOOL)animated {
7262 [super viewDidAppear:animated];
7264 search_ = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7265 [search_ layoutSubviews];
7266 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7267 UITextField *textField = [search_ searchField];
7268 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7269 [search_ setDelegate:self];
7270 [textField setEnablesReturnKeyAutomatically:NO];
7271 [[self navigationItem] setTitleView:textField];
7275 - (void) _reloadData {
7278 - (void) reloadData {
7279 _profile(SearchController$reloadData)
7280 [packages_ reloadData];
7283 [packages_ resetCursor];
7286 - (void) didSelectPackage:(Package *)package {
7287 [search_ resignFirstResponder];
7288 [super didSelectPackage:package];
7293 /* Settings Controller {{{ */
7294 @interface SettingsController : CYViewController <
7295 UITableViewDataSource,
7298 _transient Database *database_;
7301 UITableView *table_;
7302 UISwitch *subscribedSwitch_;
7303 UISwitch *ignoredSwitch_;
7304 UITableViewCell *subscribedCell_;
7305 UITableViewCell *ignoredCell_;
7308 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7312 @implementation SettingsController
7316 if (package_ != nil)
7319 [subscribedSwitch_ release];
7320 [ignoredSwitch_ release];
7321 [subscribedCell_ release];
7322 [ignoredCell_ release];
7327 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7328 if (package_ == nil)
7334 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7335 if (package_ == nil)
7341 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7342 return UCLocalize("SHOW_ALL_CHANGES_EX");
7345 - (void) onSubscribed:(id)control {
7346 bool value([control isOn]);
7347 if (package_ == nil)
7349 if ([package_ setSubscribed:value])
7350 [delegate_ updateData];
7353 - (void) onIgnored:(id)control {
7354 // TODO: set Held state - possibly call out to dpkg, etc.
7357 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7358 if (package_ == nil)
7361 switch ([indexPath row]) {
7362 case 0: return subscribedCell_;
7363 case 1: return ignoredCell_;
7371 - (NSString *) title { return UCLocalize("SETTINGS"); }
7373 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7374 if ((self = [super init])) {
7375 database_ = database;
7376 name_ = [package retain];
7378 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7380 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7381 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7382 [[self view] addSubview:table_];
7384 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7385 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7386 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7388 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7389 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7390 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7392 subscribedCell_ = [[UITableViewCell alloc] init];
7393 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7394 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7395 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7397 ignoredCell_ = [[UITableViewCell alloc] init];
7398 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7399 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7400 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7402 [table_ setDataSource:self];
7403 [table_ setDelegate:self];
7408 - (void) reloadData {
7409 if (package_ != nil)
7410 [package_ autorelease];
7411 package_ = [database_ packageWithName:name_];
7412 if (package_ != nil) {
7414 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7415 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7418 [table_ reloadData];
7423 /* Signature Controller {{{ */
7424 @interface SignatureController : CYBrowserController {
7425 _transient Database *database_;
7429 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7433 @implementation SignatureController
7440 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7442 [super webView:view didClearWindowObject:window forFrame:frame];
7445 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7446 if ((self = [super init]) != nil) {
7447 database_ = database;
7448 package_ = [package retain];
7453 - (void) reloadData {
7454 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7460 /* Role Controller {{{ */
7461 @interface RoleController : CYViewController <
7462 UITableViewDataSource,
7465 _transient Database *database_;
7466 // XXX: ok, "roledelegate_"?...
7467 _transient id roledelegate_;
7468 UITableView *table_;
7469 UISegmentedControl *segment_;
7473 - (void) showDoneButton;
7474 - (void) resizeSegmentedControl;
7478 @implementation RoleController
7482 [container_ release];
7487 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7488 if ((self = [super init])) {
7489 database_ = database;
7490 roledelegate_ = delegate;
7492 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
7494 NSArray *items = [NSArray arrayWithObjects:
7496 UCLocalize("HACKER"),
7497 UCLocalize("DEVELOPER"),
7499 segment_ = [[UISegmentedControl alloc] initWithItems:items];
7500 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
7501 [container_ addSubview:segment_];
7504 if ([Role_ isEqualToString:@"User"]) index = 0;
7505 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
7506 if ([Role_ isEqualToString:@"Developer"]) index = 2;
7508 [segment_ setSelectedSegmentIndex:index];
7509 [self showDoneButton];
7512 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
7513 [self resizeSegmentedControl];
7515 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7516 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7517 [table_ setDelegate:self];
7518 [table_ setDataSource:self];
7519 [[self view] addSubview:table_];
7520 [table_ reloadData];
7524 - (void) resizeSegmentedControl {
7525 CGFloat width = [[self view] frame].size.width;
7526 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
7529 - (void) viewWillAppear:(BOOL)animated {
7530 [super viewWillAppear:animated];
7532 [self resizeSegmentedControl];
7535 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7536 [self resizeSegmentedControl];
7539 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7540 [self resizeSegmentedControl];
7544 NSString *role(nil);
7546 switch ([segment_ selectedSegmentIndex]) {
7547 case 0: role = @"User"; break;
7548 case 1: role = @"Hacker"; break;
7549 case 2: role = @"Developer"; break;
7554 if (![role isEqualToString:Role_]) {
7555 bool rolling(Role_ == nil);
7558 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7562 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7567 [roledelegate_ loadData];
7569 [roledelegate_ updateData];
7573 - (void) segmentChanged:(UISegmentedControl *)control {
7574 [self showDoneButton];
7577 - (void) saveAndClose {
7580 [[self navigationItem] setRightBarButtonItem:nil];
7581 [[self navigationController] dismissModalViewControllerAnimated:YES];
7584 - (void) doneButtonClicked {
7585 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
7586 [spinner startAnimating];
7587 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
7588 [[self navigationItem] setRightBarButtonItem:spinItem];
7590 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
7593 - (void) showDoneButton {
7594 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7595 initWithTitle:UCLocalize("DONE")
7596 style:UIBarButtonItemStyleDone
7598 action:@selector(doneButtonClicked)
7599 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
7602 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7603 // XXX: For not having a single cell in the table, this sure is a lot of sections.
7607 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7611 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7612 return nil; // This method is required by the protocol.
7615 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7617 return UCLocalize("ROLE_EX");
7619 return [NSString stringWithFormat:
7620 @"%@: %@\n%@: %@\n%@: %@",
7621 UCLocalize("USER"), UCLocalize("USER_EX"),
7622 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
7623 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
7628 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
7629 return section == 3 ? 44.0f : 0;
7632 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
7633 return section == 3 ? container_ : nil;
7638 /* Stash Controller {{{ */
7639 @interface CYStashController : CYViewController {
7640 // XXX: just delete these things
7641 _transient UIActivityIndicatorView *spinner_;
7642 _transient UILabel *status_;
7643 _transient UILabel *caption_;
7647 @implementation CYStashController
7649 if ((self = [super init])) {
7650 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
7652 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
7653 CGRect spinrect = [spinner_ frame];
7654 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
7655 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
7656 [spinner_ setFrame:spinrect];
7657 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
7658 [[self view] addSubview:spinner_];
7659 [spinner_ startAnimating];
7662 captrect.size.width = [[self view] frame].size.width;
7663 captrect.size.height = 40.0f;
7664 captrect.origin.x = 0;
7665 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
7666 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
7667 [caption_ setText:@"Initializing Filesystem"];
7668 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7669 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
7670 [caption_ setTextColor:[UIColor whiteColor]];
7671 [caption_ setBackgroundColor:[UIColor clearColor]];
7672 [caption_ setShadowColor:[UIColor blackColor]];
7673 [caption_ setTextAlignment:UITextAlignmentCenter];
7674 [[self view] addSubview:caption_];
7677 statusrect.size.width = [[self view] frame].size.width;
7678 statusrect.size.height = 30.0f;
7679 statusrect.origin.x = 0;
7680 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
7681 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
7682 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7683 [status_ setText:@"(Cydia will exit when complete.)"];
7684 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
7685 [status_ setTextColor:[UIColor whiteColor]];
7686 [status_ setBackgroundColor:[UIColor clearColor]];
7687 [status_ setShadowColor:[UIColor blackColor]];
7688 [status_ setTextAlignment:UITextAlignmentCenter];
7689 [[self view] addSubview:status_];
7693 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7694 return IsWildcat_ || orientation == UIInterfaceOrientationPortrait;
7699 /* Cydia Container {{{ */
7700 @interface CYContainer : UIViewController <ProgressDelegate> {
7701 _transient Database *database_;
7702 RefreshBar *refreshbar_;
7706 // XXX: ok, "updatedelegate_"?...
7707 _transient NSObject<CydiaDelegate> *updatedelegate_;
7708 // XXX: can't we query for this variable when we need it?
7709 _transient UITabBarController *root_;
7712 - (void) setTabBarController:(UITabBarController *)controller;
7714 - (void) dropBar:(BOOL)animated;
7715 - (void) beginUpdate;
7716 - (void) raiseBar:(BOOL)animated;
7721 @implementation CYContainer
7723 - (BOOL) _reallyWantsFullScreenLayout {
7727 // NOTE: UIWindow only sends the top controller these messages,
7728 // So we have to forward them on.
7730 - (void) viewDidAppear:(BOOL)animated {
7731 [super viewDidAppear:animated];
7732 [root_ viewDidAppear:animated];
7735 - (void) viewWillAppear:(BOOL)animated {
7736 [super viewWillAppear:animated];
7737 [root_ viewWillAppear:animated];
7740 - (void) viewDidDisappear:(BOOL)animated {
7741 [super viewDidDisappear:animated];
7742 [root_ viewDidDisappear:animated];
7745 - (void) viewWillDisappear:(BOOL)animated {
7746 [super viewWillDisappear:animated];
7747 [root_ viewWillDisappear:animated];
7750 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7751 return ![updatedelegate_ hudIsShowing] && (IsWildcat_ || orientation == UIInterfaceOrientationPortrait);
7754 - (void) setTabBarController:(UITabBarController *)controller {
7756 [[self view] addSubview:[root_ view]];
7759 - (void) setUpdate:(NSDate *)date {
7763 - (void) beginUpdate {
7765 [refreshbar_ start];
7770 detachNewThreadSelector:@selector(performUpdate)
7776 - (void) performUpdate { _pooled
7778 status.setDelegate(self);
7779 [database_ updateWithStatus:status];
7782 performSelectorOnMainThread:@selector(completeUpdate)
7788 - (void) completeUpdate {
7793 [self raiseBar:YES];
7795 [updatedelegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
7798 - (void) cancelUpdate {
7800 [self raiseBar:YES];
7802 [updatedelegate_ performSelector:@selector(updateData) withObject:nil afterDelay:0];
7805 - (void) cancelPressed {
7806 [self cancelUpdate];
7813 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
7814 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
7817 - (void) startProgress {
7820 - (void) setProgressTitle:(NSString *)title {
7822 performSelectorOnMainThread:@selector(_setProgressTitle:)
7828 - (bool) isCancelling:(size_t)received {
7832 - (void) setProgressPercent:(float)percent {
7834 performSelectorOnMainThread:@selector(_setProgressPercent:)
7835 withObject:[NSNumber numberWithFloat:percent]
7840 - (void) addProgressOutput:(NSString *)output {
7842 performSelectorOnMainThread:@selector(_addProgressOutput:)
7848 - (void) _setProgressTitle:(NSString *)title {
7849 [refreshbar_ setPrompt:title];
7852 - (void) _setProgressPercent:(NSNumber *)percent {
7853 [refreshbar_ setProgress:[percent floatValue]];
7856 - (void) _addProgressOutput:(NSString *)output {
7859 - (void) setUpdateDelegate:(id)delegate {
7860 updatedelegate_ = delegate;
7863 - (CGFloat) statusBarHeight {
7864 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
7865 return [[UIApplication sharedApplication] statusBarFrame].size.height;
7867 return [[UIApplication sharedApplication] statusBarFrame].size.width;
7871 - (void) dropBar:(BOOL)animated {
7876 [[self view] addSubview:refreshbar_];
7878 CGFloat sboffset = [self statusBarHeight];
7880 CGRect barframe = [refreshbar_ frame];
7881 barframe.origin.y = sboffset;
7882 [refreshbar_ setFrame:barframe];
7885 [UIView beginAnimations:nil context:NULL];
7886 CGRect viewframe = [[root_ view] frame];
7887 viewframe.origin.y += barframe.size.height + sboffset;
7888 viewframe.size.height -= barframe.size.height + sboffset;
7889 [[root_ view] setFrame:viewframe];
7891 [UIView commitAnimations];
7893 // Ensure bar has the proper width for our view, it might have changed
7894 barframe.size.width = viewframe.size.width;
7895 [refreshbar_ setFrame:barframe];
7897 // XXX: fix Apple's layout bug
7898 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7901 - (void) raiseBar:(BOOL)animated {
7906 [refreshbar_ removeFromSuperview];
7908 CGFloat sboffset = [self statusBarHeight];
7911 [UIView beginAnimations:nil context:NULL];
7912 CGRect barframe = [refreshbar_ frame];
7913 CGRect viewframe = [[root_ view] frame];
7914 viewframe.origin.y -= barframe.size.height + sboffset;
7915 viewframe.size.height += barframe.size.height + sboffset;
7916 [[root_ view] setFrame:viewframe];
7918 [UIView commitAnimations];
7920 // XXX: fix Apple's layout bug
7921 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7924 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7925 // XXX: fix Apple's layout bug
7926 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7929 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7935 // XXX: fix Apple's layout bug
7936 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7939 - (void) statusBarFrameChanged:(NSNotification *)notification {
7947 [refreshbar_ release];
7948 [[NSNotificationCenter defaultCenter] removeObserver:self];
7952 - (id) initWithDatabase:(Database *)database {
7953 if ((self = [super init]) != nil) {
7954 database_ = database;
7956 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7957 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
7959 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
7976 @interface Cydia : UIApplication <
7977 ConfirmationControllerDelegate,
7978 ProgressControllerDelegate,
7980 UINavigationControllerDelegate,
7981 UITabBarControllerDelegate
7983 // XXX: evaluate all fields for _transient
7986 CYContainer *container_;
7987 CYTabBarController *tabbar_;
7989 NSMutableArray *essential_;
7990 NSMutableArray *broken_;
7992 Database *database_;
7998 SectionsController *sections_;
7999 ChangesController *changes_;
8000 ManageController *manage_;
8001 SearchController *search_;
8002 SourceTable *sources_;
8003 InstalledController *installed_;
8006 CYStashController *stash_;
8011 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class;
8012 - (void) setPage:(CYViewController *)page;
8017 static _finline void _setHomePage(Cydia *self) {
8018 [self setPage:[self _pageForURL:[NSURL URLWithString:CydiaURL(@"")] withClass:[HomeController class]]];
8021 @implementation Cydia
8023 - (void) beginUpdate {
8024 [container_ beginUpdate];
8028 return [container_ updating];
8031 - (UIView *) rotatingContentViewForWindow:(UIWindow *)window {
8036 if ([broken_ count] != 0) {
8037 int count = [broken_ count];
8039 UIAlertView *alert = [[[UIAlertView alloc]
8040 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8041 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8043 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8044 otherButtonTitles:UCLocalize("TEMPORARY_IGNORE"), nil
8047 [alert setContext:@"fixhalf"];
8049 } else if (!Ignored_ && [essential_ count] != 0) {
8050 int count = [essential_ count];
8052 UIAlertView *alert = [[[UIAlertView alloc]
8053 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8054 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8056 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8057 otherButtonTitles:UCLocalize("UPGRADE_ESSENTIAL"), UCLocalize("COMPLETE_UPGRADE"), nil
8060 [alert setContext:@"upgrade"];
8065 - (void) _saveConfig {
8068 NSString *error(nil);
8069 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8071 NSError *error(nil);
8072 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8073 NSLog(@"failure to save metadata data: %@", error);
8076 NSLog(@"failure to serialize metadata: %@", error);
8084 - (void) _updateData {
8087 /* XXX: this is just stupid */
8088 if (tag_ != 1 && sections_ != nil)
8089 [sections_ reloadData];
8090 if (tag_ != 2 && changes_ != nil)
8091 [changes_ reloadData];
8092 if (tag_ != 4 && search_ != nil)
8093 [search_ reloadData];
8095 [(CYNavigationController *)[tabbar_ selectedViewController] reloadData];
8098 - (int)indexOfTabWithTag:(int)tag {
8100 for (UINavigationController *controller in [tabbar_ viewControllers]) {
8101 if ([[controller tabBarItem] tag] == tag)
8109 - (void) _refreshIfPossible {
8110 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8112 bool recently = false;
8113 NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
8114 if (update != nil) {
8115 NSTimeInterval interval([update timeIntervalSinceNow]);
8116 if (interval <= 0 && interval > -(15*60))
8120 // Don't automatic refresh if:
8121 // - We already refreshed recently.
8122 // - We already auto-refreshed this launch.
8123 // - Auto-refresh is disabled.
8124 if (recently || loaded_ || ManualRefresh) {
8125 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8127 // If we are cancelling due to ManualRefresh or a recent refresh
8128 // we need to make sure it knows it's already loaded.
8132 // We are going to load, so remember that.
8136 SCNetworkReachabilityFlags flags; {
8137 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8138 SCNetworkReachabilityGetFlags(reachability, &flags);
8139 CFRelease(reachability);
8142 // XXX: this elaborate mess is what Apple is using to determine this? :(
8143 // XXX: do we care if the user has to intervene? maybe that's ok?
8145 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8146 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8147 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8148 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8149 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8150 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8154 // If we can reach the server, auto-refresh!
8156 [container_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8161 - (void) refreshIfPossible {
8162 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
8165 - (void) _reloadData {
8166 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8167 [hud setText:UCLocalize("RELOADING_DATA")];
8169 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
8172 [self removeProgressHUD:hud];
8176 [essential_ removeAllObjects];
8177 [broken_ removeAllObjects];
8179 NSArray *packages([database_ packages]);
8180 for (Package *package in packages) {
8182 [broken_ addObject:package];
8183 if ([package upgradableAndEssential:NO]) {
8184 if ([package essential])
8185 [essential_ addObject:package];
8190 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem];
8192 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8193 [changesItem setBadgeValue:badge];
8194 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8196 if ([self respondsToSelector:@selector(setApplicationBadge:)])
8197 [self setApplicationBadge:badge];
8199 [self setApplicationBadgeString:badge];
8201 [changesItem setBadgeValue:nil];
8202 [changesItem setAnimatedBadge:NO];
8204 if ([self respondsToSelector:@selector(removeApplicationBadge)])
8205 [self removeApplicationBadge];
8206 else // XXX: maybe use setApplicationBadgeString also?
8207 [self setApplicationIconBadgeNumber:0];
8212 [self refreshIfPossible];
8215 - (void) updateData {
8224 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8225 _assert(file != NULL);
8227 for (NSString *key in [Sources_ allKeys]) {
8228 NSDictionary *source([Sources_ objectForKey:key]);
8230 fprintf(file, "%s %s %s\n",
8231 [[source objectForKey:@"Type"] UTF8String],
8232 [[source objectForKey:@"URI"] UTF8String],
8233 [[source objectForKey:@"Distribution"] UTF8String]
8241 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8242 CYNavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8244 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8245 [container_ presentModalViewController:navigation animated:YES];
8248 detachNewThreadSelector:@selector(update_)
8251 title:UCLocalize("UPDATING_SOURCES")
8255 - (void) reloadData {
8256 @synchronized (self) {
8262 pkgProblemResolver *resolver = [database_ resolver];
8264 resolver->InstallProtect();
8265 if (!resolver->Resolve(true))
8269 - (CGRect) popUpBounds {
8270 return [[tabbar_ view] bounds];
8274 if (![database_ prepare])
8277 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8278 [page setDelegate:self];
8279 CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]);
8280 [confirm_ setDelegate:self];
8283 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8284 [container_ presentModalViewController:confirm_ animated:YES];
8290 @synchronized (self) {
8295 - (void) clearPackage:(Package *)package {
8296 @synchronized (self) {
8303 - (void) installPackages:(NSArray *)packages {
8304 @synchronized (self) {
8305 for (Package *package in packages)
8312 - (void) installPackage:(Package *)package {
8313 @synchronized (self) {
8320 - (void) removePackage:(Package *)package {
8321 @synchronized (self) {
8328 - (void) distUpgrade {
8329 @synchronized (self) {
8330 if (![database_ upgrade])
8337 @synchronized (self) {
8342 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8343 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8345 if (navigation != nil) {
8346 [navigation pushViewController:progress animated:YES];
8348 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8350 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8351 [container_ presentModalViewController:navigation animated:YES];
8355 detachNewThreadSelector:@selector(perform)
8358 title:UCLocalize("RUNNING")
8362 - (void) progressControllerIsComplete:(ProgressController *)progress {
8366 - (void) setPage:(CYViewController *)page {
8367 [page setDelegate:self];
8369 CYNavigationController *navController = (CYNavigationController *) [tabbar_ selectedViewController];
8370 [navController setViewControllers:[NSArray arrayWithObject:page]];
8371 for (CYNavigationController *page in [tabbar_ viewControllers])
8372 if (page != navController)
8373 [page setViewControllers:nil];
8376 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class {
8377 CYBrowserController *browser = [[[_class alloc] init] autorelease];
8378 [browser loadURL:url];
8382 - (SectionsController *) sectionsController {
8383 if (sections_ == nil)
8384 sections_ = [[SectionsController alloc] initWithDatabase:database_];
8388 - (ChangesController *) changesController {
8389 if (changes_ == nil)
8390 changes_ = [[ChangesController alloc] initWithDatabase:database_ delegate:self];
8394 - (ManageController *) manageController {
8395 if (manage_ == nil) {
8396 manage_ = (ManageController *) [[self
8397 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
8398 withClass:[ManageController class]
8401 queueDelegate_ = manage_;
8406 - (SearchController *) searchController {
8408 search_ = [[SearchController alloc] initWithDatabase:database_];
8412 - (SourceTable *) sourcesController {
8413 if (sources_ == nil)
8414 sources_ = [[SourceTable alloc] initWithDatabase:database_];
8418 - (InstalledController *) installedController {
8419 if (installed_ == nil) {
8420 installed_ = [[InstalledController alloc] initWithDatabase:database_];
8422 queueDelegate_ = installed_;
8427 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
8428 int tag = [[viewController tabBarItem] tag];
8430 [(CYNavigationController *)[tabbar_ selectedViewController] popToRootViewControllerAnimated:YES];
8432 } else if (tag_ == 1) {
8433 [[self sectionsController] resetView];
8437 case kCydiaTag: _setHomePage(self); break;
8439 case kSectionsTag: [self setPage:[self sectionsController]]; break;
8440 case kChangesTag: [self setPage:[self changesController]]; break;
8441 case kManageTag: [self setPage:[self manageController]]; break;
8442 case kInstalledTag: [self setPage:[self installedController]]; break;
8443 case kSourcesTag: [self setPage:[self sourcesController]]; break;
8444 case kSearchTag: [self setPage:[self searchController]]; break;
8452 - (void) showSettings {
8453 RoleController *role = [[[RoleController alloc] initWithDatabase:database_ delegate:self] autorelease];
8454 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
8456 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
8457 [container_ presentModalViewController:nav animated:YES];
8460 - (void) setPackageController:(PackageController *)view {
8462 [view setPackage:nil];
8466 - (PackageController *) _packageController {
8467 return [[[PackageController alloc] initWithDatabase:database_] autorelease];
8470 - (PackageController *) packageController {
8471 return [self _packageController];
8474 // Returns the navigation controller for the queuing badge.
8475 - (id) queueBadgeController {
8476 int index = [self indexOfTabWithTag:kManageTag];
8478 index = [self indexOfTabWithTag:kInstalledTag];
8480 return [[tabbar_ viewControllers] objectAtIndex:index];
8483 - (void) cancelAndClear:(bool)clear {
8484 @synchronized (self) {
8490 [[[self queueBadgeController] tabBarItem] setBadgeValue:nil];
8494 [[[self queueBadgeController] tabBarItem] setBadgeValue:UCLocalize("Q_D")];
8498 [queueDelegate_ queueStatusDidChange];
8502 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8503 NSString *context([alert context]);
8505 if ([context isEqualToString:@"fixhalf"]) {
8506 if (button == [alert firstOtherButtonIndex]) {
8507 @synchronized (self) {
8508 for (Package *broken in broken_) {
8511 NSString *id = [broken id];
8512 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8513 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8514 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8515 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8521 } else if (button == [alert cancelButtonIndex]) {
8522 [broken_ removeAllObjects];
8526 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8527 } else if ([context isEqualToString:@"upgrade"]) {
8528 if (button == [alert firstOtherButtonIndex]) {
8529 @synchronized (self) {
8530 for (Package *essential in essential_)
8531 [essential install];
8536 } else if (button == [alert firstOtherButtonIndex] + 1) {
8538 } else if (button == [alert cancelButtonIndex]) {
8542 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8546 - (void) system:(NSString *)command { _pooled
8547 system([command UTF8String]);
8550 - (void) applicationWillSuspend {
8552 [super applicationWillSuspend];
8555 - (BOOL) hudIsShowing {
8556 return (hudcount_ > 0);
8559 - (void) applicationSuspend:(__GSEvent *)event {
8560 // Use external process status API internally.
8561 // This is probably a really bad idea.
8562 uint64_t status = 0;
8564 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
8565 notify_get_state(notify_token, &status);
8566 notify_cancel(notify_token);
8569 if (![self hudIsShowing] && status == 0)
8570 [super applicationSuspend:event];
8573 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8574 if (![self hudIsShowing])
8575 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8578 - (void) _setSuspended:(BOOL)value {
8579 if (![self hudIsShowing])
8580 [super _setSuspended:value];
8583 - (UIProgressHUD *) addProgressHUD {
8584 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8585 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8587 [window_ setUserInteractionEnabled:NO];
8590 UIViewController *target = container_;
8591 while ([target modalViewController] != nil) target = [target modalViewController];
8592 [[target view] addSubview:hud];
8598 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8600 [hud removeFromSuperview];
8601 [window_ setUserInteractionEnabled:YES];
8605 - (CYViewController *) pageForPackage:(NSString *)name {
8606 if (Package *package = [database_ packageWithName:name]) {
8607 PackageController *view([self packageController]);
8608 [view setPackage:package];
8611 NSURL *url([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"unknown" ofType:@"html"]]);
8612 url = [NSURL URLWithString:[[url absoluteString] stringByAppendingString:[NSString stringWithFormat:@"?%@", name]]];
8613 return [self _pageForURL:url withClass:[CYBrowserController class]];
8617 - (CYViewController *) pageForURL:(NSURL *)url hasTag:(int *)tag {
8621 NSString *href([url absoluteString]);
8622 if ([href hasPrefix:@"apptapp://package/"])
8623 return [self pageForPackage:[href substringFromIndex:18]];
8625 NSString *scheme([[url scheme] lowercaseString]);
8626 if (![scheme isEqualToString:@"cydia"])
8628 NSString *path([url absoluteString]);
8629 if ([path length] < 8)
8631 path = [path substringFromIndex:8];
8632 if (![path hasPrefix:@"/"])
8633 path = [@"/" stringByAppendingString:path];
8635 if ([path isEqualToString:@"/add-source"])
8636 return [[[AddSourceController alloc] initWithDatabase:database_] autorelease];
8637 else if ([path isEqualToString:@"/storage"])
8638 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CYBrowserController class]];
8639 else if ([path isEqualToString:@"/sources"])
8640 return [[[SourceTable alloc] initWithDatabase:database_] autorelease];
8641 else if ([path isEqualToString:@"/packages"])
8642 return [[[InstalledController alloc] initWithDatabase:database_] autorelease];
8643 else if ([path hasPrefix:@"/url/"])
8644 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[CYBrowserController class]];
8645 else if ([path hasPrefix:@"/launch/"])
8646 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8647 else if ([path hasPrefix:@"/package-settings/"])
8648 return [[[SettingsController alloc] initWithDatabase:database_ package:[path substringFromIndex:18]] autorelease];
8649 else if ([path hasPrefix:@"/package-signature/"])
8650 return [[[SignatureController alloc] initWithDatabase:database_ package:[path substringFromIndex:19]] autorelease];
8651 else if ([path hasPrefix:@"/package/"])
8652 return [self pageForPackage:[path substringFromIndex:9]];
8653 else if ([path hasPrefix:@"/files/"]) {
8654 NSString *name = [path substringFromIndex:7];
8656 if (Package *package = [database_ packageWithName:name]) {
8657 FileTable *files = [[[FileTable alloc] initWithDatabase:database_] autorelease];
8658 [files setPackage:package];
8666 - (BOOL) openCydiaURL:(NSURL *)url {
8667 CYViewController *page = nil;
8670 NSLog(@"open url: %@", url);
8672 if ((page = [self pageForURL:url hasTag:&tag])) {
8673 [self setPage:page];
8675 [tabbar_ setSelectedViewController:(tag_ == -1 ? nil : [[tabbar_ viewControllers] objectAtIndex:tag_])];
8681 - (void) applicationOpenURL:(NSURL *)url {
8682 [super applicationOpenURL:url];
8683 NSLog(@"first: %@", url);
8684 if (!loaded_) starturl_ = [url retain];
8685 else [self openCydiaURL:url];
8688 - (void) applicationWillResignActive:(UIApplication *)application {
8689 // Stop refreshing if you get a phone call or lock the device.
8690 if ([container_ updating])
8691 [container_ cancelUpdate];
8693 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
8694 [super applicationWillResignActive:application];
8697 - (void) addStashController {
8698 stash_ = [[CYStashController alloc] init];
8699 [window_ addSubview:[stash_ view]];
8702 - (void) removeStashController {
8703 [[stash_ view] removeFromSuperview];
8708 [self setIdleTimerDisabled:YES];
8710 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
8711 [self setStatusBarShowsProgress:YES];
8712 UpdateExternalStatus(1);
8714 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
8716 UpdateExternalStatus(0);
8717 [self setStatusBarShowsProgress:NO];
8719 [self removeStashController];
8721 if (ExecFork() == 0) {
8722 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
8723 perror("launchctl stop");
8727 - (void) setupTabBarController {
8728 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
8729 [tabbar_ setDelegate:self];
8731 NSMutableArray *items([NSMutableArray arrayWithObjects:
8732 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:kCydiaTag] autorelease],
8733 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:kSectionsTag] autorelease],
8734 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:kChangesTag] autorelease],
8735 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:kSearchTag] autorelease],
8739 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:kSourcesTag] autorelease] atIndex:3];
8740 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:kInstalledTag] autorelease] atIndex:3];
8742 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:kManageTag] autorelease] atIndex:3];
8745 NSMutableArray *controllers([NSMutableArray array]);
8747 for (UITabBarItem *item in items) {
8748 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
8749 [controller setTabBarItem:item];
8750 [controllers addObject:controller];
8753 [tabbar_ setViewControllers:controllers];
8756 - (void) applicationDidFinishLaunching:(id)unused {
8757 [CYBrowserController _initialize];
8759 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8761 Font12_ = [[UIFont systemFontOfSize:12] retain];
8762 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8763 Font14_ = [[UIFont systemFontOfSize:14] retain];
8764 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8765 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8769 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8770 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8772 UIScreen *screen([UIScreen mainScreen]);
8774 window_ = [[UIWindow alloc] initWithFrame:[screen bounds]];
8775 [window_ orderFront:self];
8776 [window_ makeKey:self];
8777 [window_ setHidden:NO];
8780 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8781 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8782 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8783 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
8784 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8785 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8786 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8787 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
8788 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
8791 [self addStashController];
8792 // XXX: this would be much cleaner as a yieldToSelector:
8793 // that way the removeStashController could happen right here inline
8794 // we also could no longer require the useless stash_ field anymore
8795 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
8799 database_ = [Database sharedInstance];
8801 [self setupTabBarController];
8803 container_ = [[CYContainer alloc] initWithDatabase:database_];
8804 [container_ setUpdateDelegate:self];
8805 [container_ setTabBarController:tabbar_];
8806 [window_ addSubview:[container_ view]];
8808 // Show pinstripes while loading data.
8809 [[container_ view] setBackgroundColor:[UIColor pinStripeColor]];
8811 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
8818 [self showSettings];
8822 [window_ setUserInteractionEnabled:NO];
8824 UIView *container = [[[UIView alloc] init] autorelease];
8825 [container setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
8827 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
8828 [spinner startAnimating];
8829 [container addSubview:spinner];
8831 UILabel *label = [[[UILabel alloc] init] autorelease];
8832 [label setFont:[UIFont boldSystemFontOfSize:15.0f]];
8833 [label setBackgroundColor:[UIColor clearColor]];
8834 [label setTextColor:[UIColor blackColor]];
8835 [label setShadowColor:[UIColor whiteColor]];
8836 [label setShadowOffset:CGSizeMake(0, 1)];
8837 [label setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
8838 [container addSubview:label];
8840 CGSize viewsize = [[tabbar_ view] frame].size;
8841 CGSize spinnersize = [spinner bounds].size;
8842 CGSize textsize = [[label text] sizeWithFont:[label font]];
8843 float bothwidth = spinnersize.width + textsize.width + 5.0f;
8845 CGRect containrect = {
8846 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
8847 CGSizeMake(bothwidth, spinnersize.height)
8850 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
8858 [container setFrame:containrect];
8859 [spinner setFrame:spinrect];
8860 [label setFrame:textrect];
8861 [[container_ view] addSubview:container];
8866 // Show the initial page
8867 if (starturl_ == nil || ![self openCydiaURL:starturl_]) {
8868 [tabbar_ setSelectedIndex:0];
8872 [starturl_ release];
8875 [window_ setUserInteractionEnabled:YES];
8877 // XXX: does this actually slow anything down?
8878 [[container_ view] setBackgroundColor:[UIColor clearColor]];
8879 [container removeFromSuperview];
8882 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
8883 if (item != nil && IsWildcat_) {
8884 [sheet showFromBarButtonItem:item animated:YES];
8886 [sheet showInView:window_];
8893 id Alloc_(id self, SEL selector) {
8894 id object = alloc_(self, selector);
8895 lprintf("[%s]A-%p\n", self->isa->name, object);
8900 id Dealloc_(id self, SEL selector) {
8901 id object = dealloc_(self, selector);
8902 lprintf("[%s]D-%p\n", self->isa->name, object);
8906 Class $WebDefaultUIKitDelegate;
8908 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
8909 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8910 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8911 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
8914 static NSNumber *shouldPlayKeyboardSounds;
8918 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
8920 case 1104: // Keyboard Button Clicked
8921 case 1105: // Keyboard Delete Repeated
8922 if (shouldPlayKeyboardSounds == nil) {
8923 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
8924 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
8927 if (![shouldPlayKeyboardSounds boolValue])
8931 _UIHardware$_playSystemSound$(self, _cmd, sound);
8935 int main(int argc, char *argv[]) { _pooled
8938 if (Class $UIDevice = objc_getClass("UIDevice")) {
8939 UIDevice *device([$UIDevice currentDevice]);
8940 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
8944 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8946 /* Library Hacks {{{ */
8947 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8949 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8950 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8951 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8952 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8953 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8956 $UIHardware = objc_getClass("UIHardware");
8957 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
8958 if (UIHardware$_playSystemSound$ != NULL) {
8959 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
8960 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
8963 /* Set Locale {{{ */
8964 Locale_ = CFLocaleCopyCurrent();
8965 Languages_ = [NSLocale preferredLanguages];
8966 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
8967 //NSLog(@"%@", [Languages_ description]);
8970 if (Languages_ == nil || [Languages_ count] == 0)
8971 // XXX: consider just setting to C and then falling through?
8974 lang = [[Languages_ objectAtIndex:0] UTF8String];
8975 setenv("LANG", lang, true);
8978 //std::setlocale(LC_ALL, lang);
8979 NSLog(@"Setting Language: %s", lang);
8982 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
8984 /* Parse Arguments {{{ */
8985 bool substrate(false);
8991 for (int argi(1); argi != argc; ++argi)
8992 if (strcmp(argv[argi], "--") == 0) {
8994 argv[argi] = argv[0];
9000 for (int argi(1); argi != arge; ++argi)
9001 if (strcmp(args[argi], "--substrate") == 0)
9004 fprintf(stderr, "unknown argument: %s\n", args[argi]);
9008 App_ = [[NSBundle mainBundle] bundlePath];
9009 Home_ = NSHomeDirectory();
9015 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
9016 alloc_ = alloc->method_imp;
9017 alloc->method_imp = (IMP) &Alloc_;*/
9019 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
9020 dealloc_ = dealloc->method_imp;
9021 dealloc->method_imp = (IMP) &Dealloc_;*/
9023 /* System Information {{{ */
9027 size = sizeof(maxproc);
9028 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9029 perror("sysctlbyname(\"kern.maxproc\", ?)");
9030 else if (maxproc < 64) {
9032 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9033 perror("sysctlbyname(\"kern.maxproc\", #)");
9036 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
9037 char *osversion = new char[size];
9038 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
9039 perror("sysctlbyname(\"kern.osversion\", ?)");
9041 System_ = [NSString stringWithUTF8String:osversion];
9043 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
9044 char *machine = new char[size];
9045 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
9046 perror("sysctlbyname(\"hw.machine\", ?)");
9050 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
9051 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
9052 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
9053 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
9057 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
9058 NSData *data((NSData *) ecid);
9059 size_t length([data length]);
9060 uint8_t bytes[length];
9061 [data getBytes:bytes];
9062 char string[length * 2 + 1];
9063 for (size_t i(0); i != length; ++i)
9064 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
9065 ChipID_ = [NSString stringWithUTF8String:string];
9069 IOObjectRelease(service);
9073 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
9075 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
9076 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9077 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
9079 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
9080 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9081 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
9083 if (mcc != NULL && mnc != NULL)
9084 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9091 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9092 Build_ = [system objectForKey:@"ProductBuildVersion"];
9093 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9094 Product_ = [info objectForKey:@"SafariProductVersion"];
9095 Safari_ = [info objectForKey:@"CFBundleVersion"];
9098 /* Load Database {{{ */
9100 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9102 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9104 if (Metadata_ == NULL)
9105 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9107 Settings_ = [Metadata_ objectForKey:@"Settings"];
9109 Packages_ = [Metadata_ objectForKey:@"Packages"];
9110 Sections_ = [Metadata_ objectForKey:@"Sections"];
9111 Sources_ = [Metadata_ objectForKey:@"Sources"];
9113 Token_ = [Metadata_ objectForKey:@"Token"];
9116 if (Settings_ != nil)
9117 Role_ = [Settings_ objectForKey:@"Role"];
9119 if (Sections_ == nil) {
9120 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9121 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9124 if (Sources_ == nil) {
9125 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9126 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9131 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
9134 if (Packages_ != nil) {
9135 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, NULL);
9137 [Metadata_ removeObjectForKey:@"Packages"];
9142 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9144 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", F_OK) == 0)
9145 dlopen("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", RTLD_LAZY | RTLD_GLOBAL);
9146 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
9147 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
9148 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9149 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9151 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9153 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9154 unlink("/tmp/.cydia.fw");
9156 } else if (access("/User", F_OK) != 0 || version < 2) {
9159 system("/usr/libexec/cydia/firmware.sh");
9163 _assert([[NSFileManager defaultManager]
9164 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9165 withIntermediateDirectories:YES
9170 if (access("/tmp/cydia.chk", F_OK) == 0) {
9171 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9172 _assert(errno == ENOENT);
9173 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9174 _assert(errno == ENOENT);
9177 /* APT Initialization {{{ */
9178 _assert(pkgInitConfig(*_config));
9179 _assert(pkgInitSystem(*_config, _system));
9182 _config->Set("APT::Acquire::Translation", lang);
9184 // XXX: this timeout might be important :(
9185 //_config->Set("Acquire::http::Timeout", 15);
9187 _config->Set("Acquire::http::MaxParallel", 3);
9189 /* Color Choices {{{ */
9190 space_ = CGColorSpaceCreateDeviceRGB();
9192 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9193 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9194 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9195 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9196 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9197 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9198 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9199 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9200 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9202 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9203 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9205 /* UIKit Configuration {{{ */
9206 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9207 if ($GSFontSetUseLegacyFontMetrics != NULL)
9208 $GSFontSetUseLegacyFontMetrics(YES);
9210 // XXX: I have a feeling this was important
9211 //UIKeyboardDisableAutomaticAppearance();
9214 Colon_ = UCLocalize("COLON_DELIMITED");
9215 Elision_ = UCLocalize("ELISION");
9216 Error_ = UCLocalize("ERROR");
9217 Warning_ = UCLocalize("WARNING");
9220 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9222 CGColorSpaceRelease(space_);