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, ':'));
1105 version = colon + 1;
1109 NSString *LocalizeSection(NSString *section) {
1110 static Pcre title_r("^(.*?) \\((.*)\\)$");
1111 if (title_r(section)) {
1112 NSString *parent(title_r[1]);
1113 NSString *child(title_r[2]);
1115 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1116 LocalizeSection(parent),
1117 LocalizeSection(child)
1121 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1124 NSString *Simplify(NSString *title) {
1125 const char *data = [title UTF8String];
1126 size_t size = [title length];
1128 static Pcre square_r("^\\[(.*)\\]$");
1129 if (square_r(data, size))
1130 return Simplify(square_r[1]);
1132 static Pcre paren_r("^\\((.*)\\)$");
1133 if (paren_r(data, size))
1134 return Simplify(paren_r[1]);
1136 static Pcre title_r("^(.*?) \\((.*)\\)$");
1137 if (title_r(data, size))
1138 return Simplify(title_r[1]);
1144 NSString *GetLastUpdate() {
1145 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1148 return UCLocalize("NEVER_OR_UNKNOWN");
1150 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1151 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1153 CFRelease(formatter);
1155 return [(NSString *) formatted autorelease];
1158 bool isSectionVisible(NSString *section) {
1159 NSDictionary *metadata([Sections_ objectForKey:section]);
1160 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1161 return hidden == nil || ![hidden boolValue];
1166 /* Delegate Prototypes {{{ */
1170 @interface NSObject (ProgressDelegate)
1173 @protocol ProgressDelegate
1174 - (void) setProgressError:(NSString *)error withTitle:(NSString *)id;
1175 - (void) setProgressTitle:(NSString *)title;
1176 - (void) setProgressPercent:(float)percent;
1177 - (void) startProgress;
1178 - (void) addProgressOutput:(NSString *)output;
1179 - (bool) isCancelling:(size_t)received;
1182 @protocol ConfigurationDelegate
1183 - (void) repairWithSelector:(SEL)selector;
1184 - (void) setConfigurationData:(NSString *)data;
1187 @class PackageController;
1189 @protocol CydiaDelegate
1190 - (void) setPackageController:(PackageController *)view;
1191 - (void) clearPackage:(Package *)package;
1192 - (void) installPackage:(Package *)package;
1193 - (void) installPackages:(NSArray *)packages;
1194 - (void) removePackage:(Package *)package;
1195 - (void) beginUpdate;
1197 - (void) distUpgrade;
1199 - (void) updateData;
1201 - (void) showSettings;
1202 - (UIProgressHUD *) addProgressHUD;
1203 - (BOOL) hudIsShowing;
1204 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1205 - (CYViewController *) pageForPackage:(NSString *)name;
1206 - (PackageController *) packageController;
1207 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
1211 /* Status Delegation {{{ */
1213 public pkgAcquireStatus
1216 _transient NSObject<ProgressDelegate> *delegate_;
1224 void setDelegate(id delegate) {
1225 delegate_ = delegate;
1228 NSObject<ProgressDelegate> *getDelegate() const {
1232 virtual bool MediaChange(std::string media, std::string drive) {
1236 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1239 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1240 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1241 [delegate_ setProgressTitle:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), [NSString stringWithUTF8String:item.ShortDesc.c_str()]]];
1244 virtual void Done(pkgAcquire::ItemDesc &item) {
1247 virtual void Fail(pkgAcquire::ItemDesc &item) {
1249 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1250 item.Owner->Status == pkgAcquire::Item::StatDone
1254 std::string &error(item.Owner->ErrorText);
1258 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1259 NSArray *fields([description componentsSeparatedByString:@" "]);
1260 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1262 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
1263 withObject:[NSArray arrayWithObjects:
1264 [NSString stringWithUTF8String:error.c_str()],
1271 virtual bool Pulse(pkgAcquire *Owner) {
1272 bool value = pkgAcquireStatus::Pulse(Owner);
1275 double(CurrentBytes + CurrentItems) /
1276 double(TotalBytes + TotalItems)
1279 [delegate_ setProgressPercent:percent];
1280 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1283 virtual void Start() {
1284 [delegate_ startProgress];
1287 virtual void Stop() {
1291 /* Progress Delegation {{{ */
1296 _transient id<ProgressDelegate> delegate_;
1300 virtual void Update() {
1301 /*if (abs(Percent - percent_) > 2)
1302 //NSLog(@"%s:%s:%f", Op.c_str(), SubOp.c_str(), Percent);
1306 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1307 [delegate_ setProgressPercent:(Percent / 100)];*/
1317 void setDelegate(id delegate) {
1318 delegate_ = delegate;
1321 id getDelegate() const {
1325 virtual void Done() {
1327 //[delegate_ setProgressPercent:1];
1332 /* Database Interface {{{ */
1333 typedef std::map< unsigned long, _H<Source> > SourceMap;
1335 @interface Database : NSObject {
1341 pkgCacheFile cache_;
1342 pkgDepCache::Policy *policy_;
1343 pkgRecords *records_;
1344 pkgProblemResolver *resolver_;
1345 pkgAcquire *fetcher_;
1347 SPtr<pkgPackageManager> manager_;
1348 pkgSourceList *list_;
1351 CFMutableArrayRef packages_;
1353 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1362 + (Database *) sharedInstance;
1365 - (void) _readCydia:(NSNumber *)fd;
1366 - (void) _readStatus:(NSNumber *)fd;
1367 - (void) _readOutput:(NSNumber *)fd;
1371 - (Package *) packageWithName:(NSString *)name;
1373 - (pkgCacheFile &) cache;
1374 - (pkgDepCache::Policy *) policy;
1375 - (pkgRecords *) records;
1376 - (pkgProblemResolver *) resolver;
1377 - (pkgAcquire &) fetcher;
1378 - (pkgSourceList &) list;
1379 - (NSArray *) packages;
1380 - (NSArray *) sources;
1381 - (void) reloadData;
1389 - (void) updateWithStatus:(Status &)status;
1391 - (void) setDelegate:(id)delegate;
1392 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1395 /* Delegate Helpers {{{ */
1396 @implementation NSObject (ProgressDelegate)
1398 - (void) _setProgressErrorPackage:(NSArray *)args {
1399 [self performSelector:@selector(setProgressError:forPackage:)
1400 withObject:[args objectAtIndex:0]
1401 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1405 - (void) _setProgressErrorTitle:(NSArray *)args {
1406 [self performSelector:@selector(setProgressError:withTitle:)
1407 withObject:[args objectAtIndex:0]
1408 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1412 - (void) _setProgressError:(NSString *)error withTitle:(NSString *)title {
1413 [self performSelectorOnMainThread:@selector(_setProgressErrorTitle:)
1414 withObject:[NSArray arrayWithObjects:error, title, nil]
1419 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
1420 Package *package = id == nil ? nil : [[Database sharedInstance] packageWithName:id];
1422 [self performSelector:@selector(setProgressError:withTitle:)
1424 withObject:(package == nil ? id : [package name])
1431 // Cytore Definitions {{{
1432 struct PackageValue :
1435 Cytore::Offset<void> reserved_;
1436 Cytore::Offset<PackageValue> next_;
1438 uint32_t index_ : 23;
1439 uint32_t subscribed_ : 1;
1455 Cytore::Offset<void> reserved_;
1456 Cytore::Offset<PackageValue> packages_[1 << 16];
1459 static Cytore::File<MetaValue> MetaFile_;
1461 // Cytore Helper Functions {{{
1462 static PackageValue *PackageFind(const char *name, size_t length, Cytore::Offset<PackageValue> *cache = NULL) {
1463 SplitHash nhash = { hashlittle(name, length) };
1465 PackageValue *metadata;
1467 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1468 offset: if (offset->IsNull()) {
1469 *offset = MetaFile_.New<PackageValue>(length + 1);
1470 metadata = &MetaFile_.Get(*offset);
1472 memcpy(metadata->name_, name, length + 1);
1473 metadata->nhash_ = nhash.u16[1];
1475 metadata = &MetaFile_.Get(*offset);
1477 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1478 offset = &metadata->next_;
1489 static void PackageImport(const void *key, const void *value, void *context) {
1491 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1492 NSLog(@"failed to import package %@", key);
1496 PackageValue *metadata(PackageFind(buffer, strlen(buffer)));
1497 NSDictionary *package((NSDictionary *) value);
1499 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1500 if ([subscribed boolValue])
1501 metadata->subscribed_ = true;
1503 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1504 time_t time([date timeIntervalSince1970]);
1505 if (metadata->first_ > time || metadata->first_ == 0)
1506 metadata->first_ = time;
1509 if (NSDate *date = [package objectForKey:@"LastSeen"]) {
1510 time_t time([date timeIntervalSince1970]);
1511 if (metadata->last_ < time || metadata->last_ == 0) {
1512 metadata->last_ = time;
1515 } else if (metadata->last_ == 0) last: {
1516 NSString *version([package objectForKey:@"LastVersion"]);
1517 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1518 size_t length(strlen(buffer));
1519 uint16_t vhash(hashlittle(buffer, length));
1521 size_t capped(std::min<size_t>(8, length));
1522 char *latest(buffer + length - capped);
1524 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1525 metadata->vhash_ = vhash;
1531 /* Source Class {{{ */
1532 @interface Source : NSObject {
1533 CYString depiction_;
1534 CYString description_;
1540 CYString distribution_;
1545 NSString *authority_;
1547 CYString defaultIcon_;
1549 NSDictionary *record_;
1553 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1555 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1557 - (NSString *) depictionForPackage:(NSString *)package;
1558 - (NSString *) supportForPackage:(NSString *)package;
1560 - (NSDictionary *) record;
1564 - (NSString *) distribution;
1565 - (NSString *) type;
1567 - (NSString *) host;
1569 - (NSString *) name;
1570 - (NSString *) description;
1571 - (NSString *) label;
1572 - (NSString *) origin;
1573 - (NSString *) version;
1575 - (NSString *) defaultIcon;
1579 @implementation Source
1583 distribution_.clear();
1586 description_.clear();
1592 defaultIcon_.clear();
1594 if (record_ != nil) {
1604 if (authority_ != nil) {
1605 [authority_ release];
1611 // XXX: this is a very inefficient way to call these deconstructors
1616 + (NSArray *) _attributeKeys {
1617 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1620 - (NSArray *) attributeKeys {
1621 return [[self class] _attributeKeys];
1624 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1625 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1628 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1631 trusted_ = index->IsTrusted();
1633 uri_.set(pool, index->GetURI());
1634 distribution_.set(pool, index->GetDist());
1635 type_.set(pool, index->GetType());
1637 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1638 if (dindex != NULL) {
1640 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1643 pkgTagFile tags(&fd);
1645 pkgTagSection section;
1652 {"default-icon", &defaultIcon_},
1653 {"depiction", &depiction_},
1654 {"description", &description_},
1656 {"origin", &origin_},
1657 {"support", &support_},
1658 {"version", &version_},
1661 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1662 const char *start, *end;
1664 if (section.Find(names[i].name_, start, end)) {
1665 CYString &value(*names[i].value_);
1666 value.set(pool, start, end - start);
1672 record_ = [Sources_ objectForKey:[self key]];
1674 record_ = [record_ retain];
1676 NSURL *url([NSURL URLWithString:uri_]);
1680 host_ = [[host_ lowercaseString] retain];
1685 authority_ = [url path];
1687 if (authority_ != nil)
1688 authority_ = [authority_ retain];
1691 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1692 if ((self = [super init]) != nil) {
1693 [self setMetaIndex:index inPool:pool];
1697 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1698 NSDictionary *lhr = [self record];
1699 NSDictionary *rhr = [source record];
1702 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1704 NSString *lhs = [self name];
1705 NSString *rhs = [source name];
1707 if ([lhs length] != 0 && [rhs length] != 0) {
1708 unichar lhc = [lhs characterAtIndex:0];
1709 unichar rhc = [rhs characterAtIndex:0];
1711 if (isalpha(lhc) && !isalpha(rhc))
1712 return NSOrderedAscending;
1713 else if (!isalpha(lhc) && isalpha(rhc))
1714 return NSOrderedDescending;
1717 return [lhs compare:rhs options:LaxCompareOptions_];
1720 - (NSString *) depictionForPackage:(NSString *)package {
1721 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1724 - (NSString *) supportForPackage:(NSString *)package {
1725 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1728 - (NSDictionary *) record {
1736 - (NSString *) uri {
1740 - (NSString *) distribution {
1741 return distribution_;
1744 - (NSString *) type {
1748 - (NSString *) key {
1749 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1752 - (NSString *) host {
1756 - (NSString *) name {
1757 return origin_.empty() ? authority_ : origin_;
1760 - (NSString *) description {
1761 return description_;
1764 - (NSString *) label {
1765 return label_.empty() ? authority_ : label_;
1768 - (NSString *) origin {
1772 - (NSString *) version {
1776 - (NSString *) defaultIcon {
1777 return defaultIcon_;
1782 /* Relationship Class {{{ */
1783 @interface Relationship : NSObject {
1788 - (NSString *) type;
1790 - (NSString *) name;
1794 @implementation Relationship
1802 - (NSString *) type {
1810 - (NSString *) name {
1817 /* Package Class {{{ */
1818 struct ParsedPackage {
1823 CYString depiction_;
1833 @interface Package : NSObject {
1837 pkgCache::VerIterator version_;
1838 pkgCache::PkgIterator iterator_;
1839 _transient Database *database_;
1840 pkgCache::VerFileIterator file_;
1843 ParsedPackage *parsed_;
1846 _transient NSString *section$_;
1851 CYString installed_;
1856 NSMutableArray *tags_;
1859 Cytore::Offset<PackageValue> metadata_;
1864 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1865 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1867 - (pkgCache::PkgIterator) iterator;
1870 - (NSString *) section;
1871 - (NSString *) simpleSection;
1873 - (NSString *) longSection;
1874 - (NSString *) shortSection;
1878 - (Address *) maintainer;
1880 - (NSString *) longDescription;
1881 - (NSString *) shortDescription;
1884 - (PackageValue *) metadata;
1887 - (bool) subscribed;
1888 - (bool) setSubscribed:(bool)subscribed;
1892 - (NSString *) latest;
1893 - (NSString *) installed;
1894 - (BOOL) uninstalled;
1897 - (BOOL) upgradableAndEssential:(BOOL)essential;
1900 - (BOOL) unfiltered;
1904 - (BOOL) halfConfigured;
1905 - (BOOL) halfInstalled;
1907 - (NSString *) mode;
1910 - (NSString *) name;
1912 - (NSString *) homepage;
1913 - (NSString *) depiction;
1914 - (Address *) author;
1916 - (NSString *) support;
1918 - (NSArray *) files;
1919 - (NSArray *) warnings;
1920 - (NSArray *) applications;
1922 - (Source *) source;
1923 - (NSString *) role;
1925 - (BOOL) matches:(NSString *)text;
1927 - (bool) hasSupportingRole;
1928 - (BOOL) hasTag:(NSString *)tag;
1929 - (NSString *) primaryPurpose;
1930 - (NSArray *) purposes;
1931 - (bool) isCommercial;
1933 - (CYString &) cyname;
1935 - (uint32_t) compareBySection:(NSArray *)sections;
1940 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1941 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1942 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1943 - (bool) isVisibleInSection:(NSString *)section;
1944 - (bool) isVisibleInSource:(Source *)source;
1948 uint32_t PackageChangesRadix(Package *self, void *) {
1953 uint32_t timestamp : 30;
1954 uint32_t ignored : 1;
1955 uint32_t upgradable : 1;
1959 bool upgradable([self upgradableAndEssential:YES]);
1960 value.bits.upgradable = upgradable ? 1 : 0;
1963 value.bits.timestamp = 0;
1964 value.bits.ignored = [self ignored] ? 0 : 1;
1965 value.bits.upgradable = 1;
1967 value.bits.timestamp = [self seen] >> 2;
1968 value.bits.ignored = 0;
1969 value.bits.upgradable = 0;
1972 return _not(uint32_t) - value.key;
1975 _finline static void Stifle(uint8_t &value) {
1978 uint32_t PackagePrefixRadix(Package *self, void *context) {
1979 size_t offset(reinterpret_cast<size_t>(context));
1980 CYString &name([self cyname]);
1982 size_t size(name.size());
1985 char *text(name.data());
1988 if (!isdigit(text[0]))
1992 while (size != digits && isdigit(text[digits]))
2002 if (offset == 0 && zeros != 0) {
2003 memset(data, '0', zeros);
2004 memcpy(data + zeros, text, 4 - zeros);
2006 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2007 if (size <= offset - zeros)
2010 text += offset - zeros;
2011 size -= offset - zeros;
2014 memcpy(data, text, 4);
2016 memcpy(data, text, size);
2017 memset(data + size, 0, 4 - size);
2020 for (size_t i(0); i != 4; ++i)
2021 if (isalpha(data[i]))
2029 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2031 /* XXX: ntohl may be more honest */
2032 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2035 CYString &(*PackageName)(Package *self, SEL sel);
2037 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2038 _profile(PackageNameCompare)
2039 CYString &lhi(PackageName(lhs, @selector(cyname)));
2040 CYString &rhi(PackageName(rhs, @selector(cyname)));
2041 CFStringRef lhn(lhi), rhn(rhi);
2044 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2045 else if (rhn == NULL)
2046 return NSOrderedDescending;
2048 _profile(PackageNameCompare$NumbersLast)
2049 if (!lhi.empty() && !rhi.empty()) {
2050 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2051 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2052 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2053 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2054 return lha ? NSOrderedAscending : NSOrderedDescending;
2058 CFIndex length = CFStringGetLength(lhn);
2060 _profile(PackageNameCompare$Compare)
2061 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2066 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2067 return PackageNameCompare(*lhs, *rhs, context);
2070 struct PackageNameOrdering :
2071 std::binary_function<Package *, Package *, bool>
2073 _finline bool operator ()(Package *lhs, Package *rhs) const {
2074 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2078 @implementation Package
2080 - (NSString *) description {
2081 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2085 if (parsed_ != NULL)
2099 + (NSString *) webScriptNameForSelector:(SEL)selector {
2100 if (selector == @selector(hasTag:))
2106 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2107 return [self webScriptNameForSelector:selector] == nil;
2110 + (NSArray *) _attributeKeys {
2111 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];
2114 - (NSArray *) attributeKeys {
2115 return [[self class] _attributeKeys];
2118 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2119 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2123 if (parsed_ != NULL)
2125 @synchronized (database_) {
2126 if ([database_ era] != era_ || file_.end())
2129 ParsedPackage *parsed(new ParsedPackage);
2132 _profile(Package$parse)
2133 pkgRecords::Parser *parser;
2135 _profile(Package$parse$Lookup)
2136 parser = &[database_ records]->Lookup(file_);
2141 _profile(Package$parse$Find)
2146 {"icon", &parsed->icon_},
2147 {"depiction", &parsed->depiction_},
2148 {"homepage", &parsed->homepage_},
2149 {"website", &website},
2150 {"bugs", &parsed->bugs_},
2151 {"support", &parsed->support_},
2152 {"sponsor", &parsed->sponsor_},
2153 {"author", &parsed->author_},
2156 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2157 const char *start, *end;
2159 if (parser->Find(names[i].name_, start, end)) {
2160 CYString &value(*names[i].value_);
2161 _profile(Package$parse$Value)
2162 value.set(pool_, start, end - start);
2168 _profile(Package$parse$Tagline)
2169 const char *start, *end;
2170 if (parser->ShortDesc(start, end)) {
2171 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2174 while (stop != start && stop[-1] == '\r')
2176 parsed->tagline_.set(pool_, start, stop - start);
2180 _profile(Package$parse$Retain)
2181 if (parsed->homepage_.empty())
2182 parsed->homepage_ = website;
2183 if (parsed->homepage_ == parsed->depiction_)
2184 parsed->homepage_.clear();
2189 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2190 if ((self = [super init]) != nil) {
2191 _profile(Package$initWithVersion)
2192 era_ = [database era];
2197 _profile(Package$initWithVersion$ParentPkg)
2198 iterator_ = version.ParentPkg();
2201 database_ = database;
2203 _profile(Package$initWithVersion$Latest)
2204 latest_.set(NULL, StripVersion_(version_.VerStr()));
2207 pkgCache::VerIterator current;
2208 _profile(Package$initWithVersion$Versions)
2209 current = iterator_.CurrentVer();
2211 installed_.set(NULL, StripVersion_(current.VerStr()));
2213 if (!version_.end())
2214 file_ = version_.FileList();
2216 pkgCache &cache([database_ cache]);
2217 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2221 _profile(Package$initWithVersion$Name)
2222 id_.set(NULL, iterator_.Name());
2223 name_.set(NULL, iterator_.Display());
2226 _profile(Package$initWithVersion$lowercaseString)
2227 // XXX: do not use tolower() as this is not locale-specific? :(
2228 char *data(id_.data());
2229 for (size_t i(0), e(id_.size()); i != e; ++i)
2230 if ((data[i] & 0x20) == 0) {
2239 _profile(Package$initWithVersion$Tags)
2240 pkgCache::TagIterator tag(iterator_.TagList());
2242 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2244 const char *name(tag.Name());
2245 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2247 if (role_ == nil && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/)
2248 role_ = (NSString *) CYStringCreate(name + 6);
2250 if (strncmp(name, "cydia::", 7) == 0) {
2251 if (strcmp(name + 7, "essential") == 0)
2253 else if (strcmp(name + 7, "obsolete") == 0)
2258 } while (!tag.end());
2262 _profile(Package$initWithVersion$Metadata)
2263 PackageValue *metadata(PackageFind(id_.data(), id_.size(), &metadata_));
2265 const char *latest(version_.VerStr());
2266 size_t length(strlen(latest));
2268 uint16_t vhash(hashlittle(latest, length));
2270 size_t capped(std::min<size_t>(8, length));
2271 latest = latest + length - capped;
2273 if (metadata->first_ == 0)
2274 metadata->first_ = now_;
2276 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2277 metadata->last_ = now_;
2278 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2279 metadata->vhash_ = vhash;
2280 } else if (metadata->last_ == 0)
2281 metadata->last_ = metadata->first_;
2284 _profile(Package$initWithVersion$Section)
2285 section_.set(NULL, iterator_.Section());
2288 _profile(Package$initWithVersion$hasTag)
2289 essential_ |= ((iterator_->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2292 ignored_ = iterator_->SelectedState == pkgCache::State::Hold;
2296 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2297 pkgCache::VerIterator version;
2299 _profile(Package$packageWithIterator$GetCandidateVer)
2300 version = [database policy]->GetCandidateVer(iterator);
2306 return [[[Package alloc]
2307 initWithVersion:version
2314 - (pkgCache::PkgIterator) iterator {
2318 - (NSString *) section {
2319 if (section$_ == nil) {
2320 if (section_.empty())
2323 _profile(Package$section)
2324 std::replace(section_.data(), section_.data() + section_.size(), '_', ' ');
2325 NSString *name(section_);
2326 section$_ = [SectionMap_ objectForKey:name] ?: name;
2331 - (NSString *) simpleSection {
2332 if (NSString *section = [self section])
2333 return Simplify(section);
2338 - (NSString *) longSection {
2339 return LocalizeSection([self section]);
2342 - (NSString *) shortSection {
2343 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2346 - (NSString *) uri {
2349 pkgIndexFile *index;
2350 pkgCache::PkgFileIterator file(file_.File());
2351 if (![database_ list].FindIndex(file, index))
2353 return [NSString stringWithUTF8String:iterator_->Path];
2354 //return [NSString stringWithUTF8String:file.Site()];
2355 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2359 - (Address *) maintainer {
2360 @synchronized (database_) {
2361 if ([database_ era] != era_ || file_.end())
2364 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2365 const std::string &maintainer(parser->Maintainer());
2366 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2370 @synchronized (database_) {
2371 if ([database_ era] != era_ || version_.end())
2374 return version_->InstalledSize;
2377 - (NSString *) longDescription {
2378 @synchronized (database_) {
2379 if ([database_ era] != era_ || file_.end())
2382 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2383 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2385 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2386 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2387 if ([lines count] < 2)
2390 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2391 for (size_t i(1), e([lines count]); i != e; ++i) {
2392 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2393 [trimmed addObject:trim];
2396 return [trimmed componentsJoinedByString:@"\n"];
2399 - (NSString *) shortDescription {
2400 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2404 _profile(Package$index)
2405 CFStringRef name((CFStringRef) [self name]);
2406 if (CFStringGetLength(name) == 0)
2408 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2409 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2411 return toupper(character);
2415 - (PackageValue *) metadata {
2416 return &MetaFile_.Get(metadata_);
2420 PackageValue *metadata([self metadata]);
2421 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2424 - (bool) subscribed {
2425 return [self metadata]->subscribed_;
2428 - (bool) setSubscribed:(bool)subscribed {
2429 PackageValue *metadata([self metadata]);
2430 if (metadata->subscribed_ == subscribed)
2432 metadata->subscribed_ = subscribed;
2440 - (NSString *) latest {
2444 - (NSString *) installed {
2448 - (BOOL) uninstalled {
2449 return installed_.empty();
2453 return !version_.end();
2456 - (BOOL) upgradableAndEssential:(BOOL)essential {
2457 _profile(Package$upgradableAndEssential)
2458 pkgCache::VerIterator current(iterator_.CurrentVer());
2460 return essential && essential_;
2462 return !version_.end() && version_ != current;
2466 - (BOOL) essential {
2471 return [database_ cache][iterator_].InstBroken();
2474 - (BOOL) unfiltered {
2475 _profile(Package$unfiltered$obsolete)
2480 _profile(Package$unfiltered$hasSupportingRole)
2481 if (![self hasSupportingRole])
2489 if (![self unfiltered])
2492 NSString *section([self section]);
2494 _profile(Package$visible$isSectionVisible)
2495 if (section != nil && !isSectionVisible(section))
2503 unsigned char current(iterator_->CurrentState);
2504 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2507 - (BOOL) halfConfigured {
2508 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2511 - (BOOL) halfInstalled {
2512 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2516 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2517 return state.Mode != pkgDepCache::ModeKeep;
2520 - (NSString *) mode {
2521 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2523 switch (state.Mode) {
2524 case pkgDepCache::ModeDelete:
2525 if ((state.iFlags & pkgDepCache::Purge) != 0)
2529 case pkgDepCache::ModeKeep:
2530 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2531 return @"REINSTALL";
2532 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2536 case pkgDepCache::ModeInstall:
2537 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2538 return @"REINSTALL";
2539 else*/ switch (state.Status) {
2541 return @"DOWNGRADE";
2547 return @"NEW_INSTALL";
2558 - (NSString *) name {
2559 return name_.empty() ? id_ : name_;
2562 - (UIImage *) icon {
2563 NSString *section = [self simpleSection];
2566 if (parsed_ != NULL)
2567 if (NSString *href = parsed_->icon_)
2568 if ([href hasPrefix:@"file:///"])
2569 // XXX: correct escaping
2570 icon = [UIImage imageAtPath:[href substringFromIndex:7]];
2571 if (icon == nil) if (section != nil)
2572 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2573 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2574 if ([dicon hasPrefix:@"file:///"])
2575 // XXX: correct escaping
2576 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2578 icon = [UIImage applicationImageNamed:@"unknown.png"];
2582 - (NSString *) homepage {
2583 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2586 - (NSString *) depiction {
2587 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2590 - (Address *) sponsor {
2591 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [Address addressWithString:parsed_->sponsor_];
2594 - (Address *) author {
2595 return parsed_ == NULL || parsed_->author_.empty() ? nil : [Address addressWithString:parsed_->author_];
2598 - (NSString *) support {
2599 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2602 - (NSArray *) files {
2603 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2604 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2607 fin.open([path UTF8String]);
2612 while (std::getline(fin, line))
2613 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2618 - (NSArray *) warnings {
2619 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2620 const char *name(iterator_.Name());
2622 size_t length(strlen(name));
2623 if (length < 2) invalid:
2624 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2625 else for (size_t i(0); i != length; ++i)
2627 /* XXX: technically this is not allowed */
2628 (name[i] < 'A' || name[i] > 'Z') &&
2629 (name[i] < 'a' || name[i] > 'z') &&
2630 (name[i] < '0' || name[i] > '9') &&
2631 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2634 if (strcmp(name, "cydia") != 0) {
2637 bool _private = false;
2640 bool repository = [[self section] isEqualToString:@"Repositories"];
2642 if (NSArray *files = [self files])
2643 for (NSString *file in files)
2644 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2646 else if (!user && [file isEqualToString:@"/User"])
2648 else if (!_private && [file isEqualToString:@"/private"])
2650 else if (!stash && [file isEqualToString:@"/var/stash"])
2653 /* XXX: this is not sensitive enough. only some folders are valid. */
2654 if (cydia && !repository)
2655 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2657 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2659 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2661 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2664 return [warnings count] == 0 ? nil : warnings;
2667 - (NSArray *) applications {
2668 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2670 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2672 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2673 if (NSArray *files = [self files])
2674 for (NSString *file in files)
2675 if (application_r(file)) {
2676 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2677 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2678 if ([id isEqualToString:me])
2681 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2683 display = application_r[1];
2685 NSString *bundle([file stringByDeletingLastPathComponent]);
2686 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2687 if (icon == nil || [icon length] == 0)
2689 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2691 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2692 [applications addObject:application];
2694 [application addObject:id];
2695 [application addObject:display];
2696 [application addObject:url];
2699 return [applications count] == 0 ? nil : applications;
2702 - (Source *) source {
2703 if (source_ == nil) {
2704 @synchronized (database_) {
2705 if ([database_ era] != era_ || file_.end())
2706 source_ = (Source *) [NSNull null];
2708 source_ = [([database_ getSource:file_.File()] ?: (Source *) [NSNull null]) retain];
2712 return source_ == (Source *) [NSNull null] ? nil : source_;
2715 - (NSString *) role {
2719 - (BOOL) matches:(NSString *)text {
2725 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2726 if (range.location != NSNotFound)
2729 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2730 if (range.location != NSNotFound)
2733 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2734 if (range.location != NSNotFound)
2740 - (bool) hasSupportingRole {
2743 if ([role_ isEqualToString:@"enduser"])
2745 if ([Role_ isEqualToString:@"User"])
2747 if ([role_ isEqualToString:@"hacker"])
2749 if ([Role_ isEqualToString:@"Hacker"])
2751 if ([role_ isEqualToString:@"developer"])
2753 if ([Role_ isEqualToString:@"Developer"])
2758 - (BOOL) hasTag:(NSString *)tag {
2759 return tags_ == nil ? NO : [tags_ containsObject:tag];
2762 - (NSString *) primaryPurpose {
2763 for (NSString *tag in tags_)
2764 if ([tag hasPrefix:@"purpose::"])
2765 return [tag substringFromIndex:9];
2769 - (NSArray *) purposes {
2770 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2771 for (NSString *tag in tags_)
2772 if ([tag hasPrefix:@"purpose::"])
2773 [purposes addObject:[tag substringFromIndex:9]];
2774 return [purposes count] == 0 ? nil : purposes;
2777 - (bool) isCommercial {
2778 return [self hasTag:@"cydia::commercial"];
2781 - (CYString &) cyname {
2782 return name_.empty() ? id_ : name_;
2785 - (uint32_t) compareBySection:(NSArray *)sections {
2786 NSString *section([self section]);
2787 for (size_t i(0), e([sections count]); i != e; ++i) {
2788 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2792 return _not(uint32_t);
2796 @synchronized (database_) {
2797 pkgProblemResolver *resolver = [database_ resolver];
2798 resolver->Clear(iterator_);
2800 pkgCacheFile &cache([database_ cache]);
2801 cache->SetReInstall(iterator_, false);
2802 cache->MarkKeep(iterator_, false);
2806 @synchronized (database_) {
2807 pkgProblemResolver *resolver = [database_ resolver];
2808 resolver->Clear(iterator_);
2809 resolver->Protect(iterator_);
2811 pkgCacheFile &cache([database_ cache]);
2812 cache->SetReInstall(iterator_, false);
2813 cache->MarkInstall(iterator_, false);
2815 pkgDepCache::StateCache &state((*cache)[iterator_]);
2816 if (!state.Install())
2817 cache->SetReInstall(iterator_, true);
2821 @synchronized (database_) {
2822 pkgProblemResolver *resolver = [database_ resolver];
2823 resolver->Clear(iterator_);
2824 resolver->Remove(iterator_);
2825 resolver->Protect(iterator_);
2827 pkgCacheFile &cache([database_ cache]);
2828 cache->SetReInstall(iterator_, false);
2829 cache->MarkDelete(iterator_, true);
2832 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2833 _profile(Package$isUnfilteredAndSearchedForBy)
2836 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2837 value &= [self unfiltered];
2840 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2841 value &= [self matches:search];
2848 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2849 if ([search length] == 0)
2852 _profile(Package$isUnfilteredAndSelectedForBy)
2855 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2856 value &= [self unfiltered];
2859 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2860 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2867 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
2868 return ![self uninstalled] && (![number boolValue] && ![role_ isEqualToString:@"cydia"] || [self unfiltered]);
2871 - (bool) isVisibleInSection:(NSString *)name {
2872 NSString *section([self section]);
2876 section == nil && [name length] == 0 ||
2877 [name isEqualToString:section]
2878 ) && [self visible];
2881 - (bool) isVisibleInSource:(Source *)source {
2882 return [self source] == source && [self visible];
2887 /* Section Class {{{ */
2888 @interface Section : NSObject {
2893 NSString *localized_;
2896 - (NSComparisonResult) compareByLocalized:(Section *)section;
2897 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2898 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2899 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2900 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2901 - (NSString *) name;
2908 - (void) addToCount;
2910 - (void) setCount:(size_t)count;
2911 - (NSString *) localized;
2915 @implementation Section
2919 if (localized_ != nil)
2920 [localized_ release];
2924 - (NSComparisonResult) compareByLocalized:(Section *)section {
2925 NSString *lhs(localized_);
2926 NSString *rhs([section localized]);
2928 /*if ([lhs length] != 0 && [rhs length] != 0) {
2929 unichar lhc = [lhs characterAtIndex:0];
2930 unichar rhc = [rhs characterAtIndex:0];
2932 if (isalpha(lhc) && !isalpha(rhc))
2933 return NSOrderedAscending;
2934 else if (!isalpha(lhc) && isalpha(rhc))
2935 return NSOrderedDescending;
2938 return [lhs compare:rhs options:LaxCompareOptions_];
2941 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2942 if ((self = [self initWithName:name localize:NO]) != nil) {
2943 if (localized != nil)
2944 localized_ = [localized retain];
2948 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2949 return [self initWithName:name row:0 localize:localize];
2952 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2953 if ((self = [super init]) != nil) {
2954 name_ = [name retain];
2958 localized_ = [LocalizeSection(name_) retain];
2962 /* XXX: localize the index thingees */
2963 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2964 if ((self = [super init]) != nil) {
2965 name_ = [[NSString stringWithCharacters:&index length:1] retain];
2971 - (NSString *) name {
2991 - (void) addToCount {
2995 - (void) setCount:(size_t)count {
2999 - (NSString *) localized {
3006 static NSString *Colon_;
3007 static NSString *Elision_;
3008 static NSString *Error_;
3009 static NSString *Warning_;
3011 /* Database Implementation {{{ */
3012 @implementation Database
3014 + (Database *) sharedInstance {
3015 static Database *instance;
3016 if (instance == nil)
3017 instance = [[Database alloc] init];
3025 - (void) releasePackages {
3026 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3027 CFArrayRemoveAllValues(packages_);
3031 // XXX: actually implement this thing
3033 [self releasePackages];
3034 apr_pool_destroy(pool_);
3035 NSRecycleZone(zone_);
3039 - (void) _readCydia:(NSNumber *)fd { _pooled
3040 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3041 std::istream is(&ib);
3044 static Pcre finish_r("^finish:([^:]*)$");
3046 while (std::getline(is, line)) {
3047 const char *data(line.c_str());
3048 size_t size = line.size();
3049 lprintf("C:%s\n", data);
3051 if (finish_r(data, size)) {
3052 NSString *finish = finish_r[1];
3053 int index = [Finishes_ indexOfObject:finish];
3054 if (index != INT_MAX && index > Finish_)
3062 - (void) _readStatus:(NSNumber *)fd { _pooled
3063 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3064 std::istream is(&ib);
3067 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3068 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3070 while (std::getline(is, line)) {
3071 const char *data(line.c_str());
3072 size_t size(line.size());
3073 lprintf("S:%s\n", data);
3075 if (conffile_r(data, size)) {
3076 [delegate_ setConfigurationData:conffile_r[1]];
3077 } else if (strncmp(data, "status: ", 8) == 0) {
3078 NSString *string = [NSString stringWithUTF8String:(data + 8)];
3079 [delegate_ setProgressTitle:string];
3080 } else if (pmstatus_r(data, size)) {
3081 std::string type([pmstatus_r[1] UTF8String]);
3082 NSString *id = pmstatus_r[2];
3084 float percent([pmstatus_r[3] floatValue]);
3085 [delegate_ setProgressPercent:(percent / 100)];
3087 NSString *string = pmstatus_r[4];
3089 if (type == "pmerror")
3090 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3091 withObject:[NSArray arrayWithObjects:string, id, nil]
3094 else if (type == "pmstatus") {
3095 [delegate_ setProgressTitle:string];
3096 } else if (type == "pmconffile")
3097 [delegate_ setConfigurationData:string];
3099 lprintf("E:unknown pmstatus\n");
3101 lprintf("E:unknown status\n");
3107 - (void) _readOutput:(NSNumber *)fd { _pooled
3108 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3109 std::istream is(&ib);
3112 while (std::getline(is, line)) {
3113 lprintf("O:%s\n", line.c_str());
3114 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
3124 - (Package *) packageWithName:(NSString *)name {
3125 @synchronized (self) {
3126 if (static_cast<pkgDepCache *>(cache_) == NULL)
3128 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3129 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3133 if ((self = [super init]) != nil) {
3140 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3141 apr_pool_create(&pool_, NULL);
3143 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
3147 _assert(pipe(fds) != -1);
3150 _config->Set("APT::Keep-Fds::", cydiafd_);
3151 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3154 detachNewThreadSelector:@selector(_readCydia:)
3156 withObject:[NSNumber numberWithInt:fds[0]]
3159 _assert(pipe(fds) != -1);
3163 detachNewThreadSelector:@selector(_readStatus:)
3165 withObject:[NSNumber numberWithInt:fds[0]]
3168 _assert(pipe(fds) != -1);
3169 _assert(dup2(fds[0], 0) != -1);
3170 _assert(close(fds[0]) != -1);
3172 input_ = fdopen(fds[1], "a");
3174 _assert(pipe(fds) != -1);
3175 _assert(dup2(fds[1], 1) != -1);
3176 _assert(close(fds[1]) != -1);
3179 detachNewThreadSelector:@selector(_readOutput:)
3181 withObject:[NSNumber numberWithInt:fds[0]]
3186 - (pkgCacheFile &) cache {
3190 - (pkgDepCache::Policy *) policy {
3194 - (pkgRecords *) records {
3198 - (pkgProblemResolver *) resolver {
3202 - (pkgAcquire &) fetcher {
3206 - (pkgSourceList &) list {
3210 - (NSArray *) packages {
3211 return (NSArray *) packages_;
3214 - (NSArray *) sources {
3215 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3216 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3217 [sources addObject:i->second];
3221 - (NSArray *) issues {
3222 if (cache_->BrokenCount() == 0)
3225 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3227 for (Package *package in [self packages]) {
3228 if (![package broken])
3230 pkgCache::PkgIterator pkg([package iterator]);
3232 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3233 [entry addObject:[package name]];
3234 [issues addObject:entry];
3236 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3240 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3241 pkgCache::DepIterator start;
3242 pkgCache::DepIterator end;
3243 dep.GlobOr(start, end); // ++dep
3245 if (!cache_->IsImportantDep(end))
3247 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3250 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3251 [entry addObject:failure];
3252 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3254 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3255 if (Package *package = [self packageWithName:name])
3256 name = [package name];
3257 [failure addObject:name];
3259 pkgCache::PkgIterator target(start.TargetPkg());
3260 if (target->ProvidesList != 0)
3261 [failure addObject:@"?"];
3263 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3265 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3266 else if (!cache_[target].CandidateVerIter(cache_).end())
3267 [failure addObject:@"-"];
3268 else if (target->ProvidesList == 0)
3269 [failure addObject:@"!"];
3271 [failure addObject:@"%"];
3275 if (start.TargetVer() != 0)
3276 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3287 - (bool) popErrorWithTitle:(NSString *)title {
3289 std::string message;
3291 while (!_error->empty()) {
3293 bool warning(!_error->PopMessage(error));
3297 size_t size(error.size());
3298 if (size == 0 || error[size - 1] != '\n')
3300 error.resize(size - 1);
3302 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3304 if (!message.empty())
3309 if (fatal && !message.empty())
3310 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3315 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3316 return [self popErrorWithTitle:title] || !success;
3319 - (void) reloadData { CYPoolStart() {
3320 @synchronized (self) {
3323 [self releasePackages];
3344 apr_pool_clear(pool_);
3345 NSRecycleZone(zone_);
3347 int chk(creat("/tmp/cydia.chk", 0644));
3351 NSString *title(UCLocalize("DATABASE"));
3354 if (!cache_.Open(progress_, true)) { pop:
3356 bool warning(!_error->PopMessage(error));
3357 lprintf("cache_.Open():[%s]\n", error.c_str());
3359 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3360 [delegate_ repairWithSelector:@selector(configure)];
3361 else if (error == "The package lists or status file could not be parsed or opened.")
3362 [delegate_ repairWithSelector:@selector(update)];
3363 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3364 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3365 // else if (error == "The list of sources could not be read.")
3367 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3376 unlink("/tmp/cydia.chk");
3378 now_ = [[NSDate date] timeIntervalSince1970];
3380 policy_ = new pkgDepCache::Policy();
3381 records_ = new pkgRecords(cache_);
3382 resolver_ = new pkgProblemResolver(cache_);
3383 fetcher_ = new pkgAcquire(&status_);
3386 list_ = new pkgSourceList();
3387 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3390 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3391 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3395 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3398 if (cache_->BrokenCount() != 0) {
3399 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3402 if (cache_->BrokenCount() != 0) {
3403 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3407 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3411 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3412 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3413 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3414 // XXX: this could be more intelligent
3415 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3416 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3418 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3423 /*std::vector<Package *> packages;
3424 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3425 [packages_ release];
3430 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3431 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3432 //packages.push_back(package);
3433 CFArrayAppendValue(packages_, [package retain]);
3437 /*if (packages.empty())
3438 packages_ = [[NSArray alloc] init];
3440 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3443 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3444 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3445 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3453 /*if (!packages.empty())
3454 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3455 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3457 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3459 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3461 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3465 } } CYPoolEnd() _trace(); }
3468 @synchronized (self) {
3470 resolver_ = new pkgProblemResolver(cache_);
3472 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator) {
3473 if (!cache_[iterator].Keep()) {
3474 cache_->MarkKeep(iterator, false);
3475 cache_->SetReInstall(iterator, false);
3480 - (void) configure {
3481 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3482 system([dpkg UTF8String]);
3486 // XXX: I don't remember this condition
3491 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3493 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3495 if ([self popErrorWithTitle:title])
3499 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3502 public pkgArchiveCleaner
3505 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3510 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3517 fetcher_->Shutdown();
3519 pkgRecords records(cache_);
3521 lock_ = new FileFd();
3522 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3524 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3526 if ([self popErrorWithTitle:title])
3530 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3533 manager_ = (_system->CreatePM(cache_));
3534 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3541 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3543 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3545 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3547 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3548 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3551 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3556 bool failed = false;
3557 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3558 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3560 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3563 std::string uri = (*item)->DescURI();
3564 std::string error = (*item)->ErrorText;
3566 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3569 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3570 withObject:[NSArray arrayWithObjects:
3571 [NSString stringWithUTF8String:error.c_str()],
3583 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3585 if (_error->PendingError()) {
3590 if (result == pkgPackageManager::Failed) {
3595 if (result != pkgPackageManager::Completed) {
3600 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3602 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3604 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3605 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3608 if (![before isEqualToArray:after])
3613 NSString *title(UCLocalize("UPGRADE"));
3614 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3620 [self updateWithStatus:status_];
3623 - (void) updateWithStatus:(Status &)status {
3624 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3625 NSString *title(UCLocalize("REFRESHING_DATA"));
3628 if (!list.ReadMainList())
3629 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3632 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3633 if ([self popErrorWithTitle:title])
3636 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3637 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */
3638 /* XXX: why the hell is an empty if statement a clang error? */ (void) 0;
3640 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3644 - (void) setDelegate:(id)delegate {
3645 delegate_ = delegate;
3646 status_.setDelegate(delegate);
3647 progress_.setDelegate(delegate);
3650 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3651 SourceMap::const_iterator i(sources_.find(file->ID));
3652 return i == sources_.end() ? nil : i->second;
3658 /* Confirmation Controller {{{ */
3659 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3660 if (!iterator.end())
3661 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3662 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3664 pkgCache::PkgIterator package(dep.TargetPkg());
3667 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3675 /* Web Scripting {{{ */
3676 @interface CydiaObject : NSObject {
3678 _transient id delegate_;
3681 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3684 @implementation CydiaObject
3687 [indirect_ release];
3691 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3692 if ((self = [super init]) != nil) {
3693 indirect_ = [indirect retain];
3697 - (void) setDelegate:(id)delegate {
3698 delegate_ = delegate;
3701 + (NSArray *) _attributeKeys {
3702 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3705 - (NSArray *) attributeKeys {
3706 return [[self class] _attributeKeys];
3709 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3710 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3713 - (NSString *) device {
3714 return [[UIDevice currentDevice] uniqueIdentifier];
3717 #if 0 // XXX: implement!
3718 - (NSString *) mac {
3719 if (![indirect_ promptForSensitive:@"Mac Address"])
3723 - (NSString *) serial {
3724 if (![indirect_ promptForSensitive:@"Serial #"])
3728 - (NSString *) firewire {
3729 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3733 - (NSString *) imei {
3734 if (![indirect_ promptForSensitive:@"IMEI"])
3739 + (NSString *) webScriptNameForSelector:(SEL)selector {
3740 if (selector == @selector(close))
3742 else if (selector == @selector(getInstalledPackages))
3743 return @"getInstalledPackages";
3744 else if (selector == @selector(getPackageById:))
3745 return @"getPackageById";
3746 else if (selector == @selector(installPackages:))
3747 return @"installPackages";
3748 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3749 return @"setButtonImage";
3750 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3751 return @"setButtonTitle";
3752 else if (selector == @selector(setPopupHook:))
3753 return @"setPopupHook";
3754 else if (selector == @selector(setSpecial:))
3755 return @"setSpecial";
3756 else if (selector == @selector(setToken:))
3758 else if (selector == @selector(setViewportWidth:))
3759 return @"setViewportWidth";
3760 else if (selector == @selector(supports:))
3762 else if (selector == @selector(stringWithFormat:arguments:))
3764 else if (selector == @selector(localizedStringForKey:value:table:))
3766 else if (selector == @selector(du:))
3768 else if (selector == @selector(statfs:))
3774 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3775 return [self webScriptNameForSelector:selector] == nil;
3778 - (BOOL) supports:(NSString *)feature {
3779 return [feature isEqualToString:@"window.open"];
3782 - (NSArray *) getInstalledPackages {
3783 NSArray *packages([[Database sharedInstance] packages]);
3784 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
3785 for (Package *package in packages)
3786 if ([package installed] != nil)
3787 [installed addObject:package];
3791 - (Package *) getPackageById:(NSString *)id {
3792 Package *package([[Database sharedInstance] packageWithName:id]);
3797 - (NSArray *) statfs:(NSString *)path {
3800 if (path == nil || statfs([path UTF8String], &stat) == -1)
3803 return [NSArray arrayWithObjects:
3804 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3805 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3806 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3810 - (NSNumber *) du:(NSString *)path {
3811 NSNumber *value(nil);
3814 _assert(pipe(fds) != -1);
3816 pid_t pid(ExecFork());
3818 _assert(dup2(fds[1], 1) != -1);
3819 _assert(close(fds[0]) != -1);
3820 _assert(close(fds[1]) != -1);
3821 /* XXX: this should probably not use du */
3822 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3827 _assert(close(fds[1]) != -1);
3829 if (FILE *du = fdopen(fds[0], "r")) {
3831 while (fgets(line, sizeof(line), du) != NULL) {
3832 size_t length(strlen(line));
3833 while (length != 0 && line[length - 1] == '\n')
3834 line[--length] = '\0';
3835 if (char *tab = strchr(line, '\t')) {
3837 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3842 } else _assert(close(fds[0]));
3846 if (waitpid(pid, &status, 0) == -1)
3849 else _assert(false);
3858 - (void) installPackages:(NSArray *)packages {
3859 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
3862 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3863 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3866 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3867 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3870 - (void) setSpecial:(id)function {
3871 [indirect_ setSpecial:function];
3874 - (void) setToken:(NSString *)token {
3877 Token_ = [token retain];
3879 [Metadata_ setObject:Token_ forKey:@"Token"];
3883 - (void) setPopupHook:(id)function {
3884 [indirect_ setPopupHook:function];
3887 - (void) setViewportWidth:(float)width {
3888 [indirect_ setViewportWidth:width];
3891 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3892 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3893 unsigned count([arguments count]);
3895 for (unsigned i(0); i != count; ++i)
3896 values[i] = [arguments objectAtIndex:i];
3897 return [[[NSString alloc] initWithFormat:format arguments:*(reinterpret_cast<va_list *>(&values))] autorelease];
3900 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3901 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3903 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3905 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3911 /* Cydia Browser Controller {{{ */
3912 @interface CYBrowserController : BrowserController {
3913 CydiaObject *cydia_;
3918 @implementation CYBrowserController
3925 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
3928 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
3929 [super webView:view didClearWindowObject:window forFrame:frame];
3931 WebDataSource *source([frame dataSource]);
3932 NSURLResponse *response([source response]);
3933 NSURL *url([response URL]);
3934 NSString *scheme([url scheme]);
3936 NSHTTPURLResponse *http;
3937 if (scheme != nil && ([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"]))
3938 http = (NSHTTPURLResponse *) response;
3942 NSDictionary *headers([http allHeaderFields]);
3943 NSString *host([url host]);
3944 [self setHeaders:headers forHost:host];
3947 [host isEqualToString:@"cydia.saurik.com"] ||
3948 [host hasSuffix:@".cydia.saurik.com"] ||
3949 [scheme isEqualToString:@"file"]
3951 [window setValue:cydia_ forKey:@"cydia"];
3954 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
3955 if (System_ != NULL)
3956 [request setValue:System_ forHTTPHeaderField:@"X-System"];
3957 if (Machine_ != NULL)
3958 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
3960 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
3962 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
3965 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
3966 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
3967 [self _setMoreHeaders:copy];
3971 - (void) setDelegate:(id)delegate {
3972 [super setDelegate:delegate];
3973 [cydia_ setDelegate:delegate];
3977 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
3978 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
3980 WebView *webview([[webview_ _documentView] webView]);
3982 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
3984 NSString *application = package == nil ? @"Cydia" : [NSString
3985 stringWithFormat:@"Cydia/%@",
3990 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
3992 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
3993 if (Product_ != nil)
3994 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
3996 [webview setApplicationNameForUserAgent:application];
4003 /* Confirmation {{{ */
4004 @protocol ConfirmationControllerDelegate
4005 - (void) cancelAndClear:(bool)clear;
4006 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4010 @interface ConfirmationController : CYBrowserController {
4011 _transient Database *database_;
4012 UIAlertView *essential_;
4019 - (id) initWithDatabase:(Database *)database;
4023 @implementation ConfirmationController
4030 if (essential_ != nil)
4031 [essential_ release];
4035 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4036 NSString *context([alert context]);
4038 if ([context isEqualToString:@"remove"]) {
4039 if (button == [alert cancelButtonIndex]) {
4040 [self dismissModalViewControllerAnimated:YES];
4041 } else if (button == [alert firstOtherButtonIndex]) {
4044 [delegate_ confirmWithNavigationController:[self navigationController]];
4047 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4048 } else if ([context isEqualToString:@"unable"]) {
4049 [self dismissModalViewControllerAnimated:YES];
4050 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4052 [super alertView:alert clickedButtonAtIndex:button];
4056 - (void) _doContinue {
4057 [self dismissModalViewControllerAnimated:YES];
4058 [delegate_ cancelAndClear:NO];
4061 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4062 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4066 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4067 [super webView:view didClearWindowObject:window forFrame:frame];
4068 [window setValue:changes_ forKey:@"changes"];
4069 [window setValue:issues_ forKey:@"issues"];
4070 [window setValue:sizes_ forKey:@"sizes"];
4071 [window setValue:self forKey:@"queue"];
4074 - (id) initWithDatabase:(Database *)database {
4075 if ((self = [super init]) != nil) {
4076 database_ = database;
4078 [[self navigationItem] setTitle:UCLocalize("CONFIRM")];
4080 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
4081 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
4082 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
4083 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
4084 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
4088 pkgDepCache::Policy *policy([database_ policy]);
4090 pkgCacheFile &cache([database_ cache]);
4091 NSArray *packages = [database_ packages];
4092 for (Package *package in packages) {
4093 pkgCache::PkgIterator iterator = [package iterator];
4094 pkgDepCache::StateCache &state(cache[iterator]);
4096 NSString *name([package name]);
4098 if (state.NewInstall())
4099 [installing addObject:name];
4100 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4101 [reinstalling addObject:name];
4102 else if (state.Upgrade())
4103 [upgrading addObject:name];
4104 else if (state.Downgrade())
4105 [downgrading addObject:name];
4106 else if (state.Delete()) {
4107 if ([package essential])
4109 [removing addObject:name];
4112 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4113 substrate_ |= DepSubstrate(iterator.CurrentVer());
4118 else if (Advanced_) {
4119 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4121 essential_ = [[UIAlertView alloc]
4122 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4123 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4125 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4126 otherButtonTitles:[NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")], nil
4129 [essential_ setContext:@"remove"];
4131 essential_ = [[UIAlertView alloc]
4132 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4133 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4135 cancelButtonTitle:UCLocalize("OKAY")
4136 otherButtonTitles:nil
4139 [essential_ setContext:@"unable"];
4142 changes_ = [[NSArray alloc] initWithObjects:
4150 issues_ = [database_ issues];
4152 issues_ = [issues_ retain];
4154 sizes_ = [[NSArray alloc] initWithObjects:
4155 SizeString([database_ fetcher].FetchNeeded()),
4156 SizeString([database_ fetcher].PartialPresent()),
4159 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
4161 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
4162 initWithTitle:UCLocalize("CANCEL")
4163 // OLD: [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")]
4164 style:UIBarButtonItemStylePlain
4166 action:@selector(cancelButtonClicked)
4171 - (void) applyRightButton {
4172 #if !AlwaysReload && !IgnoreInstall
4173 if (issues_ == nil && ![self isLoading])
4174 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4175 initWithTitle:UCLocalize("CONFIRM")
4176 style:UIBarButtonItemStylePlain
4178 action:@selector(confirmButtonClicked)
4181 [super applyRightButton];
4183 [[self navigationItem] setRightBarButtonItem:nil];
4187 - (void) cancelButtonClicked {
4188 [self dismissModalViewControllerAnimated:YES];
4189 [delegate_ cancelAndClear:YES];
4193 - (void) confirmButtonClicked {
4197 if (essential_ != nil)
4202 [delegate_ confirmWithNavigationController:[self navigationController]];
4210 /* Progress Data {{{ */
4211 @interface ProgressData : NSObject {
4213 // XXX: should these really both be _transient?
4214 _transient id target_;
4215 _transient id object_;
4218 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4225 @implementation ProgressData
4227 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4228 if ((self = [super init]) != nil) {
4229 selector_ = selector;
4249 /* Progress Controller {{{ */
4250 @interface ProgressController : CYViewController <
4251 ConfigurationDelegate,
4254 _transient Database *database_;
4255 UIProgressBar *progress_;
4256 UITextView *output_;
4257 UITextLabel *status_;
4258 UIPushButton *close_;
4260 SHA1SumValue springlist_;
4261 SHA1SumValue notifyconf_;
4265 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4267 - (void) _retachThread;
4268 - (void) _detachNewThreadData:(ProgressData *)data;
4269 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4275 @protocol ProgressControllerDelegate
4276 - (void) progressControllerIsComplete:(ProgressController *)sender;
4279 @implementation ProgressController
4282 [database_ setDelegate:nil];
4283 [progress_ release];
4292 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4293 if ((self = [super init]) != nil) {
4294 database_ = database;
4295 [database_ setDelegate:self];
4296 delegate_ = delegate;
4298 [[self view] setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
4300 progress_ = [[UIProgressBar alloc] init];
4301 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4302 [progress_ setStyle:0];
4304 status_ = [[UITextLabel alloc] init];
4305 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4306 [status_ setColor:[UIColor whiteColor]];
4307 [status_ setBackgroundColor:[UIColor clearColor]];
4308 [status_ setCentersHorizontally:YES];
4309 //[status_ setFont:font];
4311 output_ = [[UITextView alloc] init];
4313 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4314 //[output_ setTextFont:@"Courier New"];
4315 [output_ setFont:[[output_ font] fontWithSize:12]];
4316 [output_ setTextColor:[UIColor whiteColor]];
4317 [output_ setBackgroundColor:[UIColor clearColor]];
4318 [output_ setMarginTop:0];
4319 [output_ setAllowsRubberBanding:YES];
4320 [output_ setEditable:NO];
4321 [[self view] addSubview:output_];
4323 close_ = [[UIPushButton alloc] init];
4324 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4325 [close_ setAutosizesToFit:NO];
4326 [close_ setDrawsShadow:YES];
4327 [close_ setStretchBackground:YES];
4328 [close_ setEnabled:YES];
4329 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
4330 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4331 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4332 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4336 - (void) positionViews {
4337 CGRect bounds = [[self view] bounds];
4338 CGSize prgsize = [UIProgressBar defaultSize];
4341 (bounds.size.width - prgsize.width) / 2,
4342 bounds.size.height - prgsize.height - 20
4345 float closewidth = std::min(bounds.size.width - 20, 300.0f);
4347 [progress_ setFrame:prgrect];
4348 [status_ setFrame:CGRectMake(
4350 bounds.size.height - prgsize.height - 50,
4351 bounds.size.width - 20,
4354 [output_ setFrame:CGRectMake(
4357 bounds.size.width - 20,
4358 bounds.size.height - 62
4360 [close_ setFrame:CGRectMake(
4361 (bounds.size.width - closewidth) / 2,
4362 bounds.size.height - prgsize.height - 50,
4368 - (void) viewWillAppear:(BOOL)animated {
4369 [super viewDidAppear:animated];
4370 [[self navigationItem] setHidesBackButton:YES];
4371 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4373 [self positionViews];
4376 - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4377 [self positionViews];
4380 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4381 NSString *context([alert context]);
4383 if ([context isEqualToString:@"conffile"]) {
4384 FILE *input = [database_ input];
4385 if (button == [alert cancelButtonIndex])
4386 fprintf(input, "N\n");
4387 else if (button == [alert firstOtherButtonIndex])
4388 fprintf(input, "Y\n");
4393 - (void) closeButtonPushed {
4396 UpdateExternalStatus(0);
4400 [self dismissModalViewControllerAnimated:YES];
4404 [delegate_ terminateWithSuccess];
4405 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4406 [delegate_ suspendWithAnimation:YES];
4408 [delegate_ suspend];*/
4412 system("launchctl stop com.apple.SpringBoard");
4416 system("launchctl unload "SpringBoard_"; launchctl load "SpringBoard_);
4425 - (void) _retachThread {
4426 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
4428 [[self view] addSubview:close_];
4429 [progress_ removeFromSuperview];
4430 [status_ removeFromSuperview];
4432 [database_ popErrorWithTitle:title_];
4433 [delegate_ progressControllerIsComplete:self];
4437 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4440 MMap mmap(file, MMap::ReadOnly);
4442 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4443 if (!(notifyconf_ == sha1.Result()))
4450 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4453 MMap mmap(file, MMap::ReadOnly);
4455 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4456 if (!(springlist_ == sha1.Result()))
4462 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
4463 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4464 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4465 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4466 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4469 system("su -c /usr/bin/uicache mobile");
4471 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
4473 [delegate_ setStatusBarShowsProgress:NO];
4476 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4477 [[data target] performSelector:[data selector] withObject:[data object]];
4478 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4481 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4482 UpdateExternalStatus(1);
4489 title_ = [title retain];
4491 [[self navigationItem] setTitle:title_];
4493 [status_ setText:nil];
4494 [output_ setText:@""];
4495 [progress_ setProgress:0];
4497 [close_ removeFromSuperview];
4498 [[self view] addSubview:progress_];
4499 [[self view] addSubview:status_];
4501 [delegate_ setStatusBarShowsProgress:YES];
4506 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4509 MMap mmap(file, MMap::ReadOnly);
4511 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4512 notifyconf_ = sha1.Result();
4518 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4521 MMap mmap(file, MMap::ReadOnly);
4523 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4524 springlist_ = sha1.Result();
4529 detachNewThreadSelector:@selector(_detachNewThreadData:)
4531 withObject:[[[ProgressData alloc]
4532 initWithSelector:selector
4539 - (void) repairWithSelector:(SEL)selector {
4541 detachNewThreadSelector:selector
4544 title:UCLocalize("REPAIRING")
4548 - (void) setConfigurationData:(NSString *)data {
4550 performSelectorOnMainThread:@selector(_setConfigurationData:)
4556 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4557 CYActionSheet *sheet([[[CYActionSheet alloc]
4559 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4560 defaultButtonIndex:0
4563 [sheet setMessage:error];
4564 [sheet yieldToPopupAlertAnimated:YES];
4568 - (void) setProgressTitle:(NSString *)title {
4570 performSelectorOnMainThread:@selector(_setProgressTitle:)
4576 - (void) setProgressPercent:(float)percent {
4578 performSelectorOnMainThread:@selector(_setProgressPercent:)
4579 withObject:[NSNumber numberWithFloat:percent]
4584 - (void) startProgress {
4587 - (void) addProgressOutput:(NSString *)output {
4589 performSelectorOnMainThread:@selector(_addProgressOutput:)
4595 - (bool) isCancelling:(size_t)received {
4599 - (void) _setConfigurationData:(NSString *)data {
4600 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4602 if (!conffile_r(data)) {
4603 lprintf("E:invalid conffile\n");
4607 NSString *ofile = conffile_r[1];
4608 //NSString *nfile = conffile_r[2];
4610 UIAlertView *alert = [[[UIAlertView alloc]
4611 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4612 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
4614 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
4615 otherButtonTitles:UCLocalize("ACCEPT_NEW_COPY"),
4616 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4620 [alert setContext:@"conffile"];
4624 - (void) _setProgressTitle:(NSString *)title {
4625 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4626 for (size_t i(0), e([words count]); i != e; ++i) {
4627 NSString *word([words objectAtIndex:i]);
4628 if (Package *package = [database_ packageWithName:word])
4629 [words replaceObjectAtIndex:i withObject:[package name]];
4632 [status_ setText:[words componentsJoinedByString:@" "]];
4635 - (void) _setProgressPercent:(NSNumber *)percent {
4636 [progress_ setProgress:[percent floatValue]];
4639 - (void) _addProgressOutput:(NSString *)output {
4640 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4641 CGSize size = [output_ contentSize];
4642 CGRect rect = {{0, size.height}, {size.width, 0}};
4643 [output_ scrollRectToVisible:rect animated:YES];
4646 - (BOOL) isRunning {
4653 /* Cell Content View {{{ */
4654 @protocol ContentDelegate
4655 - (void) drawContentRect:(CGRect)rect;
4658 @interface ContentView : UIView {
4659 _transient id<ContentDelegate> delegate_;
4664 @implementation ContentView
4666 - (id) initWithFrame:(CGRect)frame {
4667 if ((self = [super initWithFrame:frame]) != nil) {
4668 [self setNeedsDisplayOnBoundsChange:YES];
4672 - (void) setDelegate:(id<ContentDelegate>)delegate {
4673 delegate_ = delegate;
4676 - (void) drawRect:(CGRect)rect {
4677 [super drawRect:rect];
4678 [delegate_ drawContentRect:rect];
4683 /* Cydia TableView Cell {{{ */
4684 @interface CYTableViewCell : UITableViewCell {
4685 ContentView *content_;
4691 @implementation CYTableViewCell
4698 - (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
4699 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
4701 if (view == content_) {
4702 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
4703 highlighted_ = highlighted;
4706 [super _updateHighlightColorsForView:view highlighted:highlighted];
4709 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
4710 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
4711 highlighted_ = selected;
4713 [super setSelected:selected animated:animated];
4714 [content_ setNeedsDisplay];
4719 /* Package Cell {{{ */
4720 @interface PackageCell : CYTableViewCell <
4725 NSString *description_;
4733 - (PackageCell *) init;
4734 - (void) setPackage:(Package *)package;
4736 + (int) heightForPackage:(Package *)package;
4737 - (void) drawContentRect:(CGRect)rect;
4741 @implementation PackageCell
4743 - (void) clearPackage {
4754 if (description_ != nil) {
4755 [description_ release];
4759 if (source_ != nil) {
4764 if (badge_ != nil) {
4769 if (placard_ != nil) {
4779 [self clearPackage];
4783 - (PackageCell *) init {
4784 CGRect frame(CGRectMake(0, 0, 320, 74));
4785 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4786 UIView *content([self contentView]);
4787 CGRect bounds([content bounds]);
4789 content_ = [[ContentView alloc] initWithFrame:bounds];
4790 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4791 [content addSubview:content_];
4793 [content_ setDelegate:self];
4794 [content_ setOpaque:YES];
4798 - (void) _setBackgroundColor {
4800 if (NSString *mode = [package_ mode]) {
4801 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4802 color = remove ? RemovingColor_ : InstallingColor_;
4804 color = [UIColor whiteColor];
4806 [content_ setBackgroundColor:color];
4807 [self setNeedsDisplay];
4810 - (void) setPackage:(Package *)package {
4811 [self clearPackage];
4814 Source *source = [package source];
4816 icon_ = [[package icon] retain];
4817 name_ = [[package name] retain];
4820 description_ = [package longDescription];
4821 if (description_ == nil)
4822 description_ = [package shortDescription];
4823 if (description_ != nil)
4824 description_ = [description_ retain];
4826 commercial_ = [package isCommercial];
4828 package_ = [package retain];
4830 NSString *label = nil;
4831 bool trusted = false;
4833 if (source != nil) {
4834 label = [source label];
4835 trusted = [source trusted];
4836 } else if ([[package id] isEqualToString:@"firmware"])
4837 label = UCLocalize("APPLE");
4839 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
4841 NSString *from(label);
4843 NSString *section = [package simpleSection];
4844 if (section != nil && ![section isEqualToString:label]) {
4845 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4846 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
4849 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
4850 source_ = [from retain];
4852 if (NSString *purpose = [package primaryPurpose])
4853 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4854 badge_ = [badge_ retain];
4856 if ([package installed] != nil)
4857 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/installed.png", App_]]) != nil)
4858 placard_ = [placard_ retain];
4860 [self _setBackgroundColor];
4861 [content_ setNeedsDisplay];
4864 - (void) drawContentRect:(CGRect)rect {
4865 bool highlighted(highlighted_);
4866 float width([self bounds].size.width);
4869 CGContextRef context(UIGraphicsGetCurrentContext());
4870 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
4871 CGContextFillRect(context, rect);
4876 rect.size = [icon_ size];
4878 rect.size.width /= 2;
4879 rect.size.height /= 2;
4881 rect.origin.x = 25 - rect.size.width / 2;
4882 rect.origin.y = 25 - rect.size.height / 2;
4884 [icon_ drawInRect:rect];
4887 if (badge_ != nil) {
4888 CGSize size = [badge_ size];
4890 [badge_ drawAtPoint:CGPointMake(
4891 36 - size.width / 2,
4892 36 - size.height / 2
4900 UISetColor(commercial_ ? Purple_ : Black_);
4901 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
4902 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
4905 UISetColor(commercial_ ? Purplish_ : Gray_);
4906 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
4908 if (placard_ != nil)
4909 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
4912 + (int) heightForPackage:(Package *)package {
4918 /* Section Cell {{{ */
4919 @interface SectionCell : CYTableViewCell <
4931 - (void) setSection:(Section *)section editing:(BOOL)editing;
4935 @implementation SectionCell
4937 - (void) clearSection {
4938 if (basic_ != nil) {
4943 if (section_ != nil) {
4953 if (count_ != nil) {
4960 [self clearSection];
4966 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
4967 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
4968 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
4969 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
4970 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
4972 UIView *content([self contentView]);
4973 CGRect bounds([content bounds]);
4975 content_ = [[ContentView alloc] initWithFrame:bounds];
4976 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4977 [content addSubview:content_];
4978 [content_ setBackgroundColor:[UIColor whiteColor]];
4980 [content_ setDelegate:self];
4984 - (void) onSwitch:(id)sender {
4985 NSMutableDictionary *metadata = [Sections_ objectForKey:basic_];
4986 if (metadata == nil) {
4987 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
4988 [Sections_ setObject:metadata forKey:basic_];
4992 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
4995 - (void) setSection:(Section *)section editing:(BOOL)editing {
4996 if (editing != editing_) {
4998 [switch_ removeFromSuperview];
5000 [self addSubview:switch_];
5004 [self clearSection];
5006 if (section == nil) {
5007 name_ = [UCLocalize("ALL_PACKAGES") retain];
5010 basic_ = [section name];
5012 basic_ = [basic_ retain];
5014 section_ = [section localized];
5015 if (section_ != nil)
5016 section_ = [section_ retain];
5018 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
5019 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
5022 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5025 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5026 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5028 [content_ setNeedsDisplay];
5031 - (void) setFrame:(CGRect)frame {
5032 [super setFrame:frame];
5034 CGRect rect([switch_ frame]);
5035 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5038 - (void) drawContentRect:(CGRect)rect {
5039 bool highlighted(highlighted_);
5041 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5046 float width(rect.size.width);
5052 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5054 CGSize size = [count_ sizeWithFont:Font14_];
5058 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5064 /* File Table {{{ */
5065 @interface FileTable : CYViewController <
5066 UITableViewDataSource,
5069 _transient Database *database_;
5072 NSMutableArray *files_;
5076 - (id) initWithDatabase:(Database *)database;
5077 - (void) setPackage:(Package *)package;
5081 @implementation FileTable
5084 if (package_ != nil)
5093 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5094 return files_ == nil ? 0 : [files_ count];
5097 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5101 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5102 static NSString *reuseIdentifier = @"Cell";
5104 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5106 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5107 [cell setFont:[UIFont systemFontOfSize:16]];
5109 [cell setText:[files_ objectAtIndex:indexPath.row]];
5110 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5115 - (id) initWithDatabase:(Database *)database {
5116 if ((self = [super init]) != nil) {
5117 database_ = database;
5119 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5121 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5123 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5124 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5125 [list_ setRowHeight:24.0f];
5126 [[self view] addSubview:list_];
5128 [list_ setDataSource:self];
5129 [list_ setDelegate:self];
5133 - (void) setPackage:(Package *)package {
5134 if (package_ != nil) {
5135 [package_ autorelease];
5144 [files_ removeAllObjects];
5146 if (package != nil) {
5147 package_ = [package retain];
5148 name_ = [[package id] retain];
5150 if (NSArray *files = [package files])
5151 [files_ addObjectsFromArray:files];
5153 if ([files_ count] != 0) {
5154 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5155 [files_ removeObjectAtIndex:0];
5156 [files_ sortUsingSelector:@selector(compareByPath:)];
5158 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5159 [stack addObject:@"/"];
5161 for (int i(0), e([files_ count]); i != e; ++i) {
5162 NSString *file = [files_ objectAtIndex:i];
5163 while (![file hasPrefix:[stack lastObject]])
5164 [stack removeLastObject];
5165 NSString *directory = [stack lastObject];
5166 [stack addObject:[file stringByAppendingString:@"/"]];
5167 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5168 ([stack count] - 2) * 3, "",
5169 [file substringFromIndex:[directory length]]
5178 - (void) reloadData {
5179 [self setPackage:[database_ packageWithName:name_]];
5184 /* Package Controller {{{ */
5185 @interface PackageController : CYBrowserController <
5186 UIActionSheetDelegate
5188 _transient Database *database_;
5192 NSMutableArray *buttons_;
5193 UIBarButtonItem *button_;
5196 - (id) initWithDatabase:(Database *)database;
5197 - (void) setPackage:(Package *)package;
5201 @implementation PackageController
5204 if (package_ != nil)
5218 if ([self retainCount] == 1)
5219 [delegate_ setPackageController:self];
5223 /* XXX: this is not safe at all... localization of /fail/ */
5224 - (void) _clickButtonWithName:(NSString *)name {
5225 if ([name isEqualToString:UCLocalize("CLEAR")])
5226 [delegate_ clearPackage:package_];
5227 else if ([name isEqualToString:UCLocalize("INSTALL")])
5228 [delegate_ installPackage:package_];
5229 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5230 [delegate_ installPackage:package_];
5231 else if ([name isEqualToString:UCLocalize("REMOVE")])
5232 [delegate_ removePackage:package_];
5233 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5234 [delegate_ installPackage:package_];
5235 else _assert(false);
5238 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5239 NSString *context([sheet context]);
5241 if ([context isEqualToString:@"modify"]) {
5242 if (button != [sheet cancelButtonIndex]) {
5243 NSString *buttonName = [buttons_ objectAtIndex:button];
5244 [self _clickButtonWithName:buttonName];
5247 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5251 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5252 [super webView:view didClearWindowObject:window forFrame:frame];
5253 [window setValue:package_ forKey:@"package"];
5256 - (bool) _allowJavaScriptPanel {
5261 - (void) _customButtonClicked {
5262 int count([buttons_ count]);
5267 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5269 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5270 [buttons addObjectsFromArray:buttons_];
5272 UIActionSheet *sheet = [[[UIActionSheet alloc]
5275 cancelButtonTitle:nil
5276 destructiveButtonTitle:nil
5277 otherButtonTitles:nil
5280 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5282 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5283 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5285 [sheet setContext:@"modify"];
5287 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5291 // We don't want to allow non-commercial packages to do custom things to the install button,
5292 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5293 - (void) customButtonClicked {
5295 [super customButtonClicked];
5297 [self _customButtonClicked];
5300 - (void) reloadButtonClicked {
5301 // Don't reload a package view by clicking the button.
5304 - (void) applyLoadingTitle {
5305 // Don't show "Loading" as the title. Ever.
5308 - (UIBarButtonItem *) rightButton {
5313 - (id) initWithDatabase:(Database *)database {
5314 if ((self = [super init]) != nil) {
5315 database_ = database;
5316 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5317 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
5321 - (void) setPackage:(Package *)package {
5322 if (package_ != nil) {
5323 [package_ autorelease];
5332 [buttons_ removeAllObjects];
5334 if (package != nil) {
5337 package_ = [package retain];
5338 name_ = [[package id] retain];
5339 commercial_ = [package isCommercial];
5341 if ([package_ mode] != nil)
5342 [buttons_ addObject:UCLocalize("CLEAR")];
5343 if ([package_ source] == nil);
5344 else if ([package_ upgradableAndEssential:NO])
5345 [buttons_ addObject:UCLocalize("UPGRADE")];
5346 else if ([package_ uninstalled])
5347 [buttons_ addObject:UCLocalize("INSTALL")];
5349 [buttons_ addObject:UCLocalize("REINSTALL")];
5350 if (![package_ uninstalled])
5351 [buttons_ addObject:UCLocalize("REMOVE")];
5358 switch ([buttons_ count]) {
5359 case 0: title = nil; break;
5360 case 1: title = [buttons_ objectAtIndex:0]; break;
5361 default: title = UCLocalize("MODIFY"); break;
5364 button_ = [[UIBarButtonItem alloc]
5366 style:UIBarButtonItemStylePlain
5368 action:@selector(customButtonClicked)
5374 - (bool) isLoading {
5375 return commercial_ ? [super isLoading] : false;
5378 - (void) reloadData {
5379 [self setPackage:[database_ packageWithName:name_]];
5384 /* Package Table {{{ */
5385 @interface PackageTable : UIView <
5386 UITableViewDataSource,
5389 _transient Database *database_;
5390 NSMutableArray *packages_;
5391 NSMutableArray *sections_;
5393 NSMutableArray *index_;
5394 NSMutableDictionary *indices_;
5395 // XXX: this target_ seems to be delegate_. :(
5396 _transient id target_;
5398 // XXX: why do we even have this delegate_?
5399 _transient id delegate_;
5402 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action;
5404 - (void) setDelegate:(id)delegate;
5406 - (void) reloadData;
5407 - (void) resetCursor;
5409 - (UITableView *) list;
5411 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5413 - (void) deselectWithAnimation:(BOOL)animated;
5417 @implementation PackageTable
5420 [packages_ release];
5421 [sections_ release];
5429 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5430 NSInteger count([sections_ count]);
5431 return count == 0 ? 1 : count;
5434 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5435 if ([sections_ count] == 0)
5437 return [[sections_ objectAtIndex:section] name];
5440 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5441 if ([sections_ count] == 0)
5443 return [[sections_ objectAtIndex:section] count];
5446 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5447 Section *section([sections_ objectAtIndex:[path section]]);
5448 NSInteger row([path row]);
5449 Package *package([packages_ objectAtIndex:([section row] + row)]);
5453 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5454 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5456 cell = [[[PackageCell alloc] init] autorelease];
5457 [cell setPackage:[self packageAtIndexPath:path]];
5461 - (void) deselectWithAnimation:(BOOL)animated {
5462 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5465 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
5466 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
5469 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5470 Package *package([self packageAtIndexPath:path]);
5471 package = [database_ packageWithName:[package id]];
5472 [target_ performSelector:action_ withObject:package];
5476 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5477 return [packages_ count] > 20 ? index_ : nil;
5480 - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5484 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action {
5485 if ((self = [super initWithFrame:frame]) != nil) {
5486 database_ = database;
5491 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5492 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5494 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5495 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5497 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
5498 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5499 [list_ setRowHeight:73.0f];
5500 [self addSubview:list_];
5502 [list_ setDataSource:self];
5503 [list_ setDelegate:self];
5507 - (void) setDelegate:(id)delegate {
5508 delegate_ = delegate;
5511 - (bool) hasPackage:(Package *)package {
5515 - (void) reloadData {
5516 NSArray *packages = [database_ packages];
5518 [packages_ removeAllObjects];
5519 [sections_ removeAllObjects];
5521 _profile(PackageTable$reloadData$Filter)
5522 for (Package *package in packages)
5523 if ([self hasPackage:package])
5524 [packages_ addObject:package];
5527 [index_ removeAllObjects];
5528 [indices_ removeAllObjects];
5530 Section *section = nil;
5532 _profile(PackageTable$reloadData$Section)
5533 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5537 _profile(PackageTable$reloadData$Section$Package)
5538 package = [packages_ objectAtIndex:offset];
5539 index = [package index];
5542 if (section == nil || [section index] != index) {
5543 _profile(PackageTable$reloadData$Section$Allocate)
5544 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5547 [index_ addObject:[section name]];
5548 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5550 _profile(PackageTable$reloadData$Section$Add)
5551 [sections_ addObject:section];
5555 [section addToCount];
5559 _profile(PackageTable$reloadData$List)
5564 - (void) resetCursor {
5565 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5568 - (UITableView *) list {
5572 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5573 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
5578 /* Filtered Package Table {{{ */
5579 @interface FilteredPackageTable : PackageTable {
5585 - (void) setObject:(id)object;
5586 - (void) setObject:(id)object forFilter:(SEL)filter;
5588 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object;
5592 @implementation FilteredPackageTable
5600 - (void) setFilter:(SEL)filter {
5603 /* XXX: this is an unsafe optimization of doomy hell */
5604 Method method(class_getInstanceMethod([Package class], filter));
5605 _assert(method != NULL);
5606 imp_ = method_getImplementation(method);
5607 _assert(imp_ != NULL);
5610 - (void) setObject:(id)object {
5616 object_ = [object retain];
5619 - (void) setObject:(id)object forFilter:(SEL)filter {
5620 [self setFilter:filter];
5621 [self setObject:object];
5624 - (bool) hasPackage:(Package *)package {
5625 _profile(FilteredPackageTable$hasPackage)
5626 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5630 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object {
5631 if ((self = [super initWithFrame:frame database:database target:target action:action]) != nil) {
5632 [self setFilter:filter];
5633 object_ = [object retain];
5641 /* Filtered Package Controller {{{ */
5642 @interface FilteredPackageController : CYViewController {
5643 _transient Database *database_;
5644 FilteredPackageTable *packages_;
5648 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5652 @implementation FilteredPackageController
5655 [packages_ release];
5661 - (void) viewDidAppear:(BOOL)animated {
5662 [super viewDidAppear:animated];
5663 [packages_ deselectWithAnimation:animated];
5666 - (void) didSelectPackage:(Package *)package {
5667 PackageController *view([delegate_ packageController]);
5668 [view setPackage:package];
5669 [view setDelegate:delegate_];
5670 [[self navigationController] pushViewController:view animated:YES];
5673 - (NSString *) title { return title_; }
5675 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5676 if ((self = [super init]) != nil) {
5677 database_ = database;
5678 title_ = [title copy];
5679 [[self navigationItem] setTitle:title_];
5681 packages_ = [[FilteredPackageTable alloc]
5682 initWithFrame:[[self view] bounds]
5685 action:@selector(didSelectPackage:)
5690 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5691 [[self view] addSubview:packages_];
5695 - (void) reloadData {
5696 [packages_ reloadData];
5699 - (void) setDelegate:(id)delegate {
5700 [super setDelegate:delegate];
5701 [packages_ setDelegate:delegate];
5708 /* Add Source Controller {{{ */
5709 @interface AddSourceController : CYViewController {
5710 _transient Database *database_;
5713 - (id) initWithDatabase:(Database *)database;
5717 @implementation AddSourceController
5719 - (id) initWithDatabase:(Database *)database {
5720 if ((self = [super init]) != nil) {
5721 database_ = database;
5727 /* Source Cell {{{ */
5728 @interface SourceCell : CYTableViewCell <
5733 NSString *description_;
5737 - (void) setSource:(Source *)source;
5741 @implementation SourceCell
5743 - (void) clearSource {
5746 [description_ release];
5755 - (void) setSource:(Source *)source {
5759 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5761 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5762 icon_ = [icon_ retain];
5764 origin_ = [[source name] retain];
5765 label_ = [[source uri] retain];
5766 description_ = [[source description] retain];
5768 [content_ setNeedsDisplay];
5776 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5777 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5778 UIView *content([self contentView]);
5779 CGRect bounds([content bounds]);
5781 content_ = [[ContentView alloc] initWithFrame:bounds];
5782 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5783 [content_ setBackgroundColor:[UIColor whiteColor]];
5784 [content addSubview:content_];
5786 [content_ setDelegate:self];
5787 [content_ setOpaque:YES];
5791 - (void) drawContentRect:(CGRect)rect {
5792 bool highlighted(highlighted_);
5793 float width(rect.size.width);
5796 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5803 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5807 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5811 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 40) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5816 /* Source Table {{{ */
5817 @interface SourceTable : CYViewController <
5818 UITableViewDataSource,
5821 _transient Database *database_;
5823 NSMutableArray *sources_;
5827 UIProgressHUD *hud_;
5830 //NSURLConnection *installer_;
5831 NSURLConnection *trivial_;
5832 NSURLConnection *trivial_bz2_;
5833 NSURLConnection *trivial_gz_;
5834 //NSURLConnection *automatic_;
5839 - (id) initWithDatabase:(Database *)database;
5841 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
5845 @implementation SourceTable
5847 - (void) _releaseConnection:(NSURLConnection *)connection {
5848 if (connection != nil) {
5849 [connection cancel];
5850 //[connection setDelegate:nil];
5851 [connection release];
5863 //[self _releaseConnection:installer_];
5864 [self _releaseConnection:trivial_];
5865 [self _releaseConnection:trivial_gz_];
5866 [self _releaseConnection:trivial_bz2_];
5867 //[self _releaseConnection:automatic_];
5874 - (void) viewDidAppear:(BOOL)animated {
5875 [super viewDidAppear:animated];
5876 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5879 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
5880 return offset_ == 0 ? 1 : 2;
5883 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
5884 switch (section + (offset_ == 0 ? 1 : 0)) {
5885 case 0: return UCLocalize("ENTERED_BY_USER");
5886 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
5892 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5893 int count = [sources_ count];
5895 case 0: return (offset_ == 0 ? count : offset_);
5896 case 1: return count - offset_;
5902 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
5904 switch (indexPath.section) {
5905 case 0: idx = indexPath.row; break;
5906 case 1: idx = indexPath.row + offset_; break;
5910 return [sources_ objectAtIndex:idx];
5913 - (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5914 Source *source = [self sourceAtIndexPath:indexPath];
5915 return [source description] == nil ? 56 : 73;
5918 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5919 static NSString *cellIdentifier = @"SourceCell";
5921 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
5922 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
5923 [cell setSource:[self sourceAtIndexPath:indexPath]];
5928 - (UITableViewCellAccessoryType) tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath {
5929 return UITableViewCellAccessoryDisclosureIndicator;
5932 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
5933 Source *source = [self sourceAtIndexPath:indexPath];
5935 FilteredPackageController *packages = [[[FilteredPackageController alloc]
5936 initWithDatabase:database_
5937 title:[source label]
5938 filter:@selector(isVisibleInSource:)
5942 [packages setDelegate:delegate_];
5944 [[self navigationController] pushViewController:packages animated:YES];
5947 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
5948 Source *source = [self sourceAtIndexPath:indexPath];
5949 return [source record] != nil;
5952 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
5953 Source *source = [self sourceAtIndexPath:indexPath];
5954 [Sources_ removeObjectForKey:[source key]];
5955 [delegate_ syncData];
5959 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
5962 @"./", @"Distribution",
5963 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
5965 [delegate_ syncData];
5968 - (NSString *) getWarning {
5969 NSString *href(href_);
5970 NSRange colon([href rangeOfString:@"://"]);
5971 if (colon.location != NSNotFound)
5972 href = [href substringFromIndex:(colon.location + 3)];
5973 href = [href stringByAddingPercentEscapes];
5974 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
5975 href = [href stringByCachingURLWithCurrentCDN];
5977 NSURL *url([NSURL URLWithString:href]);
5979 NSStringEncoding encoding;
5980 NSError *error(nil);
5982 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
5983 return [warning length] == 0 ? nil : warning;
5987 - (void) _endConnection:(NSURLConnection *)connection {
5988 // XXX: the memory management in this method is horribly awkward
5990 NSURLConnection **field = NULL;
5991 if (connection == trivial_)
5993 else if (connection == trivial_bz2_)
5994 field = &trivial_bz2_;
5995 else if (connection == trivial_gz_)
5996 field = &trivial_gz_;
5997 _assert(field != NULL);
5998 [connection release];
6003 trivial_bz2_ == nil &&
6009 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
6012 UIAlertView *alert = [[[UIAlertView alloc]
6013 initWithTitle:UCLocalize("SOURCE_WARNING")
6016 cancelButtonTitle:UCLocalize("CANCEL")
6017 otherButtonTitles:UCLocalize("ADD_ANYWAY"), nil
6020 [alert setContext:@"warning"];
6021 [alert setNumberOfRows:1];
6025 } else if (error_ != nil) {
6026 UIAlertView *alert = [[[UIAlertView alloc]
6027 initWithTitle:UCLocalize("VERIFICATION_ERROR")
6028 message:[error_ localizedDescription]
6030 cancelButtonTitle:UCLocalize("OK")
6031 otherButtonTitles:nil
6034 [alert setContext:@"urlerror"];
6037 UIAlertView *alert = [[[UIAlertView alloc]
6038 initWithTitle:UCLocalize("NOT_REPOSITORY")
6039 message:UCLocalize("NOT_REPOSITORY_EX")
6041 cancelButtonTitle:UCLocalize("OK")
6042 otherButtonTitles:nil
6045 [alert setContext:@"trivial"];
6049 [delegate_ setStatusBarShowsProgress:NO];
6050 [delegate_ removeProgressHUD:hud_];
6060 if (error_ != nil) {
6067 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
6068 switch ([response statusCode]) {
6074 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
6075 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
6077 error_ = [error retain];
6078 [self _endConnection:connection];
6081 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
6082 [self _endConnection:connection];
6085 - (NSString *) title { return UCLocalize("SOURCES"); }
6087 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
6088 NSMutableURLRequest *request = [NSMutableURLRequest
6089 requestWithURL:[NSURL URLWithString:href]
6090 cachePolicy:NSURLRequestUseProtocolCachePolicy
6091 timeoutInterval:120.0
6094 [request setHTTPMethod:method];
6096 if (Machine_ != NULL)
6097 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
6098 if (UniqueID_ != nil)
6099 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6101 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
6103 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
6106 - (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
6107 NSString *context([alert context]);
6109 if ([context isEqualToString:@"source"]) {
6112 NSString *href = [[alert textField] text];
6114 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
6116 if (![href hasSuffix:@"/"])
6117 href_ = [href stringByAppendingString:@"/"];
6120 href_ = [href_ retain];
6122 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
6123 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
6124 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
6125 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
6129 // XXX: this is stupid
6130 hud_ = [[delegate_ addProgressHUD] retain];
6131 [hud_ setText:UCLocalize("VERIFYING_URL")];
6140 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6141 } else if ([context isEqualToString:@"trivial"])
6142 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6143 else if ([context isEqualToString:@"urlerror"])
6144 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6145 else if ([context isEqualToString:@"warning"]) {
6160 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6164 - (id) initWithDatabase:(Database *)database {
6165 if ((self = [super init]) != nil) {
6166 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
6167 [self updateButtonsForEditingStatus:NO animated:NO];
6169 database_ = database;
6170 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
6172 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6173 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6174 [[self view] addSubview:list_];
6176 [list_ setDataSource:self];
6177 [list_ setDelegate:self];
6183 - (void) reloadData {
6185 if (!list.ReadMainList())
6188 [sources_ removeAllObjects];
6189 [sources_ addObjectsFromArray:[database_ sources]];
6191 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
6194 int count([sources_ count]);
6196 for (int i = 0; i != count; i++) {
6197 if ([[sources_ objectAtIndex:i] record] == nil)
6202 [list_ setEditing:NO];
6203 [self updateButtonsForEditingStatus:NO animated:NO];
6207 - (void) addButtonClicked {
6208 /*[book_ pushPage:[[[AddSourceController alloc]
6213 UIAlertView *alert = [[[UIAlertView alloc]
6214 initWithTitle:UCLocalize("ENTER_APT_URL")
6217 cancelButtonTitle:UCLocalize("CANCEL")
6218 otherButtonTitles:UCLocalize("ADD_SOURCE"), nil
6221 [alert setContext:@"source"];
6222 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
6224 [alert setNumberOfRows:1];
6225 [alert addTextFieldWithValue:@"http://" label:@""];
6227 UITextInputTraits *traits = [[alert textField] textInputTraits];
6228 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6229 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6230 [traits setKeyboardType:UIKeyboardTypeURL];
6231 // XXX: UIReturnKeyDone
6232 [traits setReturnKeyType:UIReturnKeyNext];
6237 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
6238 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
6239 initWithTitle:UCLocalize("ADD")
6240 style:UIBarButtonItemStylePlain
6242 action:@selector(addButtonClicked)
6243 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
6245 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6246 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
6247 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
6249 action:@selector(editButtonClicked)
6250 ] autorelease] animated:animated];
6252 if (IsWildcat_ && !editing)
6253 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6254 initWithTitle:UCLocalize("SETTINGS")
6255 style:UIBarButtonItemStylePlain
6257 action:@selector(settingsButtonClicked)
6261 - (void) settingsButtonClicked {
6262 [delegate_ showSettings];
6265 - (void) editButtonClicked {
6266 [list_ setEditing:![list_ isEditing] animated:YES];
6268 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
6274 /* Installed Controller {{{ */
6275 @interface InstalledController : FilteredPackageController {
6279 - (id) initWithDatabase:(Database *)database;
6281 - (void) updateRoleButton;
6282 - (void) queueStatusDidChange;
6286 @implementation InstalledController
6292 - (NSString *) title { return UCLocalize("INSTALLED"); }
6294 - (id) initWithDatabase:(Database *)database {
6295 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
6296 [self updateRoleButton];
6297 [self queueStatusDidChange];
6302 - (void) queueButtonClicked {
6307 - (void) queueStatusDidChange {
6311 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6312 initWithTitle:UCLocalize("QUEUE")
6313 style:UIBarButtonItemStyleDone
6315 action:@selector(queueButtonClicked)
6318 [[self navigationItem] setLeftBarButtonItem:nil];
6324 - (void) reloadData {
6325 [packages_ reloadData];
6328 - (void) updateRoleButton {
6329 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
6330 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6331 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
6332 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
6334 action:@selector(roleButtonClicked)
6338 - (void) roleButtonClicked {
6339 [packages_ setObject:[NSNumber numberWithBool:expert_]];
6340 [packages_ reloadData];
6343 [self updateRoleButton];
6346 - (void) setDelegate:(id)delegate {
6347 [super setDelegate:delegate];
6348 [packages_ setDelegate:delegate];
6354 /* Home Controller {{{ */
6355 @interface HomeController : CYBrowserController {
6360 @implementation HomeController
6362 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6363 [super _setMoreHeaders:request];
6366 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6367 if (UniqueID_ != nil)
6368 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6370 [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"];
6373 - (void) aboutButtonClicked {
6374 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6376 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6377 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6378 [alert setCancelButtonIndex:0];
6381 @"Copyright (C) 2008-2010\n"
6382 "Jay Freeman (saurik)\n"
6383 "saurik@saurik.com\n"
6384 "http://www.saurik.com/"
6390 - (void) viewWillAppear:(BOOL)animated {
6391 [super viewWillAppear:animated];
6392 //[[self navigationController] setNavigationBarHidden:YES animated:animated];
6395 - (void) viewWillDisappear:(BOOL)animated {
6396 [super viewWillDisappear:animated];
6397 //[[self navigationController] setNavigationBarHidden:NO animated:animated];
6401 if ((self = [super init]) != nil) {
6402 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6403 initWithTitle:UCLocalize("ABOUT")
6404 style:UIBarButtonItemStylePlain
6406 action:@selector(aboutButtonClicked)
6413 /* Manage Controller {{{ */
6414 @interface ManageController : CYBrowserController {
6417 - (void) queueStatusDidChange;
6420 @implementation ManageController
6423 if ((self = [super init]) != nil) {
6424 [[self navigationItem] setTitle:UCLocalize("MANAGE")];
6426 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6427 initWithTitle:UCLocalize("SETTINGS")
6428 style:UIBarButtonItemStylePlain
6430 action:@selector(settingsButtonClicked)
6433 [self queueStatusDidChange];
6437 - (void) settingsButtonClicked {
6438 [delegate_ showSettings];
6442 - (void) queueButtonClicked {
6446 - (void) applyLoadingTitle {
6447 // No "Loading" title.
6450 - (void) applyRightButton {
6455 - (void) queueStatusDidChange {
6457 if (!IsWildcat_ && Queuing_) {
6458 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6459 initWithTitle:UCLocalize("QUEUE")
6460 style:UIBarButtonItemStyleDone
6462 action:@selector(queueButtonClicked)
6465 [[self navigationItem] setRightBarButtonItem:nil];
6470 - (bool) isLoading {
6477 /* Refresh Bar {{{ */
6478 @interface RefreshBar : UINavigationBar {
6479 UIProgressIndicator *indicator_;
6480 UITextLabel *prompt_;
6481 UIProgressBar *progress_;
6482 UINavigationButton *cancel_;
6487 @implementation RefreshBar
6490 [indicator_ release];
6492 [progress_ release];
6497 - (void) positionViews {
6498 CGRect frame = [cancel_ frame];
6499 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6500 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6501 [cancel_ setFrame:frame];
6503 CGSize prgsize = {75, 100};
6505 [self frame].size.width - prgsize.width - 10,
6506 ([self frame].size.height - prgsize.height) / 2
6508 [progress_ setFrame:prgrect];
6510 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6511 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6512 CGRect indrect = {{indoffset, indoffset}, indsize};
6513 [indicator_ setFrame:indrect];
6515 CGSize prmsize = {215, indsize.height + 4};
6517 indoffset * 2 + indsize.width,
6518 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6520 [prompt_ setFrame:prmrect];
6523 - (void)setFrame:(CGRect)frame {
6524 [super setFrame:frame];
6526 [self positionViews];
6529 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6530 if ((self = [super initWithFrame:frame])) {
6531 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6533 [self setTintColor:[UIColor colorWithRed:0.23 green:0.23 blue:0.23 alpha:1]];
6534 [self setBarStyle:UIBarStyleBlack];
6536 UIBarStyle barstyle([self _barStyle:NO]);
6537 bool ugly(barstyle == UIBarStyleDefault);
6539 UIProgressIndicatorStyle style = ugly ?
6540 UIProgressIndicatorStyleMediumBrown :
6541 UIProgressIndicatorStyleMediumWhite;
6543 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6544 [indicator_ setStyle:style];
6545 [indicator_ startAnimation];
6546 [self addSubview:indicator_];
6548 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6549 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6550 [prompt_ setBackgroundColor:[UIColor clearColor]];
6551 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6552 [self addSubview:prompt_];
6554 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6555 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6556 [progress_ setStyle:0];
6557 [self addSubview:progress_];
6559 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6560 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6561 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6562 [cancel_ setBarStyle:barstyle];
6564 [self positionViews];
6569 [cancel_ removeFromSuperview];
6573 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6574 [progress_ setProgress:0];
6575 [self addSubview:cancel_];
6579 [cancel_ removeFromSuperview];
6582 - (void) setPrompt:(NSString *)prompt {
6583 [prompt_ setText:prompt];
6586 - (void) setProgress:(float)progress {
6587 [progress_ setProgress:progress];
6593 @class CYNavigationController;
6595 /* Cydia Tab Bar Controller {{{ */
6596 @interface CYTabBarController : UITabBarController {
6597 _transient Database *database_;
6602 @implementation CYTabBarController
6604 /* XXX: some logic should probably go here related to
6605 freeing the view controllers on tab change */
6607 - (void) reloadData {
6608 size_t count([[self viewControllers] count]);
6609 for (size_t i(0); i != count; ++i) {
6610 CYNavigationController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6615 - (id) initWithDatabase:(Database *)database {
6616 if ((self = [super init]) != nil) {
6617 database_ = database;
6624 /* Cydia Navigation Controller {{{ */
6625 @interface CYNavigationController : UINavigationController {
6626 _transient Database *database_;
6627 _transient id<UINavigationControllerDelegate> delegate_;
6630 - (id) initWithDatabase:(Database *)database;
6631 - (void) reloadData;
6636 @implementation CYNavigationController
6638 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
6639 // Inherit autorotation settings for modal parents.
6640 if ([self parentViewController] && [[self parentViewController] modalViewController] == self) {
6641 return [[self parentViewController] shouldAutorotateToInterfaceOrientation:orientation];
6643 return [super shouldAutorotateToInterfaceOrientation:orientation];
6651 - (void) reloadData {
6652 size_t count([[self viewControllers] count]);
6653 for (size_t i(0); i != count; ++i) {
6654 CYViewController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6659 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
6660 delegate_ = delegate;
6663 - (id) initWithDatabase:(Database *)database {
6664 if ((self = [super init]) != nil) {
6665 database_ = database;
6671 /* Cydia:// Protocol {{{ */
6672 @interface CydiaURLProtocol : NSURLProtocol {
6677 @implementation CydiaURLProtocol
6679 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6680 NSURL *url([request URL]);
6683 NSString *scheme([[url scheme] lowercaseString]);
6684 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6689 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6693 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6694 id<NSURLProtocolClient> client([self client]);
6696 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6698 NSData *data(UIImagePNGRepresentation(icon));
6700 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6701 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6702 [client URLProtocol:self didLoadData:data];
6703 [client URLProtocolDidFinishLoading:self];
6707 - (void) startLoading {
6708 id<NSURLProtocolClient> client([self client]);
6709 NSURLRequest *request([self request]);
6711 NSURL *url([request URL]);
6712 NSString *href([url absoluteString]);
6714 NSString *path([href substringFromIndex:8]);
6715 NSRange slash([path rangeOfString:@"/"]);
6718 if (slash.location == NSNotFound) {
6722 command = [path substringToIndex:slash.location];
6723 path = [path substringFromIndex:(slash.location + 1)];
6726 Database *database([Database sharedInstance]);
6728 if ([command isEqualToString:@"package-icon"]) {
6731 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6732 Package *package([database packageWithName:path]);
6735 UIImage *icon([package icon]);
6736 [self _returnPNGWithImage:icon forRequest:request];
6737 } else if ([command isEqualToString:@"source-icon"]) {
6740 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6741 NSString *source(Simplify(path));
6742 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6744 icon = [UIImage applicationImageNamed:@"unknown.png"];
6745 [self _returnPNGWithImage:icon forRequest:request];
6746 } else if ([command isEqualToString:@"uikit-image"]) {
6749 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6750 UIImage *icon(_UIImageWithName(path));
6751 [self _returnPNGWithImage:icon forRequest:request];
6752 } else if ([command isEqualToString:@"section-icon"]) {
6755 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6756 NSString *section(Simplify(path));
6757 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6759 icon = [UIImage applicationImageNamed:@"unknown.png"];
6760 [self _returnPNGWithImage:icon forRequest:request];
6762 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6766 - (void) stopLoading {
6772 /* Sections Controller {{{ */
6773 @interface SectionsController : CYViewController <
6774 UITableViewDataSource,
6777 _transient Database *database_;
6778 NSMutableArray *sections_;
6779 NSMutableArray *filtered_;
6785 - (id) initWithDatabase:(Database *)database;
6786 - (void) reloadData;
6789 - (void) editButtonClicked;
6793 @implementation SectionsController
6796 [list_ setDataSource:nil];
6797 [list_ setDelegate:nil];
6799 [sections_ release];
6800 [filtered_ release];
6802 [accessory_ release];
6806 - (void) viewDidAppear:(BOOL)animated {
6807 [super viewDidAppear:animated];
6808 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6811 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
6812 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
6816 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6817 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6820 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6824 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6825 static NSString *reuseIdentifier = @"SectionCell";
6827 SectionCell *cell = (SectionCell *) [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6829 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6831 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
6836 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6840 Section *section = [self sectionAtIndexPath:indexPath];
6841 NSString *name = [section name];
6844 if ([indexPath row] == 0) {
6847 title = UCLocalize("ALL_PACKAGES");
6850 name = [NSString stringWithString:name];
6851 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6854 title = UCLocalize("NO_SECTION");
6858 FilteredPackageController *table = [[[FilteredPackageController alloc]
6859 initWithDatabase:database_
6861 filter:@selector(isVisibleInSection:)
6865 [table setDelegate:delegate_];
6867 [[self navigationController] pushViewController:table animated:YES];
6870 - (NSString *) title { return UCLocalize("SECTIONS"); }
6872 - (id) initWithDatabase:(Database *)database {
6873 if ((self = [super init]) != nil) {
6874 database_ = database;
6876 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
6878 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6879 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6881 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
6882 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6883 [list_ setRowHeight:45.0f];
6884 [[self view] addSubview:list_];
6886 [list_ setDataSource:self];
6887 [list_ setDelegate:self];
6893 - (void) reloadData {
6894 NSArray *packages = [database_ packages];
6896 [sections_ removeAllObjects];
6897 [filtered_ removeAllObjects];
6899 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6902 for (Package *package in packages) {
6903 NSString *name([package section]);
6904 NSString *key(name == nil ? @"" : name);
6908 _profile(SectionsView$reloadData$Section)
6909 section = [sections objectForKey:key];
6910 if (section == nil) {
6911 _profile(SectionsView$reloadData$Section$Allocate)
6912 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6913 [sections setObject:section forKey:key];
6918 [section addToCount];
6920 _profile(SectionsView$reloadData$Filter)
6921 if (![package valid] || ![package visible])
6929 [sections_ addObjectsFromArray:[sections allValues]];
6931 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6933 for (Section *section in sections_) {
6934 size_t count([section row]);
6938 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6939 [section setCount:count];
6940 [filtered_ addObject:section];
6943 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6944 initWithTitle:([sections_ count] == 0 ? nil : UCLocalize("EDIT"))
6945 style:UIBarButtonItemStylePlain
6947 action:@selector(editButtonClicked)
6948 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] != nil)];
6954 - (void) resetView {
6956 [self editButtonClicked];
6959 - (void) editButtonClicked {
6960 if ((editing_ = !editing_))
6963 [delegate_ updateData];
6965 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6966 [[[self navigationItem] rightBarButtonItem] setTitle:[sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT")];
6967 [[[self navigationItem] rightBarButtonItem] setStyle:editing_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain];
6970 - (UIView *) accessoryView {
6976 /* Changes Controller {{{ */
6977 @interface ChangesController : CYViewController <
6978 UITableViewDataSource,
6981 _transient Database *database_;
6982 CFMutableArrayRef packages_;
6983 NSMutableArray *sections_;
6986 BOOL hasSentFirstLoad_;
6989 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
6990 - (void) reloadData;
6994 @implementation ChangesController
6997 [list_ setDelegate:nil];
6998 [list_ setDataSource:nil];
7000 CFRelease(packages_);
7002 [sections_ release];
7007 - (void) viewDidAppear:(BOOL)animated {
7008 [super viewDidAppear:animated];
7009 if (!hasSentFirstLoad_) {
7010 hasSentFirstLoad_ = YES;
7011 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
7013 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7017 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7018 NSInteger count([sections_ count]);
7019 return count == 0 ? 1 : count;
7022 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7023 if ([sections_ count] == 0)
7025 return [[sections_ objectAtIndex:section] name];
7028 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7029 if ([sections_ count] == 0)
7031 return [[sections_ objectAtIndex:section] count];
7034 - (Package *) packageAtIndex:(NSUInteger)index {
7035 return (Package *) CFArrayGetValueAtIndex(packages_, index);
7038 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7039 Section *section([sections_ objectAtIndex:[path section]]);
7040 NSInteger row([path row]);
7041 return [self packageAtIndex:([section row] + row)];
7044 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7045 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7047 cell = [[[PackageCell alloc] init] autorelease];
7048 [cell setPackage:[self packageAtIndexPath:path]];
7052 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
7053 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
7056 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7057 Package *package([self packageAtIndexPath:path]);
7058 PackageController *view([delegate_ packageController]);
7059 [view setDelegate:delegate_];
7060 [view setPackage:package];
7061 [[self navigationController] pushViewController:view animated:YES];
7065 - (void) refreshButtonClicked {
7066 [delegate_ beginUpdate];
7067 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7070 - (void) upgradeButtonClicked {
7071 [delegate_ distUpgrade];
7074 - (NSString *) title { return UCLocalize("CHANGES"); }
7076 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7077 if ((self = [super init]) != nil) {
7078 database_ = database;
7079 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7081 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7083 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7085 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7086 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7087 [list_ setRowHeight:73.0f];
7088 [[self view] addSubview:list_];
7090 [list_ setDataSource:self];
7091 [list_ setDelegate:self];
7093 delegate_ = delegate;
7097 - (void) _reloadPackages:(NSArray *)packages {
7099 for (Package *package in packages)
7100 if ([package upgradableAndEssential:YES] || [package visible])
7101 CFArrayAppendValue(packages_, package);
7104 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7108 - (void) reloadData {
7109 NSArray *packages = [database_ packages];
7111 CFArrayRemoveAllValues(packages_);
7113 [sections_ removeAllObjects];
7116 UIProgressHUD *hud([delegate_ addProgressHUD]);
7117 [hud setText:UCLocalize("LOADING")];
7118 //NSLog(@"HUD:%@::%@", delegate_, hud);
7119 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7120 [delegate_ removeProgressHUD:hud];
7122 [self _reloadPackages:packages];
7125 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7126 Section *ignored = nil;
7127 Section *section = nil;
7131 bool unseens = false;
7133 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7135 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7136 Package *package = [self packageAtIndex:offset];
7138 BOOL uae = [package upgradableAndEssential:YES];
7142 time_t seen([package seen]);
7144 if (section == nil || last != seen) {
7148 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7151 _profile(ChangesController$reloadData$Allocate)
7152 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7153 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7154 [sections_ addObject:section];
7158 [section addToCount];
7159 } else if ([package ignored]) {
7160 if (ignored == nil) {
7161 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7163 [ignored addToCount];
7166 [upgradable addToCount];
7171 CFRelease(formatter);
7174 Section *last = [sections_ lastObject];
7175 size_t count = [last count];
7176 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7177 [sections_ removeLastObject];
7180 if ([ignored count] != 0)
7181 [sections_ insertObject:ignored atIndex:0];
7183 [sections_ insertObject:upgradable atIndex:0];
7188 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7189 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7190 style:UIBarButtonItemStylePlain
7192 action:@selector(upgradeButtonClicked)
7195 if (![delegate_ updating])
7196 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7197 initWithTitle:UCLocalize("REFRESH")
7198 style:UIBarButtonItemStylePlain
7200 action:@selector(refreshButtonClicked)
7206 /* Search Controller {{{ */
7207 @interface SearchController : FilteredPackageController <
7210 UISearchBar *search_;
7213 - (id) initWithDatabase:(Database *)database;
7214 - (void) reloadData;
7218 @implementation SearchController
7225 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7226 [packages_ setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7227 [search_ resignFirstResponder];
7231 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7232 [packages_ setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7236 - (NSString *) title { return nil; }
7238 - (id) initWithDatabase:(Database *)database {
7239 return [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil];
7242 - (void)viewDidAppear:(BOOL)animated {
7243 [super viewDidAppear:animated];
7245 search_ = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7246 [search_ layoutSubviews];
7247 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7248 UITextField *textField = [search_ searchField];
7249 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7250 [search_ setDelegate:self];
7251 [textField setEnablesReturnKeyAutomatically:NO];
7252 [[self navigationItem] setTitleView:textField];
7256 - (void) _reloadData {
7259 - (void) reloadData {
7260 _profile(SearchController$reloadData)
7261 [packages_ reloadData];
7264 [packages_ resetCursor];
7267 - (void) didSelectPackage:(Package *)package {
7268 [search_ resignFirstResponder];
7269 [super didSelectPackage:package];
7274 /* Settings Controller {{{ */
7275 @interface SettingsController : CYViewController <
7276 UITableViewDataSource,
7279 _transient Database *database_;
7282 UITableView *table_;
7283 UISwitch *subscribedSwitch_;
7284 UISwitch *ignoredSwitch_;
7285 UITableViewCell *subscribedCell_;
7286 UITableViewCell *ignoredCell_;
7289 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7293 @implementation SettingsController
7297 if (package_ != nil)
7300 [subscribedSwitch_ release];
7301 [ignoredSwitch_ release];
7302 [subscribedCell_ release];
7303 [ignoredCell_ release];
7308 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7309 if (package_ == nil)
7315 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7316 if (package_ == nil)
7322 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7323 return UCLocalize("SHOW_ALL_CHANGES_EX");
7326 - (void) onSubscribed:(id)control {
7327 bool value([control isOn]);
7328 if (package_ == nil)
7330 if ([package_ setSubscribed:value])
7331 [delegate_ updateData];
7334 - (void) onIgnored:(id)control {
7335 // TODO: set Held state - possibly call out to dpkg, etc.
7338 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7339 if (package_ == nil)
7342 switch ([indexPath row]) {
7343 case 0: return subscribedCell_;
7344 case 1: return ignoredCell_;
7352 - (NSString *) title { return UCLocalize("SETTINGS"); }
7354 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7355 if ((self = [super init])) {
7356 database_ = database;
7357 name_ = [package retain];
7359 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7361 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7362 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7363 [[self view] addSubview:table_];
7365 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7366 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7367 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7369 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7370 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7371 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7373 subscribedCell_ = [[UITableViewCell alloc] init];
7374 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7375 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7376 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7378 ignoredCell_ = [[UITableViewCell alloc] init];
7379 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7380 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7381 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7383 [table_ setDataSource:self];
7384 [table_ setDelegate:self];
7389 - (void) reloadData {
7390 if (package_ != nil)
7391 [package_ autorelease];
7392 package_ = [database_ packageWithName:name_];
7393 if (package_ != nil) {
7395 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7396 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7399 [table_ reloadData];
7404 /* Signature Controller {{{ */
7405 @interface SignatureController : CYBrowserController {
7406 _transient Database *database_;
7410 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7414 @implementation SignatureController
7421 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7423 [super webView:view didClearWindowObject:window forFrame:frame];
7426 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7427 if ((self = [super init]) != nil) {
7428 database_ = database;
7429 package_ = [package retain];
7434 - (void) reloadData {
7435 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7441 /* Role Controller {{{ */
7442 @interface RoleController : CYViewController <
7443 UITableViewDataSource,
7446 _transient Database *database_;
7447 // XXX: ok, "roledelegate_"?...
7448 _transient id roledelegate_;
7449 UITableView *table_;
7450 UISegmentedControl *segment_;
7454 - (void) showDoneButton;
7455 - (void) resizeSegmentedControl;
7459 @implementation RoleController
7463 [container_ release];
7468 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7469 if ((self = [super init])) {
7470 database_ = database;
7471 roledelegate_ = delegate;
7473 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
7475 NSArray *items = [NSArray arrayWithObjects:
7477 UCLocalize("HACKER"),
7478 UCLocalize("DEVELOPER"),
7480 segment_ = [[UISegmentedControl alloc] initWithItems:items];
7481 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
7482 [container_ addSubview:segment_];
7485 if ([Role_ isEqualToString:@"User"]) index = 0;
7486 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
7487 if ([Role_ isEqualToString:@"Developer"]) index = 2;
7489 [segment_ setSelectedSegmentIndex:index];
7490 [self showDoneButton];
7493 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
7494 [self resizeSegmentedControl];
7496 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7497 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7498 [table_ setDelegate:self];
7499 [table_ setDataSource:self];
7500 [[self view] addSubview:table_];
7501 [table_ reloadData];
7505 - (void) resizeSegmentedControl {
7506 CGFloat width = [[self view] frame].size.width;
7507 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
7510 - (void) viewWillAppear:(BOOL)animated {
7511 [super viewWillAppear:animated];
7513 [self resizeSegmentedControl];
7516 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7517 [self resizeSegmentedControl];
7520 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7521 [self resizeSegmentedControl];
7525 NSString *role(nil);
7527 switch ([segment_ selectedSegmentIndex]) {
7528 case 0: role = @"User"; break;
7529 case 1: role = @"Hacker"; break;
7530 case 2: role = @"Developer"; break;
7535 if (![role isEqualToString:Role_]) {
7536 bool rolling(Role_ == nil);
7539 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7543 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7548 [roledelegate_ loadData];
7550 [roledelegate_ updateData];
7554 - (void) segmentChanged:(UISegmentedControl *)control {
7555 [self showDoneButton];
7558 - (void) saveAndClose {
7561 [[self navigationItem] setRightBarButtonItem:nil];
7562 [[self navigationController] dismissModalViewControllerAnimated:YES];
7565 - (void) doneButtonClicked {
7566 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
7567 [spinner startAnimating];
7568 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
7569 [[self navigationItem] setRightBarButtonItem:spinItem];
7571 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
7574 - (void) showDoneButton {
7575 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7576 initWithTitle:UCLocalize("DONE")
7577 style:UIBarButtonItemStyleDone
7579 action:@selector(doneButtonClicked)
7580 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
7583 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7584 // XXX: For not having a single cell in the table, this sure is a lot of sections.
7588 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7592 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7593 return nil; // This method is required by the protocol.
7596 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7598 return UCLocalize("ROLE_EX");
7600 return [NSString stringWithFormat:
7601 @"%@: %@\n%@: %@\n%@: %@",
7602 UCLocalize("USER"), UCLocalize("USER_EX"),
7603 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
7604 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
7609 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
7610 return section == 3 ? 44.0f : 0;
7613 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
7614 return section == 3 ? container_ : nil;
7619 /* Stash Controller {{{ */
7620 @interface CYStashController : CYViewController {
7621 // XXX: just delete these things
7622 _transient UIActivityIndicatorView *spinner_;
7623 _transient UILabel *status_;
7624 _transient UILabel *caption_;
7628 @implementation CYStashController
7630 if ((self = [super init])) {
7631 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
7633 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
7634 CGRect spinrect = [spinner_ frame];
7635 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
7636 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
7637 [spinner_ setFrame:spinrect];
7638 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
7639 [[self view] addSubview:spinner_];
7640 [spinner_ startAnimating];
7643 captrect.size.width = [[self view] frame].size.width;
7644 captrect.size.height = 40.0f;
7645 captrect.origin.x = 0;
7646 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
7647 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
7648 [caption_ setText:@"Initializing Filesystem"];
7649 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7650 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
7651 [caption_ setTextColor:[UIColor whiteColor]];
7652 [caption_ setBackgroundColor:[UIColor clearColor]];
7653 [caption_ setShadowColor:[UIColor blackColor]];
7654 [caption_ setTextAlignment:UITextAlignmentCenter];
7655 [[self view] addSubview:caption_];
7658 statusrect.size.width = [[self view] frame].size.width;
7659 statusrect.size.height = 30.0f;
7660 statusrect.origin.x = 0;
7661 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
7662 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
7663 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7664 [status_ setText:@"(Cydia will exit when complete.)"];
7665 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
7666 [status_ setTextColor:[UIColor whiteColor]];
7667 [status_ setBackgroundColor:[UIColor clearColor]];
7668 [status_ setShadowColor:[UIColor blackColor]];
7669 [status_ setTextAlignment:UITextAlignmentCenter];
7670 [[self view] addSubview:status_];
7674 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7675 return IsWildcat_ || orientation == UIInterfaceOrientationPortrait;
7680 /* Cydia Container {{{ */
7681 @interface CYContainer : UIViewController <ProgressDelegate> {
7682 _transient Database *database_;
7683 RefreshBar *refreshbar_;
7687 // XXX: ok, "updatedelegate_"?...
7688 _transient NSObject<CydiaDelegate> *updatedelegate_;
7689 // XXX: can't we query for this variable when we need it?
7690 _transient UITabBarController *root_;
7693 - (void) setTabBarController:(UITabBarController *)controller;
7695 - (void) dropBar:(BOOL)animated;
7696 - (void) beginUpdate;
7697 - (void) raiseBar:(BOOL)animated;
7702 @implementation CYContainer
7704 - (BOOL) _reallyWantsFullScreenLayout {
7708 // NOTE: UIWindow only sends the top controller these messages,
7709 // So we have to forward them on.
7711 - (void) viewDidAppear:(BOOL)animated {
7712 [super viewDidAppear:animated];
7713 [root_ viewDidAppear:animated];
7716 - (void) viewWillAppear:(BOOL)animated {
7717 [super viewWillAppear:animated];
7718 [root_ viewWillAppear:animated];
7721 - (void) viewDidDisappear:(BOOL)animated {
7722 [super viewDidDisappear:animated];
7723 [root_ viewDidDisappear:animated];
7726 - (void) viewWillDisappear:(BOOL)animated {
7727 [super viewWillDisappear:animated];
7728 [root_ viewWillDisappear:animated];
7731 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7732 return ![updatedelegate_ hudIsShowing] && (IsWildcat_ || orientation == UIInterfaceOrientationPortrait);
7735 - (void) setTabBarController:(UITabBarController *)controller {
7737 [[self view] addSubview:[root_ view]];
7740 - (void) setUpdate:(NSDate *)date {
7744 - (void) beginUpdate {
7746 [refreshbar_ start];
7751 detachNewThreadSelector:@selector(performUpdate)
7757 - (void) performUpdate { _pooled
7759 status.setDelegate(self);
7760 [database_ updateWithStatus:status];
7763 performSelectorOnMainThread:@selector(completeUpdate)
7769 - (void) completeUpdate {
7774 [self raiseBar:YES];
7776 [updatedelegate_ performSelector:@selector(reloadData) withObject:nil afterDelay:0];
7779 - (void) cancelUpdate {
7781 [self raiseBar:YES];
7783 [updatedelegate_ performSelector:@selector(updateData) withObject:nil afterDelay:0];
7786 - (void) cancelPressed {
7787 [self cancelUpdate];
7794 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
7795 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
7798 - (void) startProgress {
7801 - (void) setProgressTitle:(NSString *)title {
7803 performSelectorOnMainThread:@selector(_setProgressTitle:)
7809 - (bool) isCancelling:(size_t)received {
7813 - (void) setProgressPercent:(float)percent {
7815 performSelectorOnMainThread:@selector(_setProgressPercent:)
7816 withObject:[NSNumber numberWithFloat:percent]
7821 - (void) addProgressOutput:(NSString *)output {
7823 performSelectorOnMainThread:@selector(_addProgressOutput:)
7829 - (void) _setProgressTitle:(NSString *)title {
7830 [refreshbar_ setPrompt:title];
7833 - (void) _setProgressPercent:(NSNumber *)percent {
7834 [refreshbar_ setProgress:[percent floatValue]];
7837 - (void) _addProgressOutput:(NSString *)output {
7840 - (void) setUpdateDelegate:(id)delegate {
7841 updatedelegate_ = delegate;
7844 - (CGFloat) statusBarHeight {
7845 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
7846 return [[UIApplication sharedApplication] statusBarFrame].size.height;
7848 return [[UIApplication sharedApplication] statusBarFrame].size.width;
7852 - (void) dropBar:(BOOL)animated {
7857 [[self view] addSubview:refreshbar_];
7859 CGFloat sboffset = [self statusBarHeight];
7861 CGRect barframe = [refreshbar_ frame];
7862 barframe.origin.y = sboffset;
7863 [refreshbar_ setFrame:barframe];
7866 [UIView beginAnimations:nil context:NULL];
7867 CGRect viewframe = [[root_ view] frame];
7868 viewframe.origin.y += barframe.size.height + sboffset;
7869 viewframe.size.height -= barframe.size.height + sboffset;
7870 [[root_ view] setFrame:viewframe];
7872 [UIView commitAnimations];
7874 // Ensure bar has the proper width for our view, it might have changed
7875 barframe.size.width = viewframe.size.width;
7876 [refreshbar_ setFrame:barframe];
7878 // XXX: fix Apple's layout bug
7879 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7882 - (void) raiseBar:(BOOL)animated {
7887 [refreshbar_ removeFromSuperview];
7889 CGFloat sboffset = [self statusBarHeight];
7892 [UIView beginAnimations:nil context:NULL];
7893 CGRect barframe = [refreshbar_ frame];
7894 CGRect viewframe = [[root_ view] frame];
7895 viewframe.origin.y -= barframe.size.height + sboffset;
7896 viewframe.size.height += barframe.size.height + sboffset;
7897 [[root_ view] setFrame:viewframe];
7899 [UIView commitAnimations];
7901 // XXX: fix Apple's layout bug
7902 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7905 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7906 // XXX: fix Apple's layout bug
7907 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7910 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7916 // XXX: fix Apple's layout bug
7917 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7920 - (void) statusBarFrameChanged:(NSNotification *)notification {
7928 [refreshbar_ release];
7929 [[NSNotificationCenter defaultCenter] removeObserver:self];
7933 - (id) initWithDatabase:(Database *)database {
7934 if ((self = [super init]) != nil) {
7935 database_ = database;
7937 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7938 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
7940 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
7957 @interface Cydia : UIApplication <
7958 ConfirmationControllerDelegate,
7959 ProgressControllerDelegate,
7961 UINavigationControllerDelegate,
7962 UITabBarControllerDelegate
7964 // XXX: evaluate all fields for _transient
7967 CYContainer *container_;
7968 CYTabBarController *tabbar_;
7970 NSMutableArray *essential_;
7971 NSMutableArray *broken_;
7973 Database *database_;
7979 SectionsController *sections_;
7980 ChangesController *changes_;
7981 ManageController *manage_;
7982 SearchController *search_;
7983 SourceTable *sources_;
7984 InstalledController *installed_;
7987 CYStashController *stash_;
7992 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class;
7993 - (void) setPage:(CYViewController *)page;
7998 static _finline void _setHomePage(Cydia *self) {
7999 [self setPage:[self _pageForURL:[NSURL URLWithString:CydiaURL(@"")] withClass:[HomeController class]]];
8002 @implementation Cydia
8004 - (void) beginUpdate {
8005 [container_ beginUpdate];
8009 return [container_ updating];
8012 - (UIView *) rotatingContentViewForWindow:(UIWindow *)window {
8017 if ([broken_ count] != 0) {
8018 int count = [broken_ count];
8020 UIAlertView *alert = [[[UIAlertView alloc]
8021 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8022 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8024 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8025 otherButtonTitles:UCLocalize("TEMPORARY_IGNORE"), nil
8028 [alert setContext:@"fixhalf"];
8030 } else if (!Ignored_ && [essential_ count] != 0) {
8031 int count = [essential_ count];
8033 UIAlertView *alert = [[[UIAlertView alloc]
8034 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8035 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8037 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8038 otherButtonTitles:UCLocalize("UPGRADE_ESSENTIAL"), UCLocalize("COMPLETE_UPGRADE"), nil
8041 [alert setContext:@"upgrade"];
8046 - (void) _saveConfig {
8049 NSString *error(nil);
8050 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8052 NSError *error(nil);
8053 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8054 NSLog(@"failure to save metadata data: %@", error);
8057 NSLog(@"failure to serialize metadata: %@", error);
8065 - (void) _updateData {
8068 /* XXX: this is just stupid */
8069 if (tag_ != 1 && sections_ != nil)
8070 [sections_ reloadData];
8071 if (tag_ != 2 && changes_ != nil)
8072 [changes_ reloadData];
8073 if (tag_ != 4 && search_ != nil)
8074 [search_ reloadData];
8076 [(CYNavigationController *)[tabbar_ selectedViewController] reloadData];
8079 - (int)indexOfTabWithTag:(int)tag {
8081 for (UINavigationController *controller in [tabbar_ viewControllers]) {
8082 if ([[controller tabBarItem] tag] == tag)
8090 - (void) _refreshIfPossible {
8091 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8093 bool recently = false;
8094 NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
8095 if (update != nil) {
8096 NSTimeInterval interval([update timeIntervalSinceNow]);
8097 if (interval <= 0 && interval > -(15*60))
8101 // Don't automatic refresh if:
8102 // - We already refreshed recently.
8103 // - We already auto-refreshed this launch.
8104 // - Auto-refresh is disabled.
8105 if (recently || loaded_ || ManualRefresh) {
8106 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8108 // If we are cancelling due to ManualRefresh or a recent refresh
8109 // we need to make sure it knows it's already loaded.
8113 // We are going to load, so remember that.
8117 SCNetworkReachabilityFlags flags; {
8118 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8119 SCNetworkReachabilityGetFlags(reachability, &flags);
8120 CFRelease(reachability);
8123 // XXX: this elaborate mess is what Apple is using to determine this? :(
8124 // XXX: do we care if the user has to intervene? maybe that's ok?
8126 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8127 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8128 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8129 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8130 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8131 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8135 // If we can reach the server, auto-refresh!
8137 [container_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8142 - (void) refreshIfPossible {
8143 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
8146 - (void) _reloadData {
8147 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8148 [hud setText:UCLocalize("RELOADING_DATA")];
8150 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
8153 [self removeProgressHUD:hud];
8157 [essential_ removeAllObjects];
8158 [broken_ removeAllObjects];
8160 NSArray *packages([database_ packages]);
8161 for (Package *package in packages) {
8163 [broken_ addObject:package];
8164 if ([package upgradableAndEssential:NO]) {
8165 if ([package essential])
8166 [essential_ addObject:package];
8171 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem];
8173 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8174 [changesItem setBadgeValue:badge];
8175 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8177 if ([self respondsToSelector:@selector(setApplicationBadge:)])
8178 [self setApplicationBadge:badge];
8180 [self setApplicationBadgeString:badge];
8182 [changesItem setBadgeValue:nil];
8183 [changesItem setAnimatedBadge:NO];
8185 if ([self respondsToSelector:@selector(removeApplicationBadge)])
8186 [self removeApplicationBadge];
8187 else // XXX: maybe use setApplicationBadgeString also?
8188 [self setApplicationIconBadgeNumber:0];
8193 [self refreshIfPossible];
8196 - (void) updateData {
8205 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8206 _assert(file != NULL);
8208 for (NSString *key in [Sources_ allKeys]) {
8209 NSDictionary *source([Sources_ objectForKey:key]);
8211 fprintf(file, "%s %s %s\n",
8212 [[source objectForKey:@"Type"] UTF8String],
8213 [[source objectForKey:@"URI"] UTF8String],
8214 [[source objectForKey:@"Distribution"] UTF8String]
8222 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8223 CYNavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8225 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8226 [container_ presentModalViewController:navigation animated:YES];
8229 detachNewThreadSelector:@selector(update_)
8232 title:UCLocalize("UPDATING_SOURCES")
8236 - (void) reloadData {
8237 @synchronized (self) {
8243 pkgProblemResolver *resolver = [database_ resolver];
8245 resolver->InstallProtect();
8246 if (!resolver->Resolve(true))
8250 - (CGRect) popUpBounds {
8251 return [[tabbar_ view] bounds];
8255 if (![database_ prepare])
8258 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8259 [page setDelegate:self];
8260 CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]);
8261 [confirm_ setDelegate:self];
8264 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8265 [container_ presentModalViewController:confirm_ animated:YES];
8271 @synchronized (self) {
8276 - (void) clearPackage:(Package *)package {
8277 @synchronized (self) {
8284 - (void) installPackages:(NSArray *)packages {
8285 @synchronized (self) {
8286 for (Package *package in packages)
8293 - (void) installPackage:(Package *)package {
8294 @synchronized (self) {
8301 - (void) removePackage:(Package *)package {
8302 @synchronized (self) {
8309 - (void) distUpgrade {
8310 @synchronized (self) {
8311 if (![database_ upgrade])
8318 @synchronized (self) {
8323 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8324 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8326 if (navigation != nil) {
8327 [navigation pushViewController:progress animated:YES];
8329 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8331 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8332 [container_ presentModalViewController:navigation animated:YES];
8336 detachNewThreadSelector:@selector(perform)
8339 title:UCLocalize("RUNNING")
8343 - (void) progressControllerIsComplete:(ProgressController *)progress {
8347 - (void) setPage:(CYViewController *)page {
8348 [page setDelegate:self];
8350 CYNavigationController *navController = (CYNavigationController *) [tabbar_ selectedViewController];
8351 [navController setViewControllers:[NSArray arrayWithObject:page]];
8352 for (CYNavigationController *page in [tabbar_ viewControllers])
8353 if (page != navController)
8354 [page setViewControllers:nil];
8357 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class {
8358 CYBrowserController *browser = [[[_class alloc] init] autorelease];
8359 [browser loadURL:url];
8363 - (SectionsController *) sectionsController {
8364 if (sections_ == nil)
8365 sections_ = [[SectionsController alloc] initWithDatabase:database_];
8369 - (ChangesController *) changesController {
8370 if (changes_ == nil)
8371 changes_ = [[ChangesController alloc] initWithDatabase:database_ delegate:self];
8375 - (ManageController *) manageController {
8376 if (manage_ == nil) {
8377 manage_ = (ManageController *) [[self
8378 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
8379 withClass:[ManageController class]
8382 queueDelegate_ = manage_;
8387 - (SearchController *) searchController {
8389 search_ = [[SearchController alloc] initWithDatabase:database_];
8393 - (SourceTable *) sourcesController {
8394 if (sources_ == nil)
8395 sources_ = [[SourceTable alloc] initWithDatabase:database_];
8399 - (InstalledController *) installedController {
8400 if (installed_ == nil) {
8401 installed_ = [[InstalledController alloc] initWithDatabase:database_];
8403 queueDelegate_ = installed_;
8408 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
8409 int tag = [[viewController tabBarItem] tag];
8411 [(CYNavigationController *)[tabbar_ selectedViewController] popToRootViewControllerAnimated:YES];
8413 } else if (tag_ == 1) {
8414 [[self sectionsController] resetView];
8418 case kCydiaTag: _setHomePage(self); break;
8420 case kSectionsTag: [self setPage:[self sectionsController]]; break;
8421 case kChangesTag: [self setPage:[self changesController]]; break;
8422 case kManageTag: [self setPage:[self manageController]]; break;
8423 case kInstalledTag: [self setPage:[self installedController]]; break;
8424 case kSourcesTag: [self setPage:[self sourcesController]]; break;
8425 case kSearchTag: [self setPage:[self searchController]]; break;
8433 - (void) showSettings {
8434 RoleController *role = [[[RoleController alloc] initWithDatabase:database_ delegate:self] autorelease];
8435 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
8437 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
8438 [container_ presentModalViewController:nav animated:YES];
8441 - (void) setPackageController:(PackageController *)view {
8443 [view setPackage:nil];
8447 - (PackageController *) _packageController {
8448 return [[[PackageController alloc] initWithDatabase:database_] autorelease];
8451 - (PackageController *) packageController {
8452 return [self _packageController];
8455 // Returns the navigation controller for the queuing badge.
8456 - (id) queueBadgeController {
8457 int index = [self indexOfTabWithTag:kManageTag];
8459 index = [self indexOfTabWithTag:kInstalledTag];
8461 return [[tabbar_ viewControllers] objectAtIndex:index];
8464 - (void) cancelAndClear:(bool)clear {
8465 @synchronized (self) {
8471 [[[self queueBadgeController] tabBarItem] setBadgeValue:nil];
8475 [[[self queueBadgeController] tabBarItem] setBadgeValue:UCLocalize("Q_D")];
8479 [queueDelegate_ queueStatusDidChange];
8483 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8484 NSString *context([alert context]);
8486 if ([context isEqualToString:@"fixhalf"]) {
8487 if (button == [alert firstOtherButtonIndex]) {
8488 @synchronized (self) {
8489 for (Package *broken in broken_) {
8492 NSString *id = [broken id];
8493 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8494 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8495 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8496 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8502 } else if (button == [alert cancelButtonIndex]) {
8503 [broken_ removeAllObjects];
8507 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8508 } else if ([context isEqualToString:@"upgrade"]) {
8509 if (button == [alert firstOtherButtonIndex]) {
8510 @synchronized (self) {
8511 for (Package *essential in essential_)
8512 [essential install];
8517 } else if (button == [alert firstOtherButtonIndex] + 1) {
8519 } else if (button == [alert cancelButtonIndex]) {
8523 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8527 - (void) system:(NSString *)command { _pooled
8528 system([command UTF8String]);
8531 - (void) applicationWillSuspend {
8533 [super applicationWillSuspend];
8536 - (BOOL) hudIsShowing {
8537 return (hudcount_ > 0);
8540 - (void) applicationSuspend:(__GSEvent *)event {
8541 // Use external process status API internally.
8542 // This is probably a really bad idea.
8543 uint64_t status = 0;
8545 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
8546 notify_get_state(notify_token, &status);
8547 notify_cancel(notify_token);
8550 if (![self hudIsShowing] && status == 0)
8551 [super applicationSuspend:event];
8554 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8555 if (![self hudIsShowing])
8556 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8559 - (void) _setSuspended:(BOOL)value {
8560 if (![self hudIsShowing])
8561 [super _setSuspended:value];
8564 - (UIProgressHUD *) addProgressHUD {
8565 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8566 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8568 [window_ setUserInteractionEnabled:NO];
8571 UIViewController *target = container_;
8572 while ([target modalViewController] != nil) target = [target modalViewController];
8573 [[target view] addSubview:hud];
8579 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8581 [hud removeFromSuperview];
8582 [window_ setUserInteractionEnabled:YES];
8586 - (CYViewController *) pageForPackage:(NSString *)name {
8587 if (Package *package = [database_ packageWithName:name]) {
8588 PackageController *view([self packageController]);
8589 [view setPackage:package];
8592 NSURL *url([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"unknown" ofType:@"html"]]);
8593 url = [NSURL URLWithString:[[url absoluteString] stringByAppendingString:[NSString stringWithFormat:@"?%@", name]]];
8594 return [self _pageForURL:url withClass:[CYBrowserController class]];
8598 - (CYViewController *) pageForURL:(NSURL *)url hasTag:(int *)tag {
8602 NSString *href([url absoluteString]);
8603 if ([href hasPrefix:@"apptapp://package/"])
8604 return [self pageForPackage:[href substringFromIndex:18]];
8606 NSString *scheme([[url scheme] lowercaseString]);
8607 if (![scheme isEqualToString:@"cydia"])
8609 NSString *path([url absoluteString]);
8610 if ([path length] < 8)
8612 path = [path substringFromIndex:8];
8613 if (![path hasPrefix:@"/"])
8614 path = [@"/" stringByAppendingString:path];
8616 if ([path isEqualToString:@"/add-source"])
8617 return [[[AddSourceController alloc] initWithDatabase:database_] autorelease];
8618 else if ([path isEqualToString:@"/storage"])
8619 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CYBrowserController class]];
8620 else if ([path isEqualToString:@"/sources"])
8621 return [[[SourceTable alloc] initWithDatabase:database_] autorelease];
8622 else if ([path isEqualToString:@"/packages"])
8623 return [[[InstalledController alloc] initWithDatabase:database_] autorelease];
8624 else if ([path hasPrefix:@"/url/"])
8625 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[CYBrowserController class]];
8626 else if ([path hasPrefix:@"/launch/"])
8627 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8628 else if ([path hasPrefix:@"/package-settings/"])
8629 return [[[SettingsController alloc] initWithDatabase:database_ package:[path substringFromIndex:18]] autorelease];
8630 else if ([path hasPrefix:@"/package-signature/"])
8631 return [[[SignatureController alloc] initWithDatabase:database_ package:[path substringFromIndex:19]] autorelease];
8632 else if ([path hasPrefix:@"/package/"])
8633 return [self pageForPackage:[path substringFromIndex:9]];
8634 else if ([path hasPrefix:@"/files/"]) {
8635 NSString *name = [path substringFromIndex:7];
8637 if (Package *package = [database_ packageWithName:name]) {
8638 FileTable *files = [[[FileTable alloc] initWithDatabase:database_] autorelease];
8639 [files setPackage:package];
8647 - (BOOL) openCydiaURL:(NSURL *)url {
8648 CYViewController *page = nil;
8651 NSLog(@"open url: %@", url);
8653 if ((page = [self pageForURL:url hasTag:&tag])) {
8654 [self setPage:page];
8656 [tabbar_ setSelectedViewController:(tag_ == -1 ? nil : [[tabbar_ viewControllers] objectAtIndex:tag_])];
8662 - (void) applicationOpenURL:(NSURL *)url {
8663 [super applicationOpenURL:url];
8664 NSLog(@"first: %@", url);
8665 if (!loaded_) starturl_ = [url retain];
8666 else [self openCydiaURL:url];
8669 - (void) applicationWillResignActive:(UIApplication *)application {
8670 // Stop refreshing if you get a phone call or lock the device.
8671 if ([container_ updating])
8672 [container_ cancelUpdate];
8674 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
8675 [super applicationWillResignActive:application];
8678 - (void) addStashController {
8679 stash_ = [[CYStashController alloc] init];
8680 [window_ addSubview:[stash_ view]];
8683 - (void) removeStashController {
8684 [[stash_ view] removeFromSuperview];
8689 [self setIdleTimerDisabled:YES];
8691 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
8692 [self setStatusBarShowsProgress:YES];
8693 UpdateExternalStatus(1);
8695 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
8697 UpdateExternalStatus(0);
8698 [self setStatusBarShowsProgress:NO];
8700 [self removeStashController];
8702 if (ExecFork() == 0) {
8703 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
8704 perror("launchctl stop");
8708 - (void) setupTabBarController {
8709 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
8710 [tabbar_ setDelegate:self];
8712 NSMutableArray *items([NSMutableArray arrayWithObjects:
8713 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:kCydiaTag] autorelease],
8714 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:kSectionsTag] autorelease],
8715 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:kChangesTag] autorelease],
8716 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:kSearchTag] autorelease],
8720 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:kSourcesTag] autorelease] atIndex:3];
8721 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:kInstalledTag] autorelease] atIndex:3];
8723 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:kManageTag] autorelease] atIndex:3];
8726 NSMutableArray *controllers([NSMutableArray array]);
8728 for (UITabBarItem *item in items) {
8729 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
8730 [controller setTabBarItem:item];
8731 [controllers addObject:controller];
8734 [tabbar_ setViewControllers:controllers];
8737 - (void) applicationDidFinishLaunching:(id)unused {
8738 [CYBrowserController _initialize];
8740 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8742 Font12_ = [[UIFont systemFontOfSize:12] retain];
8743 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8744 Font14_ = [[UIFont systemFontOfSize:14] retain];
8745 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8746 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8750 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8751 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8753 UIScreen *screen([UIScreen mainScreen]);
8755 window_ = [[UIWindow alloc] initWithFrame:[screen bounds]];
8756 [window_ orderFront:self];
8757 [window_ makeKey:self];
8758 [window_ setHidden:NO];
8761 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8762 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8763 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8764 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
8765 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8766 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8767 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8768 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
8769 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
8772 [self addStashController];
8773 // XXX: this would be much cleaner as a yieldToSelector:
8774 // that way the removeStashController could happen right here inline
8775 // we also could no longer require the useless stash_ field anymore
8776 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
8780 database_ = [Database sharedInstance];
8782 [self setupTabBarController];
8784 container_ = [[CYContainer alloc] initWithDatabase:database_];
8785 [container_ setUpdateDelegate:self];
8786 [container_ setTabBarController:tabbar_];
8787 [window_ addSubview:[container_ view]];
8789 // Show pinstripes while loading data.
8790 [[container_ view] setBackgroundColor:[UIColor pinStripeColor]];
8792 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
8799 [self showSettings];
8803 [window_ setUserInteractionEnabled:NO];
8805 UIView *container = [[[UIView alloc] init] autorelease];
8806 [container setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
8808 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
8809 [spinner startAnimating];
8810 [container addSubview:spinner];
8812 UILabel *label = [[[UILabel alloc] init] autorelease];
8813 [label setFont:[UIFont boldSystemFontOfSize:15.0f]];
8814 [label setBackgroundColor:[UIColor clearColor]];
8815 [label setTextColor:[UIColor blackColor]];
8816 [label setShadowColor:[UIColor whiteColor]];
8817 [label setShadowOffset:CGSizeMake(0, 1)];
8818 [label setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
8819 [container addSubview:label];
8821 CGSize viewsize = [[tabbar_ view] frame].size;
8822 CGSize spinnersize = [spinner bounds].size;
8823 CGSize textsize = [[label text] sizeWithFont:[label font]];
8824 float bothwidth = spinnersize.width + textsize.width + 5.0f;
8826 CGRect containrect = {
8827 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
8828 CGSizeMake(bothwidth, spinnersize.height)
8831 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
8839 [container setFrame:containrect];
8840 [spinner setFrame:spinrect];
8841 [label setFrame:textrect];
8842 [[container_ view] addSubview:container];
8847 // Show the initial page
8848 if (starturl_ == nil || ![self openCydiaURL:starturl_]) {
8849 [tabbar_ setSelectedIndex:0];
8853 [starturl_ release];
8856 [window_ setUserInteractionEnabled:YES];
8858 // XXX: does this actually slow anything down?
8859 [[container_ view] setBackgroundColor:[UIColor clearColor]];
8860 [container removeFromSuperview];
8863 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
8864 if (item != nil && IsWildcat_) {
8865 [sheet showFromBarButtonItem:item animated:YES];
8867 [sheet showInView:window_];
8874 id Alloc_(id self, SEL selector) {
8875 id object = alloc_(self, selector);
8876 lprintf("[%s]A-%p\n", self->isa->name, object);
8881 id Dealloc_(id self, SEL selector) {
8882 id object = dealloc_(self, selector);
8883 lprintf("[%s]D-%p\n", self->isa->name, object);
8887 Class $WebDefaultUIKitDelegate;
8889 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
8890 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
8891 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
8892 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
8895 static NSNumber *shouldPlayKeyboardSounds;
8899 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
8901 case 1104: // Keyboard Button Clicked
8902 case 1105: // Keyboard Delete Repeated
8903 if (shouldPlayKeyboardSounds == nil) {
8904 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
8905 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
8908 if (![shouldPlayKeyboardSounds boolValue])
8912 _UIHardware$_playSystemSound$(self, _cmd, sound);
8916 int main(int argc, char *argv[]) { _pooled
8919 if (Class $UIDevice = objc_getClass("UIDevice")) {
8920 UIDevice *device([$UIDevice currentDevice]);
8921 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
8925 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
8927 /* Library Hacks {{{ */
8928 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
8930 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
8931 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
8932 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
8933 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
8934 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
8937 $UIHardware = objc_getClass("UIHardware");
8938 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
8939 if (UIHardware$_playSystemSound$ != NULL) {
8940 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
8941 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
8944 /* Set Locale {{{ */
8945 Locale_ = CFLocaleCopyCurrent();
8946 Languages_ = [NSLocale preferredLanguages];
8947 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
8948 //NSLog(@"%@", [Languages_ description]);
8951 if (Languages_ == nil || [Languages_ count] == 0)
8952 // XXX: consider just setting to C and then falling through?
8955 lang = [[Languages_ objectAtIndex:0] UTF8String];
8956 setenv("LANG", lang, true);
8959 //std::setlocale(LC_ALL, lang);
8960 NSLog(@"Setting Language: %s", lang);
8963 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
8965 /* Parse Arguments {{{ */
8966 bool substrate(false);
8972 for (int argi(1); argi != argc; ++argi)
8973 if (strcmp(argv[argi], "--") == 0) {
8975 argv[argi] = argv[0];
8981 for (int argi(1); argi != arge; ++argi)
8982 if (strcmp(args[argi], "--substrate") == 0)
8985 fprintf(stderr, "unknown argument: %s\n", args[argi]);
8989 App_ = [[NSBundle mainBundle] bundlePath];
8990 Home_ = NSHomeDirectory();
8996 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
8997 alloc_ = alloc->method_imp;
8998 alloc->method_imp = (IMP) &Alloc_;*/
9000 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
9001 dealloc_ = dealloc->method_imp;
9002 dealloc->method_imp = (IMP) &Dealloc_;*/
9004 /* System Information {{{ */
9008 size = sizeof(maxproc);
9009 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9010 perror("sysctlbyname(\"kern.maxproc\", ?)");
9011 else if (maxproc < 64) {
9013 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9014 perror("sysctlbyname(\"kern.maxproc\", #)");
9017 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
9018 char *osversion = new char[size];
9019 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
9020 perror("sysctlbyname(\"kern.osversion\", ?)");
9022 System_ = [NSString stringWithUTF8String:osversion];
9024 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
9025 char *machine = new char[size];
9026 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
9027 perror("sysctlbyname(\"hw.machine\", ?)");
9031 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
9032 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
9033 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
9034 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
9038 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
9039 NSData *data((NSData *) ecid);
9040 size_t length([data length]);
9041 uint8_t bytes[length];
9042 [data getBytes:bytes];
9043 char string[length * 2 + 1];
9044 for (size_t i(0); i != length; ++i)
9045 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
9046 ChipID_ = [NSString stringWithUTF8String:string];
9050 IOObjectRelease(service);
9054 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
9056 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
9057 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9058 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
9060 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
9061 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9062 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
9064 if (mcc != NULL && mnc != NULL)
9065 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9072 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9073 Build_ = [system objectForKey:@"ProductBuildVersion"];
9074 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9075 Product_ = [info objectForKey:@"SafariProductVersion"];
9076 Safari_ = [info objectForKey:@"CFBundleVersion"];
9079 /* Load Database {{{ */
9081 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9083 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9085 if (Metadata_ == NULL)
9086 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9088 Settings_ = [Metadata_ objectForKey:@"Settings"];
9090 Packages_ = [Metadata_ objectForKey:@"Packages"];
9091 Sections_ = [Metadata_ objectForKey:@"Sections"];
9092 Sources_ = [Metadata_ objectForKey:@"Sources"];
9094 Token_ = [Metadata_ objectForKey:@"Token"];
9097 if (Settings_ != nil)
9098 Role_ = [Settings_ objectForKey:@"Role"];
9100 if (Sections_ == nil) {
9101 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9102 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9105 if (Sources_ == nil) {
9106 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9107 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9112 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
9115 if (Packages_ != nil) {
9116 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, NULL);
9118 [Metadata_ removeObjectForKey:@"Packages"];
9123 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9125 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", F_OK) == 0)
9126 dlopen("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", RTLD_LAZY | RTLD_GLOBAL);
9127 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
9128 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
9129 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9130 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9132 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9134 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9135 unlink("/tmp/.cydia.fw");
9137 } else if (access("/User", F_OK) != 0 || version < 2) {
9140 system("/usr/libexec/cydia/firmware.sh");
9144 _assert([[NSFileManager defaultManager]
9145 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9146 withIntermediateDirectories:YES
9151 if (access("/tmp/cydia.chk", F_OK) == 0) {
9152 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9153 _assert(errno == ENOENT);
9154 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9155 _assert(errno == ENOENT);
9158 /* APT Initialization {{{ */
9159 _assert(pkgInitConfig(*_config));
9160 _assert(pkgInitSystem(*_config, _system));
9163 _config->Set("APT::Acquire::Translation", lang);
9165 // XXX: this timeout might be important :(
9166 //_config->Set("Acquire::http::Timeout", 15);
9168 _config->Set("Acquire::http::MaxParallel", 3);
9170 /* Color Choices {{{ */
9171 space_ = CGColorSpaceCreateDeviceRGB();
9173 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9174 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9175 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9176 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9177 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9178 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9179 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9180 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9181 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9183 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9184 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9186 /* UIKit Configuration {{{ */
9187 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9188 if ($GSFontSetUseLegacyFontMetrics != NULL)
9189 $GSFontSetUseLegacyFontMetrics(YES);
9191 // XXX: I have a feeling this was important
9192 //UIKeyboardDisableAutomaticAppearance();
9195 Colon_ = UCLocalize("COLON_DELIMITED");
9196 Elision_ = UCLocalize("ELISION");
9197 Error_ = UCLocalize("ERROR");
9198 Warning_ = UCLocalize("WARNING");
9201 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9203 CGColorSpaceRelease(space_);