1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2010 Jay Freeman (saurik)
5 /* Modified BSD License {{{ */
7 * Redistribution and use in source and binary
8 * forms, with or without modification, are permitted
9 * provided that the following conditions are met:
11 * 1. Redistributions of source code must retain the
12 * above copyright notice, this list of conditions
13 * and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the
15 * above copyright notice, this list of conditions
16 * and the following disclaimer in the documentation
17 * and/or other materials provided with the
19 * 3. The name of the author may not be used to endorse
20 * or promote products derived from this software
21 * without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
24 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
25 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
26 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
28 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
34 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
36 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 // XXX: wtf/FastMalloc.h... wtf?
41 #define USE_SYSTEM_MALLOC 1
43 /* #include Directives {{{ */
44 #include "UICaboodle/UCPlatform.h"
45 #include "UICaboodle/UCLocalize.h"
47 #include <objc/objc.h>
48 #include <objc/runtime.h>
50 #include <CoreGraphics/CoreGraphics.h>
51 #include <Foundation/Foundation.h>
54 #define DEPLOYMENT_TARGET_MACOSX 1
55 #define CF_BUILDING_CF 1
56 #include <CoreFoundation/CFInternal.h>
59 #include <CoreFoundation/CFPriv.h>
60 #include <CoreFoundation/CFUniChar.h>
62 #include <SystemConfiguration/SystemConfiguration.h>
64 #include <UIKit/UIKit.h>
65 #include "iPhonePrivate.h"
67 #include <IOKit/IOKitLib.h>
69 #include <WebCore/WebCoreThread.h>
76 #include <ext/stdio_filebuf.h>
80 #include <apt-pkg/acquire.h>
81 #include <apt-pkg/acquire-item.h>
82 #include <apt-pkg/algorithms.h>
83 #include <apt-pkg/cachefile.h>
84 #include <apt-pkg/clean.h>
85 #include <apt-pkg/configuration.h>
86 #include <apt-pkg/debindexfile.h>
87 #include <apt-pkg/debmetaindex.h>
88 #include <apt-pkg/error.h>
89 #include <apt-pkg/init.h>
90 #include <apt-pkg/mmap.h>
91 #include <apt-pkg/pkgrecords.h>
92 #include <apt-pkg/sha1.h>
93 #include <apt-pkg/sourcelist.h>
94 #include <apt-pkg/sptr.h>
95 #include <apt-pkg/strutl.h>
96 #include <apt-pkg/tagfile.h>
98 #include <apr-1/apr_pools.h>
100 #include <sys/types.h>
101 #include <sys/stat.h>
102 #include <sys/sysctl.h>
103 #include <sys/param.h>
104 #include <sys/mount.h>
105 #include <sys/reboot.h>
112 #include <mach-o/nlist.h>
122 #include <Cytore.hpp>
124 #include "UICaboodle/BrowserView.h"
125 #include "SDURLCache/SDURLCache.h"
127 #include "substrate.h"
134 #define _timestamp ({ \
136 gettimeofday(&tv, NULL); \
137 tv.tv_sec * 1000000 + tv.tv_usec; \
140 typedef std::vector<class ProfileTime *> TimeList;
150 ProfileTime(const char *name) :
154 times_.push_back(this);
157 void AddTime(uint64_t time) {
164 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
176 ProfileTimer(ProfileTime &time) :
183 time_.AddTime(_timestamp - start_);
188 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
190 std::cerr << "========" << std::endl;
193 #define _profile(name) { \
194 static ProfileTime name(#name); \
195 ProfileTimer _ ## name(name);
200 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
202 #define CYPoolStart() \
203 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
205 #define CYPoolEnd() \
209 // Hash Functions/Structures {{{
210 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
218 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
220 void NSLogPoint(const char *fix, const CGPoint &point) {
221 NSLog(@"%s(%g,%g)", fix, point.x, point.y);
224 void NSLogRect(const char *fix, const CGRect &rect) {
225 NSLog(@"%s(%g,%g)+(%g,%g)", fix, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
228 static _finline NSString *CydiaURL(NSString *path) {
230 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = ':';
231 page[5] = '/'; page[6] = '/'; page[7] = 'c'; page[8] = 'y'; page[9] = 'd';
232 page[10] = 'i'; page[11] = 'a'; page[12] = '.'; page[13] = 's'; page[14] = 'a';
233 page[15] = 'u'; page[16] = 'r'; page[17] = 'i'; page[18] = 'k'; page[19] = '.';
234 page[20] = 'c'; page[21] = 'o'; page[22] = 'm'; page[23] = '/'; page[24] = '\0';
235 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
238 static _finline void UpdateExternalStatus(uint64_t newStatus) {
240 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
241 notify_set_state(notify_token, newStatus);
242 notify_cancel(notify_token);
244 notify_post("com.saurik.Cydia.status");
247 /* [NSObject yieldToSelector:(withObject:)] {{{*/
248 @interface NSObject (Cydia)
249 - (id) yieldToSelector:(SEL)selector withObject:(id)object;
250 - (id) yieldToSelector:(SEL)selector;
253 @implementation NSObject (Cydia)
258 - (void) _yieldToContext:(NSMutableArray *)context { _pooled
259 SEL selector(reinterpret_cast<SEL>([[context objectAtIndex:0] pointerValue]));
260 id object([[context objectAtIndex:1] nonretainedObjectValue]);
261 volatile bool &stopped(*reinterpret_cast<bool *>([[context objectAtIndex:2] pointerValue]));
263 /* XXX: deal with exceptions */
264 id value([self performSelector:selector withObject:object]);
266 NSMethodSignature *signature([self methodSignatureForSelector:selector]);
267 [context removeAllObjects];
268 if ([signature methodReturnLength] != 0 && value != nil)
269 [context addObject:value];
274 performSelectorOnMainThread:@selector(doNothing)
280 - (id) yieldToSelector:(SEL)selector withObject:(id)object {
281 volatile bool stopped(false);
283 NSMutableArray *context([NSMutableArray arrayWithObjects:
284 [NSValue valueWithPointer:selector],
285 [NSValue valueWithNonretainedObject:object],
286 [NSValue valueWithPointer:const_cast<bool *>(&stopped)],
289 NSThread *thread([[[NSThread alloc]
291 selector:@selector(_yieldToContext:)
297 NSRunLoop *loop([NSRunLoop currentRunLoop]);
298 NSDate *future([NSDate distantFuture]);
300 while (!stopped && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
302 return [context count] == 0 ? nil : [context objectAtIndex:0];
305 - (id) yieldToSelector:(SEL)selector {
306 return [self yieldToSelector:selector withObject:nil];
312 /* Cydia Action Sheet {{{ */
313 @interface CYActionSheet : UIAlertView {
317 - (int) yieldToPopupAlertAnimated:(BOOL)animated;
320 @implementation CYActionSheet
322 - (id) initWithTitle:(NSString *)title buttons:(NSArray *)buttons defaultButtonIndex:(int)index {
323 if ((self = [super init])) {
324 [self setTitle:title];
325 [self setDelegate:self];
326 for (NSString *button in buttons) [self addButtonWithTitle:button];
327 [self setCancelButtonIndex:index];
331 - (void) _updateFrameForDisplay {
332 [super _updateFrameForDisplay];
333 if ([self cancelButtonIndex] == -1) {
334 NSArray *buttons = [self buttons];
335 if ([buttons count]) {
336 UIImage *background = [[buttons objectAtIndex:0] backgroundForState:0];
337 for (UIThreePartButton *button in buttons)
338 [button setBackground:background forState:0];
343 - (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
344 button_ = buttonIndex + 1;
348 [self dismissWithClickedButtonIndex:-1 animated:YES];
351 - (int) yieldToPopupAlertAnimated:(BOOL)animated {
352 [self setRunsModal:YES];
361 /* NSForcedOrderingSearch doesn't work on the iPhone */
362 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
363 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
364 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
366 /* Information Dictionaries {{{ */
367 @interface NSMutableArray (Cydia)
368 - (void) addInfoDictionary:(NSDictionary *)info;
371 @implementation NSMutableArray (Cydia)
373 - (void) addInfoDictionary:(NSDictionary *)info {
374 [self addObject:info];
379 @interface NSMutableDictionary (Cydia)
380 - (void) addInfoDictionary:(NSDictionary *)info;
383 @implementation NSMutableDictionary (Cydia)
385 - (void) addInfoDictionary:(NSDictionary *)info {
386 [self setObject:info forKey:[info objectForKey:@"CFBundleIdentifier"]];
392 #define lprintf(args...) fprintf(stderr, args)
395 #define TraceLogging (1 && !ForRelease)
396 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
397 #define ProfileTimes (0 && !ForRelease)
398 #define ForSaurik (0 && !ForRelease)
399 #define LogBrowser (0 && !ForRelease)
400 #define TrackResize (0 && !ForRelease)
401 #define ManualRefresh (1 && !ForRelease)
402 #define ShowInternals (0 && !ForRelease)
403 #define IgnoreInstall (0 && !ForRelease)
404 #define AlwaysReload (0 && !ForRelease)
408 #define _trace(args...)
413 #define _profile(name) {
416 #define PrintTimes() do {} while (false)
420 typedef uint32_t (*SKRadixFunction)(id, void *);
422 @interface NSMutableArray (Radix)
423 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
431 @implementation NSMutableArray (Radix)
433 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
434 size_t count([self count]);
435 struct RadixItem_ *swap(new RadixItem_[count * 2]);
437 for (size_t i(0); i != count; ++i) {
438 RadixItem_ &item(swap[i]);
441 id object([self objectAtIndex:i]);
442 item.key = function(object, argument);
445 struct RadixItem_ *lhs(swap), *rhs(swap + count);
447 static const size_t width = 32;
448 static const size_t bits = 11;
449 static const size_t slots = 1 << bits;
450 static const size_t passes = (width + (bits - 1)) / bits;
452 size_t *hist(new size_t[slots]);
454 for (size_t pass(0); pass != passes; ++pass) {
455 memset(hist, 0, sizeof(size_t) * slots);
457 for (size_t i(0); i != count; ++i) {
458 uint32_t key(lhs[i].key);
460 key &= _not(uint32_t) >> width - bits;
465 for (size_t i(0); i != slots; ++i) {
466 size_t local(offset);
471 for (size_t i(0); i != count; ++i) {
472 uint32_t key(lhs[i].key);
474 key &= _not(uint32_t) >> width - bits;
475 rhs[hist[key]++] = lhs[i];
478 RadixItem_ *tmp(lhs);
485 const void **values(new const void *[count]);
486 for (size_t i(0); i != count; ++i)
487 values[i] = [self objectAtIndex:lhs[i].index];
488 CFArrayReplaceValues((CFMutableArrayRef) self, CFRangeMake(0, count), values, count);
496 /* Insertion Sort {{{ */
498 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
499 const char *ptr = (const char *)list;
501 CFIndex half = count / 2;
502 const char *probe = ptr + elementSize * half;
503 CFComparisonResult cr = comparator(element, probe, context);
504 if (0 == cr) return (probe - (const char *)list) / elementSize;
505 ptr = (cr < 0) ? ptr : probe + elementSize;
506 count = (cr < 0) ? half : (half + (count & 1) - 1);
508 return (ptr - (const char *)list) / elementSize;
511 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
512 const char *ptr = (const char *)list;
514 CFIndex half = count / 2;
515 const char *probe = ptr + elementSize * half;
516 CFComparisonResult cr = comparator(element, probe, context);
517 if (0 == cr) return (probe - (const char *)list) / elementSize;
518 ptr = (cr < 0) ? ptr : probe + elementSize;
519 count = (cr < 0) ? half : (half + (count & 1) - 1);
521 return (ptr - (const char *)list) / elementSize;
524 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
525 if (range.length == 0)
527 const void **values(new const void *[range.length]);
528 CFArrayGetValues(array, range, values);
530 #if HistogramInsertionSort > 0
531 uint32_t total(0), *offsets(new uint32_t[range.length]);
534 for (CFIndex index(1); index != range.length; ++index) {
535 const void *value(values[index]);
536 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
537 CFIndex correct(index);
538 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
539 #if HistogramInsertionSort > 1
540 NSLog(@"%@ < %@", value, values[correct - 1]);
545 if (correct != index) {
546 size_t offset(index - correct);
547 #if HistogramInsertionSort
551 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
553 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
554 values[correct] = value;
558 CFArrayReplaceValues(array, range, values, range.length);
561 #if HistogramInsertionSort > 0
562 for (CFIndex index(0); index != range.length; ++index)
563 if (offsets[index] != 0)
564 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
565 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
572 /* Apple Bug Fixes {{{ */
573 @implementation UIWebDocumentView (Cydia)
575 - (void) _setScrollerOffset:(CGPoint)offset {
576 UIScroller *scroller([self _scroller]);
578 CGSize size([scroller contentSize]);
579 CGSize bounds([scroller bounds].size);
582 max.x = size.width - bounds.width;
583 max.y = size.height - bounds.height;
591 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
592 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
594 [scroller setOffset:offset];
600 @implementation WebScriptObject (NSFastEnumeration)
602 - (NSUInteger) countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)objects count:(NSUInteger)count {
603 size_t length([self count] - state->state);
606 else if (length > count)
608 for (size_t i(0); i != length; ++i)
609 objects[i] = [self objectAtIndex:state->state++];
610 state->itemsPtr = objects;
611 state->mutationsPtr = (unsigned long *) self;
617 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
618 size_t length([self length] - state->state);
621 else if (length > count)
623 for (size_t i(0); i != length; ++i)
624 objects[i] = [self item:state->state++];
625 state->itemsPtr = objects;
626 state->mutationsPtr = (unsigned long *) self;
630 /* Cydia NSString Additions {{{ */
631 @interface NSString (Cydia)
632 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
633 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
634 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
635 - (NSComparisonResult) compareByPath:(NSString *)other;
636 - (NSString *) stringByCachingURLWithCurrentCDN;
637 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
640 @implementation NSString (Cydia)
642 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
643 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
646 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
647 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
648 memcpy(data, bytes, length);
649 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
652 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
653 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
656 - (NSComparisonResult) compareByPath:(NSString *)other {
657 NSString *prefix = [self commonPrefixWithString:other options:0];
658 size_t length = [prefix length];
660 NSRange lrange = NSMakeRange(length, [self length] - length);
661 NSRange rrange = NSMakeRange(length, [other length] - length);
663 lrange = [self rangeOfString:@"/" options:0 range:lrange];
664 rrange = [other rangeOfString:@"/" options:0 range:rrange];
666 NSComparisonResult value;
668 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
669 value = NSOrderedSame;
670 else if (lrange.location == NSNotFound)
671 value = NSOrderedAscending;
672 else if (rrange.location == NSNotFound)
673 value = NSOrderedDescending;
675 value = NSOrderedSame;
677 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
678 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
679 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
680 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
682 NSComparisonResult result = [lpath compare:rpath];
683 return result == NSOrderedSame ? value : result;
686 - (NSString *) stringByCachingURLWithCurrentCDN {
688 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
689 withString:@"://cache.cydia.saurik.com/"
693 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
694 return [(id)CFURLCreateStringByAddingPercentEscapes(
699 kCFStringEncodingUTF8
706 /* C++ NSString Wrapper Cache {{{ */
707 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
708 return size == 0 ? NULL :
709 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
710 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
713 static _finline CFStringRef CYStringCreate(const char *data) {
714 return CYStringCreate(data, strlen(data));
723 _finline void clear_() {
724 if (cache_ != NULL) {
731 _finline bool empty() const {
735 _finline size_t size() const {
739 _finline char *data() const {
743 _finline void clear() {
748 _finline CYString() :
755 _finline ~CYString() {
759 void operator =(const CYString &rhs) {
763 if (rhs.cache_ == nil)
766 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
769 void copy(apr_pool_t *pool) {
770 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
771 memcpy(temp, data_, size_);
776 void set(apr_pool_t *pool, const char *data, size_t size) {
782 data_ = const_cast<char *>(data);
790 _finline void set(apr_pool_t *pool, const char *data) {
791 set(pool, data, data == NULL ? 0 : strlen(data));
794 _finline void set(apr_pool_t *pool, const std::string &rhs) {
795 set(pool, rhs.data(), rhs.size());
798 bool operator ==(const CYString &rhs) const {
799 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
802 _finline operator CFStringRef() {
804 cache_ = CYStringCreate(data_, size_);
808 _finline operator id() {
809 return (NSString *) static_cast<CFStringRef>(*this);
812 _finline operator const char *() {
813 return reinterpret_cast<const char *>(data_);
817 /* C++ NSString Algorithm Adapters {{{ */
819 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
822 struct NSStringMapHash :
823 std::unary_function<NSString *, size_t>
825 _finline size_t operator ()(NSString *value) const {
826 return CFStringHashNSString((CFStringRef) value);
830 struct NSStringMapLess :
831 std::binary_function<NSString *, NSString *, bool>
833 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
834 return [lhs compare:rhs] == NSOrderedAscending;
838 struct NSStringMapEqual :
839 std::binary_function<NSString *, NSString *, bool>
841 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
842 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
843 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
844 //[lhs isEqualToString:rhs];
849 /* Perl-Compatible RegEx {{{ */
859 Pcre(const char *regex) :
864 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
867 lprintf("%d:%s\n", offset, error);
871 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
872 matches_ = new int[(capture_ + 1) * 3];
880 NSString *operator [](size_t match) {
881 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
884 bool operator ()(NSString *data) {
885 // XXX: length is for characters, not for bytes
886 return operator ()([data UTF8String], [data length]);
889 bool operator ()(const char *data, size_t size) {
891 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
895 /* Mime Addresses {{{ */
896 @interface Address : NSObject {
902 - (NSString *) address;
904 - (void) setAddress:(NSString *)address;
906 + (Address *) addressWithString:(NSString *)string;
907 - (Address *) initWithString:(NSString *)string;
910 @implementation Address
919 - (NSString *) name {
923 - (NSString *) address {
927 - (void) setAddress:(NSString *)address {
929 [address_ autorelease];
933 address_ = [address retain];
936 + (Address *) addressWithString:(NSString *)string {
937 return [[[Address alloc] initWithString:string] autorelease];
940 + (NSArray *) _attributeKeys {
941 return [NSArray arrayWithObjects:@"address", @"name", nil];
944 - (NSArray *) attributeKeys {
945 return [[self class] _attributeKeys];
948 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
949 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
952 - (Address *) initWithString:(NSString *)string {
953 if ((self = [super init]) != nil) {
954 const char *data = [string UTF8String];
955 size_t size = [string length];
957 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
959 if (address_r(data, size)) {
960 name_ = [address_r[1] retain];
961 address_ = [address_r[2] retain];
963 name_ = [string retain];
971 /* CoreGraphics Primitives {{{ */
976 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
977 CGFloat color[] = {red, green, blue, alpha};
978 return CGColorCreate(space, color);
987 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
988 color_(Create_(space, red, green, blue, alpha))
990 Set(space, red, green, blue, alpha);
995 CGColorRelease(color_);
1002 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
1004 color_ = Create_(space, red, green, blue, alpha);
1007 operator CGColorRef() {
1013 /* Random Global Variables {{{ */
1014 static const int PulseInterval_ = 50000;
1017 static NSArray *Finishes_;
1019 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
1020 #define NotifyConfig_ "/etc/notify.conf"
1022 static bool Queuing_;
1024 static CYColor Blue_;
1025 static CYColor Blueish_;
1026 static CYColor Black_;
1027 static CYColor Off_;
1028 static CYColor White_;
1029 static CYColor Gray_;
1030 static CYColor Green_;
1031 static CYColor Purple_;
1032 static CYColor Purplish_;
1034 static UIColor *InstallingColor_;
1035 static UIColor *RemovingColor_;
1037 static NSString *App_;
1038 static NSString *Home_;
1040 static BOOL Advanced_;
1041 static BOOL Ignored_;
1043 static UIFont *Font12_;
1044 static UIFont *Font12Bold_;
1045 static UIFont *Font14_;
1046 static UIFont *Font18Bold_;
1047 static UIFont *Font22Bold_;
1049 static const char *Machine_ = NULL;
1050 static NSString *System_ = nil;
1051 static NSString *SerialNumber_ = nil;
1052 static NSString *ChipID_ = nil;
1053 static NSString *Token_ = nil;
1054 static NSString *UniqueID_ = nil;
1055 static NSString *PLMN_ = nil;
1056 static NSString *Build_ = nil;
1057 static NSString *Product_ = nil;
1058 static NSString *Safari_ = nil;
1060 static CFLocaleRef Locale_;
1061 static NSArray *Languages_;
1062 static CGColorSpaceRef space_;
1064 static NSDictionary *SectionMap_;
1065 static NSMutableDictionary *Metadata_;
1066 static _transient NSMutableDictionary *Settings_;
1067 static _transient NSString *Role_;
1068 static _transient NSMutableDictionary *Packages_;
1069 static _transient NSMutableDictionary *Sections_;
1070 static _transient NSMutableDictionary *Sources_;
1071 static bool Changed_;
1074 static bool IsWildcat_;
1077 /* Display Helpers {{{ */
1078 inline float Interpolate(float begin, float end, float fraction) {
1079 return (end - begin) * fraction + begin;
1082 /* XXX: localize this! */
1083 NSString *SizeString(double size) {
1084 bool negative = size < 0;
1089 while (size > 1024) {
1094 static const char *powers_[] = {"B", "kB", "MB", "GB"};
1096 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
1099 static _finline const char *StripVersion_(const char *version) {
1100 const char *colon(strchr(version, ':'));
1101 return colon == NULL ? version : colon + 1;
1104 NSString *LocalizeSection(NSString *section) {
1105 static Pcre title_r("^(.*?) \\((.*)\\)$");
1106 if (title_r(section)) {
1107 NSString *parent(title_r[1]);
1108 NSString *child(title_r[2]);
1110 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1111 LocalizeSection(parent),
1112 LocalizeSection(child)
1116 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1119 NSString *Simplify(NSString *title) {
1120 const char *data = [title UTF8String];
1121 size_t size = [title length];
1123 static Pcre square_r("^\\[(.*)\\]$");
1124 if (square_r(data, size))
1125 return Simplify(square_r[1]);
1127 static Pcre paren_r("^\\((.*)\\)$");
1128 if (paren_r(data, size))
1129 return Simplify(paren_r[1]);
1131 static Pcre title_r("^(.*?) \\((.*)\\)$");
1132 if (title_r(data, size))
1133 return Simplify(title_r[1]);
1139 NSString *GetLastUpdate() {
1140 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1143 return UCLocalize("NEVER_OR_UNKNOWN");
1145 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1146 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1148 CFRelease(formatter);
1150 return [(NSString *) formatted autorelease];
1153 bool isSectionVisible(NSString *section) {
1154 NSDictionary *metadata([Sections_ objectForKey:section]);
1155 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1156 return hidden == nil || ![hidden boolValue];
1161 /* Delegate Prototypes {{{ */
1165 @interface NSObject (ProgressDelegate)
1168 @protocol ProgressDelegate
1169 - (void) setProgressError:(NSString *)error withTitle:(NSString *)id;
1170 - (void) setProgressTitle:(NSString *)title;
1171 - (void) setProgressPercent:(float)percent;
1172 - (void) startProgress;
1173 - (void) addProgressOutput:(NSString *)output;
1174 - (bool) isCancelling:(size_t)received;
1177 @protocol ConfigurationDelegate
1178 - (void) repairWithSelector:(SEL)selector;
1179 - (void) setConfigurationData:(NSString *)data;
1182 @class PackageController;
1184 @protocol CydiaDelegate
1185 - (void) retainNetworkActivityIndicator;
1186 - (void) releaseNetworkActivityIndicator;
1187 - (void) setPackageController:(PackageController *)view;
1188 - (void) clearPackage:(Package *)package;
1189 - (void) installPackage:(Package *)package;
1190 - (void) installPackages:(NSArray *)packages;
1191 - (void) removePackage:(Package *)package;
1192 - (void) beginUpdate;
1194 - (void) distUpgrade;
1196 - (void) updateData;
1198 - (void) showSettings;
1199 - (UIProgressHUD *) addProgressHUD;
1200 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1201 - (CYViewController *) pageForPackage:(NSString *)name;
1202 - (PackageController *) packageController;
1203 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
1206 static id<CydiaDelegate> CydiaApp;
1209 /* Status Delegation {{{ */
1211 public pkgAcquireStatus
1214 _transient NSObject<ProgressDelegate> *delegate_;
1222 void setDelegate(id delegate) {
1223 delegate_ = delegate;
1226 NSObject<ProgressDelegate> *getDelegate() const {
1230 virtual bool MediaChange(std::string media, std::string drive) {
1234 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1237 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1238 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1239 [delegate_ setProgressTitle:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), [NSString stringWithUTF8String:item.ShortDesc.c_str()]]];
1242 virtual void Done(pkgAcquire::ItemDesc &item) {
1245 virtual void Fail(pkgAcquire::ItemDesc &item) {
1247 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1248 item.Owner->Status == pkgAcquire::Item::StatDone
1252 std::string &error(item.Owner->ErrorText);
1256 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1257 NSArray *fields([description componentsSeparatedByString:@" "]);
1258 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1260 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
1261 withObject:[NSArray arrayWithObjects:
1262 [NSString stringWithUTF8String:error.c_str()],
1269 virtual bool Pulse(pkgAcquire *Owner) {
1270 bool value = pkgAcquireStatus::Pulse(Owner);
1273 double(CurrentBytes + CurrentItems) /
1274 double(TotalBytes + TotalItems)
1277 [delegate_ setProgressPercent:percent];
1278 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1281 virtual void Start() {
1282 [delegate_ startProgress];
1285 virtual void Stop() {
1289 /* Progress Delegation {{{ */
1294 _transient id<ProgressDelegate> delegate_;
1298 virtual void Update() {
1299 /*if (abs(Percent - percent_) > 2)
1300 //NSLog(@"%s:%s:%f", Op.c_str(), SubOp.c_str(), Percent);
1304 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1305 [delegate_ setProgressPercent:(Percent / 100)];*/
1315 void setDelegate(id delegate) {
1316 delegate_ = delegate;
1319 id getDelegate() const {
1323 virtual void Done() {
1325 //[delegate_ setProgressPercent:1];
1330 /* Database Interface {{{ */
1331 typedef std::map< unsigned long, _H<Source> > SourceMap;
1333 @interface Database : NSObject {
1339 pkgCacheFile cache_;
1340 pkgDepCache::Policy *policy_;
1341 pkgRecords *records_;
1342 pkgProblemResolver *resolver_;
1343 pkgAcquire *fetcher_;
1345 SPtr<pkgPackageManager> manager_;
1346 pkgSourceList *list_;
1349 CFMutableArrayRef deadSources_;
1350 CFMutableArrayRef packages_;
1352 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1360 std::map<const char *, _H<NSString> > sections_;
1363 + (Database *) sharedInstance;
1366 - (void) _readCydia:(NSNumber *)fd;
1367 - (void) _readStatus:(NSNumber *)fd;
1368 - (void) _readOutput:(NSNumber *)fd;
1372 - (Package *) packageWithName:(NSString *)name;
1374 - (pkgCacheFile &) cache;
1375 - (pkgDepCache::Policy *) policy;
1376 - (pkgRecords *) records;
1377 - (pkgProblemResolver *) resolver;
1378 - (pkgAcquire &) fetcher;
1379 - (pkgSourceList &) list;
1380 - (NSArray *) packages;
1381 - (NSArray *) sources;
1382 - (void) reloadData;
1390 - (void) updateWithStatus:(Status &)status;
1392 - (void) setDelegate:(id)delegate;
1393 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1395 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1399 /* Delegate Helpers {{{ */
1400 @implementation NSObject (ProgressDelegate)
1402 - (void) _setProgressErrorPackage:(NSArray *)args {
1403 [self performSelector:@selector(setProgressError:forPackage:)
1404 withObject:[args objectAtIndex:0]
1405 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1409 - (void) _setProgressErrorTitle:(NSArray *)args {
1410 [self performSelector:@selector(setProgressError:withTitle:)
1411 withObject:[args objectAtIndex:0]
1412 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1416 - (void) _setProgressError:(NSString *)error withTitle:(NSString *)title {
1417 [self performSelectorOnMainThread:@selector(_setProgressErrorTitle:)
1418 withObject:[NSArray arrayWithObjects:error, title, nil]
1423 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
1424 Package *package = id == nil ? nil : [[Database sharedInstance] packageWithName:id];
1426 [self performSelector:@selector(setProgressError:withTitle:)
1428 withObject:(package == nil ? id : [package name])
1435 // Cytore Definitions {{{
1436 struct PackageValue :
1439 Cytore::Offset<PackageValue> next_;
1441 uint32_t index_ : 23;
1442 uint32_t subscribed_ : 1;
1459 Cytore::Offset<PackageValue> packages_[1 << 16];
1462 static Cytore::File<MetaValue> MetaFile_;
1464 // Cytore Helper Functions {{{
1465 static PackageValue *PackageFind(const char *name, size_t length) {
1466 SplitHash nhash = { hashlittle(name, length) };
1468 PackageValue *metadata;
1470 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1471 offset: if (offset->IsNull()) {
1472 *offset = MetaFile_.New<PackageValue>(length + 1);
1473 metadata = &MetaFile_.Get(*offset);
1475 memcpy(metadata->name_, name, length + 1);
1476 metadata->nhash_ = nhash.u16[1];
1478 metadata = &MetaFile_.Get(*offset);
1480 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1481 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] && !metadata->subscribed_)
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 NSDate *date([package objectForKey:@"LastSeen"]);
1510 NSString *version([package objectForKey:@"LastVersion"]);
1512 if (date != nil && version != nil) {
1513 time_t time([date timeIntervalSince1970]);
1514 if (metadata->last_ < time || metadata->last_ == 0)
1515 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1516 size_t length(strlen(buffer));
1517 uint16_t vhash(hashlittle(buffer, length));
1519 size_t capped(std::min<size_t>(8, length));
1520 char *latest(buffer + length - capped);
1522 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1523 metadata->vhash_ = vhash;
1525 metadata->last_ = time;
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 {
1836 uint32_t essential_ : 1;
1837 uint32_t obsolete_ : 1;
1838 uint32_t ignored_ : 1;
1842 _transient Database *database_;
1844 pkgCache::VerIterator version_;
1845 pkgCache::PkgIterator iterator_;
1846 pkgCache::VerFileIterator file_;
1852 CYString installed_;
1854 const char *section_;
1855 _transient NSString *section$_;
1859 PackageValue *metadata_;
1860 ParsedPackage *parsed_;
1862 NSMutableArray *tags_;
1865 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1866 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1868 - (pkgCache::PkgIterator) iterator;
1871 - (NSString *) section;
1872 - (NSString *) simpleSection;
1874 - (NSString *) longSection;
1875 - (NSString *) shortSection;
1879 - (Address *) maintainer;
1881 - (NSString *) longDescription;
1882 - (NSString *) shortDescription;
1885 - (PackageValue *) metadata;
1888 - (bool) subscribed;
1889 - (bool) setSubscribed:(bool)subscribed;
1893 - (NSString *) latest;
1894 - (NSString *) installed;
1895 - (BOOL) uninstalled;
1898 - (BOOL) upgradableAndEssential:(BOOL)essential;
1901 - (BOOL) unfiltered;
1905 - (BOOL) halfConfigured;
1906 - (BOOL) halfInstalled;
1908 - (NSString *) mode;
1911 - (NSString *) name;
1913 - (NSString *) homepage;
1914 - (NSString *) depiction;
1915 - (Address *) author;
1917 - (NSString *) support;
1919 - (NSArray *) files;
1920 - (NSArray *) warnings;
1921 - (NSArray *) applications;
1923 - (Source *) source;
1925 - (BOOL) matches:(NSString *)text;
1927 - (bool) hasSupportingRole;
1928 - (BOOL) hasTag:(NSString *)tag;
1929 - (NSString *) primaryPurpose;
1930 - (NSArray *) purposes;
1931 - (bool) isCommercial;
1933 - (void) setIndex:(size_t)index;
1935 - (CYString &) cyname;
1937 - (uint32_t) compareBySection:(NSArray *)sections;
1942 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1943 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1944 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1945 - (bool) isVisibleInSection:(NSString *)section;
1946 - (bool) isVisibleInSource:(Source *)source;
1950 uint32_t PackageChangesRadix(Package *self, void *) {
1955 uint32_t timestamp : 30;
1956 uint32_t ignored : 1;
1957 uint32_t upgradable : 1;
1961 bool upgradable([self upgradableAndEssential:YES]);
1962 value.bits.upgradable = upgradable ? 1 : 0;
1965 value.bits.timestamp = 0;
1966 value.bits.ignored = [self ignored] ? 0 : 1;
1967 value.bits.upgradable = 1;
1969 value.bits.timestamp = [self seen] >> 2;
1970 value.bits.ignored = 0;
1971 value.bits.upgradable = 0;
1974 return _not(uint32_t) - value.key;
1977 uint32_t PackagePrefixRadix(Package *self, void *context) {
1978 size_t offset(reinterpret_cast<size_t>(context));
1979 CYString &name([self cyname]);
1981 size_t size(name.size());
1984 char *text(name.data());
1987 if (!isdigit(text[0]))
1991 while (size != digits && isdigit(text[digits]))
1999 if (offset == 0 && zeros != 0) {
2000 memset(data, '0', zeros);
2001 memcpy(data + zeros, text, 4 - zeros);
2003 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2004 if (size <= offset - zeros)
2007 text += offset - zeros;
2008 size -= offset - zeros;
2011 memcpy(data, text, 4);
2013 memcpy(data, text, size);
2014 memset(data + size, 0, 4 - size);
2017 for (size_t i(0); i != 4; ++i)
2018 if (isalpha(data[i]))
2026 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2028 /* XXX: ntohl may be more honest */
2029 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2032 CYString &(*PackageName)(Package *self, SEL sel);
2034 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2035 _profile(PackageNameCompare)
2036 CYString &lhi(PackageName(lhs, @selector(cyname)));
2037 CYString &rhi(PackageName(rhs, @selector(cyname)));
2038 CFStringRef lhn(lhi), rhn(rhi);
2041 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2042 else if (rhn == NULL)
2043 return NSOrderedDescending;
2045 _profile(PackageNameCompare$NumbersLast)
2046 if (!lhi.empty() && !rhi.empty()) {
2047 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2048 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2049 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2050 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2051 return lha ? NSOrderedAscending : NSOrderedDescending;
2055 CFIndex length = CFStringGetLength(lhn);
2057 _profile(PackageNameCompare$Compare)
2058 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2063 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2064 return PackageNameCompare(*lhs, *rhs, context);
2067 struct PackageNameOrdering :
2068 std::binary_function<Package *, Package *, bool>
2070 _finline bool operator ()(Package *lhs, Package *rhs) const {
2071 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2075 @implementation Package
2077 - (NSString *) description {
2078 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2082 if (parsed_ != NULL)
2091 + (NSString *) webScriptNameForSelector:(SEL)selector {
2092 if (selector == @selector(hasTag:))
2098 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2099 return [self webScriptNameForSelector:selector] == nil;
2102 + (NSArray *) _attributeKeys {
2103 return [NSArray arrayWithObjects:@"applications", @"author", @"depiction", @"longDescription", @"essential", @"homepage", @"icon", @"id", @"installed", @"latest", @"longSection", @"maintainer", @"mode", @"name", @"purposes", @"section", @"shortDescription", @"shortSection", @"simpleSection", @"size", @"source", @"sponsor", @"support", @"warnings", nil];
2106 - (NSArray *) attributeKeys {
2107 return [[self class] _attributeKeys];
2110 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2111 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2115 if (parsed_ != NULL)
2117 @synchronized (database_) {
2118 if ([database_ era] != era_ || file_.end())
2121 ParsedPackage *parsed(new ParsedPackage);
2124 _profile(Package$parse)
2125 pkgRecords::Parser *parser;
2127 _profile(Package$parse$Lookup)
2128 parser = &[database_ records]->Lookup(file_);
2133 _profile(Package$parse$Find)
2138 {"icon", &parsed->icon_},
2139 {"depiction", &parsed->depiction_},
2140 {"homepage", &parsed->homepage_},
2141 {"website", &website},
2142 {"bugs", &parsed->bugs_},
2143 {"support", &parsed->support_},
2144 {"sponsor", &parsed->sponsor_},
2145 {"author", &parsed->author_},
2148 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2149 const char *start, *end;
2151 if (parser->Find(names[i].name_, start, end)) {
2152 CYString &value(*names[i].value_);
2153 _profile(Package$parse$Value)
2154 value.set(pool_, start, end - start);
2160 _profile(Package$parse$Tagline)
2161 const char *start, *end;
2162 if (parser->ShortDesc(start, end)) {
2163 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2166 while (stop != start && stop[-1] == '\r')
2168 parsed->tagline_.set(pool_, start, stop - start);
2172 _profile(Package$parse$Retain)
2173 if (parsed->homepage_.empty())
2174 parsed->homepage_ = website;
2175 if (parsed->homepage_ == parsed->depiction_)
2176 parsed->homepage_.clear();
2181 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2182 if ((self = [super init]) != nil) {
2183 _profile(Package$initWithVersion)
2186 database_ = database;
2187 era_ = [database era];
2191 pkgCache::PkgIterator iterator(version.ParentPkg());
2192 iterator_ = iterator;
2194 _profile(Package$initWithVersion$Version)
2195 if (!version_.end())
2196 file_ = version_.FileList();
2198 pkgCache &cache([database_ cache]);
2199 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2203 _profile(Package$initWithVersion$Cache)
2204 name_.set(NULL, iterator.Display());
2206 latest_.set(NULL, StripVersion_(version_.VerStr()));
2208 pkgCache::VerIterator current(iterator.CurrentVer());
2210 installed_.set(NULL, StripVersion_(current.VerStr()));
2213 _profile(Package$initWithVersion$Tags)
2214 pkgCache::TagIterator tag(iterator.TagList());
2216 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2218 const char *name(tag.Name());
2219 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2221 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2222 if (strcmp(name + 6, "enduser") == 0)
2224 else if (strcmp(name + 6, "hacker") == 0)
2226 else if (strcmp(name + 6, "developer") == 0)
2228 else if (strcmp(name + 6, "cydia") == 0)
2234 if (strncmp(name, "cydia::", 7) == 0) {
2235 if (strcmp(name + 7, "essential") == 0)
2237 else if (strcmp(name + 7, "obsolete") == 0)
2242 } while (!tag.end());
2246 _profile(Package$initWithVersion$Metadata)
2247 const char *mixed(iterator.Name());
2248 size_t size(strlen(mixed));
2249 char lower[size + 1];
2251 for (size_t i(0); i != size; ++i)
2252 lower[i] = mixed[i] | 0x20;
2255 PackageValue *metadata(PackageFind(lower, size));
2256 metadata_ = metadata;
2258 id_.set(NULL, metadata->name_, size);
2260 const char *latest(version_.VerStr());
2261 size_t length(strlen(latest));
2263 uint16_t vhash(hashlittle(latest, length));
2265 size_t capped(std::min<size_t>(8, length));
2266 latest = latest + length - capped;
2268 if (metadata->first_ == 0)
2269 metadata->first_ = now_;
2271 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2272 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2273 metadata->vhash_ = vhash;
2274 metadata->last_ = now_;
2275 } else if (metadata->last_ == 0)
2276 metadata->last_ = metadata->first_;
2279 _profile(Package$initWithVersion$Section)
2280 section_ = iterator.Section();
2283 _profile(Package$initWithVersion$Flags)
2284 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2285 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2290 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2291 pkgCache::VerIterator version;
2293 _profile(Package$packageWithIterator$GetCandidateVer)
2294 version = [database policy]->GetCandidateVer(iterator);
2302 _profile(Package$packageWithIterator$Allocate)
2303 package = [Package allocWithZone:zone];
2306 _profile(Package$packageWithIterator$Initialize)
2308 initWithVersion:version
2315 _profile(Package$packageWithIterator$Autorelease)
2316 package = [package autorelease];
2322 - (pkgCache::PkgIterator) iterator {
2326 - (NSString *) section {
2327 if (section$_ == nil) {
2328 if (section_ == NULL)
2331 _profile(Package$section$mappedSectionForPointer)
2332 section$_ = [database_ mappedSectionForPointer:section_];
2337 - (NSString *) simpleSection {
2338 if (NSString *section = [self section])
2339 return Simplify(section);
2344 - (NSString *) longSection {
2345 return LocalizeSection([self section]);
2348 - (NSString *) shortSection {
2349 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2352 - (NSString *) uri {
2355 pkgIndexFile *index;
2356 pkgCache::PkgFileIterator file(file_.File());
2357 if (![database_ list].FindIndex(file, index))
2359 return [NSString stringWithUTF8String:iterator_->Path];
2360 //return [NSString stringWithUTF8String:file.Site()];
2361 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2365 - (Address *) maintainer {
2366 @synchronized (database_) {
2367 if ([database_ era] != era_ || file_.end())
2370 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2371 const std::string &maintainer(parser->Maintainer());
2372 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2376 @synchronized (database_) {
2377 if ([database_ era] != era_ || version_.end())
2380 return version_->InstalledSize;
2383 - (NSString *) longDescription {
2384 @synchronized (database_) {
2385 if ([database_ era] != era_ || file_.end())
2388 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2389 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2391 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2392 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2393 if ([lines count] < 2)
2396 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2397 for (size_t i(1), e([lines count]); i != e; ++i) {
2398 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2399 [trimmed addObject:trim];
2402 return [trimmed componentsJoinedByString:@"\n"];
2405 - (NSString *) shortDescription {
2406 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2410 _profile(Package$index)
2411 CFStringRef name((CFStringRef) [self name]);
2412 if (CFStringGetLength(name) == 0)
2414 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2415 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2417 return toupper(character);
2421 - (PackageValue *) metadata {
2426 PackageValue *metadata([self metadata]);
2427 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2430 - (bool) subscribed {
2431 return [self metadata]->subscribed_;
2434 - (bool) setSubscribed:(bool)subscribed {
2435 PackageValue *metadata([self metadata]);
2436 if (metadata->subscribed_ == subscribed)
2438 metadata->subscribed_ = subscribed;
2446 - (NSString *) latest {
2450 - (NSString *) installed {
2454 - (BOOL) uninstalled {
2455 return installed_.empty();
2459 return !version_.end();
2462 - (BOOL) upgradableAndEssential:(BOOL)essential {
2463 _profile(Package$upgradableAndEssential)
2464 pkgCache::VerIterator current(iterator_.CurrentVer());
2466 return essential && essential_;
2468 return !version_.end() && version_ != current;
2472 - (BOOL) essential {
2477 return [database_ cache][iterator_].InstBroken();
2480 - (BOOL) unfiltered {
2481 _profile(Package$unfiltered$obsolete)
2482 if (_unlikely(obsolete_))
2486 _profile(Package$unfiltered$hasSupportingRole)
2487 if (_unlikely(![self hasSupportingRole]))
2495 if (![self unfiltered])
2500 _profile(Package$visible$section)
2501 section = [self section];
2504 _profile(Package$visible$isSectionVisible)
2505 if (section != nil && !isSectionVisible(section))
2513 unsigned char current(iterator_->CurrentState);
2514 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2517 - (BOOL) halfConfigured {
2518 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2521 - (BOOL) halfInstalled {
2522 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2526 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2527 return state.Mode != pkgDepCache::ModeKeep;
2530 - (NSString *) mode {
2531 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2533 switch (state.Mode) {
2534 case pkgDepCache::ModeDelete:
2535 if ((state.iFlags & pkgDepCache::Purge) != 0)
2539 case pkgDepCache::ModeKeep:
2540 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2541 return @"REINSTALL";
2542 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2546 case pkgDepCache::ModeInstall:
2547 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2548 return @"REINSTALL";
2549 else*/ switch (state.Status) {
2551 return @"DOWNGRADE";
2557 return @"NEW_INSTALL";
2568 - (NSString *) name {
2569 return name_.empty() ? id_ : name_;
2572 - (UIImage *) icon {
2573 NSString *section = [self simpleSection];
2576 if (parsed_ != NULL)
2577 if (NSString *href = parsed_->icon_)
2578 if ([href hasPrefix:@"file:///"])
2579 // XXX: correct escaping
2580 icon = [UIImage imageAtPath:[href substringFromIndex:7]];
2581 if (icon == nil) if (section != nil)
2582 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2583 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2584 if ([dicon hasPrefix:@"file:///"])
2585 // XXX: correct escaping
2586 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2588 icon = [UIImage applicationImageNamed:@"unknown.png"];
2592 - (NSString *) homepage {
2593 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2596 - (NSString *) depiction {
2597 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2600 - (Address *) sponsor {
2601 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [Address addressWithString:parsed_->sponsor_];
2604 - (Address *) author {
2605 return parsed_ == NULL || parsed_->author_.empty() ? nil : [Address addressWithString:parsed_->author_];
2608 - (NSString *) support {
2609 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2612 - (NSArray *) files {
2613 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2614 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2617 fin.open([path UTF8String]);
2622 while (std::getline(fin, line))
2623 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2628 - (NSArray *) warnings {
2629 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2630 const char *name(iterator_.Name());
2632 size_t length(strlen(name));
2633 if (length < 2) invalid:
2634 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2635 else for (size_t i(0); i != length; ++i)
2637 /* XXX: technically this is not allowed */
2638 (name[i] < 'A' || name[i] > 'Z') &&
2639 (name[i] < 'a' || name[i] > 'z') &&
2640 (name[i] < '0' || name[i] > '9') &&
2641 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2644 if (strcmp(name, "cydia") != 0) {
2647 bool _private = false;
2650 bool repository = [[self section] isEqualToString:@"Repositories"];
2652 if (NSArray *files = [self files])
2653 for (NSString *file in files)
2654 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2656 else if (!user && [file isEqualToString:@"/User"])
2658 else if (!_private && [file isEqualToString:@"/private"])
2660 else if (!stash && [file isEqualToString:@"/var/stash"])
2663 /* XXX: this is not sensitive enough. only some folders are valid. */
2664 if (cydia && !repository)
2665 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2667 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2669 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2671 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2674 return [warnings count] == 0 ? nil : warnings;
2677 - (NSArray *) applications {
2678 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2680 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2682 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2683 if (NSArray *files = [self files])
2684 for (NSString *file in files)
2685 if (application_r(file)) {
2686 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2687 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2688 if ([id isEqualToString:me])
2691 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2693 display = application_r[1];
2695 NSString *bundle([file stringByDeletingLastPathComponent]);
2696 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2697 if (icon == nil || [icon length] == 0)
2699 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2701 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2702 [applications addObject:application];
2704 [application addObject:id];
2705 [application addObject:display];
2706 [application addObject:url];
2709 return [applications count] == 0 ? nil : applications;
2712 - (Source *) source {
2713 if (source_ == nil) {
2714 @synchronized (database_) {
2715 if ([database_ era] != era_ || file_.end())
2716 source_ = (Source *) [NSNull null];
2718 source_ = [([database_ getSource:file_.File()] ?: (Source *) [NSNull null]) retain];
2722 return source_ == (Source *) [NSNull null] ? nil : source_;
2725 - (BOOL) matches:(NSString *)text {
2731 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2732 if (range.location != NSNotFound)
2735 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2736 if (range.location != NSNotFound)
2739 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2740 if (range.location != NSNotFound)
2746 - (bool) hasSupportingRole {
2751 if ([Role_ isEqualToString:@"User"])
2755 if ([Role_ isEqualToString:@"Hacker"])
2759 if ([Role_ isEqualToString:@"Developer"])
2764 - (BOOL) hasTag:(NSString *)tag {
2765 return tags_ == nil ? NO : [tags_ containsObject:tag];
2768 - (NSString *) primaryPurpose {
2769 for (NSString *tag in tags_)
2770 if ([tag hasPrefix:@"purpose::"])
2771 return [tag substringFromIndex:9];
2775 - (NSArray *) purposes {
2776 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2777 for (NSString *tag in tags_)
2778 if ([tag hasPrefix:@"purpose::"])
2779 [purposes addObject:[tag substringFromIndex:9]];
2780 return [purposes count] == 0 ? nil : purposes;
2783 - (bool) isCommercial {
2784 return [self hasTag:@"cydia::commercial"];
2787 - (void) setIndex:(size_t)index {
2788 if (metadata_->index_ != index)
2789 metadata_->index_ = index;
2792 - (CYString &) cyname {
2793 return name_.empty() ? id_ : name_;
2796 - (uint32_t) compareBySection:(NSArray *)sections {
2797 NSString *section([self section]);
2798 for (size_t i(0), e([sections count]); i != e; ++i) {
2799 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2803 return _not(uint32_t);
2807 @synchronized (database_) {
2808 pkgProblemResolver *resolver = [database_ resolver];
2809 resolver->Clear(iterator_);
2811 pkgCacheFile &cache([database_ cache]);
2812 cache->SetReInstall(iterator_, false);
2813 cache->MarkKeep(iterator_, false);
2817 @synchronized (database_) {
2818 pkgProblemResolver *resolver = [database_ resolver];
2819 resolver->Clear(iterator_);
2820 resolver->Protect(iterator_);
2822 pkgCacheFile &cache([database_ cache]);
2823 cache->SetReInstall(iterator_, false);
2824 cache->MarkInstall(iterator_, false);
2826 pkgDepCache::StateCache &state((*cache)[iterator_]);
2827 if (!state.Install())
2828 cache->SetReInstall(iterator_, true);
2832 @synchronized (database_) {
2833 pkgProblemResolver *resolver = [database_ resolver];
2834 resolver->Clear(iterator_);
2835 resolver->Remove(iterator_);
2836 resolver->Protect(iterator_);
2838 pkgCacheFile &cache([database_ cache]);
2839 cache->SetReInstall(iterator_, false);
2840 cache->MarkDelete(iterator_, true);
2843 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2844 _profile(Package$isUnfilteredAndSearchedForBy)
2847 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2848 value &= [self unfiltered];
2851 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2852 value &= [self matches:search];
2859 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2860 if ([search length] == 0)
2863 _profile(Package$isUnfilteredAndSelectedForBy)
2866 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2867 value &= [self unfiltered];
2870 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2871 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2878 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
2879 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
2882 - (bool) isVisibleInSection:(NSString *)name {
2883 NSString *section([self section]);
2887 section == nil && [name length] == 0 ||
2888 [name isEqualToString:section]
2889 ) && [self visible];
2892 - (bool) isVisibleInSource:(Source *)source {
2893 return [self source] == source && [self visible];
2898 /* Section Class {{{ */
2899 @interface Section : NSObject {
2904 NSString *localized_;
2907 - (NSComparisonResult) compareByLocalized:(Section *)section;
2908 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2909 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2910 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2911 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2912 - (NSString *) name;
2919 - (void) addToCount;
2921 - (void) setCount:(size_t)count;
2922 - (NSString *) localized;
2926 @implementation Section
2930 if (localized_ != nil)
2931 [localized_ release];
2935 - (NSComparisonResult) compareByLocalized:(Section *)section {
2936 NSString *lhs(localized_);
2937 NSString *rhs([section localized]);
2939 /*if ([lhs length] != 0 && [rhs length] != 0) {
2940 unichar lhc = [lhs characterAtIndex:0];
2941 unichar rhc = [rhs characterAtIndex:0];
2943 if (isalpha(lhc) && !isalpha(rhc))
2944 return NSOrderedAscending;
2945 else if (!isalpha(lhc) && isalpha(rhc))
2946 return NSOrderedDescending;
2949 return [lhs compare:rhs options:LaxCompareOptions_];
2952 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2953 if ((self = [self initWithName:name localize:NO]) != nil) {
2954 if (localized != nil)
2955 localized_ = [localized retain];
2959 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2960 return [self initWithName:name row:0 localize:localize];
2963 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2964 if ((self = [super init]) != nil) {
2965 name_ = [name retain];
2969 localized_ = [LocalizeSection(name_) retain];
2973 /* XXX: localize the index thingees */
2974 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2975 if ((self = [super init]) != nil) {
2976 name_ = [[NSString stringWithCharacters:&index length:1] retain];
2982 - (NSString *) name {
3002 - (void) addToCount {
3006 - (void) setCount:(size_t)count {
3010 - (NSString *) localized {
3017 static NSString *Colon_;
3018 static NSString *Elision_;
3019 static NSString *Error_;
3020 static NSString *Warning_;
3022 /* Database Implementation {{{ */
3023 @implementation Database
3025 + (Database *) sharedInstance {
3026 static Database *instance;
3027 if (instance == nil)
3028 instance = [[Database alloc] init];
3036 - (void) releasePackages {
3037 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3038 CFArrayRemoveAllValues(packages_);
3042 // XXX: actually implement this thing
3045 CFRelease(deadSources_);
3046 [self releasePackages];
3047 apr_pool_destroy(pool_);
3048 NSRecycleZone(zone_);
3052 - (void) _readCydia:(NSNumber *)fd { _pooled
3053 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3054 std::istream is(&ib);
3057 static Pcre finish_r("^finish:([^:]*)$");
3059 while (std::getline(is, line)) {
3060 const char *data(line.c_str());
3061 size_t size = line.size();
3062 lprintf("C:%s\n", data);
3064 if (finish_r(data, size)) {
3065 NSString *finish = finish_r[1];
3066 int index = [Finishes_ indexOfObject:finish];
3067 if (index != INT_MAX && index > Finish_)
3075 - (void) _readStatus:(NSNumber *)fd { _pooled
3076 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3077 std::istream is(&ib);
3080 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3081 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3083 while (std::getline(is, line)) {
3084 const char *data(line.c_str());
3085 size_t size(line.size());
3086 lprintf("S:%s\n", data);
3088 if (conffile_r(data, size)) {
3089 [delegate_ setConfigurationData:conffile_r[1]];
3090 } else if (strncmp(data, "status: ", 8) == 0) {
3091 NSString *string = [NSString stringWithUTF8String:(data + 8)];
3092 [delegate_ setProgressTitle:string];
3093 } else if (pmstatus_r(data, size)) {
3094 std::string type([pmstatus_r[1] UTF8String]);
3095 NSString *id = pmstatus_r[2];
3097 float percent([pmstatus_r[3] floatValue]);
3098 [delegate_ setProgressPercent:(percent / 100)];
3100 NSString *string = pmstatus_r[4];
3102 if (type == "pmerror")
3103 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3104 withObject:[NSArray arrayWithObjects:string, id, nil]
3107 else if (type == "pmstatus") {
3108 [delegate_ setProgressTitle:string];
3109 } else if (type == "pmconffile")
3110 [delegate_ setConfigurationData:string];
3112 lprintf("E:unknown pmstatus\n");
3114 lprintf("E:unknown status\n");
3120 - (void) _readOutput:(NSNumber *)fd { _pooled
3121 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3122 std::istream is(&ib);
3125 while (std::getline(is, line)) {
3126 lprintf("O:%s\n", line.c_str());
3127 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
3137 - (Package *) packageWithName:(NSString *)name {
3138 @synchronized (self) {
3139 if (static_cast<pkgDepCache *>(cache_) == NULL)
3141 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3142 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3146 if ((self = [super init]) != nil) {
3153 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3154 apr_pool_create(&pool_, NULL);
3156 size_t capacity(MetaFile_->active_);
3162 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3163 deadSources_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks);
3167 _assert(pipe(fds) != -1);
3170 _config->Set("APT::Keep-Fds::", cydiafd_);
3171 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3174 detachNewThreadSelector:@selector(_readCydia:)
3176 withObject:[NSNumber numberWithInt:fds[0]]
3179 _assert(pipe(fds) != -1);
3183 detachNewThreadSelector:@selector(_readStatus:)
3185 withObject:[NSNumber numberWithInt:fds[0]]
3188 _assert(pipe(fds) != -1);
3189 _assert(dup2(fds[0], 0) != -1);
3190 _assert(close(fds[0]) != -1);
3192 input_ = fdopen(fds[1], "a");
3194 _assert(pipe(fds) != -1);
3195 _assert(dup2(fds[1], 1) != -1);
3196 _assert(close(fds[1]) != -1);
3199 detachNewThreadSelector:@selector(_readOutput:)
3201 withObject:[NSNumber numberWithInt:fds[0]]
3206 - (pkgCacheFile &) cache {
3210 - (pkgDepCache::Policy *) policy {
3214 - (pkgRecords *) records {
3218 - (pkgProblemResolver *) resolver {
3222 - (pkgAcquire &) fetcher {
3226 - (pkgSourceList &) list {
3230 - (NSArray *) packages {
3231 return (NSArray *) packages_;
3234 - (NSArray *) sources {
3235 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3236 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3237 [sources addObject:i->second];
3238 [sources addObjectsFromArray:(NSArray *)deadSources_];
3242 - (NSArray *) issues {
3243 if (cache_->BrokenCount() == 0)
3246 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3248 for (Package *package in [self packages]) {
3249 if (![package broken])
3251 pkgCache::PkgIterator pkg([package iterator]);
3253 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3254 [entry addObject:[package name]];
3255 [issues addObject:entry];
3257 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3261 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3262 pkgCache::DepIterator start;
3263 pkgCache::DepIterator end;
3264 dep.GlobOr(start, end); // ++dep
3266 if (!cache_->IsImportantDep(end))
3268 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3271 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3272 [entry addObject:failure];
3273 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3275 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3276 if (Package *package = [self packageWithName:name])
3277 name = [package name];
3278 [failure addObject:name];
3280 pkgCache::PkgIterator target(start.TargetPkg());
3281 if (target->ProvidesList != 0)
3282 [failure addObject:@"?"];
3284 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3286 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3287 else if (!cache_[target].CandidateVerIter(cache_).end())
3288 [failure addObject:@"-"];
3289 else if (target->ProvidesList == 0)
3290 [failure addObject:@"!"];
3292 [failure addObject:@"%"];
3296 if (start.TargetVer() != 0)
3297 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3308 - (bool) popErrorWithTitle:(NSString *)title {
3310 std::string message;
3312 while (!_error->empty()) {
3314 bool warning(!_error->PopMessage(error));
3318 size_t size(error.size());
3319 if (size == 0 || error[size - 1] != '\n')
3321 error.resize(size - 1);
3323 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3325 if (!message.empty())
3330 if (fatal && !message.empty())
3331 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3336 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3337 return [self popErrorWithTitle:title] || !success;
3340 - (void) reloadData { CYPoolStart() {
3341 @synchronized (self) {
3344 [self releasePackages];
3347 CFArrayRemoveAllValues(deadSources_);
3367 apr_pool_clear(pool_);
3369 NSRecycleZone(zone_);
3370 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3372 int chk(creat("/tmp/cydia.chk", 0644));
3376 NSString *title(UCLocalize("DATABASE"));
3379 if (!cache_.Open(progress_, true)) { pop:
3381 bool warning(!_error->PopMessage(error));
3382 lprintf("cache_.Open():[%s]\n", error.c_str());
3384 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3385 [delegate_ repairWithSelector:@selector(configure)];
3386 else if (error == "The package lists or status file could not be parsed or opened.")
3387 [delegate_ repairWithSelector:@selector(update)];
3388 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3389 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3390 // else if (error == "The list of sources could not be read.")
3392 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3401 unlink("/tmp/cydia.chk");
3403 now_ = [[NSDate date] timeIntervalSince1970];
3405 policy_ = new pkgDepCache::Policy();
3406 records_ = new pkgRecords(cache_);
3407 resolver_ = new pkgProblemResolver(cache_);
3408 fetcher_ = new pkgAcquire(&status_);
3411 list_ = new pkgSourceList();
3412 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3415 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3416 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3420 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3423 if (cache_->BrokenCount() != 0) {
3424 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3427 if (cache_->BrokenCount() != 0) {
3428 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3432 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3436 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3438 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3439 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3440 // XXX: this could be more intelligent
3441 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3442 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3443 if (!cached.end()) {
3444 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3449 CFArrayAppendValue(deadSources_, [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease]);
3453 /*std::vector<Package *> packages;
3454 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3455 [packages_ release];
3460 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3461 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3462 //packages.push_back(package);
3463 CFArrayAppendValue(packages_, [package retain]);
3467 /*if (packages.empty())
3468 packages_ = [[NSArray alloc] init];
3470 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3473 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3474 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3475 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3483 /*if (!packages.empty())
3484 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3485 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3487 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3489 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3491 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3495 size_t count(CFArrayGetCount(packages_));
3496 MetaFile_->active_ = count;
3498 for (size_t index(0); index != count; ++index)
3499 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3503 } } CYPoolEnd() _trace(); }
3506 @synchronized (self) {
3508 resolver_ = new pkgProblemResolver(cache_);
3510 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator) {
3511 if (!cache_[iterator].Keep()) {
3512 cache_->MarkKeep(iterator, false);
3513 cache_->SetReInstall(iterator, false);
3518 - (void) configure {
3519 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3521 system([dpkg UTF8String]);
3526 // XXX: I don't remember this condition
3531 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3533 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3535 if ([self popErrorWithTitle:title])
3539 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3542 public pkgArchiveCleaner
3545 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3550 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3557 fetcher_->Shutdown();
3559 pkgRecords records(cache_);
3561 lock_ = new FileFd();
3562 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3564 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3566 if ([self popErrorWithTitle:title])
3570 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3573 manager_ = (_system->CreatePM(cache_));
3574 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3581 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3583 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3585 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3587 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3588 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3591 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3596 [CydiaApp retainNetworkActivityIndicator];
3598 bool failed = false;
3599 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3600 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3602 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3605 std::string uri = (*item)->DescURI();
3606 std::string error = (*item)->ErrorText;
3608 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3611 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3612 withObject:[NSArray arrayWithObjects:
3613 [NSString stringWithUTF8String:error.c_str()],
3619 [CydiaApp releaseNetworkActivityIndicator];
3627 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3629 if (_error->PendingError()) {
3634 if (result == pkgPackageManager::Failed) {
3639 if (result != pkgPackageManager::Completed) {
3644 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3646 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3648 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3649 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3652 if (![before isEqualToArray:after])
3657 NSString *title(UCLocalize("UPGRADE"));
3658 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3664 [self updateWithStatus:status_];
3667 - (void) updateWithStatus:(Status &)status {
3668 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3669 NSString *title(UCLocalize("REFRESHING_DATA"));
3672 if (!list.ReadMainList())
3673 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3676 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3677 if ([self popErrorWithTitle:title])
3680 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3681 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */
3682 /* XXX: why the hell is an empty if statement a clang error? */ (void) 0;
3684 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3688 - (void) setDelegate:(id)delegate {
3689 delegate_ = delegate;
3690 status_.setDelegate(delegate);
3691 progress_.setDelegate(delegate);
3694 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3695 SourceMap::const_iterator i(sources_.find(file->ID));
3696 return i == sources_.end() ? nil : i->second;
3699 - (NSString *) mappedSectionForPointer:(const char *)section {
3700 _H<NSString> *mapped;
3702 _profile(Database$mappedSectionForPointer$Cache)
3703 mapped = §ions_[section];
3706 if (*mapped == NULL) {
3707 size_t length(strlen(section));
3708 char spaced[length + 1];
3710 _profile(Database$mappedSectionForPointer$Replace)
3711 for (size_t index(0); index != length; ++index)
3712 spaced[index] = section[index] == '_' ? ' ' : section[index];
3713 spaced[length] = '\0';
3718 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3719 string = [NSString stringWithUTF8String:spaced];
3722 _profile(Database$mappedSectionForPointer$Map)
3723 string = [SectionMap_ objectForKey:string] ?: string;
3733 /* Confirmation Controller {{{ */
3734 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3735 if (!iterator.end())
3736 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3737 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3739 pkgCache::PkgIterator package(dep.TargetPkg());
3742 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3750 /* Web Scripting {{{ */
3751 @interface CydiaObject : NSObject {
3753 _transient id delegate_;
3756 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3759 @implementation CydiaObject
3762 [indirect_ release];
3766 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3767 if ((self = [super init]) != nil) {
3768 indirect_ = [indirect retain];
3772 - (void) setDelegate:(id)delegate {
3773 delegate_ = delegate;
3776 + (NSArray *) _attributeKeys {
3777 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3780 - (NSArray *) attributeKeys {
3781 return [[self class] _attributeKeys];
3784 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3785 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3788 - (NSString *) device {
3789 return [[UIDevice currentDevice] uniqueIdentifier];
3792 #if 0 // XXX: implement!
3793 - (NSString *) mac {
3794 if (![indirect_ promptForSensitive:@"Mac Address"])
3798 - (NSString *) serial {
3799 if (![indirect_ promptForSensitive:@"Serial #"])
3803 - (NSString *) firewire {
3804 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3808 - (NSString *) imei {
3809 if (![indirect_ promptForSensitive:@"IMEI"])
3814 + (NSString *) webScriptNameForSelector:(SEL)selector {
3815 if (selector == @selector(close))
3817 else if (selector == @selector(getInstalledPackages))
3818 return @"getInstalledPackages";
3819 else if (selector == @selector(getPackageById:))
3820 return @"getPackageById";
3821 else if (selector == @selector(installPackages:))
3822 return @"installPackages";
3823 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3824 return @"setButtonImage";
3825 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3826 return @"setButtonTitle";
3827 else if (selector == @selector(setPopupHook:))
3828 return @"setPopupHook";
3829 else if (selector == @selector(setSpecial:))
3830 return @"setSpecial";
3831 else if (selector == @selector(setToken:))
3833 else if (selector == @selector(setViewportWidth:))
3834 return @"setViewportWidth";
3835 else if (selector == @selector(supports:))
3837 else if (selector == @selector(stringWithFormat:arguments:))
3839 else if (selector == @selector(localizedStringForKey:value:table:))
3841 else if (selector == @selector(du:))
3843 else if (selector == @selector(statfs:))
3849 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3850 return [self webScriptNameForSelector:selector] == nil;
3853 - (BOOL) supports:(NSString *)feature {
3854 return [feature isEqualToString:@"window.open"];
3857 - (NSArray *) getInstalledPackages {
3858 NSArray *packages([[Database sharedInstance] packages]);
3859 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
3860 for (Package *package in packages)
3861 if ([package installed] != nil)
3862 [installed addObject:package];
3866 - (Package *) getPackageById:(NSString *)id {
3867 Package *package([[Database sharedInstance] packageWithName:id]);
3872 - (NSArray *) statfs:(NSString *)path {
3875 if (path == nil || statfs([path UTF8String], &stat) == -1)
3878 return [NSArray arrayWithObjects:
3879 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3880 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3881 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3885 - (NSNumber *) du:(NSString *)path {
3886 NSNumber *value(nil);
3889 _assert(pipe(fds) != -1);
3891 pid_t pid(ExecFork());
3893 _assert(dup2(fds[1], 1) != -1);
3894 _assert(close(fds[0]) != -1);
3895 _assert(close(fds[1]) != -1);
3896 /* XXX: this should probably not use du */
3897 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3902 _assert(close(fds[1]) != -1);
3904 if (FILE *du = fdopen(fds[0], "r")) {
3906 while (fgets(line, sizeof(line), du) != NULL) {
3907 size_t length(strlen(line));
3908 while (length != 0 && line[length - 1] == '\n')
3909 line[--length] = '\0';
3910 if (char *tab = strchr(line, '\t')) {
3912 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3917 } else _assert(close(fds[0]));
3921 if (waitpid(pid, &status, 0) == -1)
3924 else _assert(false);
3933 - (void) installPackages:(NSArray *)packages {
3934 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
3937 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3938 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3941 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3942 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3945 - (void) setSpecial:(id)function {
3946 [indirect_ setSpecial:function];
3949 - (void) setToken:(NSString *)token {
3952 Token_ = [token retain];
3954 [Metadata_ setObject:Token_ forKey:@"Token"];
3958 - (void) setPopupHook:(id)function {
3959 [indirect_ setPopupHook:function];
3962 - (void) setViewportWidth:(float)width {
3963 [indirect_ setViewportWidth:width];
3966 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3967 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3968 unsigned count([arguments count]);
3970 for (unsigned i(0); i != count; ++i)
3971 values[i] = [arguments objectAtIndex:i];
3972 return [[[NSString alloc] initWithFormat:format arguments:*(reinterpret_cast<va_list *>(&values))] autorelease];
3975 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3976 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3978 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3980 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3986 /* @ Loading... Indicator {{{ */
3987 @interface CYLoadingIndicator : UIView {
3988 UIActivityIndicatorView *spinner_;
3993 @property (readonly, nonatomic) UILabel *label;
3994 @property (readonly, nonatomic) UIActivityIndicatorView *activityIndicatorView;
3998 @implementation CYLoadingIndicator
4000 - (id)initWithFrame:(CGRect)frame {
4001 if ((self = [super initWithFrame:frame])) {
4002 container_ = [[[UIView alloc] init] autorelease];
4003 [container_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
4005 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
4006 [spinner_ startAnimating];
4007 [container_ addSubview:spinner_];
4009 label_ = [[[UILabel alloc] init] autorelease];
4010 [label_ setFont:[UIFont boldSystemFontOfSize:15.0f]];
4011 [label_ setBackgroundColor:[UIColor clearColor]];
4012 [label_ setTextColor:[UIColor blackColor]];
4013 [label_ setShadowColor:[UIColor whiteColor]];
4014 [label_ setShadowOffset:CGSizeMake(0, 1)];
4015 [label_ setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
4016 [container_ addSubview:label_];
4018 CGSize viewsize = frame.size;
4019 CGSize spinnersize = [spinner_ bounds].size;
4020 CGSize textsize = [[label_ text] sizeWithFont:[label_ font]];
4021 float bothwidth = spinnersize.width + textsize.width + 5.0f;
4023 CGRect containrect = {
4024 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
4025 CGSizeMake(bothwidth, spinnersize.height)
4028 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
4036 [container_ setFrame:containrect];
4037 [spinner_ setFrame:spinrect];
4038 [label_ setFrame:textrect];
4039 [self addSubview:container_];
4045 - (UILabel *)label { return label_; }
4046 - (UIActivityIndicatorView *)activityIndicatorView { return spinner_; }
4051 /* Cydia Browser Controller {{{ */
4052 @interface CYBrowserController : BrowserController {
4053 CydiaObject *cydia_;
4058 @implementation CYBrowserController
4065 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
4068 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4069 [super webView:view didClearWindowObject:window forFrame:frame];
4071 WebDataSource *source([frame dataSource]);
4072 NSURLResponse *response([source response]);
4073 NSURL *url([response URL]);
4074 NSString *scheme([url scheme]);
4076 NSHTTPURLResponse *http;
4077 if (scheme != nil && ([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"]))
4078 http = (NSHTTPURLResponse *) response;
4082 NSDictionary *headers([http allHeaderFields]);
4083 NSString *host([url host]);
4084 [self setHeaders:headers forHost:host];
4087 [host isEqualToString:@"cydia.saurik.com"] ||
4088 [host hasSuffix:@".cydia.saurik.com"] ||
4089 [scheme isEqualToString:@"file"]
4091 [window setValue:cydia_ forKey:@"cydia"];
4094 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
4095 if (System_ != NULL)
4096 [request setValue:System_ forHTTPHeaderField:@"X-System"];
4097 if (Machine_ != NULL)
4098 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4100 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4102 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
4105 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4106 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4107 [self _setMoreHeaders:copy];
4111 - (void) setDelegate:(id)delegate {
4112 [super setDelegate:delegate];
4113 [cydia_ setDelegate:delegate];
4117 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
4118 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
4120 WebView *webview([[webview_ _documentView] webView]);
4122 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
4124 NSString *application = package == nil ? @"Cydia" : [NSString
4125 stringWithFormat:@"Cydia/%@",
4130 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4132 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4133 if (Product_ != nil)
4134 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4136 [webview setApplicationNameForUserAgent:application];
4143 /* Confirmation {{{ */
4144 @protocol ConfirmationControllerDelegate
4145 - (void) cancelAndClear:(bool)clear;
4146 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4150 @interface ConfirmationController : CYBrowserController {
4151 _transient Database *database_;
4152 UIAlertView *essential_;
4159 - (id) initWithDatabase:(Database *)database;
4163 @implementation ConfirmationController
4170 if (essential_ != nil)
4171 [essential_ release];
4175 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4176 NSString *context([alert context]);
4178 if ([context isEqualToString:@"remove"]) {
4179 if (button == [alert cancelButtonIndex]) {
4180 [self dismissModalViewControllerAnimated:YES];
4181 } else if (button == [alert firstOtherButtonIndex]) {
4184 [delegate_ confirmWithNavigationController:[self navigationController]];
4187 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4188 } else if ([context isEqualToString:@"unable"]) {
4189 [self dismissModalViewControllerAnimated:YES];
4190 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4192 [super alertView:alert clickedButtonAtIndex:button];
4196 - (void) _doContinue {
4197 [self dismissModalViewControllerAnimated:YES];
4198 [delegate_ cancelAndClear:NO];
4201 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4202 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4206 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4207 [super webView:view didClearWindowObject:window forFrame:frame];
4208 [window setValue:changes_ forKey:@"changes"];
4209 [window setValue:issues_ forKey:@"issues"];
4210 [window setValue:sizes_ forKey:@"sizes"];
4211 [window setValue:self forKey:@"queue"];
4214 - (id) initWithDatabase:(Database *)database {
4215 if ((self = [super init]) != nil) {
4216 database_ = database;
4218 [[self navigationItem] setTitle:UCLocalize("CONFIRM")];
4220 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
4221 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
4222 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
4223 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
4224 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
4228 pkgDepCache::Policy *policy([database_ policy]);
4230 pkgCacheFile &cache([database_ cache]);
4231 NSArray *packages = [database_ packages];
4232 for (Package *package in packages) {
4233 pkgCache::PkgIterator iterator = [package iterator];
4234 pkgDepCache::StateCache &state(cache[iterator]);
4236 NSString *name([package name]);
4238 if (state.NewInstall())
4239 [installing addObject:name];
4240 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4241 [reinstalling addObject:name];
4242 else if (state.Upgrade())
4243 [upgrading addObject:name];
4244 else if (state.Downgrade())
4245 [downgrading addObject:name];
4246 else if (state.Delete()) {
4247 if ([package essential])
4249 [removing addObject:name];
4252 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4253 substrate_ |= DepSubstrate(iterator.CurrentVer());
4258 else if (Advanced_) {
4259 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4261 essential_ = [[UIAlertView alloc]
4262 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4263 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4265 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4266 otherButtonTitles:[NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")], nil
4269 [essential_ setContext:@"remove"];
4271 essential_ = [[UIAlertView alloc]
4272 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4273 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4275 cancelButtonTitle:UCLocalize("OKAY")
4276 otherButtonTitles:nil
4279 [essential_ setContext:@"unable"];
4282 changes_ = [[NSArray alloc] initWithObjects:
4290 issues_ = [database_ issues];
4292 issues_ = [issues_ retain];
4294 sizes_ = [[NSArray alloc] initWithObjects:
4295 SizeString([database_ fetcher].FetchNeeded()),
4296 SizeString([database_ fetcher].PartialPresent()),
4299 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
4301 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
4302 initWithTitle:UCLocalize("CANCEL")
4303 // OLD: [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")]
4304 style:UIBarButtonItemStylePlain
4306 action:@selector(cancelButtonClicked)
4311 - (void) applyRightButton {
4312 #if !AlwaysReload && !IgnoreInstall
4313 if (issues_ == nil && ![self isLoading])
4314 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4315 initWithTitle:UCLocalize("CONFIRM")
4316 style:UIBarButtonItemStylePlain
4318 action:@selector(confirmButtonClicked)
4321 [super applyRightButton];
4323 [[self navigationItem] setRightBarButtonItem:nil];
4327 - (void) cancelButtonClicked {
4328 [self dismissModalViewControllerAnimated:YES];
4329 [delegate_ cancelAndClear:YES];
4333 - (void) confirmButtonClicked {
4337 if (essential_ != nil)
4342 [delegate_ confirmWithNavigationController:[self navigationController]];
4350 /* Progress Data {{{ */
4351 @interface ProgressData : NSObject {
4353 // XXX: should these really both be _transient?
4354 _transient id target_;
4355 _transient id object_;
4358 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4365 @implementation ProgressData
4367 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4368 if ((self = [super init]) != nil) {
4369 selector_ = selector;
4389 /* Progress Controller {{{ */
4390 @interface ProgressController : CYViewController <
4391 ConfigurationDelegate,
4394 _transient Database *database_;
4395 UIProgressBar *progress_;
4396 UITextView *output_;
4397 UITextLabel *status_;
4398 UIPushButton *close_;
4400 SHA1SumValue springlist_;
4401 SHA1SumValue notifyconf_;
4405 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4407 - (void) _retachThread;
4408 - (void) _detachNewThreadData:(ProgressData *)data;
4409 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4415 @protocol ProgressControllerDelegate
4416 - (void) progressControllerIsComplete:(ProgressController *)sender;
4419 @implementation ProgressController
4422 [database_ setDelegate:nil];
4423 [progress_ release];
4432 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4433 if ((self = [super init]) != nil) {
4434 database_ = database;
4435 [database_ setDelegate:self];
4436 delegate_ = delegate;
4438 [[self view] setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
4440 progress_ = [[UIProgressBar alloc] init];
4441 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4442 [progress_ setStyle:0];
4444 status_ = [[UITextLabel alloc] init];
4445 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4446 [status_ setColor:[UIColor whiteColor]];
4447 [status_ setBackgroundColor:[UIColor clearColor]];
4448 [status_ setCentersHorizontally:YES];
4449 //[status_ setFont:font];
4451 output_ = [[UITextView alloc] init];
4453 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4454 //[output_ setTextFont:@"Courier New"];
4455 [output_ setFont:[[output_ font] fontWithSize:12]];
4456 [output_ setTextColor:[UIColor whiteColor]];
4457 [output_ setBackgroundColor:[UIColor clearColor]];
4458 [output_ setMarginTop:0];
4459 [output_ setAllowsRubberBanding:YES];
4460 [output_ setEditable:NO];
4461 [[self view] addSubview:output_];
4463 close_ = [[UIPushButton alloc] init];
4464 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4465 [close_ setAutosizesToFit:NO];
4466 [close_ setDrawsShadow:YES];
4467 [close_ setStretchBackground:YES];
4468 [close_ setEnabled:YES];
4469 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
4470 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4471 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4472 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4476 - (void) positionViews {
4477 CGRect bounds = [[self view] bounds];
4478 CGSize prgsize = [UIProgressBar defaultSize];
4481 (bounds.size.width - prgsize.width) / 2,
4482 bounds.size.height - prgsize.height - 20
4485 float closewidth = std::min(bounds.size.width - 20, 300.0f);
4487 [progress_ setFrame:prgrect];
4488 [status_ setFrame:CGRectMake(
4490 bounds.size.height - prgsize.height - 50,
4491 bounds.size.width - 20,
4494 [output_ setFrame:CGRectMake(
4497 bounds.size.width - 20,
4498 bounds.size.height - 62
4500 [close_ setFrame:CGRectMake(
4501 (bounds.size.width - closewidth) / 2,
4502 bounds.size.height - prgsize.height - 50,
4508 - (void) viewWillAppear:(BOOL)animated {
4509 [super viewDidAppear:animated];
4510 [[self navigationItem] setHidesBackButton:YES];
4511 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4513 [self positionViews];
4516 - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4517 [self positionViews];
4520 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4521 NSString *context([alert context]);
4523 if ([context isEqualToString:@"conffile"]) {
4524 FILE *input = [database_ input];
4525 if (button == [alert cancelButtonIndex])
4526 fprintf(input, "N\n");
4527 else if (button == [alert firstOtherButtonIndex])
4528 fprintf(input, "Y\n");
4533 - (void) closeButtonPushed {
4536 UpdateExternalStatus(0);
4540 [self dismissModalViewControllerAnimated:YES];
4544 [delegate_ terminateWithSuccess];
4545 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4546 [delegate_ suspendWithAnimation:YES];
4548 [delegate_ suspend];*/
4560 system("/usr/bin/sbreload");
4566 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
4567 SBReboot(SBSSpringBoardServerPort());
4569 reboot2(RB_AUTOBOOT);
4574 - (void) _retachThread {
4575 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
4577 [[self view] addSubview:close_];
4578 [progress_ removeFromSuperview];
4579 [status_ removeFromSuperview];
4581 [database_ popErrorWithTitle:title_];
4582 [delegate_ progressControllerIsComplete:self];
4586 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4589 MMap mmap(file, MMap::ReadOnly);
4591 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4592 if (!(notifyconf_ == sha1.Result()))
4599 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4602 MMap mmap(file, MMap::ReadOnly);
4604 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4605 if (!(springlist_ == sha1.Result()))
4611 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
4612 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4613 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4614 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4615 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4619 system("su -c /usr/bin/uicache mobile");
4622 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
4624 [delegate_ setStatusBarShowsProgress:NO];
4627 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4628 [[data target] performSelector:[data selector] withObject:[data object]];
4629 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4632 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4633 UpdateExternalStatus(1);
4640 title_ = [title retain];
4642 [[self navigationItem] setTitle:title_];
4644 [status_ setText:nil];
4645 [output_ setText:@""];
4646 [progress_ setProgress:0];
4648 [close_ removeFromSuperview];
4649 [[self view] addSubview:progress_];
4650 [[self view] addSubview:status_];
4652 [delegate_ setStatusBarShowsProgress:YES];
4657 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4660 MMap mmap(file, MMap::ReadOnly);
4662 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4663 notifyconf_ = sha1.Result();
4669 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4672 MMap mmap(file, MMap::ReadOnly);
4674 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4675 springlist_ = sha1.Result();
4680 detachNewThreadSelector:@selector(_detachNewThreadData:)
4682 withObject:[[[ProgressData alloc]
4683 initWithSelector:selector
4690 - (void) repairWithSelector:(SEL)selector {
4692 detachNewThreadSelector:selector
4695 title:UCLocalize("REPAIRING")
4699 - (void) setConfigurationData:(NSString *)data {
4701 performSelectorOnMainThread:@selector(_setConfigurationData:)
4707 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4708 CYActionSheet *sheet([[[CYActionSheet alloc]
4710 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4711 defaultButtonIndex:0
4714 [sheet setMessage:error];
4715 [sheet yieldToPopupAlertAnimated:YES];
4719 - (void) setProgressTitle:(NSString *)title {
4721 performSelectorOnMainThread:@selector(_setProgressTitle:)
4727 - (void) setProgressPercent:(float)percent {
4729 performSelectorOnMainThread:@selector(_setProgressPercent:)
4730 withObject:[NSNumber numberWithFloat:percent]
4735 - (void) startProgress {
4738 - (void) addProgressOutput:(NSString *)output {
4740 performSelectorOnMainThread:@selector(_addProgressOutput:)
4746 - (bool) isCancelling:(size_t)received {
4750 - (void) _setConfigurationData:(NSString *)data {
4751 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4753 if (!conffile_r(data)) {
4754 lprintf("E:invalid conffile\n");
4758 NSString *ofile = conffile_r[1];
4759 //NSString *nfile = conffile_r[2];
4761 UIAlertView *alert = [[[UIAlertView alloc]
4762 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4763 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
4765 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
4766 otherButtonTitles:UCLocalize("ACCEPT_NEW_COPY"),
4767 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4771 [alert setContext:@"conffile"];
4775 - (void) _setProgressTitle:(NSString *)title {
4776 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4777 for (size_t i(0), e([words count]); i != e; ++i) {
4778 NSString *word([words objectAtIndex:i]);
4779 if (Package *package = [database_ packageWithName:word])
4780 [words replaceObjectAtIndex:i withObject:[package name]];
4783 [status_ setText:[words componentsJoinedByString:@" "]];
4786 - (void) _setProgressPercent:(NSNumber *)percent {
4787 [progress_ setProgress:[percent floatValue]];
4790 - (void) _addProgressOutput:(NSString *)output {
4791 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4792 CGSize size = [output_ contentSize];
4793 CGPoint offset = [output_ contentOffset];
4794 if (size.height - offset.y < [output_ frame].size.height + 20.f) {
4795 CGRect rect = {{0, size.height-1}, {size.width, 1}};
4796 [output_ scrollRectToVisible:rect animated:YES];
4800 - (BOOL) isRunning {
4807 /* Cell Content View {{{ */
4808 @protocol ContentDelegate
4809 - (void) drawContentRect:(CGRect)rect;
4812 @interface ContentView : UIView {
4813 _transient id<ContentDelegate> delegate_;
4818 @implementation ContentView
4820 - (id) initWithFrame:(CGRect)frame {
4821 if ((self = [super initWithFrame:frame]) != nil) {
4822 [self setNeedsDisplayOnBoundsChange:YES];
4826 - (void) setDelegate:(id<ContentDelegate>)delegate {
4827 delegate_ = delegate;
4830 - (void) drawRect:(CGRect)rect {
4831 [super drawRect:rect];
4832 [delegate_ drawContentRect:rect];
4837 /* Cydia TableView Cell {{{ */
4838 @interface CYTableViewCell : UITableViewCell {
4839 ContentView *content_;
4845 @implementation CYTableViewCell
4852 - (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
4853 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
4855 if (view == content_) {
4856 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
4857 highlighted_ = highlighted;
4860 [super _updateHighlightColorsForView:view highlighted:highlighted];
4863 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
4864 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
4865 highlighted_ = selected;
4867 [super setSelected:selected animated:animated];
4868 [content_ setNeedsDisplay];
4873 /* Package Cell {{{ */
4874 @interface PackageCell : CYTableViewCell <
4879 NSString *description_;
4887 - (PackageCell *) init;
4888 - (void) setPackage:(Package *)package;
4890 + (int) heightForPackage:(Package *)package;
4891 - (void) drawContentRect:(CGRect)rect;
4895 @implementation PackageCell
4897 - (void) clearPackage {
4908 if (description_ != nil) {
4909 [description_ release];
4913 if (source_ != nil) {
4918 if (badge_ != nil) {
4923 if (placard_ != nil) {
4933 [self clearPackage];
4937 - (PackageCell *) init {
4938 CGRect frame(CGRectMake(0, 0, 320, 74));
4939 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4940 UIView *content([self contentView]);
4941 CGRect bounds([content bounds]);
4943 content_ = [[ContentView alloc] initWithFrame:bounds];
4944 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4945 [content addSubview:content_];
4947 [content_ setDelegate:self];
4948 [content_ setOpaque:YES];
4952 - (void) _setBackgroundColor {
4954 if (NSString *mode = [package_ mode]) {
4955 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4956 color = remove ? RemovingColor_ : InstallingColor_;
4958 color = [UIColor whiteColor];
4960 [content_ setBackgroundColor:color];
4961 [self setNeedsDisplay];
4964 - (void) setPackage:(Package *)package {
4965 [self clearPackage];
4968 Source *source = [package source];
4970 icon_ = [[package icon] retain];
4971 name_ = [[package name] retain];
4974 description_ = [package longDescription];
4975 if (description_ == nil)
4976 description_ = [package shortDescription];
4977 if (description_ != nil)
4978 description_ = [description_ retain];
4980 commercial_ = [package isCommercial];
4982 package_ = [package retain];
4984 NSString *label = nil;
4985 bool trusted = false;
4987 if (source != nil) {
4988 label = [source label];
4989 trusted = [source trusted];
4990 } else if ([[package id] isEqualToString:@"firmware"])
4991 label = UCLocalize("APPLE");
4993 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
4995 NSString *from(label);
4997 NSString *section = [package simpleSection];
4998 if (section != nil && ![section isEqualToString:label]) {
4999 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5000 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5003 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
5004 source_ = [from retain];
5006 if (NSString *purpose = [package primaryPurpose])
5007 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
5008 badge_ = [badge_ retain];
5010 if ([package installed] != nil)
5011 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/installed.png", App_]]) != nil)
5012 placard_ = [placard_ retain];
5014 [self _setBackgroundColor];
5015 [content_ setNeedsDisplay];
5018 - (void) drawContentRect:(CGRect)rect {
5019 bool highlighted(highlighted_);
5020 float width([self bounds].size.width);
5023 CGContextRef context(UIGraphicsGetCurrentContext());
5024 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
5025 CGContextFillRect(context, rect);
5030 rect.size = [icon_ size];
5032 rect.size.width /= 2;
5033 rect.size.height /= 2;
5035 rect.origin.x = 25 - rect.size.width / 2;
5036 rect.origin.y = 25 - rect.size.height / 2;
5038 [icon_ drawInRect:rect];
5041 if (badge_ != nil) {
5043 rect.size = [badge_ size];
5045 rect.size.width /= 2;
5046 rect.size.height /= 2;
5048 rect.origin.x = 36 - rect.size.width / 2;
5049 rect.origin.y = 36 - rect.size.height / 2;
5051 [badge_ drawInRect:rect];
5058 UISetColor(commercial_ ? Purple_ : Black_);
5059 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5060 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5063 UISetColor(commercial_ ? Purplish_ : Gray_);
5064 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5066 if (placard_ != nil)
5067 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5070 + (int) heightForPackage:(Package *)package {
5076 /* Section Cell {{{ */
5077 @interface SectionCell : CYTableViewCell <
5089 - (void) setSection:(Section *)section editing:(BOOL)editing;
5093 @implementation SectionCell
5095 - (void) clearSection {
5096 if (basic_ != nil) {
5101 if (section_ != nil) {
5111 if (count_ != nil) {
5118 [self clearSection];
5124 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5125 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5126 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
5127 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
5128 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5130 UIView *content([self contentView]);
5131 CGRect bounds([content bounds]);
5133 content_ = [[ContentView alloc] initWithFrame:bounds];
5134 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5135 [content addSubview:content_];
5136 [content_ setBackgroundColor:[UIColor whiteColor]];
5138 [content_ setDelegate:self];
5142 - (void) onSwitch:(id)sender {
5143 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5144 if (metadata == nil) {
5145 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5146 [Sections_ setObject:metadata forKey:basic_];
5149 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5153 - (void) setSection:(Section *)section editing:(BOOL)editing {
5154 if (editing != editing_) {
5156 [switch_ removeFromSuperview];
5158 [self addSubview:switch_];
5162 [self clearSection];
5164 if (section == nil) {
5165 name_ = [UCLocalize("ALL_PACKAGES") retain];
5168 basic_ = [section name];
5170 basic_ = [basic_ retain];
5172 section_ = [section localized];
5173 if (section_ != nil)
5174 section_ = [section_ retain];
5176 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
5177 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
5180 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5183 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5184 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5186 [content_ setNeedsDisplay];
5189 - (void) setFrame:(CGRect)frame {
5190 [super setFrame:frame];
5192 CGRect rect([switch_ frame]);
5193 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5196 - (void) drawContentRect:(CGRect)rect {
5197 bool highlighted(highlighted_ && !editing_);
5199 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5204 float width(rect.size.width);
5210 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5212 CGSize size = [count_ sizeWithFont:Font14_];
5216 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5222 /* File Table {{{ */
5223 @interface FileTable : CYViewController <
5224 UITableViewDataSource,
5227 _transient Database *database_;
5230 NSMutableArray *files_;
5234 - (id) initWithDatabase:(Database *)database;
5235 - (void) setPackage:(Package *)package;
5239 @implementation FileTable
5242 if (package_ != nil)
5251 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5252 return files_ == nil ? 0 : [files_ count];
5255 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5259 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5260 static NSString *reuseIdentifier = @"Cell";
5262 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5264 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5265 [cell setFont:[UIFont systemFontOfSize:16]];
5267 [cell setText:[files_ objectAtIndex:indexPath.row]];
5268 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5273 - (id) initWithDatabase:(Database *)database {
5274 if ((self = [super init]) != nil) {
5275 database_ = database;
5277 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5279 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5281 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5282 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5283 [list_ setRowHeight:24.0f];
5284 [[self view] addSubview:list_];
5286 [list_ setDataSource:self];
5287 [list_ setDelegate:self];
5291 - (void) setPackage:(Package *)package {
5292 if (package_ != nil) {
5293 [package_ autorelease];
5302 [files_ removeAllObjects];
5304 if (package != nil) {
5305 package_ = [package retain];
5306 name_ = [[package id] retain];
5308 if (NSArray *files = [package files])
5309 [files_ addObjectsFromArray:files];
5311 if ([files_ count] != 0) {
5312 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5313 [files_ removeObjectAtIndex:0];
5314 [files_ sortUsingSelector:@selector(compareByPath:)];
5316 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5317 [stack addObject:@"/"];
5319 for (int i(0), e([files_ count]); i != e; ++i) {
5320 NSString *file = [files_ objectAtIndex:i];
5321 while (![file hasPrefix:[stack lastObject]])
5322 [stack removeLastObject];
5323 NSString *directory = [stack lastObject];
5324 [stack addObject:[file stringByAppendingString:@"/"]];
5325 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5326 ([stack count] - 2) * 3, "",
5327 [file substringFromIndex:[directory length]]
5336 - (void) reloadData {
5337 [self setPackage:[database_ packageWithName:name_]];
5342 /* Package Controller {{{ */
5343 @interface PackageController : CYBrowserController <
5344 UIActionSheetDelegate
5346 _transient Database *database_;
5350 NSMutableArray *buttons_;
5351 UIBarButtonItem *button_;
5354 - (id) initWithDatabase:(Database *)database;
5355 - (void) setPackage:(Package *)package;
5359 @implementation PackageController
5362 if (package_ != nil)
5376 if ([self retainCount] == 1)
5377 [delegate_ setPackageController:self];
5381 /* XXX: this is not safe at all... localization of /fail/ */
5382 - (void) _clickButtonWithName:(NSString *)name {
5383 if ([name isEqualToString:UCLocalize("CLEAR")])
5384 [delegate_ clearPackage:package_];
5385 else if ([name isEqualToString:UCLocalize("INSTALL")])
5386 [delegate_ installPackage:package_];
5387 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5388 [delegate_ installPackage:package_];
5389 else if ([name isEqualToString:UCLocalize("REMOVE")])
5390 [delegate_ removePackage:package_];
5391 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5392 [delegate_ installPackage:package_];
5393 else _assert(false);
5396 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5397 NSString *context([sheet context]);
5399 if ([context isEqualToString:@"modify"]) {
5400 if (button != [sheet cancelButtonIndex]) {
5401 NSString *buttonName = [buttons_ objectAtIndex:button];
5402 [self _clickButtonWithName:buttonName];
5405 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5409 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5410 [super webView:view didClearWindowObject:window forFrame:frame];
5411 [window setValue:package_ forKey:@"package"];
5414 - (bool) _allowJavaScriptPanel {
5419 - (void) _customButtonClicked {
5420 int count([buttons_ count]);
5425 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5427 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5428 [buttons addObjectsFromArray:buttons_];
5430 UIActionSheet *sheet = [[[UIActionSheet alloc]
5433 cancelButtonTitle:nil
5434 destructiveButtonTitle:nil
5435 otherButtonTitles:nil
5438 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5440 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5441 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5443 [sheet setContext:@"modify"];
5445 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5449 // We don't want to allow non-commercial packages to do custom things to the install button,
5450 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5451 - (void) customButtonClicked {
5453 [super customButtonClicked];
5455 [self _customButtonClicked];
5458 - (void) reloadButtonClicked {
5459 // Don't reload a commerical package by tapping the loading button,
5460 // but if it's not an Install button, we should forward it on.
5461 if (![package_ uninstalled])
5462 [self _customButtonClicked];
5465 - (void) applyLoadingTitle {
5466 // Don't show "Loading" as the title. Ever.
5469 - (UIBarButtonItem *) rightButton {
5474 - (id) initWithDatabase:(Database *)database {
5475 if ((self = [super init]) != nil) {
5476 database_ = database;
5477 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5478 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
5482 - (void) setPackage:(Package *)package {
5483 if (package_ != nil) {
5484 [package_ autorelease];
5493 [buttons_ removeAllObjects];
5495 if (package != nil) {
5498 package_ = [package retain];
5499 name_ = [[package id] retain];
5500 commercial_ = [package isCommercial];
5502 if ([package_ mode] != nil)
5503 [buttons_ addObject:UCLocalize("CLEAR")];
5504 if ([package_ source] == nil);
5505 else if ([package_ upgradableAndEssential:NO])
5506 [buttons_ addObject:UCLocalize("UPGRADE")];
5507 else if ([package_ uninstalled])
5508 [buttons_ addObject:UCLocalize("INSTALL")];
5510 [buttons_ addObject:UCLocalize("REINSTALL")];
5511 if (![package_ uninstalled])
5512 [buttons_ addObject:UCLocalize("REMOVE")];
5519 switch ([buttons_ count]) {
5520 case 0: title = nil; break;
5521 case 1: title = [buttons_ objectAtIndex:0]; break;
5522 default: title = UCLocalize("MODIFY"); break;
5525 button_ = [[UIBarButtonItem alloc]
5527 style:UIBarButtonItemStylePlain
5529 action:@selector(customButtonClicked)
5535 - (bool) isLoading {
5536 return commercial_ ? [super isLoading] : false;
5539 - (void) reloadData {
5540 [self setPackage:[database_ packageWithName:name_]];
5545 /* Package Table {{{ */
5546 @interface PackageTable : UIView <
5547 UITableViewDataSource,
5550 _transient Database *database_;
5552 NSMutableArray *packages_;
5553 NSMutableArray *sections_;
5555 NSMutableArray *index_;
5556 NSMutableDictionary *indices_;
5557 // XXX: this target_ seems to be delegate_. :(
5558 _transient id target_;
5560 // XXX: why do we even have this delegate_?
5561 _transient id delegate_;
5564 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action;
5566 - (void) setDelegate:(id)delegate;
5568 - (void) reloadData;
5569 - (void) resetCursor;
5571 - (UITableView *) list;
5573 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5575 - (void) deselectWithAnimation:(BOOL)animated;
5579 @implementation PackageTable
5582 [packages_ release];
5583 [sections_ release];
5591 + (BOOL) hasIndexedCollation {
5592 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
5595 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5596 NSInteger count([sections_ count]);
5597 return count == 0 ? 1 : count;
5600 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5601 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
5603 return [[sections_ objectAtIndex:section] name];
5606 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5607 if ([sections_ count] == 0)
5609 return [[sections_ objectAtIndex:section] count];
5612 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5613 @synchronized (database_) {
5614 if ([database_ era] != era_)
5617 Section *section([sections_ objectAtIndex:[path section]]);
5618 NSInteger row([path row]);
5619 Package *package([packages_ objectAtIndex:([section row] + row)]);
5620 return [[package retain] autorelease];
5623 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5624 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5626 cell = [[[PackageCell alloc] init] autorelease];
5627 [cell setPackage:[self packageAtIndexPath:path]];
5631 - (void) deselectWithAnimation:(BOOL)animated {
5632 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5635 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
5636 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
5639 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5640 Package *package([self packageAtIndexPath:path]);
5641 package = [database_ packageWithName:[package id]];
5642 [target_ performSelector:action_ withObject:package];
5646 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5647 // XXX: is 20 the most optimal number here?
5648 return [packages_ count] > 20 ? index_ : nil;
5651 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5652 if ([[self class] hasIndexedCollation]) {
5653 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
5659 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action {
5660 if ((self = [super initWithFrame:frame]) != nil) {
5661 database_ = database;
5666 index_ = [[self class] hasIndexedCollation]
5667 ? [[[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles] retain]
5668 : [[NSMutableArray alloc] initWithCapacity:32];
5669 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5671 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5672 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5674 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
5675 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5676 [list_ setRowHeight:73.0f];
5677 [self addSubview:list_];
5679 [list_ setDataSource:self];
5680 [list_ setDelegate:self];
5684 - (void) setDelegate:(id)delegate {
5685 delegate_ = delegate;
5688 - (bool) hasPackage:(Package *)package {
5692 - (void) reloadData {
5693 era_ = [database_ era];
5694 NSArray *packages = [database_ packages];
5696 [packages_ removeAllObjects];
5697 [sections_ removeAllObjects];
5699 _profile(PackageTable$reloadData$Filter)
5700 for (Package *package in packages)
5701 if ([self hasPackage:package])
5702 [packages_ addObject:package];
5705 [indices_ removeAllObjects];
5707 Section *section = nil;
5709 if ([[self class] hasIndexedCollation]) {
5710 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
5711 NSArray *titles = [collation sectionIndexTitles];
5714 _profile(PackageTable$reloadData$Section)
5715 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5719 _profile(PackageTable$reloadData$Section$Package)
5720 package = [packages_ objectAtIndex:offset];
5721 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
5724 while (secidx < index) {
5727 _profile(PackageTable$reloadData$Section$Allocate)
5728 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
5731 _profile(PackageTable$reloadData$Section$Add)
5732 [sections_ addObject:section];
5736 [section addToCount];
5740 [index_ removeAllObjects];
5742 _profile(PackageTable$reloadData$Section)
5743 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5747 _profile(PackageTable$reloadData$Section$Package)
5748 package = [packages_ objectAtIndex:offset];
5749 index = [package index];
5752 if (section == nil || [section index] != index) {
5753 _profile(PackageTable$reloadData$Section$Allocate)
5754 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5757 [index_ addObject:[section name]];
5758 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5760 _profile(PackageTable$reloadData$Section$Add)
5761 [sections_ addObject:section];
5765 [section addToCount];
5770 _profile(PackageTable$reloadData$List)
5775 - (void) resetCursor {
5776 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5779 - (UITableView *) list {
5783 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5784 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
5789 /* Filtered Package Table {{{ */
5790 @interface FilteredPackageTable : PackageTable {
5796 - (void) setObject:(id)object;
5797 - (void) setObject:(id)object forFilter:(SEL)filter;
5799 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object;
5803 @implementation FilteredPackageTable
5811 - (void) setFilter:(SEL)filter {
5814 /* XXX: this is an unsafe optimization of doomy hell */
5815 Method method(class_getInstanceMethod([Package class], filter));
5816 _assert(method != NULL);
5817 imp_ = method_getImplementation(method);
5818 _assert(imp_ != NULL);
5821 - (void) setObject:(id)object {
5827 object_ = [object retain];
5830 - (void) setObject:(id)object forFilter:(SEL)filter {
5831 [self setFilter:filter];
5832 [self setObject:object];
5835 - (bool) hasPackage:(Package *)package {
5836 _profile(FilteredPackageTable$hasPackage)
5837 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5841 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object {
5842 if ((self = [super initWithFrame:frame database:database target:target action:action]) != nil) {
5843 [self setFilter:filter];
5844 object_ = [object retain];
5852 /* Filtered Package Controller {{{ */
5853 @interface FilteredPackageController : CYViewController {
5854 _transient Database *database_;
5855 FilteredPackageTable *packages_;
5859 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5863 @implementation FilteredPackageController
5866 [packages_ release];
5872 - (void) viewDidAppear:(BOOL)animated {
5873 [super viewDidAppear:animated];
5874 [packages_ deselectWithAnimation:animated];
5877 - (void) didSelectPackage:(Package *)package {
5878 PackageController *view([delegate_ packageController]);
5879 [view setPackage:package];
5880 [view setDelegate:delegate_];
5881 [[self navigationController] pushViewController:view animated:YES];
5884 - (NSString *) title { return title_; }
5886 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5887 if ((self = [super init]) != nil) {
5888 database_ = database;
5889 title_ = [title copy];
5890 [[self navigationItem] setTitle:title_];
5892 packages_ = [[FilteredPackageTable alloc]
5893 initWithFrame:[[self view] bounds]
5896 action:@selector(didSelectPackage:)
5901 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5902 [[self view] addSubview:packages_];
5906 - (void) reloadData {
5907 [packages_ reloadData];
5910 - (void) setDelegate:(id)delegate {
5911 [super setDelegate:delegate];
5912 [packages_ setDelegate:delegate];
5919 /* Source Cell {{{ */
5920 @interface SourceCell : CYTableViewCell <
5925 NSString *description_;
5929 - (void) setSource:(Source *)source;
5933 @implementation SourceCell
5935 - (void) clearSource {
5938 [description_ release];
5947 - (void) setSource:(Source *)source {
5951 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5953 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5954 icon_ = [icon_ retain];
5956 origin_ = [[source name] retain];
5957 label_ = [[source uri] retain];
5958 description_ = [[source description] retain];
5960 [content_ setNeedsDisplay];
5968 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5969 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5970 UIView *content([self contentView]);
5971 CGRect bounds([content bounds]);
5973 content_ = [[ContentView alloc] initWithFrame:bounds];
5974 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5975 [content_ setBackgroundColor:[UIColor whiteColor]];
5976 [content addSubview:content_];
5978 [content_ setDelegate:self];
5979 [content_ setOpaque:YES];
5983 - (void) drawContentRect:(CGRect)rect {
5984 bool highlighted(highlighted_);
5985 float width(rect.size.width);
5988 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5995 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5999 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
6003 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 40) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
6008 /* Source Table {{{ */
6009 @interface SourceController : CYViewController <
6010 UITableViewDataSource,
6013 _transient Database *database_;
6015 NSMutableArray *sources_;
6019 UIProgressHUD *hud_;
6022 //NSURLConnection *installer_;
6023 NSURLConnection *trivial_;
6024 NSURLConnection *trivial_bz2_;
6025 NSURLConnection *trivial_gz_;
6026 //NSURLConnection *automatic_;
6031 - (id) initWithDatabase:(Database *)database;
6033 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
6037 @implementation SourceController
6039 - (void) _releaseConnection:(NSURLConnection *)connection {
6040 if (connection != nil) {
6041 [connection cancel];
6042 //[connection setDelegate:nil];
6043 [connection release];
6055 //[self _releaseConnection:installer_];
6056 [self _releaseConnection:trivial_];
6057 [self _releaseConnection:trivial_gz_];
6058 [self _releaseConnection:trivial_bz2_];
6059 //[self _releaseConnection:automatic_];
6066 - (void) viewDidAppear:(BOOL)animated {
6067 [super viewDidAppear:animated];
6068 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6071 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
6072 return offset_ == 0 ? 1 : 2;
6075 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
6076 switch (section + (offset_ == 0 ? 1 : 0)) {
6077 case 0: return UCLocalize("ENTERED_BY_USER");
6078 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
6084 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6085 int count = [sources_ count];
6087 case 0: return (offset_ == 0 ? count : offset_);
6088 case 1: return count - offset_;
6094 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
6096 switch (indexPath.section) {
6097 case 0: idx = indexPath.row; break;
6098 case 1: idx = indexPath.row + offset_; break;
6102 return [sources_ objectAtIndex:idx];
6105 - (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6106 Source *source = [self sourceAtIndexPath:indexPath];
6107 return [source description] == nil ? 56 : 73;
6110 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6111 static NSString *cellIdentifier = @"SourceCell";
6113 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
6114 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
6115 [cell setSource:[self sourceAtIndexPath:indexPath]];
6120 - (UITableViewCellAccessoryType) tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath {
6121 return UITableViewCellAccessoryDisclosureIndicator;
6124 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6125 Source *source = [self sourceAtIndexPath:indexPath];
6127 FilteredPackageController *packages = [[[FilteredPackageController alloc]
6128 initWithDatabase:database_
6129 title:[source label]
6130 filter:@selector(isVisibleInSource:)
6134 [packages setDelegate:delegate_];
6136 [[self navigationController] pushViewController:packages animated:YES];
6139 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
6140 Source *source = [self sourceAtIndexPath:indexPath];
6141 return [source record] != nil;
6144 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
6145 Source *source = [self sourceAtIndexPath:indexPath];
6146 [Sources_ removeObjectForKey:[source key]];
6147 [delegate_ syncData];
6151 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
6154 @"./", @"Distribution",
6155 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
6157 [delegate_ syncData];
6160 - (NSString *) getWarning {
6161 NSString *href(href_);
6162 NSRange colon([href rangeOfString:@"://"]);
6163 if (colon.location != NSNotFound)
6164 href = [href substringFromIndex:(colon.location + 3)];
6165 href = [href stringByAddingPercentEscapes];
6166 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
6167 href = [href stringByCachingURLWithCurrentCDN];
6169 NSURL *url([NSURL URLWithString:href]);
6171 NSStringEncoding encoding;
6172 NSError *error(nil);
6174 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
6175 return [warning length] == 0 ? nil : warning;
6179 - (void) _endConnection:(NSURLConnection *)connection {
6180 // XXX: the memory management in this method is horribly awkward
6182 NSURLConnection **field = NULL;
6183 if (connection == trivial_)
6185 else if (connection == trivial_bz2_)
6186 field = &trivial_bz2_;
6187 else if (connection == trivial_gz_)
6188 field = &trivial_gz_;
6189 _assert(field != NULL);
6190 [connection release];
6195 trivial_bz2_ == nil &&
6201 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
6204 UIAlertView *alert = [[[UIAlertView alloc]
6205 initWithTitle:UCLocalize("SOURCE_WARNING")
6208 cancelButtonTitle:UCLocalize("CANCEL")
6209 otherButtonTitles:UCLocalize("ADD_ANYWAY"), nil
6212 [alert setContext:@"warning"];
6213 [alert setNumberOfRows:1];
6217 } else if (error_ != nil) {
6218 UIAlertView *alert = [[[UIAlertView alloc]
6219 initWithTitle:UCLocalize("VERIFICATION_ERROR")
6220 message:[error_ localizedDescription]
6222 cancelButtonTitle:UCLocalize("OK")
6223 otherButtonTitles:nil
6226 [alert setContext:@"urlerror"];
6229 UIAlertView *alert = [[[UIAlertView alloc]
6230 initWithTitle:UCLocalize("NOT_REPOSITORY")
6231 message:UCLocalize("NOT_REPOSITORY_EX")
6233 cancelButtonTitle:UCLocalize("OK")
6234 otherButtonTitles:nil
6237 [alert setContext:@"trivial"];
6241 [delegate_ setStatusBarShowsProgress:NO];
6242 [delegate_ removeProgressHUD:hud_];
6252 if (error_ != nil) {
6259 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
6260 switch ([response statusCode]) {
6266 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
6267 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
6269 error_ = [error retain];
6270 [self _endConnection:connection];
6273 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
6274 [self _endConnection:connection];
6277 - (NSString *) title { return UCLocalize("SOURCES"); }
6279 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
6280 NSMutableURLRequest *request = [NSMutableURLRequest
6281 requestWithURL:[NSURL URLWithString:href]
6282 cachePolicy:NSURLRequestUseProtocolCachePolicy
6283 timeoutInterval:120.0
6286 [request setHTTPMethod:method];
6288 if (Machine_ != NULL)
6289 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
6290 if (UniqueID_ != nil)
6291 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6293 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
6295 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
6298 - (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
6299 NSString *context([alert context]);
6301 if ([context isEqualToString:@"source"]) {
6304 NSString *href = [[alert textField] text];
6306 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
6308 if (![href hasSuffix:@"/"])
6309 href_ = [href stringByAppendingString:@"/"];
6312 href_ = [href_ retain];
6314 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
6315 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
6316 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
6317 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
6321 // XXX: this is stupid
6322 hud_ = [[delegate_ addProgressHUD] retain];
6323 [hud_ setText:UCLocalize("VERIFYING_URL")];
6332 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6333 } else if ([context isEqualToString:@"trivial"])
6334 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6335 else if ([context isEqualToString:@"urlerror"])
6336 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6337 else if ([context isEqualToString:@"warning"]) {
6352 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6356 - (id) initWithDatabase:(Database *)database {
6357 if ((self = [super init]) != nil) {
6358 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
6359 [self updateButtonsForEditingStatus:NO animated:NO];
6361 database_ = database;
6362 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
6364 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6365 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6366 [[self view] addSubview:list_];
6368 [list_ setDataSource:self];
6369 [list_ setDelegate:self];
6375 - (void) reloadData {
6377 if (!list.ReadMainList())
6380 [sources_ removeAllObjects];
6381 [sources_ addObjectsFromArray:[database_ sources]];
6383 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
6386 int count([sources_ count]);
6388 for (int i = 0; i != count; i++) {
6389 if ([[sources_ objectAtIndex:i] record] == nil)
6394 [list_ setEditing:NO];
6395 [self updateButtonsForEditingStatus:NO animated:NO];
6399 - (void) addButtonClicked {
6400 /*[book_ pushPage:[[[AddSourceController alloc]
6405 UIAlertView *alert = [[[UIAlertView alloc]
6406 initWithTitle:UCLocalize("ENTER_APT_URL")
6409 cancelButtonTitle:UCLocalize("CANCEL")
6410 otherButtonTitles:UCLocalize("ADD_SOURCE"), nil
6413 [alert setContext:@"source"];
6414 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
6416 [alert setNumberOfRows:1];
6417 [alert addTextFieldWithValue:@"http://" label:@""];
6419 UITextInputTraits *traits = [[alert textField] textInputTraits];
6420 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6421 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6422 [traits setKeyboardType:UIKeyboardTypeURL];
6423 // XXX: UIReturnKeyDone
6424 [traits setReturnKeyType:UIReturnKeyNext];
6429 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
6430 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
6431 initWithTitle:UCLocalize("ADD")
6432 style:UIBarButtonItemStylePlain
6434 action:@selector(addButtonClicked)
6435 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
6437 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6438 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
6439 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
6441 action:@selector(editButtonClicked)
6442 ] autorelease] animated:animated];
6444 if (IsWildcat_ && !editing)
6445 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6446 initWithTitle:UCLocalize("SETTINGS")
6447 style:UIBarButtonItemStylePlain
6449 action:@selector(settingsButtonClicked)
6453 - (void) settingsButtonClicked {
6454 [delegate_ showSettings];
6457 - (void) editButtonClicked {
6458 [list_ setEditing:![list_ isEditing] animated:YES];
6460 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
6466 /* Installed Controller {{{ */
6467 @interface InstalledController : FilteredPackageController {
6471 - (id) initWithDatabase:(Database *)database;
6473 - (void) updateRoleButton;
6474 - (void) queueStatusDidChange;
6478 @implementation InstalledController
6484 - (NSString *) title { return UCLocalize("INSTALLED"); }
6486 - (id) initWithDatabase:(Database *)database {
6487 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
6488 [self updateRoleButton];
6489 [self queueStatusDidChange];
6494 - (void) queueButtonClicked {
6499 - (void) queueStatusDidChange {
6503 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6504 initWithTitle:UCLocalize("QUEUE")
6505 style:UIBarButtonItemStyleDone
6507 action:@selector(queueButtonClicked)
6510 [[self navigationItem] setLeftBarButtonItem:nil];
6516 - (void) reloadData {
6517 [packages_ reloadData];
6520 - (void) updateRoleButton {
6521 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
6522 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6523 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
6524 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
6526 action:@selector(roleButtonClicked)
6530 - (void) roleButtonClicked {
6531 [packages_ setObject:[NSNumber numberWithBool:expert_]];
6532 [packages_ reloadData];
6535 [self updateRoleButton];
6538 - (void) setDelegate:(id)delegate {
6539 [super setDelegate:delegate];
6540 [packages_ setDelegate:delegate];
6546 /* Home Controller {{{ */
6547 @interface HomeController : CYBrowserController {
6552 @implementation HomeController
6554 + (BOOL)shouldHideNavigationBar {
6558 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6559 [super _setMoreHeaders:request];
6562 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6563 if (UniqueID_ != nil)
6564 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6566 [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"];
6569 - (void) aboutButtonClicked {
6570 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6572 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6573 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6574 [alert setCancelButtonIndex:0];
6577 @"Copyright (C) 2008-2010\n"
6578 "Jay Freeman (saurik)\n"
6579 "saurik@saurik.com\n"
6580 "http://www.saurik.com/"
6586 - (void) viewWillAppear:(BOOL)animated {
6587 [super viewWillAppear:animated];
6589 if ([[self class] shouldHideNavigationBar])
6590 [[self navigationController] setNavigationBarHidden:YES animated:animated];
6593 - (void) viewWillDisappear:(BOOL)animated {
6594 [super viewWillDisappear:animated];
6596 if ([[self class] shouldHideNavigationBar])
6597 [[self navigationController] setNavigationBarHidden:NO animated:animated];
6601 if ((self = [super init]) != nil) {
6602 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6603 initWithTitle:UCLocalize("ABOUT")
6604 style:UIBarButtonItemStylePlain
6606 action:@selector(aboutButtonClicked)
6613 /* Manage Controller {{{ */
6614 @interface ManageController : CYBrowserController {
6617 - (void) queueStatusDidChange;
6620 @implementation ManageController
6623 if ((self = [super init]) != nil) {
6624 [[self navigationItem] setTitle:UCLocalize("MANAGE")];
6626 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6627 initWithTitle:UCLocalize("SETTINGS")
6628 style:UIBarButtonItemStylePlain
6630 action:@selector(settingsButtonClicked)
6633 [self queueStatusDidChange];
6637 - (void) settingsButtonClicked {
6638 [delegate_ showSettings];
6642 - (void) queueButtonClicked {
6646 - (void) applyLoadingTitle {
6647 // No "Loading" title.
6650 - (void) applyRightButton {
6655 - (void) queueStatusDidChange {
6657 if (!IsWildcat_ && Queuing_) {
6658 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6659 initWithTitle:UCLocalize("QUEUE")
6660 style:UIBarButtonItemStyleDone
6662 action:@selector(queueButtonClicked)
6665 [[self navigationItem] setRightBarButtonItem:nil];
6670 - (bool) isLoading {
6677 /* Refresh Bar {{{ */
6678 @interface RefreshBar : UINavigationBar {
6679 UIProgressIndicator *indicator_;
6680 UITextLabel *prompt_;
6681 UIProgressBar *progress_;
6682 UINavigationButton *cancel_;
6687 @implementation RefreshBar
6690 [indicator_ release];
6692 [progress_ release];
6697 - (void) positionViews {
6698 CGRect frame = [cancel_ frame];
6699 frame.size = [cancel_ sizeThatFits:frame.size];
6700 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6701 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6702 [cancel_ setFrame:frame];
6704 CGSize prgsize = {75, 100};
6706 [self frame].size.width - prgsize.width - 10,
6707 ([self frame].size.height - prgsize.height) / 2
6709 [progress_ setFrame:prgrect];
6711 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6712 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6713 CGRect indrect = {{indoffset, indoffset}, indsize};
6714 [indicator_ setFrame:indrect];
6716 CGSize prmsize = {215, indsize.height + 4};
6718 indoffset * 2 + indsize.width,
6719 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6721 [prompt_ setFrame:prmrect];
6724 - (void)setFrame:(CGRect)frame {
6725 [super setFrame:frame];
6727 [self positionViews];
6730 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6731 if ((self = [super initWithFrame:frame])) {
6732 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6734 [self setBarStyle:UIBarStyleBlack];
6736 UIBarStyle barstyle([self _barStyle:NO]);
6737 bool ugly(barstyle == UIBarStyleDefault);
6739 UIProgressIndicatorStyle style = ugly ?
6740 UIProgressIndicatorStyleMediumBrown :
6741 UIProgressIndicatorStyleMediumWhite;
6743 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6744 [indicator_ setStyle:style];
6745 [indicator_ startAnimation];
6746 [self addSubview:indicator_];
6748 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6749 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6750 [prompt_ setBackgroundColor:[UIColor clearColor]];
6751 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6752 [self addSubview:prompt_];
6754 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6755 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6756 [progress_ setStyle:0];
6757 [self addSubview:progress_];
6759 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6760 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6761 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6762 [cancel_ setBarStyle:barstyle];
6764 [self positionViews];
6769 [cancel_ removeFromSuperview];
6773 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6774 [progress_ setProgress:0];
6775 [self addSubview:cancel_];
6779 [cancel_ removeFromSuperview];
6782 - (void) setPrompt:(NSString *)prompt {
6783 [prompt_ setText:prompt];
6786 - (void) setProgress:(float)progress {
6787 [progress_ setProgress:progress];
6793 @class CYNavigationController;
6795 /* Cydia Tab Bar Controller {{{ */
6796 @interface CYTabBarController : UITabBarController <
6799 _transient Database *database_;
6800 RefreshBar *refreshbar_;
6804 // XXX: ok, "updatedelegate_"?...
6805 _transient NSObject<CydiaDelegate> *updatedelegate_;
6810 - (void) dropBar:(BOOL)animated;
6811 - (void) beginUpdate;
6812 - (void) raiseBar:(BOOL)animated;
6817 @implementation CYTabBarController
6819 /* XXX: some logic should probably go here related to
6820 freeing the view controllers on tab change */
6822 - (void) reloadData {
6823 size_t count([[self viewControllers] count]);
6824 for (size_t i(0); i != count; ++i) {
6825 CYNavigationController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6830 - (id) initWithDatabase:(Database *)database {
6831 if ((self = [super init]) != nil) {
6832 database_ = database;
6834 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6835 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6837 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
6841 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
6842 return IsWildcat_ || orientation == UIInterfaceOrientationPortrait;
6845 - (void) setUpdate:(NSDate *)date {
6849 - (void) beginUpdate {
6850 [refreshbar_ start];
6853 [updatedelegate_ retainNetworkActivityIndicator];
6857 detachNewThreadSelector:@selector(performUpdate)
6863 - (void) performUpdate { _pooled
6865 status.setDelegate(self);
6866 [database_ updateWithStatus:status];
6869 performSelectorOnMainThread:@selector(completeUpdate)
6875 - (void) stopUpdateWithSelector:(SEL)selector {
6877 [updatedelegate_ releaseNetworkActivityIndicator];
6879 [self raiseBar:YES];
6882 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6885 - (void) completeUpdate {
6888 [self stopUpdateWithSelector:@selector(reloadData)];
6891 - (void) cancelUpdate {
6892 [self stopUpdateWithSelector:@selector(updateData)];
6895 - (void) cancelPressed {
6896 [self cancelUpdate];
6903 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
6904 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
6907 - (void) startProgress {
6910 - (void) setProgressTitle:(NSString *)title {
6912 performSelectorOnMainThread:@selector(_setProgressTitle:)
6918 - (bool) isCancelling:(size_t)received {
6922 - (void) setProgressPercent:(float)percent {
6924 performSelectorOnMainThread:@selector(_setProgressPercent:)
6925 withObject:[NSNumber numberWithFloat:percent]
6930 - (void) addProgressOutput:(NSString *)output {
6932 performSelectorOnMainThread:@selector(_addProgressOutput:)
6938 - (void) _setProgressTitle:(NSString *)title {
6939 [refreshbar_ setPrompt:title];
6942 - (void) _setProgressPercent:(NSNumber *)percent {
6943 [refreshbar_ setProgress:[percent floatValue]];
6946 - (void) _addProgressOutput:(NSString *)output {
6949 - (void) setUpdateDelegate:(id)delegate {
6950 updatedelegate_ = delegate;
6953 - (CGFloat) statusBarHeight {
6954 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
6955 return [[UIApplication sharedApplication] statusBarFrame].size.height;
6957 return [[UIApplication sharedApplication] statusBarFrame].size.width;
6961 - (UIView *) transitionView {
6962 if ([self respondsToSelector:@selector(_transitionView)])
6963 return [self _transitionView];
6965 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6968 - (void) dropBar:(BOOL)animated {
6973 UIView *transition([self transitionView]);
6974 [[self view] addSubview:refreshbar_];
6976 CGRect barframe([refreshbar_ frame]);
6978 if (false) // XXX: _UIApplicationLinkedOnOrAfter(4)
6979 barframe.origin.y = [self statusBarHeight];
6981 barframe.origin.y = 0;
6983 [refreshbar_ setFrame:barframe];
6986 [UIView beginAnimations:nil context:NULL];
6988 CGRect viewframe = [transition frame];
6989 viewframe.origin.y += barframe.size.height;
6990 viewframe.size.height -= barframe.size.height;
6991 [transition setFrame:viewframe];
6994 [UIView commitAnimations];
6996 // Ensure bar has the proper width for our view, it might have changed
6997 barframe.size.width = viewframe.size.width;
6998 [refreshbar_ setFrame:barframe];
7000 // XXX: fix Apple's layout bug
7001 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7004 - (void) raiseBar:(BOOL)animated {
7009 UIView *transition([self transitionView]);
7010 [refreshbar_ removeFromSuperview];
7012 CGRect barframe([refreshbar_ frame]);
7015 [UIView beginAnimations:nil context:NULL];
7017 CGRect viewframe = [transition frame];
7018 viewframe.origin.y -= barframe.size.height;
7019 viewframe.size.height += barframe.size.height;
7020 [transition setFrame:viewframe];
7023 [UIView commitAnimations];
7025 // XXX: fix Apple's layout bug
7026 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7030 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7031 // XXX: fix Apple's layout bug
7032 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7036 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7037 bool dropped(dropped_);
7042 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
7047 // XXX: fix Apple's layout bug
7048 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7051 - (void) statusBarFrameChanged:(NSNotification *)notification {
7059 [refreshbar_ release];
7060 [[NSNotificationCenter defaultCenter] removeObserver:self];
7067 /* Cydia Navigation Controller {{{ */
7068 @interface CYNavigationController : UINavigationController {
7069 _transient Database *database_;
7070 _transient id<UINavigationControllerDelegate> delegate_;
7073 - (id) initWithDatabase:(Database *)database;
7074 - (void) reloadData;
7079 @implementation CYNavigationController
7081 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7082 // Inherit autorotation settings for modal parents.
7083 if ([self parentViewController] && [[self parentViewController] modalViewController] == self) {
7084 return [[self parentViewController] shouldAutorotateToInterfaceOrientation:orientation];
7085 } else if ([self parentViewController]) {
7086 return [[self parentViewController] shouldAutorotateToInterfaceOrientation:orientation];
7088 return [super shouldAutorotateToInterfaceOrientation:orientation];
7096 - (void) reloadData {
7097 size_t count([[self viewControllers] count]);
7098 for (size_t i(0); i != count; ++i) {
7099 CYViewController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
7104 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
7105 delegate_ = delegate;
7108 - (id) initWithDatabase:(Database *)database {
7109 if ((self = [super init]) != nil) {
7110 database_ = database;
7116 /* Cydia:// Protocol {{{ */
7117 @interface CydiaURLProtocol : NSURLProtocol {
7122 @implementation CydiaURLProtocol
7124 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7125 NSURL *url([request URL]);
7128 NSString *scheme([[url scheme] lowercaseString]);
7129 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
7134 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7138 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7139 id<NSURLProtocolClient> client([self client]);
7141 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7143 NSData *data(UIImagePNGRepresentation(icon));
7145 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7146 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7147 [client URLProtocol:self didLoadData:data];
7148 [client URLProtocolDidFinishLoading:self];
7152 - (void) startLoading {
7153 id<NSURLProtocolClient> client([self client]);
7154 NSURLRequest *request([self request]);
7156 NSURL *url([request URL]);
7157 NSString *href([url absoluteString]);
7159 NSString *path([href substringFromIndex:8]);
7160 NSRange slash([path rangeOfString:@"/"]);
7163 if (slash.location == NSNotFound) {
7167 command = [path substringToIndex:slash.location];
7168 path = [path substringFromIndex:(slash.location + 1)];
7171 Database *database([Database sharedInstance]);
7173 if ([command isEqualToString:@"package-icon"]) {
7176 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7177 Package *package([database packageWithName:path]);
7180 UIImage *icon([package icon]);
7181 [self _returnPNGWithImage:icon forRequest:request];
7182 } else if ([command isEqualToString:@"source-icon"]) {
7185 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7186 NSString *source(Simplify(path));
7187 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
7189 icon = [UIImage applicationImageNamed:@"unknown.png"];
7190 [self _returnPNGWithImage:icon forRequest:request];
7191 } else if ([command isEqualToString:@"uikit-image"]) {
7194 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7195 UIImage *icon(_UIImageWithName(path));
7196 [self _returnPNGWithImage:icon forRequest:request];
7197 } else if ([command isEqualToString:@"section-icon"]) {
7200 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7201 NSString *section(Simplify(path));
7202 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
7204 icon = [UIImage applicationImageNamed:@"unknown.png"];
7205 [self _returnPNGWithImage:icon forRequest:request];
7207 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7211 - (void) stopLoading {
7217 /* Sections Controller {{{ */
7218 @interface CYSectionsController : CYViewController <
7219 UITableViewDataSource,
7222 _transient Database *database_;
7223 NSMutableArray *sections_;
7224 NSMutableArray *filtered_;
7230 - (id) initWithDatabase:(Database *)database;
7231 - (void) reloadData;
7234 - (void) editButtonClicked;
7238 @implementation CYSectionsController
7241 [list_ setDataSource:nil];
7242 [list_ setDelegate:nil];
7244 [sections_ release];
7245 [filtered_ release];
7247 [accessory_ release];
7251 - (void) setEditing:(BOOL)editing {
7252 if ((editing_ = editing))
7255 [delegate_ updateData];
7257 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7258 [[[self navigationItem] rightBarButtonItem] setTitle:[sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT")];
7259 [[[self navigationItem] rightBarButtonItem] setStyle:editing_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain];
7262 - (void) viewDidAppear:(BOOL)animated {
7263 [super viewDidAppear:animated];
7264 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7267 - (void) viewWillDisappear:(BOOL)animated {
7268 [super viewWillDisappear:animated];
7269 if (editing_) [self setEditing:NO];
7272 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7273 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
7277 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7278 return editing_ ? [sections_ count] : [filtered_ count] + 1;
7281 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7285 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7286 static NSString *reuseIdentifier = @"SectionCell";
7288 SectionCell *cell = (SectionCell *) [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7290 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7292 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
7297 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7301 Section *section = [self sectionAtIndexPath:indexPath];
7302 NSString *name = [section name];
7305 if ([indexPath row] == 0) {
7308 title = UCLocalize("ALL_PACKAGES");
7311 name = [NSString stringWithString:name];
7312 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7315 title = UCLocalize("NO_SECTION");
7319 FilteredPackageController *table = [[[FilteredPackageController alloc]
7320 initWithDatabase:database_
7322 filter:@selector(isVisibleInSection:)
7326 [table setDelegate:delegate_];
7328 [[self navigationController] pushViewController:table animated:YES];
7331 - (NSString *) title { return UCLocalize("SECTIONS"); }
7333 - (id) initWithDatabase:(Database *)database {
7334 if ((self = [super init]) != nil) {
7335 database_ = database;
7337 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7339 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7340 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
7342 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
7343 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7344 [list_ setRowHeight:45.0f];
7345 [[self view] addSubview:list_];
7347 [list_ setDataSource:self];
7348 [list_ setDelegate:self];
7354 - (void) reloadData {
7355 NSArray *packages = [database_ packages];
7357 [sections_ removeAllObjects];
7358 [filtered_ removeAllObjects];
7360 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7363 for (Package *package in packages) {
7364 NSString *name([package section]);
7365 NSString *key(name == nil ? @"" : name);
7369 _profile(SectionsView$reloadData$Section)
7370 section = [sections objectForKey:key];
7371 if (section == nil) {
7372 _profile(SectionsView$reloadData$Section$Allocate)
7373 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
7374 [sections setObject:section forKey:key];
7379 [section addToCount];
7381 _profile(SectionsView$reloadData$Filter)
7382 if (![package valid] || ![package visible])
7390 [sections_ addObjectsFromArray:[sections allValues]];
7392 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7394 for (Section *section in sections_) {
7395 size_t count([section row]);
7399 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7400 [section setCount:count];
7401 [filtered_ addObject:section];
7404 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7405 initWithTitle:([sections_ count] == 0 ? nil : UCLocalize("EDIT"))
7406 style:UIBarButtonItemStylePlain
7408 action:@selector(editButtonClicked)
7409 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7415 - (void) resetView {
7417 [self editButtonClicked];
7420 - (void)editButtonClicked {
7421 [self setEditing:!editing_];
7424 - (UIView *) accessoryView {
7430 /* Changes Controller {{{ */
7431 @interface ChangesController : CYViewController <
7432 UITableViewDataSource,
7435 _transient Database *database_;
7437 CFMutableArrayRef packages_;
7438 NSMutableArray *sections_;
7441 BOOL hasSentFirstLoad_;
7444 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
7445 - (void) reloadData;
7449 @implementation ChangesController
7452 [list_ setDelegate:nil];
7453 [list_ setDataSource:nil];
7455 CFRelease(packages_);
7457 [sections_ release];
7462 - (void) viewDidAppear:(BOOL)animated {
7463 [super viewDidAppear:animated];
7464 if (!hasSentFirstLoad_) {
7465 hasSentFirstLoad_ = YES;
7466 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
7468 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7472 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7473 NSInteger count([sections_ count]);
7474 return count == 0 ? 1 : count;
7477 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7478 if ([sections_ count] == 0)
7480 return [[sections_ objectAtIndex:section] name];
7483 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7484 if ([sections_ count] == 0)
7486 return [[sections_ objectAtIndex:section] count];
7489 - (Package *) packageAtIndex:(NSUInteger)index {
7490 return (Package *) CFArrayGetValueAtIndex(packages_, index);
7493 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7494 @synchronized (database_) {
7495 if ([database_ era] != era_)
7498 NSUInteger sectionIndex([path section]);
7499 if (sectionIndex >= [sections_ count])
7501 Section *section([sections_ objectAtIndex:sectionIndex]);
7502 NSInteger row([path row]);
7503 return [[[self packageAtIndex:([section row] + row)] retain] autorelease];
7506 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7507 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7509 cell = [[[PackageCell alloc] init] autorelease];
7510 [cell setPackage:[self packageAtIndexPath:path]];
7514 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
7515 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
7518 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7519 Package *package([self packageAtIndexPath:path]);
7520 PackageController *view([delegate_ packageController]);
7521 [view setDelegate:delegate_];
7522 [view setPackage:package];
7523 [[self navigationController] pushViewController:view animated:YES];
7527 - (void) refreshButtonClicked {
7528 [delegate_ beginUpdate];
7529 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7532 - (void) upgradeButtonClicked {
7533 [delegate_ distUpgrade];
7536 - (NSString *) title { return UCLocalize("CHANGES"); }
7538 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7539 if ((self = [super init]) != nil) {
7540 database_ = database;
7541 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7543 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7545 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7547 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7548 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7549 [list_ setRowHeight:73.0f];
7550 [[self view] addSubview:list_];
7552 [list_ setDataSource:self];
7553 [list_ setDelegate:self];
7555 delegate_ = delegate;
7559 - (void) _reloadPackages:(NSArray *)packages {
7560 CFRelease(packages_);
7561 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, [packages count], NULL);
7564 _profile(ChangesController$_reloadPackages$Filter)
7565 for (Package *package in packages)
7566 if ([package upgradableAndEssential:YES] || [package visible])
7567 CFArrayAppendValue(packages_, package);
7570 _profile(ChangesController$_reloadPackages$radixSort)
7571 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7576 - (void) reloadData {
7577 @synchronized (database_) {
7578 era_ = [database_ era];
7579 NSArray *packages = [database_ packages];
7581 [sections_ removeAllObjects];
7584 UIProgressHUD *hud([delegate_ addProgressHUD]);
7585 [hud setText:UCLocalize("LOADING")];
7586 //NSLog(@"HUD:%@::%@", delegate_, hud);
7587 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7588 [delegate_ removeProgressHUD:hud];
7590 [self _reloadPackages:packages];
7593 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7594 Section *ignored = nil;
7595 Section *section = nil;
7599 bool unseens = false;
7601 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7603 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7604 Package *package = [self packageAtIndex:offset];
7606 BOOL uae = [package upgradableAndEssential:YES];
7610 time_t seen([package seen]);
7612 if (section == nil || last != seen) {
7616 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7619 _profile(ChangesController$reloadData$Allocate)
7620 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7621 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7622 [sections_ addObject:section];
7626 [section addToCount];
7627 } else if ([package ignored]) {
7628 if (ignored == nil) {
7629 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7631 [ignored addToCount];
7634 [upgradable addToCount];
7639 CFRelease(formatter);
7642 Section *last = [sections_ lastObject];
7643 size_t count = [last count];
7644 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7645 [sections_ removeLastObject];
7648 if ([ignored count] != 0)
7649 [sections_ insertObject:ignored atIndex:0];
7651 [sections_ insertObject:upgradable atIndex:0];
7656 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7657 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7658 style:UIBarButtonItemStylePlain
7660 action:@selector(upgradeButtonClicked)
7663 if (![delegate_ updating])
7664 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7665 initWithTitle:UCLocalize("REFRESH")
7666 style:UIBarButtonItemStylePlain
7668 action:@selector(refreshButtonClicked)
7676 /* Search Controller {{{ */
7677 @interface SearchController : FilteredPackageController <
7680 UISearchBar *search_;
7683 - (id) initWithDatabase:(Database *)database;
7684 - (void) reloadData;
7688 @implementation SearchController
7695 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7696 [packages_ setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7697 [search_ resignFirstResponder];
7701 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7702 [packages_ setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7706 - (NSString *) title { return nil; }
7708 - (id) initWithDatabase:(Database *)database {
7709 return [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil];
7712 - (void)viewDidAppear:(BOOL)animated {
7713 [super viewDidAppear:animated];
7715 search_ = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7716 [search_ layoutSubviews];
7717 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7719 UITextField *textField;
7720 if ([search_ respondsToSelector:@selector(searchField)])
7721 textField = [search_ searchField];
7723 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7725 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7726 [search_ setDelegate:self];
7727 [textField setEnablesReturnKeyAutomatically:NO];
7728 [[self navigationItem] setTitleView:textField];
7732 - (void) _reloadData {
7735 - (void) reloadData {
7736 _profile(SearchController$reloadData)
7737 [packages_ reloadData];
7740 [packages_ resetCursor];
7743 - (void) didSelectPackage:(Package *)package {
7744 [search_ resignFirstResponder];
7745 [super didSelectPackage:package];
7750 /* Settings Controller {{{ */
7751 @interface CYPackageSettingsController : CYViewController <
7752 UITableViewDataSource,
7755 _transient Database *database_;
7758 UITableView *table_;
7759 UISwitch *subscribedSwitch_;
7760 UISwitch *ignoredSwitch_;
7761 UITableViewCell *subscribedCell_;
7762 UITableViewCell *ignoredCell_;
7765 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7769 @implementation CYPackageSettingsController
7773 if (package_ != nil)
7776 [subscribedSwitch_ release];
7777 [ignoredSwitch_ release];
7778 [subscribedCell_ release];
7779 [ignoredCell_ release];
7784 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7785 if (package_ == nil)
7791 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7792 if (package_ == nil)
7798 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7799 return UCLocalize("SHOW_ALL_CHANGES_EX");
7802 - (void) onSubscribed:(id)control {
7803 bool value([control isOn]);
7804 if (package_ == nil)
7806 if ([package_ setSubscribed:value])
7807 [delegate_ updateData];
7810 - (void) onIgnored:(id)control {
7811 // TODO: set Held state - possibly call out to dpkg, etc.
7814 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7815 if (package_ == nil)
7818 switch ([indexPath row]) {
7819 case 0: return subscribedCell_;
7820 case 1: return ignoredCell_;
7828 - (NSString *) title { return UCLocalize("SETTINGS"); }
7830 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7831 if ((self = [super init])) {
7832 database_ = database;
7833 name_ = [package retain];
7835 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7837 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7838 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7839 [[self view] addSubview:table_];
7841 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7842 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7843 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7845 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7846 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7847 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7849 subscribedCell_ = [[UITableViewCell alloc] init];
7850 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7851 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7852 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7854 ignoredCell_ = [[UITableViewCell alloc] init];
7855 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7856 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7857 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7859 [table_ setDataSource:self];
7860 [table_ setDelegate:self];
7865 - (void) reloadData {
7866 if (package_ != nil)
7867 [package_ autorelease];
7868 package_ = [database_ packageWithName:name_];
7869 if (package_ != nil) {
7871 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7872 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7875 [table_ reloadData];
7880 /* Signature Controller {{{ */
7881 @interface SignatureController : CYBrowserController {
7882 _transient Database *database_;
7886 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7890 @implementation SignatureController
7897 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7899 [super webView:view didClearWindowObject:window forFrame:frame];
7902 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7903 if ((self = [super init]) != nil) {
7904 database_ = database;
7905 package_ = [package retain];
7910 - (void) reloadData {
7911 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7917 /* Role Controller {{{ */
7918 @interface CYSettingsController : CYViewController <
7919 UITableViewDataSource,
7922 _transient Database *database_;
7923 // XXX: ok, "roledelegate_"?...
7924 _transient id roledelegate_;
7925 UITableView *table_;
7926 UISegmentedControl *segment_;
7930 - (void) showDoneButton;
7931 - (void) resizeSegmentedControl;
7935 @implementation CYSettingsController
7939 [container_ release];
7944 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7945 if ((self = [super init])) {
7946 database_ = database;
7947 roledelegate_ = delegate;
7949 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
7951 NSArray *items = [NSArray arrayWithObjects:
7953 UCLocalize("HACKER"),
7954 UCLocalize("DEVELOPER"),
7956 segment_ = [[UISegmentedControl alloc] initWithItems:items];
7957 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
7958 [container_ addSubview:segment_];
7961 if ([Role_ isEqualToString:@"User"]) index = 0;
7962 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
7963 if ([Role_ isEqualToString:@"Developer"]) index = 2;
7965 [segment_ setSelectedSegmentIndex:index];
7966 [self showDoneButton];
7969 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
7970 [self resizeSegmentedControl];
7972 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7973 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7974 [table_ setDelegate:self];
7975 [table_ setDataSource:self];
7976 [[self view] addSubview:table_];
7977 [table_ reloadData];
7981 - (void) resizeSegmentedControl {
7982 CGFloat width = [[self view] frame].size.width;
7983 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
7986 - (void) viewWillAppear:(BOOL)animated {
7987 [super viewWillAppear:animated];
7989 [self resizeSegmentedControl];
7992 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7993 [self resizeSegmentedControl];
7996 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7997 [self resizeSegmentedControl];
8001 NSString *role(nil);
8003 switch ([segment_ selectedSegmentIndex]) {
8004 case 0: role = @"User"; break;
8005 case 1: role = @"Hacker"; break;
8006 case 2: role = @"Developer"; break;
8011 if (![role isEqualToString:Role_]) {
8012 bool rolling(Role_ == nil);
8015 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8019 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8023 [roledelegate_ loadData];
8025 [roledelegate_ updateData];
8029 - (void) segmentChanged:(UISegmentedControl *)control {
8030 [self showDoneButton];
8033 - (void) saveAndClose {
8036 [[self navigationItem] setRightBarButtonItem:nil];
8037 [[self navigationController] dismissModalViewControllerAnimated:YES];
8040 - (void) doneButtonClicked {
8041 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8042 [spinner startAnimating];
8043 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8044 [[self navigationItem] setRightBarButtonItem:spinItem];
8046 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8049 - (void) showDoneButton {
8050 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8051 initWithTitle:UCLocalize("DONE")
8052 style:UIBarButtonItemStyleDone
8054 action:@selector(doneButtonClicked)
8055 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8058 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8059 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8063 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8067 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8068 return nil; // This method is required by the protocol.
8071 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8073 return UCLocalize("ROLE_EX");
8075 return [NSString stringWithFormat:
8076 @"%@: %@\n%@: %@\n%@: %@",
8077 UCLocalize("USER"), UCLocalize("USER_EX"),
8078 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8079 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8084 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8085 return section == 3 ? 44.0f : 0;
8088 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8089 return section == 3 ? container_ : nil;
8094 /* Stash Controller {{{ */
8095 @interface CYStashController : CYViewController {
8096 // XXX: just delete these things
8097 _transient UIActivityIndicatorView *spinner_;
8098 _transient UILabel *status_;
8099 _transient UILabel *caption_;
8103 @implementation CYStashController
8105 if ((self = [super init])) {
8106 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8108 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8109 CGRect spinrect = [spinner_ frame];
8110 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8111 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8112 [spinner_ setFrame:spinrect];
8113 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8114 [[self view] addSubview:spinner_];
8115 [spinner_ startAnimating];
8118 captrect.size.width = [[self view] frame].size.width;
8119 captrect.size.height = 40.0f;
8120 captrect.origin.x = 0;
8121 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8122 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8123 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8124 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8125 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8126 [caption_ setTextColor:[UIColor whiteColor]];
8127 [caption_ setBackgroundColor:[UIColor clearColor]];
8128 [caption_ setShadowColor:[UIColor blackColor]];
8129 [caption_ setTextAlignment:UITextAlignmentCenter];
8130 [[self view] addSubview:caption_];
8133 statusrect.size.width = [[self view] frame].size.width;
8134 statusrect.size.height = 30.0f;
8135 statusrect.origin.x = 0;
8136 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8137 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8138 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8139 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8140 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8141 [status_ setTextColor:[UIColor whiteColor]];
8142 [status_ setBackgroundColor:[UIColor clearColor]];
8143 [status_ setShadowColor:[UIColor blackColor]];
8144 [status_ setTextAlignment:UITextAlignmentCenter];
8145 [[self view] addSubview:status_];
8149 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
8150 return IsWildcat_ || orientation == UIInterfaceOrientationPortrait;
8165 @interface Cydia : UIApplication <
8166 ConfirmationControllerDelegate,
8167 ProgressControllerDelegate,
8169 UINavigationControllerDelegate,
8170 UITabBarControllerDelegate
8172 // XXX: evaluate all fields for _transient
8175 CYTabBarController *tabbar_;
8177 NSMutableArray *essential_;
8178 NSMutableArray *broken_;
8180 Database *database_;
8188 CYSectionsController *sections_;
8189 ChangesController *changes_;
8190 ManageController *manage_;
8191 SearchController *search_;
8192 SourceController *sources_;
8193 InstalledController *installed_;
8196 CYStashController *stash_;
8201 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class;
8202 - (void) setPage:(CYViewController *)page;
8205 // XXX: I hate prototypes
8206 - (id) queueBadgeController;
8210 static _finline void _setHomePage(Cydia *self) {
8211 [self setPage:[self _pageForURL:[NSURL URLWithString:CydiaURL(@"")] withClass:[HomeController class]]];
8214 @implementation Cydia
8216 - (void) beginUpdate {
8217 [tabbar_ beginUpdate];
8221 return [tabbar_ updating];
8225 if ([broken_ count] != 0) {
8226 int count = [broken_ count];
8228 UIAlertView *alert = [[[UIAlertView alloc]
8229 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8230 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8232 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8233 otherButtonTitles:UCLocalize("TEMPORARY_IGNORE"), nil
8236 [alert setContext:@"fixhalf"];
8238 } else if (!Ignored_ && [essential_ count] != 0) {
8239 int count = [essential_ count];
8241 UIAlertView *alert = [[[UIAlertView alloc]
8242 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8243 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8245 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8246 otherButtonTitles:UCLocalize("UPGRADE_ESSENTIAL"), UCLocalize("COMPLETE_UPGRADE"), nil
8249 [alert setContext:@"upgrade"];
8254 - (void) _saveConfig {
8260 NSString *error(nil);
8262 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8264 NSError *error(nil);
8265 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8266 NSLog(@"failure to save metadata data: %@", error);
8271 NSLog(@"failure to serialize metadata: %@", error);
8276 - (void) _updateData {
8279 NSMutableSet *tabs([[[NSMutableSet alloc] initWithCapacity:10] autorelease]);
8281 [tabs addObject:[tabbar_ selectedViewController]];
8283 if (sections_ != nil)
8284 [tabs addObject:sections_];
8285 if (changes_ != nil)
8286 [tabs addObject:changes_];
8288 [tabs addObject:manage_];
8290 [tabs addObject:search_];
8291 if (sources_ != nil)
8292 [tabs addObject:sources_];
8293 if (installed_ != nil)
8294 [tabs addObject:installed_];
8296 for (CYNavigationController *tab in tabs)
8299 [queueDelegate_ queueStatusDidChange];
8300 [[[self queueBadgeController] tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8303 - (int)indexOfTabWithTag:(int)tag {
8305 for (UINavigationController *controller in [tabbar_ viewControllers]) {
8306 if ([[controller tabBarItem] tag] == tag)
8314 - (void) _refreshIfPossible {
8315 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8317 bool recently = false;
8318 NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
8319 if (update != nil) {
8320 NSTimeInterval interval([update timeIntervalSinceNow]);
8321 if (interval <= 0 && interval > -(15*60))
8325 // Don't automatic refresh if:
8326 // - We already refreshed recently.
8327 // - We already auto-refreshed this launch.
8328 // - Auto-refresh is disabled.
8329 if (recently || loaded_ || ManualRefresh) {
8330 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8332 // If we are cancelling due to ManualRefresh or a recent refresh
8333 // we need to make sure it knows it's already loaded.
8337 // We are going to load, so remember that.
8341 SCNetworkReachabilityFlags flags; {
8342 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8343 SCNetworkReachabilityGetFlags(reachability, &flags);
8344 CFRelease(reachability);
8347 // XXX: this elaborate mess is what Apple is using to determine this? :(
8348 // XXX: do we care if the user has to intervene? maybe that's ok?
8350 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8351 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8352 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8353 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8354 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8355 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8359 // If we can reach the server, auto-refresh!
8361 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8366 - (void) refreshIfPossible {
8367 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
8370 - (void) _reloadData {
8371 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8372 [hud setText:UCLocalize("RELOADING_DATA")];
8374 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
8377 [self removeProgressHUD:hud];
8381 [essential_ removeAllObjects];
8382 [broken_ removeAllObjects];
8384 NSArray *packages([database_ packages]);
8385 for (Package *package in packages) {
8387 [broken_ addObject:package];
8388 if ([package upgradableAndEssential:NO]) {
8389 if ([package essential])
8390 [essential_ addObject:package];
8395 NSLog(@"changes:#%u", changes);
8397 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem];
8400 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8401 [changesItem setBadgeValue:badge];
8402 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8403 [self setApplicationIconBadgeNumber:changes];
8406 [changesItem setBadgeValue:nil];
8407 [changesItem setAnimatedBadge:NO];
8408 [self setApplicationIconBadgeNumber:0];
8413 [self refreshIfPossible];
8416 - (void) updateData {
8425 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8426 _assert(file != NULL);
8428 for (NSString *key in [Sources_ allKeys]) {
8429 NSDictionary *source([Sources_ objectForKey:key]);
8431 fprintf(file, "%s %s %s\n",
8432 [[source objectForKey:@"Type"] UTF8String],
8433 [[source objectForKey:@"URI"] UTF8String],
8434 [[source objectForKey:@"Distribution"] UTF8String]
8442 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8443 CYNavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8445 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8446 [tabbar_ presentModalViewController:navigation animated:YES];
8449 detachNewThreadSelector:@selector(update_)
8452 title:UCLocalize("UPDATING_SOURCES")
8456 - (void) reloadData {
8457 @synchronized (self) {
8463 pkgProblemResolver *resolver = [database_ resolver];
8465 resolver->InstallProtect();
8466 if (!resolver->Resolve(true))
8471 if (![database_ prepare])
8474 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8475 [page setDelegate:self];
8476 CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]);
8477 [confirm_ setDelegate:self];
8480 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8481 [tabbar_ presentModalViewController:confirm_ animated:YES];
8487 @synchronized (self) {
8492 - (void) clearPackage:(Package *)package {
8493 @synchronized (self) {
8500 - (void) installPackages:(NSArray *)packages {
8501 @synchronized (self) {
8502 for (Package *package in packages)
8509 - (void) installPackage:(Package *)package {
8510 @synchronized (self) {
8517 - (void) removePackage:(Package *)package {
8518 @synchronized (self) {
8525 - (void) distUpgrade {
8526 @synchronized (self) {
8527 if (![database_ upgrade])
8534 @synchronized (self) {
8539 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8542 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8544 if (navigation != nil) {
8545 [navigation pushViewController:progress animated:YES];
8547 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8549 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8550 [tabbar_ presentModalViewController:navigation animated:YES];
8554 detachNewThreadSelector:@selector(perform)
8557 title:UCLocalize("RUNNING")
8563 - (void) progressControllerIsComplete:(ProgressController *)progress {
8568 - (void) setPage:(CYViewController *)page {
8569 [page setDelegate:self];
8571 CYNavigationController *navController = (CYNavigationController *) [tabbar_ selectedViewController];
8572 [navController setViewControllers:[NSArray arrayWithObject:page]];
8573 for (CYNavigationController *page in [tabbar_ viewControllers])
8574 if (page != navController)
8575 [page setViewControllers:nil];
8578 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class {
8579 CYBrowserController *browser = [[[_class alloc] init] autorelease];
8580 [browser loadURL:url];
8584 - (CYSectionsController *) sectionsController {
8585 if (sections_ == nil)
8586 sections_ = [[CYSectionsController alloc] initWithDatabase:database_];
8590 - (ChangesController *) changesController {
8591 if (changes_ == nil)
8592 changes_ = [[ChangesController alloc] initWithDatabase:database_ delegate:self];
8596 - (ManageController *) manageController {
8597 if (manage_ == nil) {
8598 manage_ = (ManageController *) [[self
8599 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
8600 withClass:[ManageController class]
8603 queueDelegate_ = manage_;
8608 - (SearchController *) searchController {
8610 search_ = [[SearchController alloc] initWithDatabase:database_];
8614 - (SourceController *) sourcesController {
8615 if (sources_ == nil)
8616 sources_ = [[SourceController alloc] initWithDatabase:database_];
8620 - (InstalledController *) installedController {
8621 if (installed_ == nil) {
8622 installed_ = [[InstalledController alloc] initWithDatabase:database_];
8624 queueDelegate_ = installed_;
8629 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
8630 int tag = [[viewController tabBarItem] tag];
8632 [(CYNavigationController *)[tabbar_ selectedViewController] popToRootViewControllerAnimated:YES];
8634 } else if (tag_ == 1) {
8635 [[self sectionsController] resetView];
8639 case kCydiaTag: _setHomePage(self); break;
8641 case kSectionsTag: [self setPage:[self sectionsController]]; break;
8642 case kChangesTag: [self setPage:[self changesController]]; break;
8643 case kManageTag: [self setPage:[self manageController]]; break;
8644 case kInstalledTag: [self setPage:[self installedController]]; break;
8645 case kSourcesTag: [self setPage:[self sourcesController]]; break;
8646 case kSearchTag: [self setPage:[self searchController]]; break;
8654 - (void) showSettings {
8655 CYSettingsController *role = [[[CYSettingsController alloc] initWithDatabase:database_ delegate:self] autorelease];
8656 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
8658 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
8659 [tabbar_ presentModalViewController:nav animated:YES];
8662 - (void) retainNetworkActivityIndicator {
8663 if (activity_++ == 0)
8664 [self setNetworkActivityIndicatorVisible:YES];
8667 - (void) releaseNetworkActivityIndicator {
8668 if (--activity_ == 0)
8669 [self setNetworkActivityIndicatorVisible:NO];
8672 - (void) setPackageController:(PackageController *)view {
8674 [view setPackage:nil];
8678 - (PackageController *) _packageController {
8679 return [[[PackageController alloc] initWithDatabase:database_] autorelease];
8682 - (PackageController *) packageController {
8683 return [self _packageController];
8686 // Returns the navigation controller for the queuing badge.
8687 - (id) queueBadgeController {
8688 int index = [self indexOfTabWithTag:kManageTag];
8690 index = [self indexOfTabWithTag:kInstalledTag];
8692 return [[tabbar_ viewControllers] objectAtIndex:index];
8695 - (void) cancelAndClear:(bool)clear {
8696 @synchronized (self) {
8708 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8709 NSString *context([alert context]);
8711 if ([context isEqualToString:@"fixhalf"]) {
8712 if (button == [alert firstOtherButtonIndex]) {
8713 @synchronized (self) {
8714 for (Package *broken in broken_) {
8717 NSString *id = [broken id];
8718 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8719 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8720 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8721 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8727 } else if (button == [alert cancelButtonIndex]) {
8728 [broken_ removeAllObjects];
8732 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8733 } else if ([context isEqualToString:@"upgrade"]) {
8734 if (button == [alert firstOtherButtonIndex]) {
8735 @synchronized (self) {
8736 for (Package *essential in essential_)
8737 [essential install];
8742 } else if (button == [alert firstOtherButtonIndex] + 1) {
8744 } else if (button == [alert cancelButtonIndex]) {
8748 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8752 - (void) system:(NSString *)command { _pooled
8754 system([command UTF8String]);
8758 - (void) applicationWillSuspend {
8760 [super applicationWillSuspend];
8763 - (BOOL) isSafeToSuspend {
8764 // Use external process status API internally.
8765 // This is probably a really bad idea.
8766 // XXX: what is the point of this? does this solve anything at all?
8767 uint64_t status = 0;
8769 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
8770 notify_get_state(notify_token, &status);
8771 notify_cancel(notify_token);
8774 return locked_ == 0 && status == 0;
8777 - (void) applicationSuspend:(__GSEvent *)event {
8778 if ([self isSafeToSuspend])
8779 [super applicationSuspend:event];
8782 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8783 if ([self isSafeToSuspend])
8784 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8787 - (void) _setSuspended:(BOOL)value {
8788 if ([self isSafeToSuspend])
8789 [super _setSuspended:value];
8792 - (UIProgressHUD *) addProgressHUD {
8793 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8794 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8796 [window_ setUserInteractionEnabled:NO];
8799 UIViewController *target = tabbar_;
8800 while ([target modalViewController] != nil) target = [target modalViewController];
8801 [[target view] addSubview:hud];
8807 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8809 [hud removeFromSuperview];
8810 [window_ setUserInteractionEnabled:YES];
8814 - (CYViewController *) pageForPackage:(NSString *)name {
8815 if (Package *package = [database_ packageWithName:name]) {
8816 PackageController *view([self packageController]);
8817 [view setPackage:package];
8820 NSURL *url([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"unknown" ofType:@"html"]]);
8821 url = [NSURL URLWithString:[[url absoluteString] stringByAppendingString:[NSString stringWithFormat:@"?%@", name]]];
8822 return [self _pageForURL:url withClass:[CYBrowserController class]];
8826 - (CYViewController *) pageForURL:(NSURL *)url hasTag:(int *)tag {
8830 NSString *href([url absoluteString]);
8831 if ([href hasPrefix:@"apptapp://package/"])
8832 return [self pageForPackage:[href substringFromIndex:18]];
8834 NSString *scheme([[url scheme] lowercaseString]);
8835 if (![scheme isEqualToString:@"cydia"])
8837 NSString *path([url absoluteString]);
8838 if ([path length] < 8)
8840 path = [path substringFromIndex:8];
8841 if (![path hasPrefix:@"/"])
8842 path = [@"/" stringByAppendingString:path];
8844 if ([path isEqualToString:@"/storage"])
8845 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CYBrowserController class]];
8846 /*else if ([path isEqualToString:@"/add-source"])
8847 return [[[AddSourceController alloc] initWithDatabase:database_] autorelease];*/
8848 else if ([path isEqualToString:@"/sources"])
8849 return [[[SourceController alloc] initWithDatabase:database_] autorelease];
8850 else if ([path isEqualToString:@"/packages"])
8851 return [[[InstalledController alloc] initWithDatabase:database_] autorelease];
8852 else if ([path hasPrefix:@"/url/"])
8853 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[CYBrowserController class]];
8854 else if ([path hasPrefix:@"/launch/"])
8855 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8856 else if ([path hasPrefix:@"/package-settings/"])
8857 return [[[CYPackageSettingsController alloc] initWithDatabase:database_ package:[path substringFromIndex:18]] autorelease];
8858 else if ([path hasPrefix:@"/package-signature/"])
8859 return [[[SignatureController alloc] initWithDatabase:database_ package:[path substringFromIndex:19]] autorelease];
8860 else if ([path hasPrefix:@"/package/"])
8861 return [self pageForPackage:[path substringFromIndex:9]];
8862 else if ([path hasPrefix:@"/files/"]) {
8863 NSString *name = [path substringFromIndex:7];
8865 if (Package *package = [database_ packageWithName:name]) {
8866 FileTable *files = [[[FileTable alloc] initWithDatabase:database_] autorelease];
8867 [files setPackage:package];
8875 - (BOOL) openCydiaURL:(NSURL *)url {
8876 CYViewController *page = nil;
8879 if ((page = [self pageForURL:url hasTag:&tag])) {
8880 [self setPage:page];
8882 [tabbar_ setSelectedViewController:(tag_ == -1 ? nil : [[tabbar_ viewControllers] objectAtIndex:tag_])];
8888 - (void) applicationOpenURL:(NSURL *)url {
8889 [super applicationOpenURL:url];
8891 if (!loaded_) starturl_ = [url retain];
8892 else [self openCydiaURL:url];
8895 - (void) applicationWillResignActive:(UIApplication *)application {
8896 // Stop refreshing if you get a phone call or lock the device.
8897 if ([tabbar_ updating])
8898 [tabbar_ cancelUpdate];
8900 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
8901 [super applicationWillResignActive:application];
8904 - (void) addStashController {
8906 stash_ = [[CYStashController alloc] init];
8907 [window_ addSubview:[stash_ view]];
8910 - (void) removeStashController {
8911 [[stash_ view] removeFromSuperview];
8917 [self setIdleTimerDisabled:YES];
8919 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
8920 [self setStatusBarShowsProgress:YES];
8921 UpdateExternalStatus(1);
8923 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
8925 UpdateExternalStatus(0);
8926 [self setStatusBarShowsProgress:NO];
8928 [self removeStashController];
8930 if (ExecFork() == 0) {
8931 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
8932 perror("launchctl stop");
8936 - (void) setupTabBarController {
8937 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
8938 [tabbar_ setDelegate:self];
8940 NSMutableArray *items([NSMutableArray arrayWithObjects:
8941 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:kCydiaTag] autorelease],
8942 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:kSectionsTag] autorelease],
8943 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:kChangesTag] autorelease],
8944 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:kSearchTag] autorelease],
8948 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:kSourcesTag] autorelease] atIndex:3];
8949 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:kInstalledTag] autorelease] atIndex:3];
8951 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:kManageTag] autorelease] atIndex:3];
8954 NSMutableArray *controllers([NSMutableArray array]);
8956 for (UITabBarItem *item in items) {
8957 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
8958 [controller setTabBarItem:item];
8959 [controllers addObject:controller];
8962 [tabbar_ setViewControllers:controllers];
8965 - (void)showFakeTabBarInView:(UIView *)view {
8966 static UITabBar *fake = [[UITabBar alloc] initWithFrame:CGRectMake(0, 0, 0, 49.0f)];
8968 CGRect frame = [fake frame];
8969 frame.origin.y = [view frame].size.height - frame.size.height;
8970 frame.size.width = [view frame].size.width;
8971 [fake setFrame:frame];
8972 [fake setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
8973 [view addSubview:fake];
8975 [fake removeFromSuperview];
8979 - (void) applicationDidFinishLaunching:(id)unused {
8983 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
8984 [self setApplicationSupportsShakeToEdit:NO];
8986 [NSURLCache setSharedURLCache:[[[SDURLCache alloc]
8987 initWithMemoryCapacity:524288
8988 diskCapacity:10485760
8989 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
8992 [CYBrowserController _initialize];
8994 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8996 Font12_ = [[UIFont systemFontOfSize:12] retain];
8997 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8998 Font14_ = [[UIFont systemFontOfSize:14] retain];
8999 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
9000 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
9004 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
9005 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
9007 window_ = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
9008 [window_ orderFront:self];
9009 [window_ makeKey:self];
9010 [window_ setHidden:NO];
9013 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9014 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9015 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9016 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9017 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9018 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9019 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9020 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9021 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9024 [self addStashController];
9025 // XXX: this would be much cleaner as a yieldToSelector:
9026 // that way the removeStashController could happen right here inline
9027 // we also could no longer require the useless stash_ field anymore
9028 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9032 database_ = [Database sharedInstance];
9034 [self setupTabBarController];
9035 [tabbar_ setUpdateDelegate:self];
9036 [window_ addSubview:[tabbar_ view]];
9038 // Show pinstripes while loading data.
9039 [[tabbar_ view] setBackgroundColor:[UIColor pinStripeColor]];
9040 [self showFakeTabBarInView:[tabbar_ tabBar]];
9042 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9049 [self showSettings];
9053 CGRect fixframe = [[tabbar_ view] frame];
9054 if (UIInterfaceOrientationIsLandscape([[UIApplication sharedApplication] statusBarOrientation]))
9055 fixframe.size = CGSizeMake(fixframe.size.height, fixframe.size.width);
9056 CYLoadingIndicator *loading = [[[CYLoadingIndicator alloc] initWithFrame:fixframe] autorelease];
9057 [loading setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9058 [[tabbar_ view] addSubview:loading];
9059 [window_ setUserInteractionEnabled:NO];
9064 // Show the initial page
9065 if (starturl_ == nil || ![self openCydiaURL:starturl_]) {
9066 [tabbar_ setSelectedIndex:0];
9070 [self showFakeTabBarInView:nil];
9072 [starturl_ release];
9075 [window_ setUserInteractionEnabled:YES];
9077 // XXX: does this actually slow anything down?
9078 [[tabbar_ view] setBackgroundColor:[UIColor clearColor]];
9079 [loading removeFromSuperview];
9082 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9083 if (item != nil && IsWildcat_) {
9084 [sheet showFromBarButtonItem:item animated:YES];
9086 [sheet showInView:window_];
9093 id Alloc_(id self, SEL selector) {
9094 id object = alloc_(self, selector);
9095 lprintf("[%s]A-%p\n", self->isa->name, object);
9100 id Dealloc_(id self, SEL selector) {
9101 id object = dealloc_(self, selector);
9102 lprintf("[%s]D-%p\n", self->isa->name, object);
9106 Class $WebDefaultUIKitDelegate;
9108 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9109 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9110 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9111 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9114 static NSNumber *shouldPlayKeyboardSounds;
9118 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
9120 case 1104: // Keyboard Button Clicked
9121 case 1105: // Keyboard Delete Repeated
9122 if (shouldPlayKeyboardSounds == nil) {
9123 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
9124 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
9127 if (![shouldPlayKeyboardSounds boolValue])
9131 _UIHardware$_playSystemSound$(self, _cmd, sound);
9135 int main(int argc, char *argv[]) { _pooled
9138 if (Class $UIDevice = objc_getClass("UIDevice")) {
9139 UIDevice *device([$UIDevice currentDevice]);
9140 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
9144 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9146 /* Library Hacks {{{ */
9147 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
9149 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
9150 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
9151 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
9152 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
9153 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
9156 $UIHardware = objc_getClass("UIHardware");
9157 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
9158 if (UIHardware$_playSystemSound$ != NULL) {
9159 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
9160 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
9163 /* Set Locale {{{ */
9164 Locale_ = CFLocaleCopyCurrent();
9165 Languages_ = [NSLocale preferredLanguages];
9166 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
9167 //NSLog(@"%@", [Languages_ description]);
9170 if (Languages_ == nil || [Languages_ count] == 0)
9171 // XXX: consider just setting to C and then falling through?
9174 lang = [[Languages_ objectAtIndex:0] UTF8String];
9175 setenv("LANG", lang, true);
9178 //std::setlocale(LC_ALL, lang);
9179 NSLog(@"Setting Language: %s", lang);
9182 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
9184 /* Parse Arguments {{{ */
9185 bool substrate(false);
9191 for (int argi(1); argi != argc; ++argi)
9192 if (strcmp(argv[argi], "--") == 0) {
9194 argv[argi] = argv[0];
9200 for (int argi(1); argi != arge; ++argi)
9201 if (strcmp(args[argi], "--substrate") == 0)
9204 fprintf(stderr, "unknown argument: %s\n", args[argi]);
9208 App_ = [[NSBundle mainBundle] bundlePath];
9209 Home_ = NSHomeDirectory();
9215 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
9216 alloc_ = alloc->method_imp;
9217 alloc->method_imp = (IMP) &Alloc_;*/
9219 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
9220 dealloc_ = dealloc->method_imp;
9221 dealloc->method_imp = (IMP) &Dealloc_;*/
9223 /* System Information {{{ */
9227 size = sizeof(maxproc);
9228 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9229 perror("sysctlbyname(\"kern.maxproc\", ?)");
9230 else if (maxproc < 64) {
9232 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9233 perror("sysctlbyname(\"kern.maxproc\", #)");
9236 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
9237 char *osversion = new char[size];
9238 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
9239 perror("sysctlbyname(\"kern.osversion\", ?)");
9241 System_ = [NSString stringWithUTF8String:osversion];
9243 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
9244 char *machine = new char[size];
9245 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
9246 perror("sysctlbyname(\"hw.machine\", ?)");
9250 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
9251 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
9252 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
9253 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
9257 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
9258 NSData *data((NSData *) ecid);
9259 size_t length([data length]);
9260 uint8_t bytes[length];
9261 [data getBytes:bytes];
9262 char string[length * 2 + 1];
9263 for (size_t i(0); i != length; ++i)
9264 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
9265 ChipID_ = [NSString stringWithUTF8String:string];
9269 IOObjectRelease(service);
9273 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
9275 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
9276 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9277 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
9279 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
9280 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9281 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
9283 if (mcc != NULL && mnc != NULL)
9284 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9291 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9292 Build_ = [system objectForKey:@"ProductBuildVersion"];
9293 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9294 Product_ = [info objectForKey:@"SafariProductVersion"];
9295 Safari_ = [info objectForKey:@"CFBundleVersion"];
9298 /* Load Database {{{ */
9300 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9302 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9304 if (Metadata_ == NULL)
9305 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9307 Settings_ = [Metadata_ objectForKey:@"Settings"];
9309 Packages_ = [Metadata_ objectForKey:@"Packages"];
9310 Sections_ = [Metadata_ objectForKey:@"Sections"];
9311 Sources_ = [Metadata_ objectForKey:@"Sources"];
9313 Token_ = [Metadata_ objectForKey:@"Token"];
9316 if (Settings_ != nil)
9317 Role_ = [Settings_ objectForKey:@"Role"];
9319 if (Sections_ == nil) {
9320 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9321 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9324 if (Sources_ == nil) {
9325 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9326 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9331 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
9334 if (Packages_ != nil) {
9335 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, NULL);
9337 [Metadata_ removeObjectForKey:@"Packages"];
9342 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9344 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", F_OK) == 0)
9345 dlopen("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", RTLD_LAZY | RTLD_GLOBAL);
9346 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
9347 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
9348 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9349 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9351 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9353 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9354 unlink("/tmp/.cydia.fw");
9356 } else if (access("/User", F_OK) != 0 || version < 2) {
9359 system("/usr/libexec/cydia/firmware.sh");
9363 _assert([[NSFileManager defaultManager]
9364 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9365 withIntermediateDirectories:YES
9370 if (access("/tmp/cydia.chk", F_OK) == 0) {
9371 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9372 _assert(errno == ENOENT);
9373 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9374 _assert(errno == ENOENT);
9377 /* APT Initialization {{{ */
9378 _assert(pkgInitConfig(*_config));
9379 _assert(pkgInitSystem(*_config, _system));
9382 _config->Set("APT::Acquire::Translation", lang);
9384 // XXX: this timeout might be important :(
9385 //_config->Set("Acquire::http::Timeout", 15);
9387 _config->Set("Acquire::http::MaxParallel", 3);
9389 /* Color Choices {{{ */
9390 space_ = CGColorSpaceCreateDeviceRGB();
9392 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9393 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9394 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9395 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9396 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9397 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9398 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9399 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9400 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9402 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9403 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9405 /* UIKit Configuration {{{ */
9406 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9407 if ($GSFontSetUseLegacyFontMetrics != NULL)
9408 $GSFontSetUseLegacyFontMetrics(YES);
9410 // XXX: I have a feeling this was important
9411 //UIKeyboardDisableAutomaticAppearance();
9414 Colon_ = UCLocalize("COLON_DELIMITED");
9415 Elision_ = UCLocalize("ELISION");
9416 Error_ = UCLocalize("ERROR");
9417 Warning_ = UCLocalize("WARNING");
9420 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9422 CGColorSpaceRelease(space_);