1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2010 Jay Freeman (saurik)
5 /* Modified BSD License {{{ */
7 * Redistribution and use in source and binary
8 * forms, with or without modification, are permitted
9 * provided that the following conditions are met:
11 * 1. Redistributions of source code must retain the
12 * above copyright notice, this list of conditions
13 * and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the
15 * above copyright notice, this list of conditions
16 * and the following disclaimer in the documentation
17 * and/or other materials provided with the
19 * 3. The name of the author may not be used to endorse
20 * or promote products derived from this software
21 * without specific prior written permission.
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
24 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
25 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
26 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
28 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
34 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
36 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
40 // XXX: wtf/FastMalloc.h... wtf?
41 #define USE_SYSTEM_MALLOC 1
43 /* #include Directives {{{ */
44 #include "UICaboodle/UCPlatform.h"
45 #include "UICaboodle/UCLocalize.h"
47 #include <objc/objc.h>
48 #include <objc/runtime.h>
50 #include <CoreGraphics/CoreGraphics.h>
51 #include <Foundation/Foundation.h>
54 #define DEPLOYMENT_TARGET_MACOSX 1
55 #define CF_BUILDING_CF 1
56 #include <CoreFoundation/CFInternal.h>
59 #include <CoreFoundation/CFPriv.h>
60 #include <CoreFoundation/CFUniChar.h>
62 #include <SystemConfiguration/SystemConfiguration.h>
64 #include <UIKit/UIKit.h>
65 #include "iPhonePrivate.h"
67 #include <IOKit/IOKitLib.h>
69 #include <WebCore/WebCoreThread.h>
76 #include <ext/stdio_filebuf.h>
80 #include <apt-pkg/acquire.h>
81 #include <apt-pkg/acquire-item.h>
82 #include <apt-pkg/algorithms.h>
83 #include <apt-pkg/cachefile.h>
84 #include <apt-pkg/clean.h>
85 #include <apt-pkg/configuration.h>
86 #include <apt-pkg/debindexfile.h>
87 #include <apt-pkg/debmetaindex.h>
88 #include <apt-pkg/error.h>
89 #include <apt-pkg/init.h>
90 #include <apt-pkg/mmap.h>
91 #include <apt-pkg/pkgrecords.h>
92 #include <apt-pkg/sha1.h>
93 #include <apt-pkg/sourcelist.h>
94 #include <apt-pkg/sptr.h>
95 #include <apt-pkg/strutl.h>
96 #include <apt-pkg/tagfile.h>
98 #include <apr-1/apr_pools.h>
100 #include <sys/types.h>
101 #include <sys/stat.h>
102 #include <sys/sysctl.h>
103 #include <sys/param.h>
104 #include <sys/mount.h>
105 #include <sys/reboot.h>
112 #include <mach-o/nlist.h>
122 #include <Cytore.hpp>
124 #include "UICaboodle/BrowserView.h"
125 #include "SDURLCache/SDURLCache.h"
127 #include "substrate.h"
134 #define _timestamp ({ \
136 gettimeofday(&tv, NULL); \
137 tv.tv_sec * 1000000 + tv.tv_usec; \
140 typedef std::vector<class ProfileTime *> TimeList;
150 ProfileTime(const char *name) :
154 times_.push_back(this);
157 void AddTime(uint64_t time) {
164 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
176 ProfileTimer(ProfileTime &time) :
183 time_.AddTime(_timestamp - start_);
188 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
190 std::cerr << "========" << std::endl;
193 #define _profile(name) { \
194 static ProfileTime name(#name); \
195 ProfileTimer _ ## name(name);
200 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
202 #define CYPoolStart() \
203 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
205 #define CYPoolEnd() \
209 // Hash Functions/Structures {{{
210 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
218 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
220 void NSLogPoint(const char *fix, const CGPoint &point) {
221 NSLog(@"%s(%g,%g)", fix, point.x, point.y);
224 void NSLogRect(const char *fix, const CGRect &rect) {
225 NSLog(@"%s(%g,%g)+(%g,%g)", fix, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
228 static _finline NSString *CydiaURL(NSString *path) {
230 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = ':';
231 page[5] = '/'; page[6] = '/'; page[7] = 'c'; page[8] = 'y'; page[9] = 'd';
232 page[10] = 'i'; page[11] = 'a'; page[12] = '.'; page[13] = 's'; page[14] = 'a';
233 page[15] = 'u'; page[16] = 'r'; page[17] = 'i'; page[18] = 'k'; page[19] = '.';
234 page[20] = 'c'; page[21] = 'o'; page[22] = 'm'; page[23] = '/'; page[24] = '\0';
235 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
238 static _finline void UpdateExternalStatus(uint64_t newStatus) {
240 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
241 notify_set_state(notify_token, newStatus);
242 notify_cancel(notify_token);
244 notify_post("com.saurik.Cydia.status");
247 /* [NSObject yieldToSelector:(withObject:)] {{{*/
248 @interface NSObject (Cydia)
249 - (id) yieldToSelector:(SEL)selector withObject:(id)object;
250 - (id) yieldToSelector:(SEL)selector;
253 @implementation NSObject (Cydia)
258 - (void) _yieldToContext:(NSMutableArray *)context { _pooled
259 SEL selector(reinterpret_cast<SEL>([[context objectAtIndex:0] pointerValue]));
260 id object([[context objectAtIndex:1] nonretainedObjectValue]);
261 volatile bool &stopped(*reinterpret_cast<bool *>([[context objectAtIndex:2] pointerValue]));
263 /* XXX: deal with exceptions */
264 id value([self performSelector:selector withObject:object]);
266 NSMethodSignature *signature([self methodSignatureForSelector:selector]);
267 [context removeAllObjects];
268 if ([signature methodReturnLength] != 0 && value != nil)
269 [context addObject:value];
274 performSelectorOnMainThread:@selector(doNothing)
280 - (id) yieldToSelector:(SEL)selector withObject:(id)object {
281 volatile bool stopped(false);
283 NSMutableArray *context([NSMutableArray arrayWithObjects:
284 [NSValue valueWithPointer:selector],
285 [NSValue valueWithNonretainedObject:object],
286 [NSValue valueWithPointer:const_cast<bool *>(&stopped)],
289 NSThread *thread([[[NSThread alloc]
291 selector:@selector(_yieldToContext:)
297 NSRunLoop *loop([NSRunLoop currentRunLoop]);
298 NSDate *future([NSDate distantFuture]);
300 while (!stopped && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
302 return [context count] == 0 ? nil : [context objectAtIndex:0];
305 - (id) yieldToSelector:(SEL)selector {
306 return [self yieldToSelector:selector withObject:nil];
312 /* Cydia Action Sheet {{{ */
313 @interface CYActionSheet : UIAlertView {
317 - (int) yieldToPopupAlertAnimated:(BOOL)animated;
320 @implementation CYActionSheet
322 - (id) initWithTitle:(NSString *)title buttons:(NSArray *)buttons defaultButtonIndex:(int)index {
323 if ((self = [super init])) {
324 [self setTitle:title];
325 [self setDelegate:self];
326 for (NSString *button in buttons) [self addButtonWithTitle:button];
327 [self setCancelButtonIndex:index];
331 - (void) _updateFrameForDisplay {
332 [super _updateFrameForDisplay];
333 if ([self cancelButtonIndex] == -1) {
334 NSArray *buttons = [self buttons];
335 if ([buttons count]) {
336 UIImage *background = [[buttons objectAtIndex:0] backgroundForState:0];
337 for (UIThreePartButton *button in buttons)
338 [button setBackground:background forState:0];
343 - (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
344 button_ = buttonIndex + 1;
348 [self dismissWithClickedButtonIndex:-1 animated:YES];
351 - (int) yieldToPopupAlertAnimated:(BOOL)animated {
352 [self setRunsModal:YES];
361 /* NSForcedOrderingSearch doesn't work on the iPhone */
362 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
363 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
364 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
366 /* Information Dictionaries {{{ */
367 @interface NSMutableArray (Cydia)
368 - (void) addInfoDictionary:(NSDictionary *)info;
371 @implementation NSMutableArray (Cydia)
373 - (void) addInfoDictionary:(NSDictionary *)info {
374 [self addObject:info];
379 @interface NSMutableDictionary (Cydia)
380 - (void) addInfoDictionary:(NSDictionary *)info;
383 @implementation NSMutableDictionary (Cydia)
385 - (void) addInfoDictionary:(NSDictionary *)info {
386 [self setObject:info forKey:[info objectForKey:@"CFBundleIdentifier"]];
392 #define lprintf(args...) fprintf(stderr, args)
395 #define TraceLogging (1 && !ForRelease)
396 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
397 #define ProfileTimes (0 && !ForRelease)
398 #define ForSaurik (0 && !ForRelease)
399 #define LogBrowser (0 && !ForRelease)
400 #define TrackResize (0 && !ForRelease)
401 #define ManualRefresh (1 && !ForRelease)
402 #define ShowInternals (0 && !ForRelease)
403 #define IgnoreInstall (0 && !ForRelease)
404 #define AlwaysReload (0 && !ForRelease)
408 #define _trace(args...)
413 #define _profile(name) {
416 #define PrintTimes() do {} while (false)
420 typedef uint32_t (*SKRadixFunction)(id, void *);
422 @interface NSMutableArray (Radix)
423 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
431 @implementation NSMutableArray (Radix)
433 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
434 size_t count([self count]);
435 struct RadixItem_ *swap(new RadixItem_[count * 2]);
437 for (size_t i(0); i != count; ++i) {
438 RadixItem_ &item(swap[i]);
441 id object([self objectAtIndex:i]);
442 item.key = function(object, argument);
445 struct RadixItem_ *lhs(swap), *rhs(swap + count);
447 static const size_t width = 32;
448 static const size_t bits = 11;
449 static const size_t slots = 1 << bits;
450 static const size_t passes = (width + (bits - 1)) / bits;
452 size_t *hist(new size_t[slots]);
454 for (size_t pass(0); pass != passes; ++pass) {
455 memset(hist, 0, sizeof(size_t) * slots);
457 for (size_t i(0); i != count; ++i) {
458 uint32_t key(lhs[i].key);
460 key &= _not(uint32_t) >> width - bits;
465 for (size_t i(0); i != slots; ++i) {
466 size_t local(offset);
471 for (size_t i(0); i != count; ++i) {
472 uint32_t key(lhs[i].key);
474 key &= _not(uint32_t) >> width - bits;
475 rhs[hist[key]++] = lhs[i];
478 RadixItem_ *tmp(lhs);
485 const void **values(new const void *[count]);
486 for (size_t i(0); i != count; ++i)
487 values[i] = [self objectAtIndex:lhs[i].index];
488 CFArrayReplaceValues((CFMutableArrayRef) self, CFRangeMake(0, count), values, count);
496 /* Insertion Sort {{{ */
498 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
499 const char *ptr = (const char *)list;
501 CFIndex half = count / 2;
502 const char *probe = ptr + elementSize * half;
503 CFComparisonResult cr = comparator(element, probe, context);
504 if (0 == cr) return (probe - (const char *)list) / elementSize;
505 ptr = (cr < 0) ? ptr : probe + elementSize;
506 count = (cr < 0) ? half : (half + (count & 1) - 1);
508 return (ptr - (const char *)list) / elementSize;
511 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
512 const char *ptr = (const char *)list;
514 CFIndex half = count / 2;
515 const char *probe = ptr + elementSize * half;
516 CFComparisonResult cr = comparator(element, probe, context);
517 if (0 == cr) return (probe - (const char *)list) / elementSize;
518 ptr = (cr < 0) ? ptr : probe + elementSize;
519 count = (cr < 0) ? half : (half + (count & 1) - 1);
521 return (ptr - (const char *)list) / elementSize;
524 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
525 if (range.length == 0)
527 const void **values(new const void *[range.length]);
528 CFArrayGetValues(array, range, values);
530 #if HistogramInsertionSort > 0
531 uint32_t total(0), *offsets(new uint32_t[range.length]);
534 for (CFIndex index(1); index != range.length; ++index) {
535 const void *value(values[index]);
536 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
537 CFIndex correct(index);
538 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
539 #if HistogramInsertionSort > 1
540 NSLog(@"%@ < %@", value, values[correct - 1]);
545 if (correct != index) {
546 size_t offset(index - correct);
547 #if HistogramInsertionSort
551 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
553 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
554 values[correct] = value;
558 CFArrayReplaceValues(array, range, values, range.length);
561 #if HistogramInsertionSort > 0
562 for (CFIndex index(0); index != range.length; ++index)
563 if (offsets[index] != 0)
564 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
565 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
572 /* Apple Bug Fixes {{{ */
573 @implementation UIWebDocumentView (Cydia)
575 - (void) _setScrollerOffset:(CGPoint)offset {
576 UIScroller *scroller([self _scroller]);
578 CGSize size([scroller contentSize]);
579 CGSize bounds([scroller bounds].size);
582 max.x = size.width - bounds.width;
583 max.y = size.height - bounds.height;
591 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
592 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
594 [scroller setOffset:offset];
600 @implementation WebScriptObject (NSFastEnumeration)
602 - (NSUInteger) countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)objects count:(NSUInteger)count {
603 size_t length([self count] - state->state);
606 else if (length > count)
608 for (size_t i(0); i != length; ++i)
609 objects[i] = [self objectAtIndex:state->state++];
610 state->itemsPtr = objects;
611 state->mutationsPtr = (unsigned long *) self;
617 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
618 size_t length([self length] - state->state);
621 else if (length > count)
623 for (size_t i(0); i != length; ++i)
624 objects[i] = [self item:state->state++];
625 state->itemsPtr = objects;
626 state->mutationsPtr = (unsigned long *) self;
630 /* Cydia NSString Additions {{{ */
631 @interface NSString (Cydia)
632 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
633 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
634 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
635 - (NSComparisonResult) compareByPath:(NSString *)other;
636 - (NSString *) stringByCachingURLWithCurrentCDN;
637 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
640 @implementation NSString (Cydia)
642 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
643 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
646 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
647 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
648 memcpy(data, bytes, length);
649 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
652 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
653 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
656 - (NSComparisonResult) compareByPath:(NSString *)other {
657 NSString *prefix = [self commonPrefixWithString:other options:0];
658 size_t length = [prefix length];
660 NSRange lrange = NSMakeRange(length, [self length] - length);
661 NSRange rrange = NSMakeRange(length, [other length] - length);
663 lrange = [self rangeOfString:@"/" options:0 range:lrange];
664 rrange = [other rangeOfString:@"/" options:0 range:rrange];
666 NSComparisonResult value;
668 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
669 value = NSOrderedSame;
670 else if (lrange.location == NSNotFound)
671 value = NSOrderedAscending;
672 else if (rrange.location == NSNotFound)
673 value = NSOrderedDescending;
675 value = NSOrderedSame;
677 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
678 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
679 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
680 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
682 NSComparisonResult result = [lpath compare:rpath];
683 return result == NSOrderedSame ? value : result;
686 - (NSString *) stringByCachingURLWithCurrentCDN {
688 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
689 withString:@"://cache.cydia.saurik.com/"
693 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
694 return [(id)CFURLCreateStringByAddingPercentEscapes(
699 kCFStringEncodingUTF8
706 /* C++ NSString Wrapper Cache {{{ */
707 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
708 return size == 0 ? NULL :
709 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
710 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
713 static _finline CFStringRef CYStringCreate(const char *data) {
714 return CYStringCreate(data, strlen(data));
723 _finline void clear_() {
724 if (cache_ != NULL) {
731 _finline bool empty() const {
735 _finline size_t size() const {
739 _finline char *data() const {
743 _finline void clear() {
748 _finline CYString() :
755 _finline ~CYString() {
759 void operator =(const CYString &rhs) {
763 if (rhs.cache_ == nil)
766 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
769 void copy(apr_pool_t *pool) {
770 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
771 memcpy(temp, data_, size_);
776 void set(apr_pool_t *pool, const char *data, size_t size) {
782 data_ = const_cast<char *>(data);
790 _finline void set(apr_pool_t *pool, const char *data) {
791 set(pool, data, data == NULL ? 0 : strlen(data));
794 _finline void set(apr_pool_t *pool, const std::string &rhs) {
795 set(pool, rhs.data(), rhs.size());
798 bool operator ==(const CYString &rhs) const {
799 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
802 _finline operator CFStringRef() {
804 cache_ = CYStringCreate(data_, size_);
808 _finline operator id() {
809 return (NSString *) static_cast<CFStringRef>(*this);
812 _finline operator const char *() {
813 return reinterpret_cast<const char *>(data_);
817 /* C++ NSString Algorithm Adapters {{{ */
819 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
822 struct NSStringMapHash :
823 std::unary_function<NSString *, size_t>
825 _finline size_t operator ()(NSString *value) const {
826 return CFStringHashNSString((CFStringRef) value);
830 struct NSStringMapLess :
831 std::binary_function<NSString *, NSString *, bool>
833 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
834 return [lhs compare:rhs] == NSOrderedAscending;
838 struct NSStringMapEqual :
839 std::binary_function<NSString *, NSString *, bool>
841 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
842 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
843 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
844 //[lhs isEqualToString:rhs];
849 /* Perl-Compatible RegEx {{{ */
859 Pcre(const char *regex) :
864 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
867 lprintf("%d:%s\n", offset, error);
871 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
872 matches_ = new int[(capture_ + 1) * 3];
880 NSString *operator [](size_t match) {
881 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
884 bool operator ()(NSString *data) {
885 // XXX: length is for characters, not for bytes
886 return operator ()([data UTF8String], [data length]);
889 bool operator ()(const char *data, size_t size) {
891 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
895 /* Mime Addresses {{{ */
896 @interface Address : NSObject {
902 - (NSString *) address;
904 - (void) setAddress:(NSString *)address;
906 + (Address *) addressWithString:(NSString *)string;
907 - (Address *) initWithString:(NSString *)string;
910 @implementation Address
919 - (NSString *) name {
923 - (NSString *) address {
927 - (void) setAddress:(NSString *)address {
929 [address_ autorelease];
933 address_ = [address retain];
936 + (Address *) addressWithString:(NSString *)string {
937 return [[[Address alloc] initWithString:string] autorelease];
940 + (NSArray *) _attributeKeys {
941 return [NSArray arrayWithObjects:@"address", @"name", nil];
944 - (NSArray *) attributeKeys {
945 return [[self class] _attributeKeys];
948 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
949 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
952 - (Address *) initWithString:(NSString *)string {
953 if ((self = [super init]) != nil) {
954 const char *data = [string UTF8String];
955 size_t size = [string length];
957 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
959 if (address_r(data, size)) {
960 name_ = [address_r[1] retain];
961 address_ = [address_r[2] retain];
963 name_ = [string retain];
971 /* CoreGraphics Primitives {{{ */
976 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
977 CGFloat color[] = {red, green, blue, alpha};
978 return CGColorCreate(space, color);
987 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
988 color_(Create_(space, red, green, blue, alpha))
990 Set(space, red, green, blue, alpha);
995 CGColorRelease(color_);
1002 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
1004 color_ = Create_(space, red, green, blue, alpha);
1007 operator CGColorRef() {
1013 /* Random Global Variables {{{ */
1014 static const int PulseInterval_ = 50000;
1017 static NSArray *Finishes_;
1019 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
1020 #define NotifyConfig_ "/etc/notify.conf"
1022 static bool Queuing_;
1024 static CYColor Blue_;
1025 static CYColor Blueish_;
1026 static CYColor Black_;
1027 static CYColor Off_;
1028 static CYColor White_;
1029 static CYColor Gray_;
1030 static CYColor Green_;
1031 static CYColor Purple_;
1032 static CYColor Purplish_;
1034 static UIColor *InstallingColor_;
1035 static UIColor *RemovingColor_;
1037 static NSString *App_;
1038 static NSString *Home_;
1040 static BOOL Advanced_;
1041 static BOOL Ignored_;
1043 static UIFont *Font12_;
1044 static UIFont *Font12Bold_;
1045 static UIFont *Font14_;
1046 static UIFont *Font18Bold_;
1047 static UIFont *Font22Bold_;
1049 static const char *Machine_ = NULL;
1050 static NSString *System_ = nil;
1051 static NSString *SerialNumber_ = nil;
1052 static NSString *ChipID_ = nil;
1053 static NSString *Token_ = nil;
1054 static NSString *UniqueID_ = nil;
1055 static NSString *PLMN_ = nil;
1056 static NSString *Build_ = nil;
1057 static NSString *Product_ = nil;
1058 static NSString *Safari_ = nil;
1060 static CFLocaleRef Locale_;
1061 static NSArray *Languages_;
1062 static CGColorSpaceRef space_;
1064 static NSDictionary *SectionMap_;
1065 static NSMutableDictionary *Metadata_;
1066 static _transient NSMutableDictionary *Settings_;
1067 static _transient NSString *Role_;
1068 static _transient NSMutableDictionary *Packages_;
1069 static _transient NSMutableDictionary *Sections_;
1070 static _transient NSMutableDictionary *Sources_;
1071 static bool Changed_;
1074 static bool IsWildcat_;
1077 /* Display Helpers {{{ */
1078 inline float Interpolate(float begin, float end, float fraction) {
1079 return (end - begin) * fraction + begin;
1082 /* XXX: localize this! */
1083 NSString *SizeString(double size) {
1084 bool negative = size < 0;
1089 while (size > 1024) {
1094 static const char *powers_[] = {"B", "kB", "MB", "GB"};
1096 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
1099 static _finline const char *StripVersion_(const char *version) {
1100 const char *colon(strchr(version, ':'));
1101 return colon == NULL ? version : colon + 1;
1104 NSString *LocalizeSection(NSString *section) {
1105 static Pcre title_r("^(.*?) \\((.*)\\)$");
1106 if (title_r(section)) {
1107 NSString *parent(title_r[1]);
1108 NSString *child(title_r[2]);
1110 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1111 LocalizeSection(parent),
1112 LocalizeSection(child)
1116 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1119 NSString *Simplify(NSString *title) {
1120 const char *data = [title UTF8String];
1121 size_t size = [title length];
1123 static Pcre square_r("^\\[(.*)\\]$");
1124 if (square_r(data, size))
1125 return Simplify(square_r[1]);
1127 static Pcre paren_r("^\\((.*)\\)$");
1128 if (paren_r(data, size))
1129 return Simplify(paren_r[1]);
1131 static Pcre title_r("^(.*?) \\((.*)\\)$");
1132 if (title_r(data, size))
1133 return Simplify(title_r[1]);
1139 NSString *GetLastUpdate() {
1140 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1143 return UCLocalize("NEVER_OR_UNKNOWN");
1145 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1146 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1148 CFRelease(formatter);
1150 return [(NSString *) formatted autorelease];
1153 bool isSectionVisible(NSString *section) {
1154 NSDictionary *metadata([Sections_ objectForKey:section]);
1155 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1156 return hidden == nil || ![hidden boolValue];
1161 /* Delegate Prototypes {{{ */
1165 @interface NSObject (ProgressDelegate)
1168 @protocol ProgressDelegate
1169 - (void) setProgressError:(NSString *)error withTitle:(NSString *)id;
1170 - (void) setProgressTitle:(NSString *)title;
1171 - (void) setProgressPercent:(float)percent;
1172 - (void) startProgress;
1173 - (void) addProgressOutput:(NSString *)output;
1174 - (bool) isCancelling:(size_t)received;
1177 @protocol ConfigurationDelegate
1178 - (void) repairWithSelector:(SEL)selector;
1179 - (void) setConfigurationData:(NSString *)data;
1182 @class PackageController;
1184 @protocol CydiaDelegate
1185 - (void) retainNetworkActivityIndicator;
1186 - (void) releaseNetworkActivityIndicator;
1187 - (void) setPackageController:(PackageController *)view;
1188 - (void) clearPackage:(Package *)package;
1189 - (void) installPackage:(Package *)package;
1190 - (void) installPackages:(NSArray *)packages;
1191 - (void) removePackage:(Package *)package;
1192 - (void) beginUpdate;
1194 - (void) distUpgrade;
1196 - (void) updateData;
1198 - (void) showSettings;
1199 - (UIProgressHUD *) addProgressHUD;
1200 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1201 - (CYViewController *) pageForPackage:(NSString *)name;
1202 - (PackageController *) packageController;
1203 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
1206 static id<CydiaDelegate> CydiaApp;
1209 /* Status Delegation {{{ */
1211 public pkgAcquireStatus
1214 _transient NSObject<ProgressDelegate> *delegate_;
1222 void setDelegate(id delegate) {
1223 delegate_ = delegate;
1226 NSObject<ProgressDelegate> *getDelegate() const {
1230 virtual bool MediaChange(std::string media, std::string drive) {
1234 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1237 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1238 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1239 [delegate_ setProgressTitle:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), [NSString stringWithUTF8String:item.ShortDesc.c_str()]]];
1242 virtual void Done(pkgAcquire::ItemDesc &item) {
1245 virtual void Fail(pkgAcquire::ItemDesc &item) {
1247 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1248 item.Owner->Status == pkgAcquire::Item::StatDone
1252 std::string &error(item.Owner->ErrorText);
1256 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1257 NSArray *fields([description componentsSeparatedByString:@" "]);
1258 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1260 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
1261 withObject:[NSArray arrayWithObjects:
1262 [NSString stringWithUTF8String:error.c_str()],
1269 virtual bool Pulse(pkgAcquire *Owner) {
1270 bool value = pkgAcquireStatus::Pulse(Owner);
1273 double(CurrentBytes + CurrentItems) /
1274 double(TotalBytes + TotalItems)
1277 [delegate_ setProgressPercent:percent];
1278 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1281 virtual void Start() {
1282 [delegate_ startProgress];
1285 virtual void Stop() {
1289 /* Progress Delegation {{{ */
1294 _transient id<ProgressDelegate> delegate_;
1298 virtual void Update() {
1299 /*if (abs(Percent - percent_) > 2)
1300 //NSLog(@"%s:%s:%f", Op.c_str(), SubOp.c_str(), Percent);
1304 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1305 [delegate_ setProgressPercent:(Percent / 100)];*/
1315 void setDelegate(id delegate) {
1316 delegate_ = delegate;
1319 id getDelegate() const {
1323 virtual void Done() {
1325 //[delegate_ setProgressPercent:1];
1330 /* Database Interface {{{ */
1331 typedef std::map< unsigned long, _H<Source> > SourceMap;
1333 @interface Database : NSObject {
1339 pkgCacheFile cache_;
1340 pkgDepCache::Policy *policy_;
1341 pkgRecords *records_;
1342 pkgProblemResolver *resolver_;
1343 pkgAcquire *fetcher_;
1345 SPtr<pkgPackageManager> manager_;
1346 pkgSourceList *list_;
1349 CFMutableArrayRef packages_;
1351 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1360 + (Database *) sharedInstance;
1363 - (void) _readCydia:(NSNumber *)fd;
1364 - (void) _readStatus:(NSNumber *)fd;
1365 - (void) _readOutput:(NSNumber *)fd;
1369 - (Package *) packageWithName:(NSString *)name;
1371 - (pkgCacheFile &) cache;
1372 - (pkgDepCache::Policy *) policy;
1373 - (pkgRecords *) records;
1374 - (pkgProblemResolver *) resolver;
1375 - (pkgAcquire &) fetcher;
1376 - (pkgSourceList &) list;
1377 - (NSArray *) packages;
1378 - (NSArray *) sources;
1379 - (void) reloadData;
1387 - (void) updateWithStatus:(Status &)status;
1389 - (void) setDelegate:(id)delegate;
1390 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1393 /* Delegate Helpers {{{ */
1394 @implementation NSObject (ProgressDelegate)
1396 - (void) _setProgressErrorPackage:(NSArray *)args {
1397 [self performSelector:@selector(setProgressError:forPackage:)
1398 withObject:[args objectAtIndex:0]
1399 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1403 - (void) _setProgressErrorTitle:(NSArray *)args {
1404 [self performSelector:@selector(setProgressError:withTitle:)
1405 withObject:[args objectAtIndex:0]
1406 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1410 - (void) _setProgressError:(NSString *)error withTitle:(NSString *)title {
1411 [self performSelectorOnMainThread:@selector(_setProgressErrorTitle:)
1412 withObject:[NSArray arrayWithObjects:error, title, nil]
1417 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
1418 Package *package = id == nil ? nil : [[Database sharedInstance] packageWithName:id];
1420 [self performSelector:@selector(setProgressError:withTitle:)
1422 withObject:(package == nil ? id : [package name])
1429 // Cytore Definitions {{{
1430 struct PackageValue :
1433 Cytore::Offset<PackageValue> next_;
1435 uint32_t index_ : 23;
1436 uint32_t subscribed_ : 1;
1453 Cytore::Offset<PackageValue> packages_[1 << 16];
1456 static Cytore::File<MetaValue> MetaFile_;
1458 // Cytore Helper Functions {{{
1459 static PackageValue *PackageFind(const char *name, size_t length) {
1460 SplitHash nhash = { hashlittle(name, length) };
1462 PackageValue *metadata;
1464 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1465 offset: if (offset->IsNull()) {
1466 *offset = MetaFile_.New<PackageValue>(length + 1);
1467 metadata = &MetaFile_.Get(*offset);
1469 memcpy(metadata->name_, name, length + 1);
1470 metadata->nhash_ = nhash.u16[1];
1472 metadata = &MetaFile_.Get(*offset);
1474 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1475 offset = &metadata->next_;
1483 static void PackageImport(const void *key, const void *value, void *context) {
1485 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1486 NSLog(@"failed to import package %@", key);
1490 PackageValue *metadata(PackageFind(buffer, strlen(buffer)));
1491 NSDictionary *package((NSDictionary *) value);
1493 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1494 if ([subscribed boolValue] && !metadata->subscribed_)
1495 metadata->subscribed_ = true;
1497 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1498 time_t time([date timeIntervalSince1970]);
1499 if (metadata->first_ > time || metadata->first_ == 0)
1500 metadata->first_ = time;
1503 NSDate *date([package objectForKey:@"LastSeen"]);
1504 NSString *version([package objectForKey:@"LastVersion"]);
1506 if (date != nil && version != nil) {
1507 time_t time([date timeIntervalSince1970]);
1508 if (metadata->last_ < time || metadata->last_ == 0)
1509 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1510 size_t length(strlen(buffer));
1511 uint16_t vhash(hashlittle(buffer, length));
1513 size_t capped(std::min<size_t>(8, length));
1514 char *latest(buffer + length - capped);
1516 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1517 metadata->vhash_ = vhash;
1519 metadata->last_ = time;
1525 /* Source Class {{{ */
1526 @interface Source : NSObject {
1527 CYString depiction_;
1528 CYString description_;
1534 CYString distribution_;
1539 NSString *authority_;
1541 CYString defaultIcon_;
1543 NSDictionary *record_;
1547 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1549 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1551 - (NSString *) depictionForPackage:(NSString *)package;
1552 - (NSString *) supportForPackage:(NSString *)package;
1554 - (NSDictionary *) record;
1558 - (NSString *) distribution;
1559 - (NSString *) type;
1561 - (NSString *) host;
1563 - (NSString *) name;
1564 - (NSString *) description;
1565 - (NSString *) label;
1566 - (NSString *) origin;
1567 - (NSString *) version;
1569 - (NSString *) defaultIcon;
1573 @implementation Source
1577 distribution_.clear();
1580 description_.clear();
1586 defaultIcon_.clear();
1588 if (record_ != nil) {
1598 if (authority_ != nil) {
1599 [authority_ release];
1605 // XXX: this is a very inefficient way to call these deconstructors
1610 + (NSArray *) _attributeKeys {
1611 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1614 - (NSArray *) attributeKeys {
1615 return [[self class] _attributeKeys];
1618 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1619 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1622 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1625 trusted_ = index->IsTrusted();
1627 uri_.set(pool, index->GetURI());
1628 distribution_.set(pool, index->GetDist());
1629 type_.set(pool, index->GetType());
1631 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1632 if (dindex != NULL) {
1634 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1637 pkgTagFile tags(&fd);
1639 pkgTagSection section;
1646 {"default-icon", &defaultIcon_},
1647 {"depiction", &depiction_},
1648 {"description", &description_},
1650 {"origin", &origin_},
1651 {"support", &support_},
1652 {"version", &version_},
1655 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1656 const char *start, *end;
1658 if (section.Find(names[i].name_, start, end)) {
1659 CYString &value(*names[i].value_);
1660 value.set(pool, start, end - start);
1666 record_ = [Sources_ objectForKey:[self key]];
1668 record_ = [record_ retain];
1670 NSURL *url([NSURL URLWithString:uri_]);
1674 host_ = [[host_ lowercaseString] retain];
1679 authority_ = [url path];
1681 if (authority_ != nil)
1682 authority_ = [authority_ retain];
1685 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1686 if ((self = [super init]) != nil) {
1687 [self setMetaIndex:index inPool:pool];
1691 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1692 NSDictionary *lhr = [self record];
1693 NSDictionary *rhr = [source record];
1696 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1698 NSString *lhs = [self name];
1699 NSString *rhs = [source name];
1701 if ([lhs length] != 0 && [rhs length] != 0) {
1702 unichar lhc = [lhs characterAtIndex:0];
1703 unichar rhc = [rhs characterAtIndex:0];
1705 if (isalpha(lhc) && !isalpha(rhc))
1706 return NSOrderedAscending;
1707 else if (!isalpha(lhc) && isalpha(rhc))
1708 return NSOrderedDescending;
1711 return [lhs compare:rhs options:LaxCompareOptions_];
1714 - (NSString *) depictionForPackage:(NSString *)package {
1715 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1718 - (NSString *) supportForPackage:(NSString *)package {
1719 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1722 - (NSDictionary *) record {
1730 - (NSString *) uri {
1734 - (NSString *) distribution {
1735 return distribution_;
1738 - (NSString *) type {
1742 - (NSString *) key {
1743 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1746 - (NSString *) host {
1750 - (NSString *) name {
1751 return origin_.empty() ? authority_ : origin_;
1754 - (NSString *) description {
1755 return description_;
1758 - (NSString *) label {
1759 return label_.empty() ? authority_ : label_;
1762 - (NSString *) origin {
1766 - (NSString *) version {
1770 - (NSString *) defaultIcon {
1771 return defaultIcon_;
1776 /* Relationship Class {{{ */
1777 @interface Relationship : NSObject {
1782 - (NSString *) type;
1784 - (NSString *) name;
1788 @implementation Relationship
1796 - (NSString *) type {
1804 - (NSString *) name {
1811 /* Package Class {{{ */
1812 struct ParsedPackage {
1817 CYString depiction_;
1827 @interface Package : NSObject {
1829 uint32_t essential_ : 1;
1830 uint32_t obsolete_ : 1;
1831 uint32_t ignored_ : 1;
1835 _transient Database *database_;
1837 pkgCache::VerIterator version_;
1838 pkgCache::PkgIterator iterator_;
1839 pkgCache::VerFileIterator file_;
1845 CYString installed_;
1848 _transient NSString *section$_;
1852 PackageValue *metadata_;
1853 ParsedPackage *parsed_;
1855 NSMutableArray *tags_;
1859 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1860 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1862 - (pkgCache::PkgIterator) iterator;
1865 - (NSString *) section;
1866 - (NSString *) simpleSection;
1868 - (NSString *) longSection;
1869 - (NSString *) shortSection;
1873 - (Address *) maintainer;
1875 - (NSString *) longDescription;
1876 - (NSString *) shortDescription;
1879 - (PackageValue *) metadata;
1882 - (bool) subscribed;
1883 - (bool) setSubscribed:(bool)subscribed;
1887 - (NSString *) latest;
1888 - (NSString *) installed;
1889 - (BOOL) uninstalled;
1892 - (BOOL) upgradableAndEssential:(BOOL)essential;
1895 - (BOOL) unfiltered;
1899 - (BOOL) halfConfigured;
1900 - (BOOL) halfInstalled;
1902 - (NSString *) mode;
1905 - (NSString *) name;
1907 - (NSString *) homepage;
1908 - (NSString *) depiction;
1909 - (Address *) author;
1911 - (NSString *) support;
1913 - (NSArray *) files;
1914 - (NSArray *) warnings;
1915 - (NSArray *) applications;
1917 - (Source *) source;
1918 - (NSString *) role;
1920 - (BOOL) matches:(NSString *)text;
1922 - (bool) hasSupportingRole;
1923 - (BOOL) hasTag:(NSString *)tag;
1924 - (NSString *) primaryPurpose;
1925 - (NSArray *) purposes;
1926 - (bool) isCommercial;
1928 - (void) setIndex:(size_t)index;
1930 - (CYString &) cyname;
1932 - (uint32_t) compareBySection:(NSArray *)sections;
1937 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1938 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1939 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1940 - (bool) isVisibleInSection:(NSString *)section;
1941 - (bool) isVisibleInSource:(Source *)source;
1945 uint32_t PackageChangesRadix(Package *self, void *) {
1950 uint32_t timestamp : 30;
1951 uint32_t ignored : 1;
1952 uint32_t upgradable : 1;
1956 bool upgradable([self upgradableAndEssential:YES]);
1957 value.bits.upgradable = upgradable ? 1 : 0;
1960 value.bits.timestamp = 0;
1961 value.bits.ignored = [self ignored] ? 0 : 1;
1962 value.bits.upgradable = 1;
1964 value.bits.timestamp = [self seen] >> 2;
1965 value.bits.ignored = 0;
1966 value.bits.upgradable = 0;
1969 return _not(uint32_t) - value.key;
1972 uint32_t PackagePrefixRadix(Package *self, void *context) {
1973 size_t offset(reinterpret_cast<size_t>(context));
1974 CYString &name([self cyname]);
1976 size_t size(name.size());
1979 char *text(name.data());
1982 if (!isdigit(text[0]))
1986 while (size != digits && isdigit(text[digits]))
1994 if (offset == 0 && zeros != 0) {
1995 memset(data, '0', zeros);
1996 memcpy(data + zeros, text, 4 - zeros);
1998 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
1999 if (size <= offset - zeros)
2002 text += offset - zeros;
2003 size -= offset - zeros;
2006 memcpy(data, text, 4);
2008 memcpy(data, text, size);
2009 memset(data + size, 0, 4 - size);
2012 for (size_t i(0); i != 4; ++i)
2013 if (isalpha(data[i]))
2021 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2023 /* XXX: ntohl may be more honest */
2024 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2027 CYString &(*PackageName)(Package *self, SEL sel);
2029 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2030 _profile(PackageNameCompare)
2031 CYString &lhi(PackageName(lhs, @selector(cyname)));
2032 CYString &rhi(PackageName(rhs, @selector(cyname)));
2033 CFStringRef lhn(lhi), rhn(rhi);
2036 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2037 else if (rhn == NULL)
2038 return NSOrderedDescending;
2040 _profile(PackageNameCompare$NumbersLast)
2041 if (!lhi.empty() && !rhi.empty()) {
2042 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2043 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2044 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2045 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2046 return lha ? NSOrderedAscending : NSOrderedDescending;
2050 CFIndex length = CFStringGetLength(lhn);
2052 _profile(PackageNameCompare$Compare)
2053 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2058 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2059 return PackageNameCompare(*lhs, *rhs, context);
2062 struct PackageNameOrdering :
2063 std::binary_function<Package *, Package *, bool>
2065 _finline bool operator ()(Package *lhs, Package *rhs) const {
2066 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2070 @implementation Package
2072 - (NSString *) description {
2073 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2077 if (parsed_ != NULL)
2091 + (NSString *) webScriptNameForSelector:(SEL)selector {
2092 if (selector == @selector(hasTag:))
2098 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2099 return [self webScriptNameForSelector:selector] == nil;
2102 + (NSArray *) _attributeKeys {
2103 return [NSArray arrayWithObjects:@"applications", @"author", @"depiction", @"longDescription", @"essential", @"homepage", @"icon", @"id", @"installed", @"latest", @"longSection", @"maintainer", @"mode", @"name", @"purposes", @"section", @"shortDescription", @"shortSection", @"simpleSection", @"size", @"source", @"sponsor", @"support", @"warnings", nil];
2106 - (NSArray *) attributeKeys {
2107 return [[self class] _attributeKeys];
2110 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2111 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2115 if (parsed_ != NULL)
2117 @synchronized (database_) {
2118 if ([database_ era] != era_ || file_.end())
2121 ParsedPackage *parsed(new ParsedPackage);
2124 _profile(Package$parse)
2125 pkgRecords::Parser *parser;
2127 _profile(Package$parse$Lookup)
2128 parser = &[database_ records]->Lookup(file_);
2133 _profile(Package$parse$Find)
2138 {"icon", &parsed->icon_},
2139 {"depiction", &parsed->depiction_},
2140 {"homepage", &parsed->homepage_},
2141 {"website", &website},
2142 {"bugs", &parsed->bugs_},
2143 {"support", &parsed->support_},
2144 {"sponsor", &parsed->sponsor_},
2145 {"author", &parsed->author_},
2148 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2149 const char *start, *end;
2151 if (parser->Find(names[i].name_, start, end)) {
2152 CYString &value(*names[i].value_);
2153 _profile(Package$parse$Value)
2154 value.set(pool_, start, end - start);
2160 _profile(Package$parse$Tagline)
2161 const char *start, *end;
2162 if (parser->ShortDesc(start, end)) {
2163 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2166 while (stop != start && stop[-1] == '\r')
2168 parsed->tagline_.set(pool_, start, stop - start);
2172 _profile(Package$parse$Retain)
2173 if (parsed->homepage_.empty())
2174 parsed->homepage_ = website;
2175 if (parsed->homepage_ == parsed->depiction_)
2176 parsed->homepage_.clear();
2181 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2182 if ((self = [super init]) != nil) {
2183 _profile(Package$initWithVersion)
2186 database_ = database;
2187 era_ = [database era];
2191 pkgCache::PkgIterator iterator(version.ParentPkg());
2192 iterator_ = iterator;
2194 _profile(Package$initWithVersion$Version)
2195 if (!version_.end())
2196 file_ = version_.FileList();
2198 pkgCache &cache([database_ cache]);
2199 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2203 _profile(Package$initWithVersion$Cache)
2204 name_.set(NULL, iterator.Display());
2206 latest_.set(NULL, StripVersion_(version_.VerStr()));
2208 pkgCache::VerIterator current(iterator.CurrentVer());
2210 installed_.set(NULL, StripVersion_(current.VerStr()));
2213 _profile(Package$initWithVersion$Tags)
2214 pkgCache::TagIterator tag(iterator.TagList());
2216 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2218 const char *name(tag.Name());
2219 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2221 if (role_ == nil && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/)
2222 role_ = (NSString *) CYStringCreate(name + 6);
2224 if (strncmp(name, "cydia::", 7) == 0) {
2225 if (strcmp(name + 7, "essential") == 0)
2227 else if (strcmp(name + 7, "obsolete") == 0)
2232 } while (!tag.end());
2236 _profile(Package$initWithVersion$Metadata)
2237 const char *mixed(iterator.Name());
2238 size_t size(strlen(mixed));
2239 char lower[size + 1];
2241 for (size_t i(0); i != size; ++i)
2242 lower[i] = mixed[i] | 0x20;
2245 PackageValue *metadata(PackageFind(lower, size));
2246 metadata_ = metadata;
2248 id_.set(NULL, metadata->name_, size);
2250 const char *latest(version_.VerStr());
2251 size_t length(strlen(latest));
2253 uint16_t vhash(hashlittle(latest, length));
2255 size_t capped(std::min<size_t>(8, length));
2256 latest = latest + length - capped;
2258 if (metadata->first_ == 0)
2259 metadata->first_ = now_;
2261 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2262 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2263 metadata->vhash_ = vhash;
2264 metadata->last_ = now_;
2265 } else if (metadata->last_ == 0)
2266 metadata->last_ = metadata->first_;
2269 _profile(Package$initWithVersion$Section)
2270 section_.set(NULL, iterator.Section());
2273 _profile(Package$initWithVersion$Flags)
2274 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2275 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2280 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2281 pkgCache::VerIterator version;
2283 _profile(Package$packageWithIterator$GetCandidateVer)
2284 version = [database policy]->GetCandidateVer(iterator);
2292 _profile(Package$packageWithIterator$Allocate)
2293 package = [Package allocWithZone:zone];
2296 _profile(Package$packageWithIterator$Initialize)
2298 initWithVersion:version
2305 _profile(Package$packageWithIterator$Autorelease)
2306 package = [package autorelease];
2312 - (pkgCache::PkgIterator) iterator {
2316 - (NSString *) section {
2317 if (section$_ == nil) {
2318 if (section_.empty())
2321 _profile(Package$section)
2322 std::replace(section_.data(), section_.data() + section_.size(), '_', ' ');
2323 NSString *name(section_);
2324 section$_ = [SectionMap_ objectForKey:name] ?: name;
2329 - (NSString *) simpleSection {
2330 if (NSString *section = [self section])
2331 return Simplify(section);
2336 - (NSString *) longSection {
2337 return LocalizeSection([self section]);
2340 - (NSString *) shortSection {
2341 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2344 - (NSString *) uri {
2347 pkgIndexFile *index;
2348 pkgCache::PkgFileIterator file(file_.File());
2349 if (![database_ list].FindIndex(file, index))
2351 return [NSString stringWithUTF8String:iterator_->Path];
2352 //return [NSString stringWithUTF8String:file.Site()];
2353 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2357 - (Address *) maintainer {
2358 @synchronized (database_) {
2359 if ([database_ era] != era_ || file_.end())
2362 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2363 const std::string &maintainer(parser->Maintainer());
2364 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2368 @synchronized (database_) {
2369 if ([database_ era] != era_ || version_.end())
2372 return version_->InstalledSize;
2375 - (NSString *) longDescription {
2376 @synchronized (database_) {
2377 if ([database_ era] != era_ || file_.end())
2380 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2381 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2383 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2384 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2385 if ([lines count] < 2)
2388 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2389 for (size_t i(1), e([lines count]); i != e; ++i) {
2390 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2391 [trimmed addObject:trim];
2394 return [trimmed componentsJoinedByString:@"\n"];
2397 - (NSString *) shortDescription {
2398 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2402 _profile(Package$index)
2403 CFStringRef name((CFStringRef) [self name]);
2404 if (CFStringGetLength(name) == 0)
2406 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2407 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2409 return toupper(character);
2413 - (PackageValue *) metadata {
2418 PackageValue *metadata([self metadata]);
2419 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2422 - (bool) subscribed {
2423 return [self metadata]->subscribed_;
2426 - (bool) setSubscribed:(bool)subscribed {
2427 PackageValue *metadata([self metadata]);
2428 if (metadata->subscribed_ == subscribed)
2430 metadata->subscribed_ = subscribed;
2438 - (NSString *) latest {
2442 - (NSString *) installed {
2446 - (BOOL) uninstalled {
2447 return installed_.empty();
2451 return !version_.end();
2454 - (BOOL) upgradableAndEssential:(BOOL)essential {
2455 _profile(Package$upgradableAndEssential)
2456 pkgCache::VerIterator current(iterator_.CurrentVer());
2458 return essential && essential_;
2460 return !version_.end() && version_ != current;
2464 - (BOOL) essential {
2469 return [database_ cache][iterator_].InstBroken();
2472 - (BOOL) unfiltered {
2473 _profile(Package$unfiltered$obsolete)
2478 _profile(Package$unfiltered$hasSupportingRole)
2479 if (![self hasSupportingRole])
2487 if (![self unfiltered])
2490 NSString *section([self section]);
2492 _profile(Package$visible$isSectionVisible)
2493 if (section != nil && !isSectionVisible(section))
2501 unsigned char current(iterator_->CurrentState);
2502 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2505 - (BOOL) halfConfigured {
2506 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2509 - (BOOL) halfInstalled {
2510 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2514 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2515 return state.Mode != pkgDepCache::ModeKeep;
2518 - (NSString *) mode {
2519 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2521 switch (state.Mode) {
2522 case pkgDepCache::ModeDelete:
2523 if ((state.iFlags & pkgDepCache::Purge) != 0)
2527 case pkgDepCache::ModeKeep:
2528 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2529 return @"REINSTALL";
2530 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2534 case pkgDepCache::ModeInstall:
2535 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2536 return @"REINSTALL";
2537 else*/ switch (state.Status) {
2539 return @"DOWNGRADE";
2545 return @"NEW_INSTALL";
2556 - (NSString *) name {
2557 return name_.empty() ? id_ : name_;
2560 - (UIImage *) icon {
2561 NSString *section = [self simpleSection];
2564 if (parsed_ != NULL)
2565 if (NSString *href = parsed_->icon_)
2566 if ([href hasPrefix:@"file:///"])
2567 // XXX: correct escaping
2568 icon = [UIImage imageAtPath:[href substringFromIndex:7]];
2569 if (icon == nil) if (section != nil)
2570 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2571 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2572 if ([dicon hasPrefix:@"file:///"])
2573 // XXX: correct escaping
2574 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2576 icon = [UIImage applicationImageNamed:@"unknown.png"];
2580 - (NSString *) homepage {
2581 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2584 - (NSString *) depiction {
2585 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2588 - (Address *) sponsor {
2589 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [Address addressWithString:parsed_->sponsor_];
2592 - (Address *) author {
2593 return parsed_ == NULL || parsed_->author_.empty() ? nil : [Address addressWithString:parsed_->author_];
2596 - (NSString *) support {
2597 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2600 - (NSArray *) files {
2601 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2602 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2605 fin.open([path UTF8String]);
2610 while (std::getline(fin, line))
2611 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2616 - (NSArray *) warnings {
2617 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2618 const char *name(iterator_.Name());
2620 size_t length(strlen(name));
2621 if (length < 2) invalid:
2622 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2623 else for (size_t i(0); i != length; ++i)
2625 /* XXX: technically this is not allowed */
2626 (name[i] < 'A' || name[i] > 'Z') &&
2627 (name[i] < 'a' || name[i] > 'z') &&
2628 (name[i] < '0' || name[i] > '9') &&
2629 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2632 if (strcmp(name, "cydia") != 0) {
2635 bool _private = false;
2638 bool repository = [[self section] isEqualToString:@"Repositories"];
2640 if (NSArray *files = [self files])
2641 for (NSString *file in files)
2642 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2644 else if (!user && [file isEqualToString:@"/User"])
2646 else if (!_private && [file isEqualToString:@"/private"])
2648 else if (!stash && [file isEqualToString:@"/var/stash"])
2651 /* XXX: this is not sensitive enough. only some folders are valid. */
2652 if (cydia && !repository)
2653 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2655 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2657 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2659 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2662 return [warnings count] == 0 ? nil : warnings;
2665 - (NSArray *) applications {
2666 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2668 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2670 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2671 if (NSArray *files = [self files])
2672 for (NSString *file in files)
2673 if (application_r(file)) {
2674 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2675 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2676 if ([id isEqualToString:me])
2679 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2681 display = application_r[1];
2683 NSString *bundle([file stringByDeletingLastPathComponent]);
2684 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2685 if (icon == nil || [icon length] == 0)
2687 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2689 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2690 [applications addObject:application];
2692 [application addObject:id];
2693 [application addObject:display];
2694 [application addObject:url];
2697 return [applications count] == 0 ? nil : applications;
2700 - (Source *) source {
2701 if (source_ == nil) {
2702 @synchronized (database_) {
2703 if ([database_ era] != era_ || file_.end())
2704 source_ = (Source *) [NSNull null];
2706 source_ = [([database_ getSource:file_.File()] ?: (Source *) [NSNull null]) retain];
2710 return source_ == (Source *) [NSNull null] ? nil : source_;
2713 - (NSString *) role {
2717 - (BOOL) matches:(NSString *)text {
2723 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2724 if (range.location != NSNotFound)
2727 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2728 if (range.location != NSNotFound)
2731 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2732 if (range.location != NSNotFound)
2738 - (bool) hasSupportingRole {
2741 if ([role_ isEqualToString:@"enduser"])
2743 if ([Role_ isEqualToString:@"User"])
2745 if ([role_ isEqualToString:@"hacker"])
2747 if ([Role_ isEqualToString:@"Hacker"])
2749 if ([role_ isEqualToString:@"developer"])
2751 if ([Role_ isEqualToString:@"Developer"])
2756 - (BOOL) hasTag:(NSString *)tag {
2757 return tags_ == nil ? NO : [tags_ containsObject:tag];
2760 - (NSString *) primaryPurpose {
2761 for (NSString *tag in tags_)
2762 if ([tag hasPrefix:@"purpose::"])
2763 return [tag substringFromIndex:9];
2767 - (NSArray *) purposes {
2768 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2769 for (NSString *tag in tags_)
2770 if ([tag hasPrefix:@"purpose::"])
2771 [purposes addObject:[tag substringFromIndex:9]];
2772 return [purposes count] == 0 ? nil : purposes;
2775 - (bool) isCommercial {
2776 return [self hasTag:@"cydia::commercial"];
2779 - (void) setIndex:(size_t)index {
2780 if (metadata_->index_ != index)
2781 metadata_->index_ = index;
2784 - (CYString &) cyname {
2785 return name_.empty() ? id_ : name_;
2788 - (uint32_t) compareBySection:(NSArray *)sections {
2789 NSString *section([self section]);
2790 for (size_t i(0), e([sections count]); i != e; ++i) {
2791 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2795 return _not(uint32_t);
2799 @synchronized (database_) {
2800 pkgProblemResolver *resolver = [database_ resolver];
2801 resolver->Clear(iterator_);
2803 pkgCacheFile &cache([database_ cache]);
2804 cache->SetReInstall(iterator_, false);
2805 cache->MarkKeep(iterator_, false);
2809 @synchronized (database_) {
2810 pkgProblemResolver *resolver = [database_ resolver];
2811 resolver->Clear(iterator_);
2812 resolver->Protect(iterator_);
2814 pkgCacheFile &cache([database_ cache]);
2815 cache->SetReInstall(iterator_, false);
2816 cache->MarkInstall(iterator_, false);
2818 pkgDepCache::StateCache &state((*cache)[iterator_]);
2819 if (!state.Install())
2820 cache->SetReInstall(iterator_, true);
2824 @synchronized (database_) {
2825 pkgProblemResolver *resolver = [database_ resolver];
2826 resolver->Clear(iterator_);
2827 resolver->Remove(iterator_);
2828 resolver->Protect(iterator_);
2830 pkgCacheFile &cache([database_ cache]);
2831 cache->SetReInstall(iterator_, false);
2832 cache->MarkDelete(iterator_, true);
2835 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2836 _profile(Package$isUnfilteredAndSearchedForBy)
2839 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2840 value &= [self unfiltered];
2843 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2844 value &= [self matches:search];
2851 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2852 if ([search length] == 0)
2855 _profile(Package$isUnfilteredAndSelectedForBy)
2858 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2859 value &= [self unfiltered];
2862 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2863 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2870 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
2871 return ![self uninstalled] && (![number boolValue] && ![role_ isEqualToString:@"cydia"] || [self unfiltered]);
2874 - (bool) isVisibleInSection:(NSString *)name {
2875 NSString *section([self section]);
2879 section == nil && [name length] == 0 ||
2880 [name isEqualToString:section]
2881 ) && [self visible];
2884 - (bool) isVisibleInSource:(Source *)source {
2885 return [self source] == source && [self visible];
2890 /* Section Class {{{ */
2891 @interface Section : NSObject {
2896 NSString *localized_;
2899 - (NSComparisonResult) compareByLocalized:(Section *)section;
2900 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2901 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2902 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2903 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2904 - (NSString *) name;
2911 - (void) addToCount;
2913 - (void) setCount:(size_t)count;
2914 - (NSString *) localized;
2918 @implementation Section
2922 if (localized_ != nil)
2923 [localized_ release];
2927 - (NSComparisonResult) compareByLocalized:(Section *)section {
2928 NSString *lhs(localized_);
2929 NSString *rhs([section localized]);
2931 /*if ([lhs length] != 0 && [rhs length] != 0) {
2932 unichar lhc = [lhs characterAtIndex:0];
2933 unichar rhc = [rhs characterAtIndex:0];
2935 if (isalpha(lhc) && !isalpha(rhc))
2936 return NSOrderedAscending;
2937 else if (!isalpha(lhc) && isalpha(rhc))
2938 return NSOrderedDescending;
2941 return [lhs compare:rhs options:LaxCompareOptions_];
2944 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2945 if ((self = [self initWithName:name localize:NO]) != nil) {
2946 if (localized != nil)
2947 localized_ = [localized retain];
2951 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2952 return [self initWithName:name row:0 localize:localize];
2955 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2956 if ((self = [super init]) != nil) {
2957 name_ = [name retain];
2961 localized_ = [LocalizeSection(name_) retain];
2965 /* XXX: localize the index thingees */
2966 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2967 if ((self = [super init]) != nil) {
2968 name_ = [[NSString stringWithCharacters:&index length:1] retain];
2974 - (NSString *) name {
2994 - (void) addToCount {
2998 - (void) setCount:(size_t)count {
3002 - (NSString *) localized {
3009 static NSString *Colon_;
3010 static NSString *Elision_;
3011 static NSString *Error_;
3012 static NSString *Warning_;
3014 /* Database Implementation {{{ */
3015 @implementation Database
3017 + (Database *) sharedInstance {
3018 static Database *instance;
3019 if (instance == nil)
3020 instance = [[Database alloc] init];
3028 - (void) releasePackages {
3029 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3030 CFArrayRemoveAllValues(packages_);
3034 // XXX: actually implement this thing
3036 [self releasePackages];
3037 apr_pool_destroy(pool_);
3038 NSRecycleZone(zone_);
3042 - (void) _readCydia:(NSNumber *)fd { _pooled
3043 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3044 std::istream is(&ib);
3047 static Pcre finish_r("^finish:([^:]*)$");
3049 while (std::getline(is, line)) {
3050 const char *data(line.c_str());
3051 size_t size = line.size();
3052 lprintf("C:%s\n", data);
3054 if (finish_r(data, size)) {
3055 NSString *finish = finish_r[1];
3056 int index = [Finishes_ indexOfObject:finish];
3057 if (index != INT_MAX && index > Finish_)
3065 - (void) _readStatus:(NSNumber *)fd { _pooled
3066 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3067 std::istream is(&ib);
3070 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3071 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3073 while (std::getline(is, line)) {
3074 const char *data(line.c_str());
3075 size_t size(line.size());
3076 lprintf("S:%s\n", data);
3078 if (conffile_r(data, size)) {
3079 [delegate_ setConfigurationData:conffile_r[1]];
3080 } else if (strncmp(data, "status: ", 8) == 0) {
3081 NSString *string = [NSString stringWithUTF8String:(data + 8)];
3082 [delegate_ setProgressTitle:string];
3083 } else if (pmstatus_r(data, size)) {
3084 std::string type([pmstatus_r[1] UTF8String]);
3085 NSString *id = pmstatus_r[2];
3087 float percent([pmstatus_r[3] floatValue]);
3088 [delegate_ setProgressPercent:(percent / 100)];
3090 NSString *string = pmstatus_r[4];
3092 if (type == "pmerror")
3093 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3094 withObject:[NSArray arrayWithObjects:string, id, nil]
3097 else if (type == "pmstatus") {
3098 [delegate_ setProgressTitle:string];
3099 } else if (type == "pmconffile")
3100 [delegate_ setConfigurationData:string];
3102 lprintf("E:unknown pmstatus\n");
3104 lprintf("E:unknown status\n");
3110 - (void) _readOutput:(NSNumber *)fd { _pooled
3111 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3112 std::istream is(&ib);
3115 while (std::getline(is, line)) {
3116 lprintf("O:%s\n", line.c_str());
3117 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
3127 - (Package *) packageWithName:(NSString *)name {
3128 @synchronized (self) {
3129 if (static_cast<pkgDepCache *>(cache_) == NULL)
3131 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3132 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3136 if ((self = [super init]) != nil) {
3143 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3144 apr_pool_create(&pool_, NULL);
3146 size_t capacity(MetaFile_->active_);
3152 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3156 _assert(pipe(fds) != -1);
3159 _config->Set("APT::Keep-Fds::", cydiafd_);
3160 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3163 detachNewThreadSelector:@selector(_readCydia:)
3165 withObject:[NSNumber numberWithInt:fds[0]]
3168 _assert(pipe(fds) != -1);
3172 detachNewThreadSelector:@selector(_readStatus:)
3174 withObject:[NSNumber numberWithInt:fds[0]]
3177 _assert(pipe(fds) != -1);
3178 _assert(dup2(fds[0], 0) != -1);
3179 _assert(close(fds[0]) != -1);
3181 input_ = fdopen(fds[1], "a");
3183 _assert(pipe(fds) != -1);
3184 _assert(dup2(fds[1], 1) != -1);
3185 _assert(close(fds[1]) != -1);
3188 detachNewThreadSelector:@selector(_readOutput:)
3190 withObject:[NSNumber numberWithInt:fds[0]]
3195 - (pkgCacheFile &) cache {
3199 - (pkgDepCache::Policy *) policy {
3203 - (pkgRecords *) records {
3207 - (pkgProblemResolver *) resolver {
3211 - (pkgAcquire &) fetcher {
3215 - (pkgSourceList &) list {
3219 - (NSArray *) packages {
3220 return (NSArray *) packages_;
3223 - (NSArray *) sources {
3224 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3225 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3226 [sources addObject:i->second];
3230 - (NSArray *) issues {
3231 if (cache_->BrokenCount() == 0)
3234 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3236 for (Package *package in [self packages]) {
3237 if (![package broken])
3239 pkgCache::PkgIterator pkg([package iterator]);
3241 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3242 [entry addObject:[package name]];
3243 [issues addObject:entry];
3245 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3249 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3250 pkgCache::DepIterator start;
3251 pkgCache::DepIterator end;
3252 dep.GlobOr(start, end); // ++dep
3254 if (!cache_->IsImportantDep(end))
3256 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3259 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3260 [entry addObject:failure];
3261 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3263 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3264 if (Package *package = [self packageWithName:name])
3265 name = [package name];
3266 [failure addObject:name];
3268 pkgCache::PkgIterator target(start.TargetPkg());
3269 if (target->ProvidesList != 0)
3270 [failure addObject:@"?"];
3272 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3274 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3275 else if (!cache_[target].CandidateVerIter(cache_).end())
3276 [failure addObject:@"-"];
3277 else if (target->ProvidesList == 0)
3278 [failure addObject:@"!"];
3280 [failure addObject:@"%"];
3284 if (start.TargetVer() != 0)
3285 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3296 - (bool) popErrorWithTitle:(NSString *)title {
3298 std::string message;
3300 while (!_error->empty()) {
3302 bool warning(!_error->PopMessage(error));
3306 size_t size(error.size());
3307 if (size == 0 || error[size - 1] != '\n')
3309 error.resize(size - 1);
3311 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3313 if (!message.empty())
3318 if (fatal && !message.empty())
3319 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3324 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3325 return [self popErrorWithTitle:title] || !success;
3328 - (void) reloadData { CYPoolStart() {
3329 @synchronized (self) {
3332 [self releasePackages];
3353 apr_pool_clear(pool_);
3355 NSRecycleZone(zone_);
3356 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3358 int chk(creat("/tmp/cydia.chk", 0644));
3362 NSString *title(UCLocalize("DATABASE"));
3365 if (!cache_.Open(progress_, true)) { pop:
3367 bool warning(!_error->PopMessage(error));
3368 lprintf("cache_.Open():[%s]\n", error.c_str());
3370 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3371 [delegate_ repairWithSelector:@selector(configure)];
3372 else if (error == "The package lists or status file could not be parsed or opened.")
3373 [delegate_ repairWithSelector:@selector(update)];
3374 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3375 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3376 // else if (error == "The list of sources could not be read.")
3378 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3387 unlink("/tmp/cydia.chk");
3389 now_ = [[NSDate date] timeIntervalSince1970];
3391 policy_ = new pkgDepCache::Policy();
3392 records_ = new pkgRecords(cache_);
3393 resolver_ = new pkgProblemResolver(cache_);
3394 fetcher_ = new pkgAcquire(&status_);
3397 list_ = new pkgSourceList();
3398 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3401 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3402 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3406 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3409 if (cache_->BrokenCount() != 0) {
3410 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3413 if (cache_->BrokenCount() != 0) {
3414 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3418 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3422 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3423 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3424 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3425 // XXX: this could be more intelligent
3426 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3427 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3429 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3434 /*std::vector<Package *> packages;
3435 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3436 [packages_ release];
3441 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3442 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3443 //packages.push_back(package);
3444 CFArrayAppendValue(packages_, [package retain]);
3448 /*if (packages.empty())
3449 packages_ = [[NSArray alloc] init];
3451 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3454 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3455 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3456 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3464 /*if (!packages.empty())
3465 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3466 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3468 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3470 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3472 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3476 size_t count(CFArrayGetCount(packages_));
3477 MetaFile_->active_ = count;
3479 for (size_t index(0); index != count; ++index)
3480 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3484 } } CYPoolEnd() _trace(); }
3487 @synchronized (self) {
3489 resolver_ = new pkgProblemResolver(cache_);
3491 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator) {
3492 if (!cache_[iterator].Keep()) {
3493 cache_->MarkKeep(iterator, false);
3494 cache_->SetReInstall(iterator, false);
3499 - (void) configure {
3500 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3502 system([dpkg UTF8String]);
3507 // XXX: I don't remember this condition
3512 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3514 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3516 if ([self popErrorWithTitle:title])
3520 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3523 public pkgArchiveCleaner
3526 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3531 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3538 fetcher_->Shutdown();
3540 pkgRecords records(cache_);
3542 lock_ = new FileFd();
3543 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3545 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3547 if ([self popErrorWithTitle:title])
3551 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3554 manager_ = (_system->CreatePM(cache_));
3555 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3562 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3564 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3566 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3568 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3569 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3572 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3577 [CydiaApp retainNetworkActivityIndicator];
3579 bool failed = false;
3580 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3581 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3583 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3586 std::string uri = (*item)->DescURI();
3587 std::string error = (*item)->ErrorText;
3589 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3592 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3593 withObject:[NSArray arrayWithObjects:
3594 [NSString stringWithUTF8String:error.c_str()],
3600 [CydiaApp releaseNetworkActivityIndicator];
3608 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3610 if (_error->PendingError()) {
3615 if (result == pkgPackageManager::Failed) {
3620 if (result != pkgPackageManager::Completed) {
3625 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3627 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3629 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3630 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3633 if (![before isEqualToArray:after])
3638 NSString *title(UCLocalize("UPGRADE"));
3639 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3645 [self updateWithStatus:status_];
3648 - (void) updateWithStatus:(Status &)status {
3649 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3650 NSString *title(UCLocalize("REFRESHING_DATA"));
3653 if (!list.ReadMainList())
3654 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3657 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3658 if ([self popErrorWithTitle:title])
3661 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3662 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */
3663 /* XXX: why the hell is an empty if statement a clang error? */ (void) 0;
3665 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3669 - (void) setDelegate:(id)delegate {
3670 delegate_ = delegate;
3671 status_.setDelegate(delegate);
3672 progress_.setDelegate(delegate);
3675 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3676 SourceMap::const_iterator i(sources_.find(file->ID));
3677 return i == sources_.end() ? nil : i->second;
3683 /* Confirmation Controller {{{ */
3684 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
3685 if (!iterator.end())
3686 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
3687 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
3689 pkgCache::PkgIterator package(dep.TargetPkg());
3692 if (strcmp(package.Name(), "mobilesubstrate") == 0)
3700 /* Web Scripting {{{ */
3701 @interface CydiaObject : NSObject {
3703 _transient id delegate_;
3706 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3709 @implementation CydiaObject
3712 [indirect_ release];
3716 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3717 if ((self = [super init]) != nil) {
3718 indirect_ = [indirect retain];
3722 - (void) setDelegate:(id)delegate {
3723 delegate_ = delegate;
3726 + (NSArray *) _attributeKeys {
3727 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3730 - (NSArray *) attributeKeys {
3731 return [[self class] _attributeKeys];
3734 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3735 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3738 - (NSString *) device {
3739 return [[UIDevice currentDevice] uniqueIdentifier];
3742 #if 0 // XXX: implement!
3743 - (NSString *) mac {
3744 if (![indirect_ promptForSensitive:@"Mac Address"])
3748 - (NSString *) serial {
3749 if (![indirect_ promptForSensitive:@"Serial #"])
3753 - (NSString *) firewire {
3754 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3758 - (NSString *) imei {
3759 if (![indirect_ promptForSensitive:@"IMEI"])
3764 + (NSString *) webScriptNameForSelector:(SEL)selector {
3765 if (selector == @selector(close))
3767 else if (selector == @selector(getInstalledPackages))
3768 return @"getInstalledPackages";
3769 else if (selector == @selector(getPackageById:))
3770 return @"getPackageById";
3771 else if (selector == @selector(installPackages:))
3772 return @"installPackages";
3773 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3774 return @"setButtonImage";
3775 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3776 return @"setButtonTitle";
3777 else if (selector == @selector(setPopupHook:))
3778 return @"setPopupHook";
3779 else if (selector == @selector(setSpecial:))
3780 return @"setSpecial";
3781 else if (selector == @selector(setToken:))
3783 else if (selector == @selector(setViewportWidth:))
3784 return @"setViewportWidth";
3785 else if (selector == @selector(supports:))
3787 else if (selector == @selector(stringWithFormat:arguments:))
3789 else if (selector == @selector(localizedStringForKey:value:table:))
3791 else if (selector == @selector(du:))
3793 else if (selector == @selector(statfs:))
3799 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3800 return [self webScriptNameForSelector:selector] == nil;
3803 - (BOOL) supports:(NSString *)feature {
3804 return [feature isEqualToString:@"window.open"];
3807 - (NSArray *) getInstalledPackages {
3808 NSArray *packages([[Database sharedInstance] packages]);
3809 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
3810 for (Package *package in packages)
3811 if ([package installed] != nil)
3812 [installed addObject:package];
3816 - (Package *) getPackageById:(NSString *)id {
3817 Package *package([[Database sharedInstance] packageWithName:id]);
3822 - (NSArray *) statfs:(NSString *)path {
3825 if (path == nil || statfs([path UTF8String], &stat) == -1)
3828 return [NSArray arrayWithObjects:
3829 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3830 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3831 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3835 - (NSNumber *) du:(NSString *)path {
3836 NSNumber *value(nil);
3839 _assert(pipe(fds) != -1);
3841 pid_t pid(ExecFork());
3843 _assert(dup2(fds[1], 1) != -1);
3844 _assert(close(fds[0]) != -1);
3845 _assert(close(fds[1]) != -1);
3846 /* XXX: this should probably not use du */
3847 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3852 _assert(close(fds[1]) != -1);
3854 if (FILE *du = fdopen(fds[0], "r")) {
3856 while (fgets(line, sizeof(line), du) != NULL) {
3857 size_t length(strlen(line));
3858 while (length != 0 && line[length - 1] == '\n')
3859 line[--length] = '\0';
3860 if (char *tab = strchr(line, '\t')) {
3862 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3867 } else _assert(close(fds[0]));
3871 if (waitpid(pid, &status, 0) == -1)
3874 else _assert(false);
3883 - (void) installPackages:(NSArray *)packages {
3884 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
3887 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3888 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3891 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3892 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3895 - (void) setSpecial:(id)function {
3896 [indirect_ setSpecial:function];
3899 - (void) setToken:(NSString *)token {
3902 Token_ = [token retain];
3904 [Metadata_ setObject:Token_ forKey:@"Token"];
3908 - (void) setPopupHook:(id)function {
3909 [indirect_ setPopupHook:function];
3912 - (void) setViewportWidth:(float)width {
3913 [indirect_ setViewportWidth:width];
3916 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3917 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3918 unsigned count([arguments count]);
3920 for (unsigned i(0); i != count; ++i)
3921 values[i] = [arguments objectAtIndex:i];
3922 return [[[NSString alloc] initWithFormat:format arguments:*(reinterpret_cast<va_list *>(&values))] autorelease];
3925 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3926 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3928 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3930 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3936 /* @ Loading... Indicator {{{ */
3937 @interface CYLoadingIndicator : UIView {
3938 UIActivityIndicatorView *spinner_;
3943 @property (readonly, nonatomic) UILabel *label;
3944 @property (readonly, nonatomic) UIActivityIndicatorView *activityIndicatorView;
3948 @implementation CYLoadingIndicator
3950 - (id)initWithFrame:(CGRect)frame {
3951 if ((self = [super initWithFrame:frame])) {
3952 container_ = [[[UIView alloc] init] autorelease];
3953 [container_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
3955 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
3956 [spinner_ startAnimating];
3957 [container_ addSubview:spinner_];
3959 label_ = [[[UILabel alloc] init] autorelease];
3960 [label_ setFont:[UIFont boldSystemFontOfSize:15.0f]];
3961 [label_ setBackgroundColor:[UIColor clearColor]];
3962 [label_ setTextColor:[UIColor blackColor]];
3963 [label_ setShadowColor:[UIColor whiteColor]];
3964 [label_ setShadowOffset:CGSizeMake(0, 1)];
3965 [label_ setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
3966 [container_ addSubview:label_];
3968 CGSize viewsize = frame.size;
3969 CGSize spinnersize = [spinner_ bounds].size;
3970 CGSize textsize = [[label_ text] sizeWithFont:[label_ font]];
3971 float bothwidth = spinnersize.width + textsize.width + 5.0f;
3973 CGRect containrect = {
3974 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
3975 CGSizeMake(bothwidth, spinnersize.height)
3978 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
3986 [container_ setFrame:containrect];
3987 [spinner_ setFrame:spinrect];
3988 [label_ setFrame:textrect];
3989 [self addSubview:container_];
3995 - (UILabel *)label { return label_; }
3996 - (UIActivityIndicatorView *)activityIndicatorView { return spinner_; }
4001 /* Cydia Browser Controller {{{ */
4002 @interface CYBrowserController : BrowserController {
4003 CydiaObject *cydia_;
4008 @implementation CYBrowserController
4015 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
4018 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4019 [super webView:view didClearWindowObject:window forFrame:frame];
4021 WebDataSource *source([frame dataSource]);
4022 NSURLResponse *response([source response]);
4023 NSURL *url([response URL]);
4024 NSString *scheme([url scheme]);
4026 NSHTTPURLResponse *http;
4027 if (scheme != nil && ([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"]))
4028 http = (NSHTTPURLResponse *) response;
4032 NSDictionary *headers([http allHeaderFields]);
4033 NSString *host([url host]);
4034 [self setHeaders:headers forHost:host];
4037 [host isEqualToString:@"cydia.saurik.com"] ||
4038 [host hasSuffix:@".cydia.saurik.com"] ||
4039 [scheme isEqualToString:@"file"]
4041 [window setValue:cydia_ forKey:@"cydia"];
4044 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
4045 if (System_ != NULL)
4046 [request setValue:System_ forHTTPHeaderField:@"X-System"];
4047 if (Machine_ != NULL)
4048 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4050 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4052 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
4055 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4056 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4057 [self _setMoreHeaders:copy];
4061 - (void) setDelegate:(id)delegate {
4062 [super setDelegate:delegate];
4063 [cydia_ setDelegate:delegate];
4067 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
4068 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
4070 WebView *webview([[webview_ _documentView] webView]);
4072 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
4074 NSString *application = package == nil ? @"Cydia" : [NSString
4075 stringWithFormat:@"Cydia/%@",
4080 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4082 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4083 if (Product_ != nil)
4084 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4086 [webview setApplicationNameForUserAgent:application];
4093 /* Confirmation {{{ */
4094 @protocol ConfirmationControllerDelegate
4095 - (void) cancelAndClear:(bool)clear;
4096 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4100 @interface ConfirmationController : CYBrowserController {
4101 _transient Database *database_;
4102 UIAlertView *essential_;
4109 - (id) initWithDatabase:(Database *)database;
4113 @implementation ConfirmationController
4120 if (essential_ != nil)
4121 [essential_ release];
4125 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4126 NSString *context([alert context]);
4128 if ([context isEqualToString:@"remove"]) {
4129 if (button == [alert cancelButtonIndex]) {
4130 [self dismissModalViewControllerAnimated:YES];
4131 } else if (button == [alert firstOtherButtonIndex]) {
4134 [delegate_ confirmWithNavigationController:[self navigationController]];
4137 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4138 } else if ([context isEqualToString:@"unable"]) {
4139 [self dismissModalViewControllerAnimated:YES];
4140 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4142 [super alertView:alert clickedButtonAtIndex:button];
4146 - (void) _doContinue {
4147 [self dismissModalViewControllerAnimated:YES];
4148 [delegate_ cancelAndClear:NO];
4151 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4152 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4156 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4157 [super webView:view didClearWindowObject:window forFrame:frame];
4158 [window setValue:changes_ forKey:@"changes"];
4159 [window setValue:issues_ forKey:@"issues"];
4160 [window setValue:sizes_ forKey:@"sizes"];
4161 [window setValue:self forKey:@"queue"];
4164 - (id) initWithDatabase:(Database *)database {
4165 if ((self = [super init]) != nil) {
4166 database_ = database;
4168 [[self navigationItem] setTitle:UCLocalize("CONFIRM")];
4170 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
4171 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
4172 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
4173 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
4174 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
4178 pkgDepCache::Policy *policy([database_ policy]);
4180 pkgCacheFile &cache([database_ cache]);
4181 NSArray *packages = [database_ packages];
4182 for (Package *package in packages) {
4183 pkgCache::PkgIterator iterator = [package iterator];
4184 pkgDepCache::StateCache &state(cache[iterator]);
4186 NSString *name([package name]);
4188 if (state.NewInstall())
4189 [installing addObject:name];
4190 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4191 [reinstalling addObject:name];
4192 else if (state.Upgrade())
4193 [upgrading addObject:name];
4194 else if (state.Downgrade())
4195 [downgrading addObject:name];
4196 else if (state.Delete()) {
4197 if ([package essential])
4199 [removing addObject:name];
4202 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4203 substrate_ |= DepSubstrate(iterator.CurrentVer());
4208 else if (Advanced_) {
4209 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4211 essential_ = [[UIAlertView alloc]
4212 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4213 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4215 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4216 otherButtonTitles:[NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")], nil
4219 [essential_ setContext:@"remove"];
4221 essential_ = [[UIAlertView alloc]
4222 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4223 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4225 cancelButtonTitle:UCLocalize("OKAY")
4226 otherButtonTitles:nil
4229 [essential_ setContext:@"unable"];
4232 changes_ = [[NSArray alloc] initWithObjects:
4240 issues_ = [database_ issues];
4242 issues_ = [issues_ retain];
4244 sizes_ = [[NSArray alloc] initWithObjects:
4245 SizeString([database_ fetcher].FetchNeeded()),
4246 SizeString([database_ fetcher].PartialPresent()),
4249 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
4251 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
4252 initWithTitle:UCLocalize("CANCEL")
4253 // OLD: [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")]
4254 style:UIBarButtonItemStylePlain
4256 action:@selector(cancelButtonClicked)
4261 - (void) applyRightButton {
4262 #if !AlwaysReload && !IgnoreInstall
4263 if (issues_ == nil && ![self isLoading])
4264 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4265 initWithTitle:UCLocalize("CONFIRM")
4266 style:UIBarButtonItemStylePlain
4268 action:@selector(confirmButtonClicked)
4271 [super applyRightButton];
4273 [[self navigationItem] setRightBarButtonItem:nil];
4277 - (void) cancelButtonClicked {
4278 [self dismissModalViewControllerAnimated:YES];
4279 [delegate_ cancelAndClear:YES];
4283 - (void) confirmButtonClicked {
4287 if (essential_ != nil)
4292 [delegate_ confirmWithNavigationController:[self navigationController]];
4300 /* Progress Data {{{ */
4301 @interface ProgressData : NSObject {
4303 // XXX: should these really both be _transient?
4304 _transient id target_;
4305 _transient id object_;
4308 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4315 @implementation ProgressData
4317 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4318 if ((self = [super init]) != nil) {
4319 selector_ = selector;
4339 /* Progress Controller {{{ */
4340 @interface ProgressController : CYViewController <
4341 ConfigurationDelegate,
4344 _transient Database *database_;
4345 UIProgressBar *progress_;
4346 UITextView *output_;
4347 UITextLabel *status_;
4348 UIPushButton *close_;
4350 SHA1SumValue springlist_;
4351 SHA1SumValue notifyconf_;
4355 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4357 - (void) _retachThread;
4358 - (void) _detachNewThreadData:(ProgressData *)data;
4359 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4365 @protocol ProgressControllerDelegate
4366 - (void) progressControllerIsComplete:(ProgressController *)sender;
4369 @implementation ProgressController
4372 [database_ setDelegate:nil];
4373 [progress_ release];
4382 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4383 if ((self = [super init]) != nil) {
4384 database_ = database;
4385 [database_ setDelegate:self];
4386 delegate_ = delegate;
4388 [[self view] setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
4390 progress_ = [[UIProgressBar alloc] init];
4391 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4392 [progress_ setStyle:0];
4394 status_ = [[UITextLabel alloc] init];
4395 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4396 [status_ setColor:[UIColor whiteColor]];
4397 [status_ setBackgroundColor:[UIColor clearColor]];
4398 [status_ setCentersHorizontally:YES];
4399 //[status_ setFont:font];
4401 output_ = [[UITextView alloc] init];
4403 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4404 //[output_ setTextFont:@"Courier New"];
4405 [output_ setFont:[[output_ font] fontWithSize:12]];
4406 [output_ setTextColor:[UIColor whiteColor]];
4407 [output_ setBackgroundColor:[UIColor clearColor]];
4408 [output_ setMarginTop:0];
4409 [output_ setAllowsRubberBanding:YES];
4410 [output_ setEditable:NO];
4411 [[self view] addSubview:output_];
4413 close_ = [[UIPushButton alloc] init];
4414 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4415 [close_ setAutosizesToFit:NO];
4416 [close_ setDrawsShadow:YES];
4417 [close_ setStretchBackground:YES];
4418 [close_ setEnabled:YES];
4419 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
4420 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4421 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4422 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4426 - (void) positionViews {
4427 CGRect bounds = [[self view] bounds];
4428 CGSize prgsize = [UIProgressBar defaultSize];
4431 (bounds.size.width - prgsize.width) / 2,
4432 bounds.size.height - prgsize.height - 20
4435 float closewidth = std::min(bounds.size.width - 20, 300.0f);
4437 [progress_ setFrame:prgrect];
4438 [status_ setFrame:CGRectMake(
4440 bounds.size.height - prgsize.height - 50,
4441 bounds.size.width - 20,
4444 [output_ setFrame:CGRectMake(
4447 bounds.size.width - 20,
4448 bounds.size.height - 62
4450 [close_ setFrame:CGRectMake(
4451 (bounds.size.width - closewidth) / 2,
4452 bounds.size.height - prgsize.height - 50,
4458 - (void) viewWillAppear:(BOOL)animated {
4459 [super viewDidAppear:animated];
4460 [[self navigationItem] setHidesBackButton:YES];
4461 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4463 [self positionViews];
4466 - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4467 [self positionViews];
4470 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4471 NSString *context([alert context]);
4473 if ([context isEqualToString:@"conffile"]) {
4474 FILE *input = [database_ input];
4475 if (button == [alert cancelButtonIndex])
4476 fprintf(input, "N\n");
4477 else if (button == [alert firstOtherButtonIndex])
4478 fprintf(input, "Y\n");
4483 - (void) closeButtonPushed {
4486 UpdateExternalStatus(0);
4490 [self dismissModalViewControllerAnimated:YES];
4494 [delegate_ terminateWithSuccess];
4495 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4496 [delegate_ suspendWithAnimation:YES];
4498 [delegate_ suspend];*/
4510 system("/usr/bin/sbreload");
4516 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
4517 SBReboot(SBSSpringBoardServerPort());
4519 reboot2(RB_AUTOBOOT);
4524 - (void) _retachThread {
4525 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
4527 [[self view] addSubview:close_];
4528 [progress_ removeFromSuperview];
4529 [status_ removeFromSuperview];
4531 [database_ popErrorWithTitle:title_];
4532 [delegate_ progressControllerIsComplete:self];
4536 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4539 MMap mmap(file, MMap::ReadOnly);
4541 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4542 if (!(notifyconf_ == sha1.Result()))
4549 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4552 MMap mmap(file, MMap::ReadOnly);
4554 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4555 if (!(springlist_ == sha1.Result()))
4561 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
4562 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4563 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4564 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4565 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4569 system("su -c /usr/bin/uicache mobile");
4572 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
4574 [delegate_ setStatusBarShowsProgress:NO];
4577 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4578 [[data target] performSelector:[data selector] withObject:[data object]];
4579 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4582 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4583 UpdateExternalStatus(1);
4590 title_ = [title retain];
4592 [[self navigationItem] setTitle:title_];
4594 [status_ setText:nil];
4595 [output_ setText:@""];
4596 [progress_ setProgress:0];
4598 [close_ removeFromSuperview];
4599 [[self view] addSubview:progress_];
4600 [[self view] addSubview:status_];
4602 [delegate_ setStatusBarShowsProgress:YES];
4607 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4610 MMap mmap(file, MMap::ReadOnly);
4612 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4613 notifyconf_ = sha1.Result();
4619 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4622 MMap mmap(file, MMap::ReadOnly);
4624 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4625 springlist_ = sha1.Result();
4630 detachNewThreadSelector:@selector(_detachNewThreadData:)
4632 withObject:[[[ProgressData alloc]
4633 initWithSelector:selector
4640 - (void) repairWithSelector:(SEL)selector {
4642 detachNewThreadSelector:selector
4645 title:UCLocalize("REPAIRING")
4649 - (void) setConfigurationData:(NSString *)data {
4651 performSelectorOnMainThread:@selector(_setConfigurationData:)
4657 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4658 CYActionSheet *sheet([[[CYActionSheet alloc]
4660 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4661 defaultButtonIndex:0
4664 [sheet setMessage:error];
4665 [sheet yieldToPopupAlertAnimated:YES];
4669 - (void) setProgressTitle:(NSString *)title {
4671 performSelectorOnMainThread:@selector(_setProgressTitle:)
4677 - (void) setProgressPercent:(float)percent {
4679 performSelectorOnMainThread:@selector(_setProgressPercent:)
4680 withObject:[NSNumber numberWithFloat:percent]
4685 - (void) startProgress {
4688 - (void) addProgressOutput:(NSString *)output {
4690 performSelectorOnMainThread:@selector(_addProgressOutput:)
4696 - (bool) isCancelling:(size_t)received {
4700 - (void) _setConfigurationData:(NSString *)data {
4701 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4703 if (!conffile_r(data)) {
4704 lprintf("E:invalid conffile\n");
4708 NSString *ofile = conffile_r[1];
4709 //NSString *nfile = conffile_r[2];
4711 UIAlertView *alert = [[[UIAlertView alloc]
4712 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4713 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
4715 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
4716 otherButtonTitles:UCLocalize("ACCEPT_NEW_COPY"),
4717 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4721 [alert setContext:@"conffile"];
4725 - (void) _setProgressTitle:(NSString *)title {
4726 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4727 for (size_t i(0), e([words count]); i != e; ++i) {
4728 NSString *word([words objectAtIndex:i]);
4729 if (Package *package = [database_ packageWithName:word])
4730 [words replaceObjectAtIndex:i withObject:[package name]];
4733 [status_ setText:[words componentsJoinedByString:@" "]];
4736 - (void) _setProgressPercent:(NSNumber *)percent {
4737 [progress_ setProgress:[percent floatValue]];
4740 - (void) _addProgressOutput:(NSString *)output {
4741 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4742 CGSize size = [output_ contentSize];
4743 CGPoint offset = [output_ contentOffset];
4744 if (size.height - offset.y < [output_ frame].size.height + 20.f) {
4745 CGRect rect = {{0, size.height-1}, {size.width, 1}};
4746 [output_ scrollRectToVisible:rect animated:YES];
4750 - (BOOL) isRunning {
4757 /* Cell Content View {{{ */
4758 @protocol ContentDelegate
4759 - (void) drawContentRect:(CGRect)rect;
4762 @interface ContentView : UIView {
4763 _transient id<ContentDelegate> delegate_;
4768 @implementation ContentView
4770 - (id) initWithFrame:(CGRect)frame {
4771 if ((self = [super initWithFrame:frame]) != nil) {
4772 [self setNeedsDisplayOnBoundsChange:YES];
4776 - (void) setDelegate:(id<ContentDelegate>)delegate {
4777 delegate_ = delegate;
4780 - (void) drawRect:(CGRect)rect {
4781 [super drawRect:rect];
4782 [delegate_ drawContentRect:rect];
4787 /* Cydia TableView Cell {{{ */
4788 @interface CYTableViewCell : UITableViewCell {
4789 ContentView *content_;
4795 @implementation CYTableViewCell
4802 - (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
4803 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
4805 if (view == content_) {
4806 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
4807 highlighted_ = highlighted;
4810 [super _updateHighlightColorsForView:view highlighted:highlighted];
4813 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
4814 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
4815 highlighted_ = selected;
4817 [super setSelected:selected animated:animated];
4818 [content_ setNeedsDisplay];
4823 /* Package Cell {{{ */
4824 @interface PackageCell : CYTableViewCell <
4829 NSString *description_;
4837 - (PackageCell *) init;
4838 - (void) setPackage:(Package *)package;
4840 + (int) heightForPackage:(Package *)package;
4841 - (void) drawContentRect:(CGRect)rect;
4845 @implementation PackageCell
4847 - (void) clearPackage {
4858 if (description_ != nil) {
4859 [description_ release];
4863 if (source_ != nil) {
4868 if (badge_ != nil) {
4873 if (placard_ != nil) {
4883 [self clearPackage];
4887 - (PackageCell *) init {
4888 CGRect frame(CGRectMake(0, 0, 320, 74));
4889 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4890 UIView *content([self contentView]);
4891 CGRect bounds([content bounds]);
4893 content_ = [[ContentView alloc] initWithFrame:bounds];
4894 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4895 [content addSubview:content_];
4897 [content_ setDelegate:self];
4898 [content_ setOpaque:YES];
4902 - (void) _setBackgroundColor {
4904 if (NSString *mode = [package_ mode]) {
4905 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4906 color = remove ? RemovingColor_ : InstallingColor_;
4908 color = [UIColor whiteColor];
4910 [content_ setBackgroundColor:color];
4911 [self setNeedsDisplay];
4914 - (void) setPackage:(Package *)package {
4915 [self clearPackage];
4918 Source *source = [package source];
4920 icon_ = [[package icon] retain];
4921 name_ = [[package name] retain];
4924 description_ = [package longDescription];
4925 if (description_ == nil)
4926 description_ = [package shortDescription];
4927 if (description_ != nil)
4928 description_ = [description_ retain];
4930 commercial_ = [package isCommercial];
4932 package_ = [package retain];
4934 NSString *label = nil;
4935 bool trusted = false;
4937 if (source != nil) {
4938 label = [source label];
4939 trusted = [source trusted];
4940 } else if ([[package id] isEqualToString:@"firmware"])
4941 label = UCLocalize("APPLE");
4943 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
4945 NSString *from(label);
4947 NSString *section = [package simpleSection];
4948 if (section != nil && ![section isEqualToString:label]) {
4949 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
4950 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
4953 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
4954 source_ = [from retain];
4956 if (NSString *purpose = [package primaryPurpose])
4957 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
4958 badge_ = [badge_ retain];
4960 if ([package installed] != nil)
4961 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/installed.png", App_]]) != nil)
4962 placard_ = [placard_ retain];
4964 [self _setBackgroundColor];
4965 [content_ setNeedsDisplay];
4968 - (void) drawContentRect:(CGRect)rect {
4969 bool highlighted(highlighted_);
4970 float width([self bounds].size.width);
4973 CGContextRef context(UIGraphicsGetCurrentContext());
4974 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
4975 CGContextFillRect(context, rect);
4980 rect.size = [icon_ size];
4982 rect.size.width /= 2;
4983 rect.size.height /= 2;
4985 rect.origin.x = 25 - rect.size.width / 2;
4986 rect.origin.y = 25 - rect.size.height / 2;
4988 [icon_ drawInRect:rect];
4991 if (badge_ != nil) {
4993 rect.size = [badge_ size];
4995 rect.size.width /= 2;
4996 rect.size.height /= 2;
4998 rect.origin.x = 36 - rect.size.width / 2;
4999 rect.origin.y = 36 - rect.size.height / 2;
5001 [badge_ drawInRect:rect];
5008 UISetColor(commercial_ ? Purple_ : Black_);
5009 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5010 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5013 UISetColor(commercial_ ? Purplish_ : Gray_);
5014 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5016 if (placard_ != nil)
5017 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5020 + (int) heightForPackage:(Package *)package {
5026 /* Section Cell {{{ */
5027 @interface SectionCell : CYTableViewCell <
5039 - (void) setSection:(Section *)section editing:(BOOL)editing;
5043 @implementation SectionCell
5045 - (void) clearSection {
5046 if (basic_ != nil) {
5051 if (section_ != nil) {
5061 if (count_ != nil) {
5068 [self clearSection];
5074 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5075 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5076 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
5077 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
5078 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5080 UIView *content([self contentView]);
5081 CGRect bounds([content bounds]);
5083 content_ = [[ContentView alloc] initWithFrame:bounds];
5084 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5085 [content addSubview:content_];
5086 [content_ setBackgroundColor:[UIColor whiteColor]];
5088 [content_ setDelegate:self];
5092 - (void) onSwitch:(id)sender {
5093 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5094 if (metadata == nil) {
5095 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5096 [Sections_ setObject:metadata forKey:basic_];
5099 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5103 - (void) setSection:(Section *)section editing:(BOOL)editing {
5104 if (editing != editing_) {
5106 [switch_ removeFromSuperview];
5108 [self addSubview:switch_];
5112 [self clearSection];
5114 if (section == nil) {
5115 name_ = [UCLocalize("ALL_PACKAGES") retain];
5118 basic_ = [section name];
5120 basic_ = [basic_ retain];
5122 section_ = [section localized];
5123 if (section_ != nil)
5124 section_ = [section_ retain];
5126 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
5127 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
5130 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5133 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5134 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5136 [content_ setNeedsDisplay];
5139 - (void) setFrame:(CGRect)frame {
5140 [super setFrame:frame];
5142 CGRect rect([switch_ frame]);
5143 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5146 - (void) drawContentRect:(CGRect)rect {
5147 bool highlighted(highlighted_);
5149 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5154 float width(rect.size.width);
5160 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5162 CGSize size = [count_ sizeWithFont:Font14_];
5166 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5172 /* File Table {{{ */
5173 @interface FileTable : CYViewController <
5174 UITableViewDataSource,
5177 _transient Database *database_;
5180 NSMutableArray *files_;
5184 - (id) initWithDatabase:(Database *)database;
5185 - (void) setPackage:(Package *)package;
5189 @implementation FileTable
5192 if (package_ != nil)
5201 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5202 return files_ == nil ? 0 : [files_ count];
5205 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5209 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5210 static NSString *reuseIdentifier = @"Cell";
5212 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5214 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5215 [cell setFont:[UIFont systemFontOfSize:16]];
5217 [cell setText:[files_ objectAtIndex:indexPath.row]];
5218 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5223 - (id) initWithDatabase:(Database *)database {
5224 if ((self = [super init]) != nil) {
5225 database_ = database;
5227 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5229 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5231 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5232 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5233 [list_ setRowHeight:24.0f];
5234 [[self view] addSubview:list_];
5236 [list_ setDataSource:self];
5237 [list_ setDelegate:self];
5241 - (void) setPackage:(Package *)package {
5242 if (package_ != nil) {
5243 [package_ autorelease];
5252 [files_ removeAllObjects];
5254 if (package != nil) {
5255 package_ = [package retain];
5256 name_ = [[package id] retain];
5258 if (NSArray *files = [package files])
5259 [files_ addObjectsFromArray:files];
5261 if ([files_ count] != 0) {
5262 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5263 [files_ removeObjectAtIndex:0];
5264 [files_ sortUsingSelector:@selector(compareByPath:)];
5266 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5267 [stack addObject:@"/"];
5269 for (int i(0), e([files_ count]); i != e; ++i) {
5270 NSString *file = [files_ objectAtIndex:i];
5271 while (![file hasPrefix:[stack lastObject]])
5272 [stack removeLastObject];
5273 NSString *directory = [stack lastObject];
5274 [stack addObject:[file stringByAppendingString:@"/"]];
5275 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5276 ([stack count] - 2) * 3, "",
5277 [file substringFromIndex:[directory length]]
5286 - (void) reloadData {
5287 [self setPackage:[database_ packageWithName:name_]];
5292 /* Package Controller {{{ */
5293 @interface PackageController : CYBrowserController <
5294 UIActionSheetDelegate
5296 _transient Database *database_;
5300 NSMutableArray *buttons_;
5301 UIBarButtonItem *button_;
5304 - (id) initWithDatabase:(Database *)database;
5305 - (void) setPackage:(Package *)package;
5309 @implementation PackageController
5312 if (package_ != nil)
5326 if ([self retainCount] == 1)
5327 [delegate_ setPackageController:self];
5331 /* XXX: this is not safe at all... localization of /fail/ */
5332 - (void) _clickButtonWithName:(NSString *)name {
5333 if ([name isEqualToString:UCLocalize("CLEAR")])
5334 [delegate_ clearPackage:package_];
5335 else if ([name isEqualToString:UCLocalize("INSTALL")])
5336 [delegate_ installPackage:package_];
5337 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5338 [delegate_ installPackage:package_];
5339 else if ([name isEqualToString:UCLocalize("REMOVE")])
5340 [delegate_ removePackage:package_];
5341 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5342 [delegate_ installPackage:package_];
5343 else _assert(false);
5346 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5347 NSString *context([sheet context]);
5349 if ([context isEqualToString:@"modify"]) {
5350 if (button != [sheet cancelButtonIndex]) {
5351 NSString *buttonName = [buttons_ objectAtIndex:button];
5352 [self _clickButtonWithName:buttonName];
5355 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5359 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5360 [super webView:view didClearWindowObject:window forFrame:frame];
5361 [window setValue:package_ forKey:@"package"];
5364 - (bool) _allowJavaScriptPanel {
5369 - (void) _customButtonClicked {
5370 int count([buttons_ count]);
5375 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5377 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5378 [buttons addObjectsFromArray:buttons_];
5380 UIActionSheet *sheet = [[[UIActionSheet alloc]
5383 cancelButtonTitle:nil
5384 destructiveButtonTitle:nil
5385 otherButtonTitles:nil
5388 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5390 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5391 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5393 [sheet setContext:@"modify"];
5395 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5399 // We don't want to allow non-commercial packages to do custom things to the install button,
5400 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5401 - (void) customButtonClicked {
5403 [super customButtonClicked];
5405 [self _customButtonClicked];
5408 - (void) reloadButtonClicked {
5409 // Don't reload a commerical package by tapping the loading button,
5410 // but if it's not an Install button, we should forward it on.
5411 if (![package_ uninstalled])
5412 [self _customButtonClicked];
5415 - (void) applyLoadingTitle {
5416 // Don't show "Loading" as the title. Ever.
5419 - (UIBarButtonItem *) rightButton {
5424 - (id) initWithDatabase:(Database *)database {
5425 if ((self = [super init]) != nil) {
5426 database_ = database;
5427 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5428 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
5432 - (void) setPackage:(Package *)package {
5433 if (package_ != nil) {
5434 [package_ autorelease];
5443 [buttons_ removeAllObjects];
5445 if (package != nil) {
5448 package_ = [package retain];
5449 name_ = [[package id] retain];
5450 commercial_ = [package isCommercial];
5452 if ([package_ mode] != nil)
5453 [buttons_ addObject:UCLocalize("CLEAR")];
5454 if ([package_ source] == nil);
5455 else if ([package_ upgradableAndEssential:NO])
5456 [buttons_ addObject:UCLocalize("UPGRADE")];
5457 else if ([package_ uninstalled])
5458 [buttons_ addObject:UCLocalize("INSTALL")];
5460 [buttons_ addObject:UCLocalize("REINSTALL")];
5461 if (![package_ uninstalled])
5462 [buttons_ addObject:UCLocalize("REMOVE")];
5469 switch ([buttons_ count]) {
5470 case 0: title = nil; break;
5471 case 1: title = [buttons_ objectAtIndex:0]; break;
5472 default: title = UCLocalize("MODIFY"); break;
5475 button_ = [[UIBarButtonItem alloc]
5477 style:UIBarButtonItemStylePlain
5479 action:@selector(customButtonClicked)
5485 - (bool) isLoading {
5486 return commercial_ ? [super isLoading] : false;
5489 - (void) reloadData {
5490 [self setPackage:[database_ packageWithName:name_]];
5495 /* Package Table {{{ */
5496 @interface PackageTable : UIView <
5497 UITableViewDataSource,
5500 _transient Database *database_;
5502 NSMutableArray *packages_;
5503 NSMutableArray *sections_;
5505 NSMutableArray *index_;
5506 NSMutableDictionary *indices_;
5507 // XXX: this target_ seems to be delegate_. :(
5508 _transient id target_;
5510 // XXX: why do we even have this delegate_?
5511 _transient id delegate_;
5514 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action;
5516 - (void) setDelegate:(id)delegate;
5518 - (void) reloadData;
5519 - (void) resetCursor;
5521 - (UITableView *) list;
5523 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5525 - (void) deselectWithAnimation:(BOOL)animated;
5529 @implementation PackageTable
5532 [packages_ release];
5533 [sections_ release];
5541 + (BOOL) hasIndexedCollation {
5542 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
5545 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5546 NSInteger count([sections_ count]);
5547 return count == 0 ? 1 : count;
5550 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5551 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
5553 return [[sections_ objectAtIndex:section] name];
5556 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5557 if ([sections_ count] == 0)
5559 return [[sections_ objectAtIndex:section] count];
5562 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5563 @synchronized (database_) {
5564 if ([database_ era] != era_)
5567 Section *section([sections_ objectAtIndex:[path section]]);
5568 NSInteger row([path row]);
5569 Package *package([packages_ objectAtIndex:([section row] + row)]);
5570 return [[package retain] autorelease];
5573 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5574 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5576 cell = [[[PackageCell alloc] init] autorelease];
5577 [cell setPackage:[self packageAtIndexPath:path]];
5581 - (void) deselectWithAnimation:(BOOL)animated {
5582 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5585 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
5586 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
5589 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5590 Package *package([self packageAtIndexPath:path]);
5591 package = [database_ packageWithName:[package id]];
5592 [target_ performSelector:action_ withObject:package];
5596 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5597 // XXX: is 20 the most optimal number here?
5598 return [packages_ count] > 20 ? index_ : nil;
5601 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5602 if ([[self class] hasIndexedCollation]) {
5603 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
5609 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action {
5610 if ((self = [super initWithFrame:frame]) != nil) {
5611 database_ = database;
5616 index_ = [[self class] hasIndexedCollation]
5617 ? [[[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles] retain]
5618 : [[NSMutableArray alloc] initWithCapacity:32];
5619 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5621 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5622 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5624 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
5625 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5626 [list_ setRowHeight:73.0f];
5627 [self addSubview:list_];
5629 [list_ setDataSource:self];
5630 [list_ setDelegate:self];
5634 - (void) setDelegate:(id)delegate {
5635 delegate_ = delegate;
5638 - (bool) hasPackage:(Package *)package {
5642 - (void) reloadData {
5643 era_ = [database_ era];
5644 NSArray *packages = [database_ packages];
5646 [packages_ removeAllObjects];
5647 [sections_ removeAllObjects];
5649 _profile(PackageTable$reloadData$Filter)
5650 for (Package *package in packages)
5651 if ([self hasPackage:package])
5652 [packages_ addObject:package];
5655 [indices_ removeAllObjects];
5657 Section *section = nil;
5659 if ([[self class] hasIndexedCollation]) {
5660 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
5661 NSArray *titles = [collation sectionIndexTitles];
5664 _profile(PackageTable$reloadData$Section)
5665 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5669 _profile(PackageTable$reloadData$Section$Package)
5670 package = [packages_ objectAtIndex:offset];
5671 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
5674 while (secidx < index) {
5677 _profile(PackageTable$reloadData$Section$Allocate)
5678 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
5681 _profile(PackageTable$reloadData$Section$Add)
5682 [sections_ addObject:section];
5686 [section addToCount];
5690 [index_ removeAllObjects];
5692 _profile(PackageTable$reloadData$Section)
5693 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5697 _profile(PackageTable$reloadData$Section$Package)
5698 package = [packages_ objectAtIndex:offset];
5699 index = [package index];
5702 if (section == nil || [section index] != index) {
5703 _profile(PackageTable$reloadData$Section$Allocate)
5704 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5707 [index_ addObject:[section name]];
5708 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5710 _profile(PackageTable$reloadData$Section$Add)
5711 [sections_ addObject:section];
5715 [section addToCount];
5720 _profile(PackageTable$reloadData$List)
5725 - (void) resetCursor {
5726 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5729 - (UITableView *) list {
5733 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5734 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
5739 /* Filtered Package Table {{{ */
5740 @interface FilteredPackageTable : PackageTable {
5746 - (void) setObject:(id)object;
5747 - (void) setObject:(id)object forFilter:(SEL)filter;
5749 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object;
5753 @implementation FilteredPackageTable
5761 - (void) setFilter:(SEL)filter {
5764 /* XXX: this is an unsafe optimization of doomy hell */
5765 Method method(class_getInstanceMethod([Package class], filter));
5766 _assert(method != NULL);
5767 imp_ = method_getImplementation(method);
5768 _assert(imp_ != NULL);
5771 - (void) setObject:(id)object {
5777 object_ = [object retain];
5780 - (void) setObject:(id)object forFilter:(SEL)filter {
5781 [self setFilter:filter];
5782 [self setObject:object];
5785 - (bool) hasPackage:(Package *)package {
5786 _profile(FilteredPackageTable$hasPackage)
5787 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5791 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object {
5792 if ((self = [super initWithFrame:frame database:database target:target action:action]) != nil) {
5793 [self setFilter:filter];
5794 object_ = [object retain];
5802 /* Filtered Package Controller {{{ */
5803 @interface FilteredPackageController : CYViewController {
5804 _transient Database *database_;
5805 FilteredPackageTable *packages_;
5809 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5813 @implementation FilteredPackageController
5816 [packages_ release];
5822 - (void) viewDidAppear:(BOOL)animated {
5823 [super viewDidAppear:animated];
5824 [packages_ deselectWithAnimation:animated];
5827 - (void) didSelectPackage:(Package *)package {
5828 PackageController *view([delegate_ packageController]);
5829 [view setPackage:package];
5830 [view setDelegate:delegate_];
5831 [[self navigationController] pushViewController:view animated:YES];
5834 - (NSString *) title { return title_; }
5836 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5837 if ((self = [super init]) != nil) {
5838 database_ = database;
5839 title_ = [title copy];
5840 [[self navigationItem] setTitle:title_];
5842 packages_ = [[FilteredPackageTable alloc]
5843 initWithFrame:[[self view] bounds]
5846 action:@selector(didSelectPackage:)
5851 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5852 [[self view] addSubview:packages_];
5856 - (void) reloadData {
5857 [packages_ reloadData];
5860 - (void) setDelegate:(id)delegate {
5861 [super setDelegate:delegate];
5862 [packages_ setDelegate:delegate];
5869 /* Source Cell {{{ */
5870 @interface SourceCell : CYTableViewCell <
5875 NSString *description_;
5879 - (void) setSource:(Source *)source;
5883 @implementation SourceCell
5885 - (void) clearSource {
5888 [description_ release];
5897 - (void) setSource:(Source *)source {
5901 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
5903 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
5904 icon_ = [icon_ retain];
5906 origin_ = [[source name] retain];
5907 label_ = [[source uri] retain];
5908 description_ = [[source description] retain];
5910 [content_ setNeedsDisplay];
5918 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5919 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5920 UIView *content([self contentView]);
5921 CGRect bounds([content bounds]);
5923 content_ = [[ContentView alloc] initWithFrame:bounds];
5924 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5925 [content_ setBackgroundColor:[UIColor whiteColor]];
5926 [content addSubview:content_];
5928 [content_ setDelegate:self];
5929 [content_ setOpaque:YES];
5933 - (void) drawContentRect:(CGRect)rect {
5934 bool highlighted(highlighted_);
5935 float width(rect.size.width);
5938 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
5945 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5949 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5953 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 40) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5958 /* Source Table {{{ */
5959 @interface SourceController : CYViewController <
5960 UITableViewDataSource,
5963 _transient Database *database_;
5965 NSMutableArray *sources_;
5969 UIProgressHUD *hud_;
5972 //NSURLConnection *installer_;
5973 NSURLConnection *trivial_;
5974 NSURLConnection *trivial_bz2_;
5975 NSURLConnection *trivial_gz_;
5976 //NSURLConnection *automatic_;
5981 - (id) initWithDatabase:(Database *)database;
5983 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
5987 @implementation SourceController
5989 - (void) _releaseConnection:(NSURLConnection *)connection {
5990 if (connection != nil) {
5991 [connection cancel];
5992 //[connection setDelegate:nil];
5993 [connection release];
6005 //[self _releaseConnection:installer_];
6006 [self _releaseConnection:trivial_];
6007 [self _releaseConnection:trivial_gz_];
6008 [self _releaseConnection:trivial_bz2_];
6009 //[self _releaseConnection:automatic_];
6016 - (void) viewDidAppear:(BOOL)animated {
6017 [super viewDidAppear:animated];
6018 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6021 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
6022 return offset_ == 0 ? 1 : 2;
6025 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
6026 switch (section + (offset_ == 0 ? 1 : 0)) {
6027 case 0: return UCLocalize("ENTERED_BY_USER");
6028 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
6034 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6035 int count = [sources_ count];
6037 case 0: return (offset_ == 0 ? count : offset_);
6038 case 1: return count - offset_;
6044 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
6046 switch (indexPath.section) {
6047 case 0: idx = indexPath.row; break;
6048 case 1: idx = indexPath.row + offset_; break;
6052 return [sources_ objectAtIndex:idx];
6055 - (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6056 Source *source = [self sourceAtIndexPath:indexPath];
6057 return [source description] == nil ? 56 : 73;
6060 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6061 static NSString *cellIdentifier = @"SourceCell";
6063 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
6064 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
6065 [cell setSource:[self sourceAtIndexPath:indexPath]];
6070 - (UITableViewCellAccessoryType) tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath {
6071 return UITableViewCellAccessoryDisclosureIndicator;
6074 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6075 Source *source = [self sourceAtIndexPath:indexPath];
6077 FilteredPackageController *packages = [[[FilteredPackageController alloc]
6078 initWithDatabase:database_
6079 title:[source label]
6080 filter:@selector(isVisibleInSource:)
6084 [packages setDelegate:delegate_];
6086 [[self navigationController] pushViewController:packages animated:YES];
6089 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
6090 Source *source = [self sourceAtIndexPath:indexPath];
6091 return [source record] != nil;
6094 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
6095 Source *source = [self sourceAtIndexPath:indexPath];
6096 [Sources_ removeObjectForKey:[source key]];
6097 [delegate_ syncData];
6101 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
6104 @"./", @"Distribution",
6105 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
6107 [delegate_ syncData];
6110 - (NSString *) getWarning {
6111 NSString *href(href_);
6112 NSRange colon([href rangeOfString:@"://"]);
6113 if (colon.location != NSNotFound)
6114 href = [href substringFromIndex:(colon.location + 3)];
6115 href = [href stringByAddingPercentEscapes];
6116 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
6117 href = [href stringByCachingURLWithCurrentCDN];
6119 NSURL *url([NSURL URLWithString:href]);
6121 NSStringEncoding encoding;
6122 NSError *error(nil);
6124 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
6125 return [warning length] == 0 ? nil : warning;
6129 - (void) _endConnection:(NSURLConnection *)connection {
6130 // XXX: the memory management in this method is horribly awkward
6132 NSURLConnection **field = NULL;
6133 if (connection == trivial_)
6135 else if (connection == trivial_bz2_)
6136 field = &trivial_bz2_;
6137 else if (connection == trivial_gz_)
6138 field = &trivial_gz_;
6139 _assert(field != NULL);
6140 [connection release];
6145 trivial_bz2_ == nil &&
6151 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
6154 UIAlertView *alert = [[[UIAlertView alloc]
6155 initWithTitle:UCLocalize("SOURCE_WARNING")
6158 cancelButtonTitle:UCLocalize("CANCEL")
6159 otherButtonTitles:UCLocalize("ADD_ANYWAY"), nil
6162 [alert setContext:@"warning"];
6163 [alert setNumberOfRows:1];
6167 } else if (error_ != nil) {
6168 UIAlertView *alert = [[[UIAlertView alloc]
6169 initWithTitle:UCLocalize("VERIFICATION_ERROR")
6170 message:[error_ localizedDescription]
6172 cancelButtonTitle:UCLocalize("OK")
6173 otherButtonTitles:nil
6176 [alert setContext:@"urlerror"];
6179 UIAlertView *alert = [[[UIAlertView alloc]
6180 initWithTitle:UCLocalize("NOT_REPOSITORY")
6181 message:UCLocalize("NOT_REPOSITORY_EX")
6183 cancelButtonTitle:UCLocalize("OK")
6184 otherButtonTitles:nil
6187 [alert setContext:@"trivial"];
6191 [delegate_ setStatusBarShowsProgress:NO];
6192 [delegate_ removeProgressHUD:hud_];
6202 if (error_ != nil) {
6209 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
6210 switch ([response statusCode]) {
6216 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
6217 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
6219 error_ = [error retain];
6220 [self _endConnection:connection];
6223 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
6224 [self _endConnection:connection];
6227 - (NSString *) title { return UCLocalize("SOURCES"); }
6229 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
6230 NSMutableURLRequest *request = [NSMutableURLRequest
6231 requestWithURL:[NSURL URLWithString:href]
6232 cachePolicy:NSURLRequestUseProtocolCachePolicy
6233 timeoutInterval:120.0
6236 [request setHTTPMethod:method];
6238 if (Machine_ != NULL)
6239 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
6240 if (UniqueID_ != nil)
6241 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6243 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
6245 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
6248 - (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
6249 NSString *context([alert context]);
6251 if ([context isEqualToString:@"source"]) {
6254 NSString *href = [[alert textField] text];
6256 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
6258 if (![href hasSuffix:@"/"])
6259 href_ = [href stringByAppendingString:@"/"];
6262 href_ = [href_ retain];
6264 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
6265 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
6266 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
6267 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
6271 // XXX: this is stupid
6272 hud_ = [[delegate_ addProgressHUD] retain];
6273 [hud_ setText:UCLocalize("VERIFYING_URL")];
6282 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6283 } else if ([context isEqualToString:@"trivial"])
6284 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6285 else if ([context isEqualToString:@"urlerror"])
6286 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6287 else if ([context isEqualToString:@"warning"]) {
6302 [alert dismissWithClickedButtonIndex:-1 animated:YES];
6306 - (id) initWithDatabase:(Database *)database {
6307 if ((self = [super init]) != nil) {
6308 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
6309 [self updateButtonsForEditingStatus:NO animated:NO];
6311 database_ = database;
6312 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
6314 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6315 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6316 [[self view] addSubview:list_];
6318 [list_ setDataSource:self];
6319 [list_ setDelegate:self];
6325 - (void) reloadData {
6327 if (!list.ReadMainList())
6330 [sources_ removeAllObjects];
6331 [sources_ addObjectsFromArray:[database_ sources]];
6333 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
6336 int count([sources_ count]);
6338 for (int i = 0; i != count; i++) {
6339 if ([[sources_ objectAtIndex:i] record] == nil)
6344 [list_ setEditing:NO];
6345 [self updateButtonsForEditingStatus:NO animated:NO];
6349 - (void) addButtonClicked {
6350 /*[book_ pushPage:[[[AddSourceController alloc]
6355 UIAlertView *alert = [[[UIAlertView alloc]
6356 initWithTitle:UCLocalize("ENTER_APT_URL")
6359 cancelButtonTitle:UCLocalize("CANCEL")
6360 otherButtonTitles:UCLocalize("ADD_SOURCE"), nil
6363 [alert setContext:@"source"];
6364 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
6366 [alert setNumberOfRows:1];
6367 [alert addTextFieldWithValue:@"http://" label:@""];
6369 UITextInputTraits *traits = [[alert textField] textInputTraits];
6370 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
6371 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
6372 [traits setKeyboardType:UIKeyboardTypeURL];
6373 // XXX: UIReturnKeyDone
6374 [traits setReturnKeyType:UIReturnKeyNext];
6379 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
6380 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
6381 initWithTitle:UCLocalize("ADD")
6382 style:UIBarButtonItemStylePlain
6384 action:@selector(addButtonClicked)
6385 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
6387 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6388 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
6389 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
6391 action:@selector(editButtonClicked)
6392 ] autorelease] animated:animated];
6394 if (IsWildcat_ && !editing)
6395 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6396 initWithTitle:UCLocalize("SETTINGS")
6397 style:UIBarButtonItemStylePlain
6399 action:@selector(settingsButtonClicked)
6403 - (void) settingsButtonClicked {
6404 [delegate_ showSettings];
6407 - (void) editButtonClicked {
6408 [list_ setEditing:![list_ isEditing] animated:YES];
6410 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
6416 /* Installed Controller {{{ */
6417 @interface InstalledController : FilteredPackageController {
6421 - (id) initWithDatabase:(Database *)database;
6423 - (void) updateRoleButton;
6424 - (void) queueStatusDidChange;
6428 @implementation InstalledController
6434 - (NSString *) title { return UCLocalize("INSTALLED"); }
6436 - (id) initWithDatabase:(Database *)database {
6437 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
6438 [self updateRoleButton];
6439 [self queueStatusDidChange];
6444 - (void) queueButtonClicked {
6449 - (void) queueStatusDidChange {
6453 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6454 initWithTitle:UCLocalize("QUEUE")
6455 style:UIBarButtonItemStyleDone
6457 action:@selector(queueButtonClicked)
6460 [[self navigationItem] setLeftBarButtonItem:nil];
6466 - (void) reloadData {
6467 [packages_ reloadData];
6470 - (void) updateRoleButton {
6471 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
6472 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6473 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
6474 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
6476 action:@selector(roleButtonClicked)
6480 - (void) roleButtonClicked {
6481 [packages_ setObject:[NSNumber numberWithBool:expert_]];
6482 [packages_ reloadData];
6485 [self updateRoleButton];
6488 - (void) setDelegate:(id)delegate {
6489 [super setDelegate:delegate];
6490 [packages_ setDelegate:delegate];
6496 /* Home Controller {{{ */
6497 @interface HomeController : CYBrowserController {
6502 @implementation HomeController
6504 + (BOOL)shouldHideNavigationBar {
6508 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6509 [super _setMoreHeaders:request];
6512 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6513 if (UniqueID_ != nil)
6514 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6516 [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"];
6519 - (void) aboutButtonClicked {
6520 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6522 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6523 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6524 [alert setCancelButtonIndex:0];
6527 @"Copyright (C) 2008-2010\n"
6528 "Jay Freeman (saurik)\n"
6529 "saurik@saurik.com\n"
6530 "http://www.saurik.com/"
6536 - (void) viewWillAppear:(BOOL)animated {
6537 [super viewWillAppear:animated];
6539 if ([[self class] shouldHideNavigationBar])
6540 [[self navigationController] setNavigationBarHidden:YES animated:animated];
6543 - (void) viewWillDisappear:(BOOL)animated {
6544 [super viewWillDisappear:animated];
6546 if ([[self class] shouldHideNavigationBar])
6547 [[self navigationController] setNavigationBarHidden:NO animated:animated];
6551 if ((self = [super init]) != nil) {
6552 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6553 initWithTitle:UCLocalize("ABOUT")
6554 style:UIBarButtonItemStylePlain
6556 action:@selector(aboutButtonClicked)
6563 /* Manage Controller {{{ */
6564 @interface ManageController : CYBrowserController {
6567 - (void) queueStatusDidChange;
6570 @implementation ManageController
6573 if ((self = [super init]) != nil) {
6574 [[self navigationItem] setTitle:UCLocalize("MANAGE")];
6576 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6577 initWithTitle:UCLocalize("SETTINGS")
6578 style:UIBarButtonItemStylePlain
6580 action:@selector(settingsButtonClicked)
6583 [self queueStatusDidChange];
6587 - (void) settingsButtonClicked {
6588 [delegate_ showSettings];
6592 - (void) queueButtonClicked {
6596 - (void) applyLoadingTitle {
6597 // No "Loading" title.
6600 - (void) applyRightButton {
6605 - (void) queueStatusDidChange {
6607 if (!IsWildcat_ && Queuing_) {
6608 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6609 initWithTitle:UCLocalize("QUEUE")
6610 style:UIBarButtonItemStyleDone
6612 action:@selector(queueButtonClicked)
6615 [[self navigationItem] setRightBarButtonItem:nil];
6620 - (bool) isLoading {
6627 /* Refresh Bar {{{ */
6628 @interface RefreshBar : UINavigationBar {
6629 UIProgressIndicator *indicator_;
6630 UITextLabel *prompt_;
6631 UIProgressBar *progress_;
6632 UINavigationButton *cancel_;
6637 @implementation RefreshBar
6640 [indicator_ release];
6642 [progress_ release];
6647 - (void) positionViews {
6648 CGRect frame = [cancel_ frame];
6649 frame.size = [cancel_ sizeThatFits:frame.size];
6650 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6651 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6652 [cancel_ setFrame:frame];
6654 CGSize prgsize = {75, 100};
6656 [self frame].size.width - prgsize.width - 10,
6657 ([self frame].size.height - prgsize.height) / 2
6659 [progress_ setFrame:prgrect];
6661 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6662 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6663 CGRect indrect = {{indoffset, indoffset}, indsize};
6664 [indicator_ setFrame:indrect];
6666 CGSize prmsize = {215, indsize.height + 4};
6668 indoffset * 2 + indsize.width,
6669 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6671 [prompt_ setFrame:prmrect];
6674 - (void)setFrame:(CGRect)frame {
6675 [super setFrame:frame];
6677 [self positionViews];
6680 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6681 if ((self = [super initWithFrame:frame])) {
6682 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6684 [self setBarStyle:UIBarStyleBlack];
6686 UIBarStyle barstyle([self _barStyle:NO]);
6687 bool ugly(barstyle == UIBarStyleDefault);
6689 UIProgressIndicatorStyle style = ugly ?
6690 UIProgressIndicatorStyleMediumBrown :
6691 UIProgressIndicatorStyleMediumWhite;
6693 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6694 [indicator_ setStyle:style];
6695 [indicator_ startAnimation];
6696 [self addSubview:indicator_];
6698 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6699 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6700 [prompt_ setBackgroundColor:[UIColor clearColor]];
6701 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6702 [self addSubview:prompt_];
6704 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6705 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6706 [progress_ setStyle:0];
6707 [self addSubview:progress_];
6709 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6710 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6711 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6712 [cancel_ setBarStyle:barstyle];
6714 [self positionViews];
6719 [cancel_ removeFromSuperview];
6723 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6724 [progress_ setProgress:0];
6725 [self addSubview:cancel_];
6729 [cancel_ removeFromSuperview];
6732 - (void) setPrompt:(NSString *)prompt {
6733 [prompt_ setText:prompt];
6736 - (void) setProgress:(float)progress {
6737 [progress_ setProgress:progress];
6743 @class CYNavigationController;
6745 /* Cydia Tab Bar Controller {{{ */
6746 @interface CYTabBarController : UITabBarController <
6749 _transient Database *database_;
6750 RefreshBar *refreshbar_;
6754 // XXX: ok, "updatedelegate_"?...
6755 _transient NSObject<CydiaDelegate> *updatedelegate_;
6760 - (void) dropBar:(BOOL)animated;
6761 - (void) beginUpdate;
6762 - (void) raiseBar:(BOOL)animated;
6767 @implementation CYTabBarController
6769 /* XXX: some logic should probably go here related to
6770 freeing the view controllers on tab change */
6772 - (void) reloadData {
6773 size_t count([[self viewControllers] count]);
6774 for (size_t i(0); i != count; ++i) {
6775 CYNavigationController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6780 - (id) initWithDatabase:(Database *)database {
6781 if ((self = [super init]) != nil) {
6782 database_ = database;
6784 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6785 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6787 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
6791 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
6792 return IsWildcat_ || orientation == UIInterfaceOrientationPortrait;
6795 - (void) setUpdate:(NSDate *)date {
6799 - (void) beginUpdate {
6800 [refreshbar_ start];
6803 [updatedelegate_ retainNetworkActivityIndicator];
6807 detachNewThreadSelector:@selector(performUpdate)
6813 - (void) performUpdate { _pooled
6815 status.setDelegate(self);
6816 [database_ updateWithStatus:status];
6819 performSelectorOnMainThread:@selector(completeUpdate)
6825 - (void) stopUpdateWithSelector:(SEL)selector {
6827 [updatedelegate_ releaseNetworkActivityIndicator];
6829 [self raiseBar:YES];
6832 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6835 - (void) completeUpdate {
6838 [self stopUpdateWithSelector:@selector(reloadData)];
6841 - (void) cancelUpdate {
6842 [self stopUpdateWithSelector:@selector(updateData)];
6845 - (void) cancelPressed {
6846 [self cancelUpdate];
6853 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
6854 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
6857 - (void) startProgress {
6860 - (void) setProgressTitle:(NSString *)title {
6862 performSelectorOnMainThread:@selector(_setProgressTitle:)
6868 - (bool) isCancelling:(size_t)received {
6872 - (void) setProgressPercent:(float)percent {
6874 performSelectorOnMainThread:@selector(_setProgressPercent:)
6875 withObject:[NSNumber numberWithFloat:percent]
6880 - (void) addProgressOutput:(NSString *)output {
6882 performSelectorOnMainThread:@selector(_addProgressOutput:)
6888 - (void) _setProgressTitle:(NSString *)title {
6889 [refreshbar_ setPrompt:title];
6892 - (void) _setProgressPercent:(NSNumber *)percent {
6893 [refreshbar_ setProgress:[percent floatValue]];
6896 - (void) _addProgressOutput:(NSString *)output {
6899 - (void) setUpdateDelegate:(id)delegate {
6900 updatedelegate_ = delegate;
6903 - (CGFloat) statusBarHeight {
6904 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
6905 return [[UIApplication sharedApplication] statusBarFrame].size.height;
6907 return [[UIApplication sharedApplication] statusBarFrame].size.width;
6911 - (UIView *) transitionView {
6912 if ([self respondsToSelector:@selector(_transitionView)])
6913 return [self _transitionView];
6915 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6918 - (void) dropBar:(BOOL)animated {
6923 UIView *transition([self transitionView]);
6924 [[self view] addSubview:refreshbar_];
6926 CGRect barframe([refreshbar_ frame]);
6928 if (false) // XXX: _UIApplicationLinkedOnOrAfter(4)
6929 barframe.origin.y = [self statusBarHeight];
6931 barframe.origin.y = 0;
6933 [refreshbar_ setFrame:barframe];
6936 [UIView beginAnimations:nil context:NULL];
6938 CGRect viewframe = [transition frame];
6939 viewframe.origin.y += barframe.size.height;
6940 viewframe.size.height -= barframe.size.height;
6941 [transition setFrame:viewframe];
6944 [UIView commitAnimations];
6946 // Ensure bar has the proper width for our view, it might have changed
6947 barframe.size.width = viewframe.size.width;
6948 [refreshbar_ setFrame:barframe];
6950 // XXX: fix Apple's layout bug
6951 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6954 - (void) raiseBar:(BOOL)animated {
6959 UIView *transition([self transitionView]);
6960 [refreshbar_ removeFromSuperview];
6962 CGRect barframe([refreshbar_ frame]);
6965 [UIView beginAnimations:nil context:NULL];
6967 CGRect viewframe = [transition frame];
6968 viewframe.origin.y -= barframe.size.height;
6969 viewframe.size.height += barframe.size.height;
6970 [transition setFrame:viewframe];
6973 [UIView commitAnimations];
6975 // XXX: fix Apple's layout bug
6976 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6980 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
6981 // XXX: fix Apple's layout bug
6982 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6986 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6987 bool dropped(dropped_);
6992 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6997 // XXX: fix Apple's layout bug
6998 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7001 - (void) statusBarFrameChanged:(NSNotification *)notification {
7009 [refreshbar_ release];
7010 [[NSNotificationCenter defaultCenter] removeObserver:self];
7017 /* Cydia Navigation Controller {{{ */
7018 @interface CYNavigationController : UINavigationController {
7019 _transient Database *database_;
7020 _transient id<UINavigationControllerDelegate> delegate_;
7023 - (id) initWithDatabase:(Database *)database;
7024 - (void) reloadData;
7029 @implementation CYNavigationController
7031 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
7032 // Inherit autorotation settings for modal parents.
7033 if ([self parentViewController] && [[self parentViewController] modalViewController] == self) {
7034 return [[self parentViewController] shouldAutorotateToInterfaceOrientation:orientation];
7035 } else if ([self parentViewController]) {
7036 return [[self parentViewController] shouldAutorotateToInterfaceOrientation:orientation];
7038 return [super shouldAutorotateToInterfaceOrientation:orientation];
7046 - (void) reloadData {
7047 size_t count([[self viewControllers] count]);
7048 for (size_t i(0); i != count; ++i) {
7049 CYViewController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
7054 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
7055 delegate_ = delegate;
7058 - (id) initWithDatabase:(Database *)database {
7059 if ((self = [super init]) != nil) {
7060 database_ = database;
7066 /* Cydia:// Protocol {{{ */
7067 @interface CydiaURLProtocol : NSURLProtocol {
7072 @implementation CydiaURLProtocol
7074 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7075 NSURL *url([request URL]);
7078 NSString *scheme([[url scheme] lowercaseString]);
7079 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
7084 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7088 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7089 id<NSURLProtocolClient> client([self client]);
7091 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7093 NSData *data(UIImagePNGRepresentation(icon));
7095 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7096 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7097 [client URLProtocol:self didLoadData:data];
7098 [client URLProtocolDidFinishLoading:self];
7102 - (void) startLoading {
7103 id<NSURLProtocolClient> client([self client]);
7104 NSURLRequest *request([self request]);
7106 NSURL *url([request URL]);
7107 NSString *href([url absoluteString]);
7109 NSString *path([href substringFromIndex:8]);
7110 NSRange slash([path rangeOfString:@"/"]);
7113 if (slash.location == NSNotFound) {
7117 command = [path substringToIndex:slash.location];
7118 path = [path substringFromIndex:(slash.location + 1)];
7121 Database *database([Database sharedInstance]);
7123 if ([command isEqualToString:@"package-icon"]) {
7126 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7127 Package *package([database packageWithName:path]);
7130 UIImage *icon([package icon]);
7131 [self _returnPNGWithImage:icon forRequest:request];
7132 } else if ([command isEqualToString:@"source-icon"]) {
7135 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7136 NSString *source(Simplify(path));
7137 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
7139 icon = [UIImage applicationImageNamed:@"unknown.png"];
7140 [self _returnPNGWithImage:icon forRequest:request];
7141 } else if ([command isEqualToString:@"uikit-image"]) {
7144 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7145 UIImage *icon(_UIImageWithName(path));
7146 [self _returnPNGWithImage:icon forRequest:request];
7147 } else if ([command isEqualToString:@"section-icon"]) {
7150 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7151 NSString *section(Simplify(path));
7152 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
7154 icon = [UIImage applicationImageNamed:@"unknown.png"];
7155 [self _returnPNGWithImage:icon forRequest:request];
7157 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7161 - (void) stopLoading {
7167 /* Sections Controller {{{ */
7168 @interface CYSectionsController : CYViewController <
7169 UITableViewDataSource,
7172 _transient Database *database_;
7173 NSMutableArray *sections_;
7174 NSMutableArray *filtered_;
7180 - (id) initWithDatabase:(Database *)database;
7181 - (void) reloadData;
7184 - (void) editButtonClicked;
7188 @implementation CYSectionsController
7191 [list_ setDataSource:nil];
7192 [list_ setDelegate:nil];
7194 [sections_ release];
7195 [filtered_ release];
7197 [accessory_ release];
7201 - (void) setEditing:(BOOL)editing {
7202 if ((editing_ = editing))
7205 [delegate_ updateData];
7207 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7208 [[[self navigationItem] rightBarButtonItem] setTitle:[sections_ count] == 0 ? nil : editing_ ? UCLocalize("DONE") : UCLocalize("EDIT")];
7209 [[[self navigationItem] rightBarButtonItem] setStyle:editing_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain];
7212 - (void) viewDidAppear:(BOOL)animated {
7213 [super viewDidAppear:animated];
7214 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7217 - (void) viewWillDisappear:(BOOL)animated {
7218 [super viewWillDisappear:animated];
7219 if (editing_) [self setEditing:NO];
7222 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7223 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
7227 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7228 return editing_ ? [sections_ count] : [filtered_ count] + 1;
7231 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7235 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7236 static NSString *reuseIdentifier = @"SectionCell";
7238 SectionCell *cell = (SectionCell *) [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7240 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7242 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
7247 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7251 Section *section = [self sectionAtIndexPath:indexPath];
7252 NSString *name = [section name];
7255 if ([indexPath row] == 0) {
7258 title = UCLocalize("ALL_PACKAGES");
7261 name = [NSString stringWithString:name];
7262 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7265 title = UCLocalize("NO_SECTION");
7269 FilteredPackageController *table = [[[FilteredPackageController alloc]
7270 initWithDatabase:database_
7272 filter:@selector(isVisibleInSection:)
7276 [table setDelegate:delegate_];
7278 [[self navigationController] pushViewController:table animated:YES];
7281 - (NSString *) title { return UCLocalize("SECTIONS"); }
7283 - (id) initWithDatabase:(Database *)database {
7284 if ((self = [super init]) != nil) {
7285 database_ = database;
7287 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7289 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7290 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
7292 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
7293 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7294 [list_ setRowHeight:45.0f];
7295 [[self view] addSubview:list_];
7297 [list_ setDataSource:self];
7298 [list_ setDelegate:self];
7304 - (void) reloadData {
7305 NSArray *packages = [database_ packages];
7307 [sections_ removeAllObjects];
7308 [filtered_ removeAllObjects];
7310 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7313 for (Package *package in packages) {
7314 NSString *name([package section]);
7315 NSString *key(name == nil ? @"" : name);
7319 _profile(SectionsView$reloadData$Section)
7320 section = [sections objectForKey:key];
7321 if (section == nil) {
7322 _profile(SectionsView$reloadData$Section$Allocate)
7323 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
7324 [sections setObject:section forKey:key];
7329 [section addToCount];
7331 _profile(SectionsView$reloadData$Filter)
7332 if (![package valid] || ![package visible])
7340 [sections_ addObjectsFromArray:[sections allValues]];
7342 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7344 for (Section *section in sections_) {
7345 size_t count([section row]);
7349 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7350 [section setCount:count];
7351 [filtered_ addObject:section];
7354 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7355 initWithTitle:([sections_ count] == 0 ? nil : UCLocalize("EDIT"))
7356 style:UIBarButtonItemStylePlain
7358 action:@selector(editButtonClicked)
7359 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7365 - (void) resetView {
7367 [self editButtonClicked];
7370 - (void)editButtonClicked {
7371 [self setEditing:!editing_];
7374 - (UIView *) accessoryView {
7380 /* Changes Controller {{{ */
7381 @interface ChangesController : CYViewController <
7382 UITableViewDataSource,
7385 _transient Database *database_;
7387 CFMutableArrayRef packages_;
7388 NSMutableArray *sections_;
7391 BOOL hasSentFirstLoad_;
7394 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
7395 - (void) reloadData;
7399 @implementation ChangesController
7402 [list_ setDelegate:nil];
7403 [list_ setDataSource:nil];
7405 CFRelease(packages_);
7407 [sections_ release];
7412 - (void) viewDidAppear:(BOOL)animated {
7413 [super viewDidAppear:animated];
7414 if (!hasSentFirstLoad_) {
7415 hasSentFirstLoad_ = YES;
7416 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
7418 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7422 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7423 NSInteger count([sections_ count]);
7424 return count == 0 ? 1 : count;
7427 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7428 if ([sections_ count] == 0)
7430 return [[sections_ objectAtIndex:section] name];
7433 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7434 if ([sections_ count] == 0)
7436 return [[sections_ objectAtIndex:section] count];
7439 - (Package *) packageAtIndex:(NSUInteger)index {
7440 return (Package *) CFArrayGetValueAtIndex(packages_, index);
7443 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7444 @synchronized (database_) {
7445 if ([database_ era] != era_)
7448 Section *section([sections_ objectAtIndex:[path section]]);
7449 NSInteger row([path row]);
7450 return [[[self packageAtIndex:([section row] + row)] retain] autorelease];
7453 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7454 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7456 cell = [[[PackageCell alloc] init] autorelease];
7457 [cell setPackage:[self packageAtIndexPath:path]];
7461 /*- (CGFloat) tableView:(UITableView *)table heightForRowAtIndexPath:(NSIndexPath *)path {
7462 return [PackageCell heightForPackage:[self packageAtIndexPath:path]];
7465 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7466 Package *package([self packageAtIndexPath:path]);
7467 PackageController *view([delegate_ packageController]);
7468 [view setDelegate:delegate_];
7469 [view setPackage:package];
7470 [[self navigationController] pushViewController:view animated:YES];
7474 - (void) refreshButtonClicked {
7475 [delegate_ beginUpdate];
7476 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7479 - (void) upgradeButtonClicked {
7480 [delegate_ distUpgrade];
7483 - (NSString *) title { return UCLocalize("CHANGES"); }
7485 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7486 if ((self = [super init]) != nil) {
7487 database_ = database;
7488 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7490 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7492 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7494 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7495 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7496 [list_ setRowHeight:73.0f];
7497 [[self view] addSubview:list_];
7499 [list_ setDataSource:self];
7500 [list_ setDelegate:self];
7502 delegate_ = delegate;
7506 - (void) _reloadPackages:(NSArray *)packages {
7508 for (Package *package in packages)
7509 if ([package upgradableAndEssential:YES] || [package visible])
7510 CFArrayAppendValue(packages_, package);
7513 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7517 - (void) reloadData {
7518 era_ = [database_ era];
7519 NSArray *packages = [database_ packages];
7521 CFArrayRemoveAllValues(packages_);
7523 [sections_ removeAllObjects];
7526 UIProgressHUD *hud([delegate_ addProgressHUD]);
7527 [hud setText:UCLocalize("LOADING")];
7528 //NSLog(@"HUD:%@::%@", delegate_, hud);
7529 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7530 [delegate_ removeProgressHUD:hud];
7532 [self _reloadPackages:packages];
7535 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7536 Section *ignored = nil;
7537 Section *section = nil;
7541 bool unseens = false;
7543 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7545 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7546 Package *package = [self packageAtIndex:offset];
7548 BOOL uae = [package upgradableAndEssential:YES];
7552 time_t seen([package seen]);
7554 if (section == nil || last != seen) {
7558 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7561 _profile(ChangesController$reloadData$Allocate)
7562 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7563 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7564 [sections_ addObject:section];
7568 [section addToCount];
7569 } else if ([package ignored]) {
7570 if (ignored == nil) {
7571 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7573 [ignored addToCount];
7576 [upgradable addToCount];
7581 CFRelease(formatter);
7584 Section *last = [sections_ lastObject];
7585 size_t count = [last count];
7586 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7587 [sections_ removeLastObject];
7590 if ([ignored count] != 0)
7591 [sections_ insertObject:ignored atIndex:0];
7593 [sections_ insertObject:upgradable atIndex:0];
7598 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7599 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7600 style:UIBarButtonItemStylePlain
7602 action:@selector(upgradeButtonClicked)
7605 if (![delegate_ updating])
7606 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7607 initWithTitle:UCLocalize("REFRESH")
7608 style:UIBarButtonItemStylePlain
7610 action:@selector(refreshButtonClicked)
7616 /* Search Controller {{{ */
7617 @interface SearchController : FilteredPackageController <
7620 UISearchBar *search_;
7623 - (id) initWithDatabase:(Database *)database;
7624 - (void) reloadData;
7628 @implementation SearchController
7635 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7636 [packages_ setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7637 [search_ resignFirstResponder];
7641 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7642 [packages_ setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7646 - (NSString *) title { return nil; }
7648 - (id) initWithDatabase:(Database *)database {
7649 return [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil];
7652 - (void)viewDidAppear:(BOOL)animated {
7653 [super viewDidAppear:animated];
7655 search_ = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7656 [search_ layoutSubviews];
7657 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7659 UITextField *textField;
7660 if ([search_ respondsToSelector:@selector(searchField)])
7661 textField = [search_ searchField];
7663 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7665 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7666 [search_ setDelegate:self];
7667 [textField setEnablesReturnKeyAutomatically:NO];
7668 [[self navigationItem] setTitleView:textField];
7672 - (void) _reloadData {
7675 - (void) reloadData {
7676 _profile(SearchController$reloadData)
7677 [packages_ reloadData];
7680 [packages_ resetCursor];
7683 - (void) didSelectPackage:(Package *)package {
7684 [search_ resignFirstResponder];
7685 [super didSelectPackage:package];
7690 /* Settings Controller {{{ */
7691 @interface CYPackageSettingsController : CYViewController <
7692 UITableViewDataSource,
7695 _transient Database *database_;
7698 UITableView *table_;
7699 UISwitch *subscribedSwitch_;
7700 UISwitch *ignoredSwitch_;
7701 UITableViewCell *subscribedCell_;
7702 UITableViewCell *ignoredCell_;
7705 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7709 @implementation CYPackageSettingsController
7713 if (package_ != nil)
7716 [subscribedSwitch_ release];
7717 [ignoredSwitch_ release];
7718 [subscribedCell_ release];
7719 [ignoredCell_ release];
7724 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7725 if (package_ == nil)
7731 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7732 if (package_ == nil)
7738 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7739 return UCLocalize("SHOW_ALL_CHANGES_EX");
7742 - (void) onSubscribed:(id)control {
7743 bool value([control isOn]);
7744 if (package_ == nil)
7746 if ([package_ setSubscribed:value])
7747 [delegate_ updateData];
7750 - (void) onIgnored:(id)control {
7751 // TODO: set Held state - possibly call out to dpkg, etc.
7754 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7755 if (package_ == nil)
7758 switch ([indexPath row]) {
7759 case 0: return subscribedCell_;
7760 case 1: return ignoredCell_;
7768 - (NSString *) title { return UCLocalize("SETTINGS"); }
7770 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7771 if ((self = [super init])) {
7772 database_ = database;
7773 name_ = [package retain];
7775 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7777 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7778 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7779 [[self view] addSubview:table_];
7781 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7782 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7783 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7785 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7786 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7787 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7789 subscribedCell_ = [[UITableViewCell alloc] init];
7790 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7791 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7792 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7794 ignoredCell_ = [[UITableViewCell alloc] init];
7795 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7796 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7797 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7799 [table_ setDataSource:self];
7800 [table_ setDelegate:self];
7805 - (void) reloadData {
7806 if (package_ != nil)
7807 [package_ autorelease];
7808 package_ = [database_ packageWithName:name_];
7809 if (package_ != nil) {
7811 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7812 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7815 [table_ reloadData];
7820 /* Signature Controller {{{ */
7821 @interface SignatureController : CYBrowserController {
7822 _transient Database *database_;
7826 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7830 @implementation SignatureController
7837 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7839 [super webView:view didClearWindowObject:window forFrame:frame];
7842 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7843 if ((self = [super init]) != nil) {
7844 database_ = database;
7845 package_ = [package retain];
7850 - (void) reloadData {
7851 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7857 /* Role Controller {{{ */
7858 @interface CYSettingsController : CYViewController <
7859 UITableViewDataSource,
7862 _transient Database *database_;
7863 // XXX: ok, "roledelegate_"?...
7864 _transient id roledelegate_;
7865 UITableView *table_;
7866 UISegmentedControl *segment_;
7870 - (void) showDoneButton;
7871 - (void) resizeSegmentedControl;
7875 @implementation CYSettingsController
7879 [container_ release];
7884 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7885 if ((self = [super init])) {
7886 database_ = database;
7887 roledelegate_ = delegate;
7889 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
7891 NSArray *items = [NSArray arrayWithObjects:
7893 UCLocalize("HACKER"),
7894 UCLocalize("DEVELOPER"),
7896 segment_ = [[UISegmentedControl alloc] initWithItems:items];
7897 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
7898 [container_ addSubview:segment_];
7901 if ([Role_ isEqualToString:@"User"]) index = 0;
7902 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
7903 if ([Role_ isEqualToString:@"Developer"]) index = 2;
7905 [segment_ setSelectedSegmentIndex:index];
7906 [self showDoneButton];
7909 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
7910 [self resizeSegmentedControl];
7912 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7913 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7914 [table_ setDelegate:self];
7915 [table_ setDataSource:self];
7916 [[self view] addSubview:table_];
7917 [table_ reloadData];
7921 - (void) resizeSegmentedControl {
7922 CGFloat width = [[self view] frame].size.width;
7923 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
7926 - (void) viewWillAppear:(BOOL)animated {
7927 [super viewWillAppear:animated];
7929 [self resizeSegmentedControl];
7932 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
7933 [self resizeSegmentedControl];
7936 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
7937 [self resizeSegmentedControl];
7941 NSString *role(nil);
7943 switch ([segment_ selectedSegmentIndex]) {
7944 case 0: role = @"User"; break;
7945 case 1: role = @"Hacker"; break;
7946 case 2: role = @"Developer"; break;
7951 if (![role isEqualToString:Role_]) {
7952 bool rolling(Role_ == nil);
7955 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
7959 [Metadata_ setObject:Settings_ forKey:@"Settings"];
7963 [roledelegate_ loadData];
7965 [roledelegate_ updateData];
7969 - (void) segmentChanged:(UISegmentedControl *)control {
7970 [self showDoneButton];
7973 - (void) saveAndClose {
7976 [[self navigationItem] setRightBarButtonItem:nil];
7977 [[self navigationController] dismissModalViewControllerAnimated:YES];
7980 - (void) doneButtonClicked {
7981 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
7982 [spinner startAnimating];
7983 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
7984 [[self navigationItem] setRightBarButtonItem:spinItem];
7986 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
7989 - (void) showDoneButton {
7990 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7991 initWithTitle:UCLocalize("DONE")
7992 style:UIBarButtonItemStyleDone
7994 action:@selector(doneButtonClicked)
7995 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
7998 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7999 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8003 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8007 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8008 return nil; // This method is required by the protocol.
8011 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8013 return UCLocalize("ROLE_EX");
8015 return [NSString stringWithFormat:
8016 @"%@: %@\n%@: %@\n%@: %@",
8017 UCLocalize("USER"), UCLocalize("USER_EX"),
8018 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8019 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8024 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8025 return section == 3 ? 44.0f : 0;
8028 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8029 return section == 3 ? container_ : nil;
8034 /* Stash Controller {{{ */
8035 @interface CYStashController : CYViewController {
8036 // XXX: just delete these things
8037 _transient UIActivityIndicatorView *spinner_;
8038 _transient UILabel *status_;
8039 _transient UILabel *caption_;
8043 @implementation CYStashController
8045 if ((self = [super init])) {
8046 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8048 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8049 CGRect spinrect = [spinner_ frame];
8050 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8051 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8052 [spinner_ setFrame:spinrect];
8053 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8054 [[self view] addSubview:spinner_];
8055 [spinner_ startAnimating];
8058 captrect.size.width = [[self view] frame].size.width;
8059 captrect.size.height = 40.0f;
8060 captrect.origin.x = 0;
8061 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8062 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8063 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8064 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8065 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8066 [caption_ setTextColor:[UIColor whiteColor]];
8067 [caption_ setBackgroundColor:[UIColor clearColor]];
8068 [caption_ setShadowColor:[UIColor blackColor]];
8069 [caption_ setTextAlignment:UITextAlignmentCenter];
8070 [[self view] addSubview:caption_];
8073 statusrect.size.width = [[self view] frame].size.width;
8074 statusrect.size.height = 30.0f;
8075 statusrect.origin.x = 0;
8076 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8077 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8078 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8079 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8080 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8081 [status_ setTextColor:[UIColor whiteColor]];
8082 [status_ setBackgroundColor:[UIColor clearColor]];
8083 [status_ setShadowColor:[UIColor blackColor]];
8084 [status_ setTextAlignment:UITextAlignmentCenter];
8085 [[self view] addSubview:status_];
8089 - (BOOL) shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)orientation {
8090 return IsWildcat_ || orientation == UIInterfaceOrientationPortrait;
8105 @interface Cydia : UIApplication <
8106 ConfirmationControllerDelegate,
8107 ProgressControllerDelegate,
8109 UINavigationControllerDelegate,
8110 UITabBarControllerDelegate
8112 // XXX: evaluate all fields for _transient
8115 CYTabBarController *tabbar_;
8117 NSMutableArray *essential_;
8118 NSMutableArray *broken_;
8120 Database *database_;
8128 CYSectionsController *sections_;
8129 ChangesController *changes_;
8130 ManageController *manage_;
8131 SearchController *search_;
8132 SourceController *sources_;
8133 InstalledController *installed_;
8136 CYStashController *stash_;
8141 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class;
8142 - (void) setPage:(CYViewController *)page;
8145 // XXX: I hate prototypes
8146 - (id) queueBadgeController;
8150 static _finline void _setHomePage(Cydia *self) {
8151 [self setPage:[self _pageForURL:[NSURL URLWithString:CydiaURL(@"")] withClass:[HomeController class]]];
8154 @implementation Cydia
8156 - (void) beginUpdate {
8157 [tabbar_ beginUpdate];
8161 return [tabbar_ updating];
8165 if ([broken_ count] != 0) {
8166 int count = [broken_ count];
8168 UIAlertView *alert = [[[UIAlertView alloc]
8169 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8170 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8172 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8173 otherButtonTitles:UCLocalize("TEMPORARY_IGNORE"), nil
8176 [alert setContext:@"fixhalf"];
8178 } else if (!Ignored_ && [essential_ count] != 0) {
8179 int count = [essential_ count];
8181 UIAlertView *alert = [[[UIAlertView alloc]
8182 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8183 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8185 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8186 otherButtonTitles:UCLocalize("UPGRADE_ESSENTIAL"), UCLocalize("COMPLETE_UPGRADE"), nil
8189 [alert setContext:@"upgrade"];
8194 - (void) _saveConfig {
8200 NSString *error(nil);
8202 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8204 NSError *error(nil);
8205 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8206 NSLog(@"failure to save metadata data: %@", error);
8211 NSLog(@"failure to serialize metadata: %@", error);
8216 - (void) _updateData {
8219 NSMutableSet *tabs([[[NSMutableSet alloc] initWithCapacity:10] autorelease]);
8221 [tabs addObject:[tabbar_ selectedViewController]];
8223 if (sections_ != nil)
8224 [tabs addObject:sections_];
8225 if (changes_ != nil)
8226 [tabs addObject:changes_];
8228 [tabs addObject:manage_];
8230 [tabs addObject:search_];
8231 if (sources_ != nil)
8232 [tabs addObject:sources_];
8233 if (installed_ != nil)
8234 [tabs addObject:installed_];
8236 for (CYNavigationController *tab in tabs)
8239 [queueDelegate_ queueStatusDidChange];
8240 [[[self queueBadgeController] tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8243 - (int)indexOfTabWithTag:(int)tag {
8245 for (UINavigationController *controller in [tabbar_ viewControllers]) {
8246 if ([[controller tabBarItem] tag] == tag)
8254 - (void) _refreshIfPossible {
8255 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8257 bool recently = false;
8258 NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
8259 if (update != nil) {
8260 NSTimeInterval interval([update timeIntervalSinceNow]);
8261 if (interval <= 0 && interval > -(15*60))
8265 // Don't automatic refresh if:
8266 // - We already refreshed recently.
8267 // - We already auto-refreshed this launch.
8268 // - Auto-refresh is disabled.
8269 if (recently || loaded_ || ManualRefresh) {
8270 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8272 // If we are cancelling due to ManualRefresh or a recent refresh
8273 // we need to make sure it knows it's already loaded.
8277 // We are going to load, so remember that.
8281 SCNetworkReachabilityFlags flags; {
8282 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8283 SCNetworkReachabilityGetFlags(reachability, &flags);
8284 CFRelease(reachability);
8287 // XXX: this elaborate mess is what Apple is using to determine this? :(
8288 // XXX: do we care if the user has to intervene? maybe that's ok?
8290 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8291 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8292 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8293 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8294 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8295 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8299 // If we can reach the server, auto-refresh!
8301 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8306 - (void) refreshIfPossible {
8307 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
8310 - (void) _reloadData {
8311 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8312 [hud setText:UCLocalize("RELOADING_DATA")];
8314 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
8317 [self removeProgressHUD:hud];
8321 [essential_ removeAllObjects];
8322 [broken_ removeAllObjects];
8324 NSArray *packages([database_ packages]);
8325 for (Package *package in packages) {
8327 [broken_ addObject:package];
8328 if ([package upgradableAndEssential:NO]) {
8329 if ([package essential])
8330 [essential_ addObject:package];
8335 NSLog(@"changes:#%u", changes);
8337 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:[self indexOfTabWithTag:kChangesTag]] tabBarItem];
8340 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8341 [changesItem setBadgeValue:badge];
8342 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8343 [self setApplicationIconBadgeNumber:changes];
8346 [changesItem setBadgeValue:nil];
8347 [changesItem setAnimatedBadge:NO];
8348 [self setApplicationIconBadgeNumber:0];
8353 [self refreshIfPossible];
8356 - (void) updateData {
8365 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8366 _assert(file != NULL);
8368 for (NSString *key in [Sources_ allKeys]) {
8369 NSDictionary *source([Sources_ objectForKey:key]);
8371 fprintf(file, "%s %s %s\n",
8372 [[source objectForKey:@"Type"] UTF8String],
8373 [[source objectForKey:@"URI"] UTF8String],
8374 [[source objectForKey:@"Distribution"] UTF8String]
8382 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8383 CYNavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8385 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8386 [tabbar_ presentModalViewController:navigation animated:YES];
8389 detachNewThreadSelector:@selector(update_)
8392 title:UCLocalize("UPDATING_SOURCES")
8396 - (void) reloadData {
8397 @synchronized (self) {
8403 pkgProblemResolver *resolver = [database_ resolver];
8405 resolver->InstallProtect();
8406 if (!resolver->Resolve(true))
8411 if (![database_ prepare])
8414 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8415 [page setDelegate:self];
8416 CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]);
8417 [confirm_ setDelegate:self];
8420 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8421 [tabbar_ presentModalViewController:confirm_ animated:YES];
8427 @synchronized (self) {
8432 - (void) clearPackage:(Package *)package {
8433 @synchronized (self) {
8440 - (void) installPackages:(NSArray *)packages {
8441 @synchronized (self) {
8442 for (Package *package in packages)
8449 - (void) installPackage:(Package *)package {
8450 @synchronized (self) {
8457 - (void) removePackage:(Package *)package {
8458 @synchronized (self) {
8465 - (void) distUpgrade {
8466 @synchronized (self) {
8467 if (![database_ upgrade])
8474 @synchronized (self) {
8479 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8482 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8484 if (navigation != nil) {
8485 [navigation pushViewController:progress animated:YES];
8487 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8489 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8490 [tabbar_ presentModalViewController:navigation animated:YES];
8494 detachNewThreadSelector:@selector(perform)
8497 title:UCLocalize("RUNNING")
8503 - (void) progressControllerIsComplete:(ProgressController *)progress {
8508 - (void) setPage:(CYViewController *)page {
8509 [page setDelegate:self];
8511 CYNavigationController *navController = (CYNavigationController *) [tabbar_ selectedViewController];
8512 [navController setViewControllers:[NSArray arrayWithObject:page]];
8513 for (CYNavigationController *page in [tabbar_ viewControllers])
8514 if (page != navController)
8515 [page setViewControllers:nil];
8518 - (CYViewController *) _pageForURL:(NSURL *)url withClass:(Class)_class {
8519 CYBrowserController *browser = [[[_class alloc] init] autorelease];
8520 [browser loadURL:url];
8524 - (CYSectionsController *) sectionsController {
8525 if (sections_ == nil)
8526 sections_ = [[CYSectionsController alloc] initWithDatabase:database_];
8530 - (ChangesController *) changesController {
8531 if (changes_ == nil)
8532 changes_ = [[ChangesController alloc] initWithDatabase:database_ delegate:self];
8536 - (ManageController *) manageController {
8537 if (manage_ == nil) {
8538 manage_ = (ManageController *) [[self
8539 _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]
8540 withClass:[ManageController class]
8543 queueDelegate_ = manage_;
8548 - (SearchController *) searchController {
8550 search_ = [[SearchController alloc] initWithDatabase:database_];
8554 - (SourceController *) sourcesController {
8555 if (sources_ == nil)
8556 sources_ = [[SourceController alloc] initWithDatabase:database_];
8560 - (InstalledController *) installedController {
8561 if (installed_ == nil) {
8562 installed_ = [[InstalledController alloc] initWithDatabase:database_];
8564 queueDelegate_ = installed_;
8569 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
8570 int tag = [[viewController tabBarItem] tag];
8572 [(CYNavigationController *)[tabbar_ selectedViewController] popToRootViewControllerAnimated:YES];
8574 } else if (tag_ == 1) {
8575 [[self sectionsController] resetView];
8579 case kCydiaTag: _setHomePage(self); break;
8581 case kSectionsTag: [self setPage:[self sectionsController]]; break;
8582 case kChangesTag: [self setPage:[self changesController]]; break;
8583 case kManageTag: [self setPage:[self manageController]]; break;
8584 case kInstalledTag: [self setPage:[self installedController]]; break;
8585 case kSourcesTag: [self setPage:[self sourcesController]]; break;
8586 case kSearchTag: [self setPage:[self searchController]]; break;
8594 - (void) showSettings {
8595 CYSettingsController *role = [[[CYSettingsController alloc] initWithDatabase:database_ delegate:self] autorelease];
8596 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
8598 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
8599 [tabbar_ presentModalViewController:nav animated:YES];
8602 - (void) retainNetworkActivityIndicator {
8603 if (activity_++ == 0)
8604 [self setNetworkActivityIndicatorVisible:YES];
8607 - (void) releaseNetworkActivityIndicator {
8608 if (--activity_ == 0)
8609 [self setNetworkActivityIndicatorVisible:NO];
8612 - (void) setPackageController:(PackageController *)view {
8614 [view setPackage:nil];
8618 - (PackageController *) _packageController {
8619 return [[[PackageController alloc] initWithDatabase:database_] autorelease];
8622 - (PackageController *) packageController {
8623 return [self _packageController];
8626 // Returns the navigation controller for the queuing badge.
8627 - (id) queueBadgeController {
8628 int index = [self indexOfTabWithTag:kManageTag];
8630 index = [self indexOfTabWithTag:kInstalledTag];
8632 return [[tabbar_ viewControllers] objectAtIndex:index];
8635 - (void) cancelAndClear:(bool)clear {
8636 @synchronized (self) {
8648 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8649 NSString *context([alert context]);
8651 if ([context isEqualToString:@"fixhalf"]) {
8652 if (button == [alert firstOtherButtonIndex]) {
8653 @synchronized (self) {
8654 for (Package *broken in broken_) {
8657 NSString *id = [broken id];
8658 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8659 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8660 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8661 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8667 } else if (button == [alert cancelButtonIndex]) {
8668 [broken_ removeAllObjects];
8672 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8673 } else if ([context isEqualToString:@"upgrade"]) {
8674 if (button == [alert firstOtherButtonIndex]) {
8675 @synchronized (self) {
8676 for (Package *essential in essential_)
8677 [essential install];
8682 } else if (button == [alert firstOtherButtonIndex] + 1) {
8684 } else if (button == [alert cancelButtonIndex]) {
8688 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8692 - (void) system:(NSString *)command { _pooled
8694 system([command UTF8String]);
8698 - (void) applicationWillSuspend {
8700 [super applicationWillSuspend];
8703 - (BOOL) isSafeToSuspend {
8704 // Use external process status API internally.
8705 // This is probably a really bad idea.
8706 // XXX: what is the point of this? does this solve anything at all?
8707 uint64_t status = 0;
8709 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
8710 notify_get_state(notify_token, &status);
8711 notify_cancel(notify_token);
8714 return locked_ == 0 && status == 0;
8717 - (void) applicationSuspend:(__GSEvent *)event {
8718 if ([self isSafeToSuspend])
8719 [super applicationSuspend:event];
8722 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8723 if ([self isSafeToSuspend])
8724 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8727 - (void) _setSuspended:(BOOL)value {
8728 if ([self isSafeToSuspend])
8729 [super _setSuspended:value];
8732 - (UIProgressHUD *) addProgressHUD {
8733 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8734 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8736 [window_ setUserInteractionEnabled:NO];
8739 UIViewController *target = tabbar_;
8740 while ([target modalViewController] != nil) target = [target modalViewController];
8741 [[target view] addSubview:hud];
8747 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8749 [hud removeFromSuperview];
8750 [window_ setUserInteractionEnabled:YES];
8754 - (CYViewController *) pageForPackage:(NSString *)name {
8755 if (Package *package = [database_ packageWithName:name]) {
8756 PackageController *view([self packageController]);
8757 [view setPackage:package];
8760 NSURL *url([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"unknown" ofType:@"html"]]);
8761 url = [NSURL URLWithString:[[url absoluteString] stringByAppendingString:[NSString stringWithFormat:@"?%@", name]]];
8762 return [self _pageForURL:url withClass:[CYBrowserController class]];
8766 - (CYViewController *) pageForURL:(NSURL *)url hasTag:(int *)tag {
8770 NSString *href([url absoluteString]);
8771 if ([href hasPrefix:@"apptapp://package/"])
8772 return [self pageForPackage:[href substringFromIndex:18]];
8774 NSString *scheme([[url scheme] lowercaseString]);
8775 if (![scheme isEqualToString:@"cydia"])
8777 NSString *path([url absoluteString]);
8778 if ([path length] < 8)
8780 path = [path substringFromIndex:8];
8781 if (![path hasPrefix:@"/"])
8782 path = [@"/" stringByAppendingString:path];
8784 if ([path isEqualToString:@"/storage"])
8785 return [self _pageForURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]] withClass:[CYBrowserController class]];
8786 /*else if ([path isEqualToString:@"/add-source"])
8787 return [[[AddSourceController alloc] initWithDatabase:database_] autorelease];*/
8788 else if ([path isEqualToString:@"/sources"])
8789 return [[[SourceController alloc] initWithDatabase:database_] autorelease];
8790 else if ([path isEqualToString:@"/packages"])
8791 return [[[InstalledController alloc] initWithDatabase:database_] autorelease];
8792 else if ([path hasPrefix:@"/url/"])
8793 return [self _pageForURL:[NSURL URLWithString:[path substringFromIndex:5]] withClass:[CYBrowserController class]];
8794 else if ([path hasPrefix:@"/launch/"])
8795 [self launchApplicationWithIdentifier:[path substringFromIndex:8] suspended:NO];
8796 else if ([path hasPrefix:@"/package-settings/"])
8797 return [[[CYPackageSettingsController alloc] initWithDatabase:database_ package:[path substringFromIndex:18]] autorelease];
8798 else if ([path hasPrefix:@"/package-signature/"])
8799 return [[[SignatureController alloc] initWithDatabase:database_ package:[path substringFromIndex:19]] autorelease];
8800 else if ([path hasPrefix:@"/package/"])
8801 return [self pageForPackage:[path substringFromIndex:9]];
8802 else if ([path hasPrefix:@"/files/"]) {
8803 NSString *name = [path substringFromIndex:7];
8805 if (Package *package = [database_ packageWithName:name]) {
8806 FileTable *files = [[[FileTable alloc] initWithDatabase:database_] autorelease];
8807 [files setPackage:package];
8815 - (BOOL) openCydiaURL:(NSURL *)url {
8816 CYViewController *page = nil;
8819 if ((page = [self pageForURL:url hasTag:&tag])) {
8820 [self setPage:page];
8822 [tabbar_ setSelectedViewController:(tag_ == -1 ? nil : [[tabbar_ viewControllers] objectAtIndex:tag_])];
8828 - (void) applicationOpenURL:(NSURL *)url {
8829 [super applicationOpenURL:url];
8831 if (!loaded_) starturl_ = [url retain];
8832 else [self openCydiaURL:url];
8835 - (void) applicationWillResignActive:(UIApplication *)application {
8836 // Stop refreshing if you get a phone call or lock the device.
8837 if ([tabbar_ updating])
8838 [tabbar_ cancelUpdate];
8840 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
8841 [super applicationWillResignActive:application];
8844 - (void) addStashController {
8846 stash_ = [[CYStashController alloc] init];
8847 [window_ addSubview:[stash_ view]];
8850 - (void) removeStashController {
8851 [[stash_ view] removeFromSuperview];
8857 [self setIdleTimerDisabled:YES];
8859 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
8860 [self setStatusBarShowsProgress:YES];
8861 UpdateExternalStatus(1);
8863 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
8865 UpdateExternalStatus(0);
8866 [self setStatusBarShowsProgress:NO];
8868 [self removeStashController];
8870 if (ExecFork() == 0) {
8871 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
8872 perror("launchctl stop");
8876 - (void) setupTabBarController {
8877 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
8878 [tabbar_ setDelegate:self];
8880 NSMutableArray *items([NSMutableArray arrayWithObjects:
8881 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:kCydiaTag] autorelease],
8882 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:kSectionsTag] autorelease],
8883 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:kChangesTag] autorelease],
8884 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:kSearchTag] autorelease],
8888 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:kSourcesTag] autorelease] atIndex:3];
8889 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:kInstalledTag] autorelease] atIndex:3];
8891 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:kManageTag] autorelease] atIndex:3];
8894 NSMutableArray *controllers([NSMutableArray array]);
8896 for (UITabBarItem *item in items) {
8897 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
8898 [controller setTabBarItem:item];
8899 [controllers addObject:controller];
8902 [tabbar_ setViewControllers:controllers];
8905 - (void)showFakeTabBarInView:(UIView *)view {
8906 static UITabBar *fake = [[UITabBar alloc] initWithFrame:CGRectMake(0, 0, 0, 49.0f)];
8908 CGRect frame = [fake frame];
8909 frame.origin.y = [view frame].size.height - frame.size.height;
8910 frame.size.width = [view frame].size.width;
8911 [fake setFrame:frame];
8912 [fake setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin];
8913 [view addSubview:fake];
8915 [fake removeFromSuperview];
8919 - (void) applicationDidFinishLaunching:(id)unused {
8923 [NSURLCache setSharedURLCache:[[[SDURLCache alloc]
8924 initWithMemoryCapacity:524288
8925 diskCapacity:10485760
8926 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
8929 [CYBrowserController _initialize];
8931 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8933 Font12_ = [[UIFont systemFontOfSize:12] retain];
8934 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8935 Font14_ = [[UIFont systemFontOfSize:14] retain];
8936 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8937 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8941 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8942 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8944 window_ = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
8945 [window_ orderFront:self];
8946 [window_ makeKey:self];
8947 [window_ setHidden:NO];
8950 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8951 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8952 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8953 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
8954 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8955 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8956 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8957 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
8958 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
8961 [self addStashController];
8962 // XXX: this would be much cleaner as a yieldToSelector:
8963 // that way the removeStashController could happen right here inline
8964 // we also could no longer require the useless stash_ field anymore
8965 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
8969 database_ = [Database sharedInstance];
8971 [self setupTabBarController];
8972 [tabbar_ setUpdateDelegate:self];
8973 [window_ addSubview:[tabbar_ view]];
8975 // Show pinstripes while loading data.
8976 [[tabbar_ view] setBackgroundColor:[UIColor pinStripeColor]];
8977 [self showFakeTabBarInView:[tabbar_ tabBar]];
8979 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
8986 [self showSettings];
8990 CGRect fixframe = [[tabbar_ view] frame];
8991 if (UIInterfaceOrientationIsLandscape([[UIApplication sharedApplication] statusBarOrientation]))
8992 fixframe.size = CGSizeMake(fixframe.size.height, fixframe.size.width);
8993 CYLoadingIndicator *loading = [[[CYLoadingIndicator alloc] initWithFrame:fixframe] autorelease];
8994 [loading setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8995 [[tabbar_ view] addSubview:loading];
8996 [window_ setUserInteractionEnabled:NO];
9001 // Show the initial page
9002 if (starturl_ == nil || ![self openCydiaURL:starturl_]) {
9003 [tabbar_ setSelectedIndex:0];
9007 [self showFakeTabBarInView:nil];
9009 [starturl_ release];
9012 [window_ setUserInteractionEnabled:YES];
9014 // XXX: does this actually slow anything down?
9015 [[tabbar_ view] setBackgroundColor:[UIColor clearColor]];
9016 [loading removeFromSuperview];
9019 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9020 if (item != nil && IsWildcat_) {
9021 [sheet showFromBarButtonItem:item animated:YES];
9023 [sheet showInView:window_];
9030 id Alloc_(id self, SEL selector) {
9031 id object = alloc_(self, selector);
9032 lprintf("[%s]A-%p\n", self->isa->name, object);
9037 id Dealloc_(id self, SEL selector) {
9038 id object = dealloc_(self, selector);
9039 lprintf("[%s]D-%p\n", self->isa->name, object);
9043 Class $WebDefaultUIKitDelegate;
9045 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9046 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9047 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9048 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9051 static NSNumber *shouldPlayKeyboardSounds;
9055 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
9057 case 1104: // Keyboard Button Clicked
9058 case 1105: // Keyboard Delete Repeated
9059 if (shouldPlayKeyboardSounds == nil) {
9060 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
9061 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
9064 if (![shouldPlayKeyboardSounds boolValue])
9068 _UIHardware$_playSystemSound$(self, _cmd, sound);
9072 int main(int argc, char *argv[]) { _pooled
9075 if (Class $UIDevice = objc_getClass("UIDevice")) {
9076 UIDevice *device([$UIDevice currentDevice]);
9077 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
9081 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9083 /* Library Hacks {{{ */
9084 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
9086 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
9087 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
9088 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
9089 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
9090 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
9093 $UIHardware = objc_getClass("UIHardware");
9094 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
9095 if (UIHardware$_playSystemSound$ != NULL) {
9096 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
9097 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
9100 /* Set Locale {{{ */
9101 Locale_ = CFLocaleCopyCurrent();
9102 Languages_ = [NSLocale preferredLanguages];
9103 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
9104 //NSLog(@"%@", [Languages_ description]);
9107 if (Languages_ == nil || [Languages_ count] == 0)
9108 // XXX: consider just setting to C and then falling through?
9111 lang = [[Languages_ objectAtIndex:0] UTF8String];
9112 setenv("LANG", lang, true);
9115 //std::setlocale(LC_ALL, lang);
9116 NSLog(@"Setting Language: %s", lang);
9119 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
9121 /* Parse Arguments {{{ */
9122 bool substrate(false);
9128 for (int argi(1); argi != argc; ++argi)
9129 if (strcmp(argv[argi], "--") == 0) {
9131 argv[argi] = argv[0];
9137 for (int argi(1); argi != arge; ++argi)
9138 if (strcmp(args[argi], "--substrate") == 0)
9141 fprintf(stderr, "unknown argument: %s\n", args[argi]);
9145 App_ = [[NSBundle mainBundle] bundlePath];
9146 Home_ = NSHomeDirectory();
9152 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
9153 alloc_ = alloc->method_imp;
9154 alloc->method_imp = (IMP) &Alloc_;*/
9156 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
9157 dealloc_ = dealloc->method_imp;
9158 dealloc->method_imp = (IMP) &Dealloc_;*/
9160 /* System Information {{{ */
9164 size = sizeof(maxproc);
9165 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9166 perror("sysctlbyname(\"kern.maxproc\", ?)");
9167 else if (maxproc < 64) {
9169 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9170 perror("sysctlbyname(\"kern.maxproc\", #)");
9173 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
9174 char *osversion = new char[size];
9175 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
9176 perror("sysctlbyname(\"kern.osversion\", ?)");
9178 System_ = [NSString stringWithUTF8String:osversion];
9180 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
9181 char *machine = new char[size];
9182 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
9183 perror("sysctlbyname(\"hw.machine\", ?)");
9187 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
9188 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
9189 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
9190 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
9194 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
9195 NSData *data((NSData *) ecid);
9196 size_t length([data length]);
9197 uint8_t bytes[length];
9198 [data getBytes:bytes];
9199 char string[length * 2 + 1];
9200 for (size_t i(0); i != length; ++i)
9201 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
9202 ChipID_ = [NSString stringWithUTF8String:string];
9206 IOObjectRelease(service);
9210 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
9212 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
9213 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9214 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
9216 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
9217 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9218 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
9220 if (mcc != NULL && mnc != NULL)
9221 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9228 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9229 Build_ = [system objectForKey:@"ProductBuildVersion"];
9230 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9231 Product_ = [info objectForKey:@"SafariProductVersion"];
9232 Safari_ = [info objectForKey:@"CFBundleVersion"];
9235 /* Load Database {{{ */
9237 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9239 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9241 if (Metadata_ == NULL)
9242 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9244 Settings_ = [Metadata_ objectForKey:@"Settings"];
9246 Packages_ = [Metadata_ objectForKey:@"Packages"];
9247 Sections_ = [Metadata_ objectForKey:@"Sections"];
9248 Sources_ = [Metadata_ objectForKey:@"Sources"];
9250 Token_ = [Metadata_ objectForKey:@"Token"];
9253 if (Settings_ != nil)
9254 Role_ = [Settings_ objectForKey:@"Role"];
9256 if (Sections_ == nil) {
9257 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9258 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9261 if (Sources_ == nil) {
9262 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9263 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9268 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
9271 if (Packages_ != nil) {
9272 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, NULL);
9274 [Metadata_ removeObjectForKey:@"Packages"];
9279 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9281 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", F_OK) == 0)
9282 dlopen("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", RTLD_LAZY | RTLD_GLOBAL);
9283 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
9284 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
9285 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9286 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9288 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9290 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9291 unlink("/tmp/.cydia.fw");
9293 } else if (access("/User", F_OK) != 0 || version < 2) {
9296 system("/usr/libexec/cydia/firmware.sh");
9300 _assert([[NSFileManager defaultManager]
9301 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9302 withIntermediateDirectories:YES
9307 if (access("/tmp/cydia.chk", F_OK) == 0) {
9308 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9309 _assert(errno == ENOENT);
9310 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9311 _assert(errno == ENOENT);
9314 /* APT Initialization {{{ */
9315 _assert(pkgInitConfig(*_config));
9316 _assert(pkgInitSystem(*_config, _system));
9319 _config->Set("APT::Acquire::Translation", lang);
9321 // XXX: this timeout might be important :(
9322 //_config->Set("Acquire::http::Timeout", 15);
9324 _config->Set("Acquire::http::MaxParallel", 3);
9326 /* Color Choices {{{ */
9327 space_ = CGColorSpaceCreateDeviceRGB();
9329 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9330 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9331 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9332 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9333 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9334 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9335 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9336 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9337 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9339 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9340 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9342 /* UIKit Configuration {{{ */
9343 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9344 if ($GSFontSetUseLegacyFontMetrics != NULL)
9345 $GSFontSetUseLegacyFontMetrics(YES);
9347 // XXX: I have a feeling this was important
9348 //UIKeyboardDisableAutomaticAppearance();
9351 Colon_ = UCLocalize("COLON_DELIMITED");
9352 Elision_ = UCLocalize("ELISION");
9353 Error_ = UCLocalize("ERROR");
9354 Warning_ = UCLocalize("WARNING");
9357 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9359 CGColorSpaceRelease(space_);