1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2011 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 static _finline NSString *CydiaURL(NSString *path) {
222 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = ':';
223 page[5] = '/'; page[6] = '/'; page[7] = 'c'; page[8] = 'y'; page[9] = 'd';
224 page[10] = 'i'; page[11] = 'a'; page[12] = '.'; page[13] = 's'; page[14] = 'a';
225 page[15] = 'u'; page[16] = 'r'; page[17] = 'i'; page[18] = 'k'; page[19] = '.';
226 page[20] = 'c'; page[21] = 'o'; page[22] = 'm'; page[23] = '/'; page[24] = '\0';
227 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
230 static _finline void UpdateExternalStatus(uint64_t newStatus) {
232 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
233 notify_set_state(notify_token, newStatus);
234 notify_cancel(notify_token);
236 notify_post("com.saurik.Cydia.status");
239 /* [NSObject yieldToSelector:(withObject:)] {{{*/
240 @interface NSObject (Cydia)
241 - (id) yieldToSelector:(SEL)selector withObject:(id)object;
242 - (id) yieldToSelector:(SEL)selector;
245 @implementation NSObject (Cydia)
250 - (void) _yieldToContext:(NSMutableArray *)context { _pooled
251 SEL selector(reinterpret_cast<SEL>([[context objectAtIndex:0] pointerValue]));
252 id object([[context objectAtIndex:1] nonretainedObjectValue]);
253 volatile bool &stopped(*reinterpret_cast<bool *>([[context objectAtIndex:2] pointerValue]));
255 /* XXX: deal with exceptions */
256 id value([self performSelector:selector withObject:object]);
258 NSMethodSignature *signature([self methodSignatureForSelector:selector]);
259 [context removeAllObjects];
260 if ([signature methodReturnLength] != 0 && value != nil)
261 [context addObject:value];
266 performSelectorOnMainThread:@selector(doNothing)
272 - (id) yieldToSelector:(SEL)selector withObject:(id)object {
273 volatile bool stopped(false);
275 NSMutableArray *context([NSMutableArray arrayWithObjects:
276 [NSValue valueWithPointer:selector],
277 [NSValue valueWithNonretainedObject:object],
278 [NSValue valueWithPointer:const_cast<bool *>(&stopped)],
281 NSThread *thread([[[NSThread alloc]
283 selector:@selector(_yieldToContext:)
289 NSRunLoop *loop([NSRunLoop currentRunLoop]);
290 NSDate *future([NSDate distantFuture]);
292 while (!stopped && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
294 return [context count] == 0 ? nil : [context objectAtIndex:0];
297 - (id) yieldToSelector:(SEL)selector {
298 return [self yieldToSelector:selector withObject:nil];
304 /* Cydia Alert View {{{ */
305 @interface CYAlertView : UIAlertView {
309 - (int) yieldToPopupAlertAnimated:(BOOL)animated;
313 @implementation CYAlertView
315 - (id) initWithTitle:(NSString *)title buttons:(NSArray *)buttons defaultButtonIndex:(int)index {
316 if ((self = [super init]) != nil) {
317 [self setTitle:title];
318 [self setDelegate:self];
319 for (NSString *button in buttons) [self addButtonWithTitle:button];
320 [self setCancelButtonIndex:index];
324 - (void) _updateFrameForDisplay {
325 [super _updateFrameForDisplay];
326 if ([self cancelButtonIndex] == -1) {
327 NSArray *buttons = [self buttons];
328 if ([buttons count]) {
329 UIImage *background = [[buttons objectAtIndex:0] backgroundForState:0];
330 for (UIThreePartButton *button in buttons)
331 [button setBackground:background forState:0];
336 - (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
337 button_ = buttonIndex + 1;
341 [self dismissWithClickedButtonIndex:-1 animated:YES];
344 - (int) yieldToPopupAlertAnimated:(BOOL)animated {
345 [self setRunsModal:YES];
354 /* NSForcedOrderingSearch doesn't work on the iPhone */
355 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
356 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
357 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
359 #define lprintf(args...) fprintf(stderr, args)
362 #define TraceLogging (1 && !ForRelease)
363 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
364 #define ProfileTimes (0 && !ForRelease)
365 #define ForSaurik (0 && !ForRelease)
366 #define LogBrowser (0 && !ForRelease)
367 #define TrackResize (0 && !ForRelease)
368 #define ManualRefresh (1 && !ForRelease)
369 #define ShowInternals (0 && !ForRelease)
370 #define AlwaysReload (0 && !ForRelease)
371 #define TryIndexedCollation (0 && !ForRelease)
375 #define _trace(args...)
380 #define _profile(name) {
383 #define PrintTimes() do {} while (false)
387 typedef uint32_t (*SKRadixFunction)(id, void *);
389 @interface NSMutableArray (Radix)
390 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
398 @implementation NSMutableArray (Radix)
400 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
401 size_t count([self count]);
402 struct RadixItem_ *swap(new RadixItem_[count * 2]);
404 for (size_t i(0); i != count; ++i) {
405 RadixItem_ &item(swap[i]);
408 id object([self objectAtIndex:i]);
409 item.key = function(object, argument);
412 struct RadixItem_ *lhs(swap), *rhs(swap + count);
414 static const size_t width = 32;
415 static const size_t bits = 11;
416 static const size_t slots = 1 << bits;
417 static const size_t passes = (width + (bits - 1)) / bits;
419 size_t *hist(new size_t[slots]);
421 for (size_t pass(0); pass != passes; ++pass) {
422 memset(hist, 0, sizeof(size_t) * slots);
424 for (size_t i(0); i != count; ++i) {
425 uint32_t key(lhs[i].key);
427 key &= _not(uint32_t) >> width - bits;
432 for (size_t i(0); i != slots; ++i) {
433 size_t local(offset);
438 for (size_t i(0); i != count; ++i) {
439 uint32_t key(lhs[i].key);
441 key &= _not(uint32_t) >> width - bits;
442 rhs[hist[key]++] = lhs[i];
445 RadixItem_ *tmp(lhs);
452 const void **values(new const void *[count]);
453 for (size_t i(0); i != count; ++i)
454 values[i] = [self objectAtIndex:lhs[i].index];
455 CFArrayReplaceValues((CFMutableArrayRef) self, CFRangeMake(0, count), values, count);
463 /* Insertion Sort {{{ */
465 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
466 const char *ptr = (const char *)list;
468 CFIndex half = count / 2;
469 const char *probe = ptr + elementSize * half;
470 CFComparisonResult cr = comparator(element, probe, context);
471 if (0 == cr) return (probe - (const char *)list) / elementSize;
472 ptr = (cr < 0) ? ptr : probe + elementSize;
473 count = (cr < 0) ? half : (half + (count & 1) - 1);
475 return (ptr - (const char *)list) / elementSize;
478 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
479 const char *ptr = (const char *)list;
481 CFIndex half = count / 2;
482 const char *probe = ptr + elementSize * half;
483 CFComparisonResult cr = comparator(element, probe, context);
484 if (0 == cr) return (probe - (const char *)list) / elementSize;
485 ptr = (cr < 0) ? ptr : probe + elementSize;
486 count = (cr < 0) ? half : (half + (count & 1) - 1);
488 return (ptr - (const char *)list) / elementSize;
491 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
492 if (range.length == 0)
494 const void **values(new const void *[range.length]);
495 CFArrayGetValues(array, range, values);
497 #if HistogramInsertionSort > 0
498 uint32_t total(0), *offsets(new uint32_t[range.length]);
501 for (CFIndex index(1); index != range.length; ++index) {
502 const void *value(values[index]);
503 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
504 CFIndex correct(index);
505 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
506 #if HistogramInsertionSort > 1
507 NSLog(@"%@ < %@", value, values[correct - 1]);
512 if (correct != index) {
513 size_t offset(index - correct);
514 #if HistogramInsertionSort
518 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
520 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
521 values[correct] = value;
525 CFArrayReplaceValues(array, range, values, range.length);
528 #if HistogramInsertionSort > 0
529 for (CFIndex index(0); index != range.length; ++index)
530 if (offsets[index] != 0)
531 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
532 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
539 /* Apple Bug Fixes {{{ */
540 @implementation UIWebDocumentView (Cydia)
542 - (void) _setScrollerOffset:(CGPoint)offset {
543 UIScroller *scroller([self _scroller]);
545 CGSize size([scroller contentSize]);
546 CGSize bounds([scroller bounds].size);
549 max.x = size.width - bounds.width;
550 max.y = size.height - bounds.height;
558 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
559 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
561 [scroller setOffset:offset];
567 @interface NSInvocation (Cydia)
568 + (NSInvocation *) invocationWithSelector:(SEL)selector forTarget:(id)target;
571 @implementation NSInvocation (Cydia)
573 + (NSInvocation *) invocationWithSelector:(SEL)selector forTarget:(id)target {
574 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[target methodSignatureForSelector:selector]]);
575 [invocation setTarget:target];
576 [invocation setSelector:selector];
582 @implementation WebScriptObject (NSFastEnumeration)
584 - (NSUInteger) countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)objects count:(NSUInteger)count {
585 size_t length([self count] - state->state);
588 else if (length > count)
590 for (size_t i(0); i != length; ++i)
591 objects[i] = [self objectAtIndex:state->state++];
592 state->itemsPtr = objects;
593 state->mutationsPtr = (unsigned long *) self;
599 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
600 size_t length([self length] - state->state);
603 else if (length > count)
605 for (size_t i(0); i != length; ++i)
606 objects[i] = [self item:state->state++];
607 state->itemsPtr = objects;
608 state->mutationsPtr = (unsigned long *) self;
612 /* Cydia NSString Additions {{{ */
613 @interface NSString (Cydia)
614 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
615 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
616 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
617 - (NSComparisonResult) compareByPath:(NSString *)other;
618 - (NSString *) stringByCachingURLWithCurrentCDN;
619 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
622 @implementation NSString (Cydia)
624 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
625 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
628 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
629 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
630 memcpy(data, bytes, length);
631 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
634 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
635 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
638 - (NSComparisonResult) compareByPath:(NSString *)other {
639 NSString *prefix = [self commonPrefixWithString:other options:0];
640 size_t length = [prefix length];
642 NSRange lrange = NSMakeRange(length, [self length] - length);
643 NSRange rrange = NSMakeRange(length, [other length] - length);
645 lrange = [self rangeOfString:@"/" options:0 range:lrange];
646 rrange = [other rangeOfString:@"/" options:0 range:rrange];
648 NSComparisonResult value;
650 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
651 value = NSOrderedSame;
652 else if (lrange.location == NSNotFound)
653 value = NSOrderedAscending;
654 else if (rrange.location == NSNotFound)
655 value = NSOrderedDescending;
657 value = NSOrderedSame;
659 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
660 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
661 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
662 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
664 NSComparisonResult result = [lpath compare:rpath];
665 return result == NSOrderedSame ? value : result;
668 - (NSString *) stringByCachingURLWithCurrentCDN {
670 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
671 withString:@"://cache.cydia.saurik.com/"
675 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
676 return [(id)CFURLCreateStringByAddingPercentEscapes(
681 kCFStringEncodingUTF8
688 /* C++ NSString Wrapper Cache {{{ */
689 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
690 return size == 0 ? NULL :
691 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
692 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
695 static _finline CFStringRef CYStringCreate(const char *data) {
696 return CYStringCreate(data, strlen(data));
705 _finline void clear_() {
706 if (cache_ != NULL) {
713 _finline bool empty() const {
717 _finline size_t size() const {
721 _finline char *data() const {
725 _finline void clear() {
730 _finline CYString() :
737 _finline ~CYString() {
741 void operator =(const CYString &rhs) {
745 if (rhs.cache_ == nil)
748 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
751 void copy(apr_pool_t *pool) {
752 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
753 memcpy(temp, data_, size_);
758 void set(apr_pool_t *pool, const char *data, size_t size) {
764 data_ = const_cast<char *>(data);
772 _finline void set(apr_pool_t *pool, const char *data) {
773 set(pool, data, data == NULL ? 0 : strlen(data));
776 _finline void set(apr_pool_t *pool, const std::string &rhs) {
777 set(pool, rhs.data(), rhs.size());
780 bool operator ==(const CYString &rhs) const {
781 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
784 _finline operator CFStringRef() {
786 cache_ = CYStringCreate(data_, size_);
790 _finline operator id() {
791 return (NSString *) static_cast<CFStringRef>(*this);
794 _finline operator const char *() {
795 return reinterpret_cast<const char *>(data_);
799 /* C++ NSString Algorithm Adapters {{{ */
801 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
804 struct NSStringMapHash :
805 std::unary_function<NSString *, size_t>
807 _finline size_t operator ()(NSString *value) const {
808 return CFStringHashNSString((CFStringRef) value);
812 struct NSStringMapLess :
813 std::binary_function<NSString *, NSString *, bool>
815 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
816 return [lhs compare:rhs] == NSOrderedAscending;
820 struct NSStringMapEqual :
821 std::binary_function<NSString *, NSString *, bool>
823 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
824 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
825 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
826 //[lhs isEqualToString:rhs];
831 /* Perl-Compatible RegEx {{{ */
841 Pcre(const char *regex) :
846 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
849 lprintf("%d:%s\n", offset, error);
853 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
854 matches_ = new int[(capture_ + 1) * 3];
862 NSString *operator [](size_t match) {
863 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
866 bool operator ()(NSString *data) {
867 // XXX: length is for characters, not for bytes
868 return operator ()([data UTF8String], [data length]);
871 bool operator ()(const char *data, size_t size) {
873 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
877 /* Mime Addresses {{{ */
878 @interface Address : NSObject {
884 - (NSString *) address;
886 - (void) setAddress:(NSString *)address;
888 + (Address *) addressWithString:(NSString *)string;
889 - (Address *) initWithString:(NSString *)string;
893 @implementation Address
902 - (NSString *) name {
906 - (NSString *) address {
910 - (void) setAddress:(NSString *)address {
912 [address_ autorelease];
916 address_ = [address retain];
919 + (Address *) addressWithString:(NSString *)string {
920 return [[[Address alloc] initWithString:string] autorelease];
923 + (NSArray *) _attributeKeys {
924 return [NSArray arrayWithObjects:
930 - (NSArray *) attributeKeys {
931 return [[self class] _attributeKeys];
934 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
935 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
938 - (Address *) initWithString:(NSString *)string {
939 if ((self = [super init]) != nil) {
940 const char *data = [string UTF8String];
941 size_t size = [string length];
943 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
945 if (address_r(data, size)) {
946 name_ = [address_r[1] retain];
947 address_ = [address_r[2] retain];
949 name_ = [string retain];
957 /* CoreGraphics Primitives {{{ */
962 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
963 CGFloat color[] = {red, green, blue, alpha};
964 return CGColorCreate(space, color);
973 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
974 color_(Create_(space, red, green, blue, alpha))
976 Set(space, red, green, blue, alpha);
981 CGColorRelease(color_);
988 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
990 color_ = Create_(space, red, green, blue, alpha);
993 operator CGColorRef() {
999 /* Random Global Variables {{{ */
1000 static const int PulseInterval_ = 50000;
1002 static const NSString *UI_;
1005 static bool RestartSubstrate_;
1006 static NSArray *Finishes_;
1008 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
1009 #define NotifyConfig_ "/etc/notify.conf"
1011 static bool Queuing_;
1013 static CYColor Blue_;
1014 static CYColor Blueish_;
1015 static CYColor Black_;
1016 static CYColor Off_;
1017 static CYColor White_;
1018 static CYColor Gray_;
1019 static CYColor Green_;
1020 static CYColor Purple_;
1021 static CYColor Purplish_;
1023 static UIColor *InstallingColor_;
1024 static UIColor *RemovingColor_;
1026 static NSString *App_;
1027 static NSString *Home_;
1029 static BOOL Advanced_;
1030 static BOOL Ignored_;
1032 static UIFont *Font12_;
1033 static UIFont *Font12Bold_;
1034 static UIFont *Font14_;
1035 static UIFont *Font18Bold_;
1036 static UIFont *Font22Bold_;
1038 static const char *Machine_ = NULL;
1039 static NSString *System_ = nil;
1040 static NSString *SerialNumber_ = nil;
1041 static NSString *ChipID_ = nil;
1042 static NSString *Token_ = nil;
1043 static NSString *UniqueID_ = nil;
1044 static NSString *PLMN_ = nil;
1045 static NSString *Build_ = nil;
1046 static NSString *Product_ = nil;
1047 static NSString *Safari_ = nil;
1049 static CFLocaleRef Locale_;
1050 static NSArray *Languages_;
1051 static CGColorSpaceRef space_;
1053 static NSDictionary *SectionMap_;
1054 static NSMutableDictionary *Metadata_;
1055 static _transient NSMutableDictionary *Settings_;
1056 static _transient NSString *Role_;
1057 static _transient NSMutableDictionary *Packages_;
1058 static _transient NSMutableDictionary *Sections_;
1059 static _transient NSMutableDictionary *Sources_;
1060 static bool Changed_;
1064 static CGFloat ScreenScale_;
1067 /* Display Helpers {{{ */
1068 inline float Interpolate(float begin, float end, float fraction) {
1069 return (end - begin) * fraction + begin;
1072 static _finline const char *StripVersion_(const char *version) {
1073 const char *colon(strchr(version, ':'));
1074 return colon == NULL ? version : colon + 1;
1077 NSString *LocalizeSection(NSString *section) {
1078 static Pcre title_r("^(.*?) \\((.*)\\)$");
1079 if (title_r(section)) {
1080 NSString *parent(title_r[1]);
1081 NSString *child(title_r[2]);
1083 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1084 LocalizeSection(parent),
1085 LocalizeSection(child)
1089 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1092 NSString *Simplify(NSString *title) {
1093 const char *data = [title UTF8String];
1094 size_t size = [title length];
1096 static Pcre square_r("^\\[(.*)\\]$");
1097 if (square_r(data, size))
1098 return Simplify(square_r[1]);
1100 static Pcre paren_r("^\\((.*)\\)$");
1101 if (paren_r(data, size))
1102 return Simplify(paren_r[1]);
1104 static Pcre title_r("^(.*?) \\((.*)\\)$");
1105 if (title_r(data, size))
1106 return Simplify(title_r[1]);
1112 NSString *GetLastUpdate() {
1113 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1116 return UCLocalize("NEVER_OR_UNKNOWN");
1118 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1119 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1121 CFRelease(formatter);
1123 return [(NSString *) formatted autorelease];
1126 bool isSectionVisible(NSString *section) {
1127 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
1128 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1129 return hidden == nil || ![hidden boolValue];
1134 /* Delegate Prototypes {{{ */
1137 @class CydiaProgressEvent;
1139 @protocol DatabaseDelegate
1140 - (void) repairWithSelector:(SEL)selector;
1141 - (void) setConfigurationData:(NSString *)data;
1142 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
1145 @class CYPackageController;
1147 @protocol CydiaDelegate
1148 - (void) retainNetworkActivityIndicator;
1149 - (void) releaseNetworkActivityIndicator;
1150 - (void) clearPackage:(Package *)package;
1151 - (void) installPackage:(Package *)package;
1152 - (void) installPackages:(NSArray *)packages;
1153 - (void) removePackage:(Package *)package;
1154 - (void) beginUpdate;
1156 - (void) distUpgrade;
1158 - (void) updateData;
1160 - (void) addTrivialSource:(NSString *)href;
1161 - (void) showSettings;
1162 - (UIProgressHUD *) addProgressHUD;
1163 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1164 - (CYViewController *) pageForPackage:(NSString *)name;
1165 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
1166 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1170 /* ProgressEvent Interface/Delegate {{{ */
1171 @interface CydiaProgressEvent : NSObject {
1172 _H<NSString> message_;
1174 _H<NSString> package_;
1178 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type;
1179 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package;
1181 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type;
1183 - (NSString *) message;
1184 - (NSString *) type;
1185 - (NSString *) package;
1188 - (void) setPackage:(NSString *)package;
1190 - (NSString *) compound:(NSString *)value;
1191 - (NSString *) compoundMessage;
1192 - (NSString *) compoundTitle;
1196 @protocol ProgressDelegate
1197 - (void) addProgressEvent:(CydiaProgressEvent *)event;
1198 - (void) setProgressPercent:(NSNumber *)percent;
1199 - (bool) isProgressCancelled;
1200 - (void) setTitle:(NSString *)title;
1203 /* Status Delegation {{{ */
1205 public pkgAcquireStatus
1208 _transient NSObject<ProgressDelegate> *delegate_;
1216 void setDelegate(NSObject<ProgressDelegate> *delegate) {
1217 delegate_ = delegate;
1220 NSObject<ProgressDelegate> *getDelegate() const {
1224 virtual bool MediaChange(std::string media, std::string drive) {
1228 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1231 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1232 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1233 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:@"STATUS"]);
1234 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1237 virtual void Done(pkgAcquire::ItemDesc &item) {
1240 virtual void Fail(pkgAcquire::ItemDesc &item) {
1242 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1243 item.Owner->Status == pkgAcquire::Item::StatDone
1247 std::string &error(item.Owner->ErrorText);
1251 //NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1252 //NSArray *fields([description componentsSeparatedByString:@" "]);
1253 //NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1255 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:@"ERROR"]);
1256 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1259 virtual bool Pulse(pkgAcquire *Owner) {
1260 bool value = pkgAcquireStatus::Pulse(Owner);
1263 double(CurrentBytes + CurrentItems) /
1264 double(TotalBytes + TotalItems)
1267 [delegate_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:percent] waitUntilDone:YES];
1268 return ![delegate_ isProgressCancelled] && value;
1271 virtual void Start() {
1272 pkgAcquireStatus::Start();
1275 virtual void Stop() {
1276 pkgAcquireStatus::Stop();
1280 /* Database Interface {{{ */
1281 typedef std::map< unsigned long, _H<Source> > SourceMap;
1283 @interface Database : NSObject {
1289 pkgCacheFile cache_;
1290 pkgDepCache::Policy *policy_;
1291 pkgRecords *records_;
1292 pkgProblemResolver *resolver_;
1293 pkgAcquire *fetcher_;
1295 SPtr<pkgPackageManager> manager_;
1296 pkgSourceList *list_;
1298 SourceMap sourceMap_;
1299 NSMutableArray *sourceList_;
1301 CFMutableArrayRef packages_;
1303 _transient NSObject<DatabaseDelegate> *delegate_;
1304 _transient NSObject<ProgressDelegate> *progress_;
1312 std::map<const char *, _H<NSString> > sections_;
1315 + (Database *) sharedInstance;
1318 - (void) _readCydia:(NSNumber *)fd;
1319 - (void) _readStatus:(NSNumber *)fd;
1320 - (void) _readOutput:(NSNumber *)fd;
1324 - (Package *) packageWithName:(NSString *)name;
1326 - (pkgCacheFile &) cache;
1327 - (pkgDepCache::Policy *) policy;
1328 - (pkgRecords *) records;
1329 - (pkgProblemResolver *) resolver;
1330 - (pkgAcquire &) fetcher;
1331 - (pkgSourceList &) list;
1332 - (NSArray *) packages;
1333 - (NSArray *) sources;
1334 - (Source *) sourceWithKey:(NSString *)key;
1335 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1343 - (void) updateWithStatus:(Status &)status;
1345 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1347 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1348 - (NSObject<ProgressDelegate> *) progressDelegate;
1350 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1352 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1356 /* ProgressEvent Implementation {{{ */
1357 @implementation CydiaProgressEvent
1359 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1360 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1363 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1364 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1365 [event setPackage:package];
1369 + (NSArray *) _attributeKeys {
1370 return [NSArray arrayWithObjects:
1378 - (NSArray *) attributeKeys {
1379 return [[self class] _attributeKeys];
1382 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1383 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1386 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1387 if ((self = [super init]) != nil) {
1393 - (NSString *) message {
1397 - (NSString *) type {
1401 - (NSString *) package {
1405 - (NSString *) uri {
1409 - (void) setPackage:(NSString *)package {
1413 - (NSString *) compound:(NSString *)value {
1415 NSString *mode(nil); {
1416 NSString *type([self type]);
1417 if ([type isEqualToString:@"ERROR"])
1418 mode = UCLocalize("ERROR");
1419 else if ([type isEqualToString:@"WARNING"])
1420 mode = UCLocalize("WARNING");
1424 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1430 - (NSString *) compoundMessage {
1431 return [self compound:[self message]];
1434 - (NSString *) compoundTitle {
1437 if (package_ == nil)
1439 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1440 title = [package name];
1444 return [self compound:title];
1450 // Cytore Definitions {{{
1451 struct PackageValue :
1454 Cytore::Offset<PackageValue> next_;
1456 uint32_t index_ : 23;
1457 uint32_t subscribed_ : 1;
1474 Cytore::Offset<PackageValue> packages_[1 << 16];
1477 static Cytore::File<MetaValue> MetaFile_;
1479 // Cytore Helper Functions {{{
1480 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1481 SplitHash nhash = { hashlittle(name, length) };
1483 PackageValue *metadata;
1485 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1486 offset: if (offset->IsNull()) {
1487 *offset = MetaFile_.New<PackageValue>(length + 1);
1488 metadata = &MetaFile_.Get(*offset);
1490 if (metadata == NULL) {
1494 metadata = new PackageValue();
1495 memset(metadata, 0, sizeof(*metadata));
1498 memcpy(metadata->name_, name, length + 1);
1499 metadata->nhash_ = nhash.u16[1];
1501 metadata = &MetaFile_.Get(*offset);
1503 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1504 offset = &metadata->next_;
1512 static void PackageImport(const void *key, const void *value, void *context) {
1513 bool &fail(*reinterpret_cast<bool *>(context));
1516 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1517 NSLog(@"failed to import package %@", key);
1521 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1522 NSDictionary *package((NSDictionary *) value);
1524 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1525 if ([subscribed boolValue] && !metadata->subscribed_)
1526 metadata->subscribed_ = true;
1528 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1529 time_t time([date timeIntervalSince1970]);
1530 if (metadata->first_ > time || metadata->first_ == 0)
1531 metadata->first_ = time;
1534 NSDate *date([package objectForKey:@"LastSeen"]);
1535 NSString *version([package objectForKey:@"LastVersion"]);
1537 if (date != nil && version != nil) {
1538 time_t time([date timeIntervalSince1970]);
1539 if (metadata->last_ < time || metadata->last_ == 0)
1540 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1541 size_t length(strlen(buffer));
1542 uint16_t vhash(hashlittle(buffer, length));
1544 size_t capped(std::min<size_t>(8, length));
1545 char *latest(buffer + length - capped);
1547 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1548 metadata->vhash_ = vhash;
1550 metadata->last_ = time;
1556 /* Source Class {{{ */
1557 @interface Source : NSObject {
1558 CYString depiction_;
1559 CYString description_;
1565 CYString distribution_;
1570 NSString *authority_;
1572 CYString defaultIcon_;
1574 NSDictionary *record_;
1578 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1580 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1582 - (NSString *) depictionForPackage:(NSString *)package;
1583 - (NSString *) supportForPackage:(NSString *)package;
1585 - (NSDictionary *) record;
1589 - (NSString *) distribution;
1590 - (NSString *) type;
1592 - (NSString *) host;
1594 - (NSString *) name;
1595 - (NSString *) description;
1596 - (NSString *) label;
1597 - (NSString *) origin;
1598 - (NSString *) version;
1600 - (NSString *) defaultIcon;
1604 @implementation Source
1608 distribution_.clear();
1611 description_.clear();
1617 defaultIcon_.clear();
1619 if (record_ != nil) {
1629 if (authority_ != nil) {
1630 [authority_ release];
1636 // XXX: this is a very inefficient way to call these deconstructors
1641 + (NSArray *) _attributeKeys {
1642 return [NSArray arrayWithObjects:
1657 - (NSArray *) attributeKeys {
1658 return [[self class] _attributeKeys];
1661 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1662 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1665 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1668 trusted_ = index->IsTrusted();
1670 uri_.set(pool, index->GetURI());
1671 distribution_.set(pool, index->GetDist());
1672 type_.set(pool, index->GetType());
1674 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1675 if (dindex != NULL) {
1677 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1680 pkgTagFile tags(&fd);
1682 pkgTagSection section;
1689 {"default-icon", &defaultIcon_},
1690 {"depiction", &depiction_},
1691 {"description", &description_},
1693 {"origin", &origin_},
1694 {"support", &support_},
1695 {"version", &version_},
1698 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1699 const char *start, *end;
1701 if (section.Find(names[i].name_, start, end)) {
1702 CYString &value(*names[i].value_);
1703 value.set(pool, start, end - start);
1709 record_ = [Sources_ objectForKey:[self key]];
1711 record_ = [record_ retain];
1713 NSURL *url([NSURL URLWithString:uri_]);
1717 host_ = [[host_ lowercaseString] retain];
1722 authority_ = [url path];
1724 if (authority_ != nil)
1725 authority_ = [authority_ retain];
1728 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1729 if ((self = [super init]) != nil) {
1730 [self setMetaIndex:index inPool:pool];
1734 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1735 NSDictionary *lhr = [self record];
1736 NSDictionary *rhr = [source record];
1739 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1741 NSString *lhs = [self name];
1742 NSString *rhs = [source name];
1744 if ([lhs length] != 0 && [rhs length] != 0) {
1745 unichar lhc = [lhs characterAtIndex:0];
1746 unichar rhc = [rhs characterAtIndex:0];
1748 if (isalpha(lhc) && !isalpha(rhc))
1749 return NSOrderedAscending;
1750 else if (!isalpha(lhc) && isalpha(rhc))
1751 return NSOrderedDescending;
1754 return [lhs compare:rhs options:LaxCompareOptions_];
1757 - (NSString *) depictionForPackage:(NSString *)package {
1758 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1761 - (NSString *) supportForPackage:(NSString *)package {
1762 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1765 - (NSDictionary *) record {
1773 - (NSString *) uri {
1777 - (NSString *) distribution {
1778 return distribution_;
1781 - (NSString *) type {
1785 - (NSString *) key {
1786 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1789 - (NSString *) host {
1793 - (NSString *) name {
1794 return origin_.empty() ? authority_ : origin_;
1797 - (NSString *) description {
1798 return description_;
1801 - (NSString *) label {
1802 return label_.empty() ? authority_ : label_;
1805 - (NSString *) origin {
1809 - (NSString *) version {
1813 - (NSString *) defaultIcon {
1814 return defaultIcon_;
1819 /* CydiaOperation Class {{{ */
1820 @interface CydiaOperation : NSObject {
1821 NSString *operator_;
1825 - (NSString *) operator;
1826 - (NSString *) value;
1830 @implementation CydiaOperation
1833 [operator_ release];
1838 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1839 if ((self = [super init]) != nil) {
1840 operator_ = [[NSString alloc] initWithUTF8String:_operator];
1841 value_ = [[NSString alloc] initWithUTF8String:value];
1845 + (NSArray *) _attributeKeys {
1846 return [NSArray arrayWithObjects:
1852 - (NSArray *) attributeKeys {
1853 return [[self class] _attributeKeys];
1856 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1857 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1860 - (NSString *) operator {
1864 - (NSString *) value {
1870 /* CydiaClause Class {{{ */
1871 @interface CydiaClause : NSObject {
1873 CydiaOperation *version_;
1876 - (NSString *) package;
1877 - (CydiaOperation *) version;
1881 @implementation CydiaClause
1889 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1890 if ((self = [super init]) != nil) {
1891 package_ = [[NSString alloc] initWithUTF8String:dep.TargetPkg().Name()];
1893 if (const char *version = dep.TargetVer())
1894 version_ = [[CydiaOperation alloc] initWithOperator:dep.CompType() value:version];
1896 version_ = [[NSNull null] retain];
1900 + (NSArray *) _attributeKeys {
1901 return [NSArray arrayWithObjects:
1907 - (NSArray *) attributeKeys {
1908 return [[self class] _attributeKeys];
1911 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1912 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1915 - (NSString *) package {
1919 - (CydiaOperation *) version {
1925 /* CydiaRelation Class {{{ */
1926 @interface CydiaRelation : NSObject {
1927 NSString *relationship_;
1928 NSMutableArray *clauses_;
1931 - (NSString *) relationship;
1932 - (NSArray *) clauses;
1936 @implementation CydiaRelation
1939 [relationship_ release];
1944 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1945 if ((self = [super init]) != nil) {
1946 relationship_ = [[NSString alloc] initWithUTF8String:dep.DepType()];
1947 clauses_ = [[NSMutableArray alloc] initWithCapacity:8];
1949 pkgCache::DepIterator start;
1950 pkgCache::DepIterator end;
1951 dep.GlobOr(start, end); // ++dep
1954 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1956 // yes, seriously. (wtf?)
1964 + (NSArray *) _attributeKeys {
1965 return [NSArray arrayWithObjects:
1971 - (NSArray *) attributeKeys {
1972 return [[self class] _attributeKeys];
1975 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1976 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1979 - (NSString *) relationship {
1980 return relationship_;
1983 - (NSArray *) clauses {
1987 - (void) addClause:(CydiaClause *)clause {
1988 [clauses_ addObject:clause];
1993 /* Package Class {{{ */
1994 struct ParsedPackage {
1999 CYString depiction_;
2009 @interface Package : NSObject {
2012 uint32_t essential_ : 1;
2013 uint32_t obsolete_ : 1;
2014 uint32_t ignored_ : 1;
2018 _transient Database *database_;
2020 pkgCache::VerIterator version_;
2021 pkgCache::PkgIterator iterator_;
2022 pkgCache::VerFileIterator file_;
2028 CYString installed_;
2030 const char *section_;
2031 _transient NSString *section$_;
2035 PackageValue *metadata_;
2036 ParsedPackage *parsed_;
2038 NSMutableArray *tags_;
2041 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
2042 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
2044 - (pkgCache::PkgIterator) iterator;
2047 - (NSString *) section;
2048 - (NSString *) simpleSection;
2050 - (NSString *) longSection;
2051 - (NSString *) shortSection;
2055 - (Address *) maintainer;
2057 - (NSString *) longDescription;
2058 - (NSString *) shortDescription;
2061 - (PackageValue *) metadata;
2064 - (bool) subscribed;
2065 - (bool) setSubscribed:(bool)subscribed;
2069 - (NSString *) latest;
2070 - (NSString *) installed;
2071 - (BOOL) uninstalled;
2074 - (BOOL) upgradableAndEssential:(BOOL)essential;
2077 - (BOOL) unfiltered;
2081 - (BOOL) halfConfigured;
2082 - (BOOL) halfInstalled;
2084 - (NSString *) mode;
2087 - (NSString *) name;
2089 - (NSString *) homepage;
2090 - (NSString *) depiction;
2091 - (Address *) author;
2093 - (NSString *) support;
2095 - (NSArray *) files;
2096 - (NSArray *) warnings;
2097 - (NSArray *) applications;
2099 - (Source *) source;
2101 - (BOOL) matches:(NSString *)text;
2103 - (bool) hasSupportingRole;
2104 - (BOOL) hasTag:(NSString *)tag;
2105 - (NSString *) primaryPurpose;
2106 - (NSArray *) purposes;
2107 - (bool) isCommercial;
2109 - (void) setIndex:(size_t)index;
2111 - (CYString &) cyname;
2113 - (uint32_t) compareBySection:(NSArray *)sections;
2118 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
2119 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
2120 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
2121 - (bool) isVisibleInSection:(NSString *)section;
2122 - (bool) isVisibleInSource:(Source *)source;
2126 uint32_t PackageChangesRadix(Package *self, void *) {
2131 uint32_t timestamp : 30;
2132 uint32_t ignored : 1;
2133 uint32_t upgradable : 1;
2137 bool upgradable([self upgradableAndEssential:YES]);
2138 value.bits.upgradable = upgradable ? 1 : 0;
2141 value.bits.timestamp = 0;
2142 value.bits.ignored = [self ignored] ? 0 : 1;
2143 value.bits.upgradable = 1;
2145 value.bits.timestamp = [self seen] >> 2;
2146 value.bits.ignored = 0;
2147 value.bits.upgradable = 0;
2150 return _not(uint32_t) - value.key;
2153 uint32_t PackagePrefixRadix(Package *self, void *context) {
2154 size_t offset(reinterpret_cast<size_t>(context));
2155 CYString &name([self cyname]);
2157 size_t size(name.size());
2160 char *text(name.data());
2163 if (!isdigit(text[0]))
2167 while (size != digits && isdigit(text[digits]))
2175 if (offset == 0 && zeros != 0) {
2176 memset(data, '0', zeros);
2177 memcpy(data + zeros, text, 4 - zeros);
2179 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2180 if (size <= offset - zeros)
2183 text += offset - zeros;
2184 size -= offset - zeros;
2187 memcpy(data, text, 4);
2189 memcpy(data, text, size);
2190 memset(data + size, 0, 4 - size);
2193 for (size_t i(0); i != 4; ++i)
2194 if (isalpha(data[i]))
2202 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2204 /* XXX: ntohl may be more honest */
2205 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2208 CYString &(*PackageName)(Package *self, SEL sel);
2210 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2211 _profile(PackageNameCompare)
2212 CYString &lhi(PackageName(lhs, @selector(cyname)));
2213 CYString &rhi(PackageName(rhs, @selector(cyname)));
2214 CFStringRef lhn(lhi), rhn(rhi);
2217 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2218 else if (rhn == NULL)
2219 return NSOrderedDescending;
2221 _profile(PackageNameCompare$NumbersLast)
2222 if (!lhi.empty() && !rhi.empty()) {
2223 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2224 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2225 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2226 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2227 return lha ? NSOrderedAscending : NSOrderedDescending;
2231 CFIndex length = CFStringGetLength(lhn);
2233 _profile(PackageNameCompare$Compare)
2234 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2239 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2240 return PackageNameCompare(*lhs, *rhs, context);
2243 struct PackageNameOrdering :
2244 std::binary_function<Package *, Package *, bool>
2246 _finline bool operator ()(Package *lhs, Package *rhs) const {
2247 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2251 @implementation Package
2253 - (NSString *) description {
2254 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2258 if (parsed_ != NULL)
2267 + (NSString *) webScriptNameForSelector:(SEL)selector {
2269 else if (selector == @selector(clear))
2271 else if (selector == @selector(getField:))
2273 else if (selector == @selector(hasTag:))
2275 else if (selector == @selector(install))
2277 else if (selector == @selector(remove))
2283 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2284 return [self webScriptNameForSelector:selector] == nil;
2287 + (NSArray *) _attributeKeys {
2288 return [NSArray arrayWithObjects:
2306 @"shortDescription",
2317 - (NSArray *) attributeKeys {
2318 return [[self class] _attributeKeys];
2321 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2322 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2325 - (NSArray *) relations {
2326 @synchronized (database_) {
2327 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2328 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2329 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2333 - (NSString *) getField:(NSString *)name {
2334 @synchronized (database_) {
2335 if ([database_ era] != era_ || file_.end())
2338 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2340 const char *start, *end;
2341 if (!parser.Find([name UTF8String], start, end))
2342 return (NSString *) [NSNull null];
2344 return [(NSString *) CYStringCreate(start, end - start) autorelease];
2348 if (parsed_ != NULL)
2350 @synchronized (database_) {
2351 if ([database_ era] != era_ || file_.end())
2354 ParsedPackage *parsed(new ParsedPackage);
2357 _profile(Package$parse)
2358 pkgRecords::Parser *parser;
2360 _profile(Package$parse$Lookup)
2361 parser = &[database_ records]->Lookup(file_);
2366 _profile(Package$parse$Find)
2371 {"icon", &parsed->icon_},
2372 {"depiction", &parsed->depiction_},
2373 {"homepage", &parsed->homepage_},
2374 {"website", &website},
2375 {"bugs", &parsed->bugs_},
2376 {"support", &parsed->support_},
2377 {"sponsor", &parsed->sponsor_},
2378 {"author", &parsed->author_},
2381 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2382 const char *start, *end;
2384 if (parser->Find(names[i].name_, start, end)) {
2385 CYString &value(*names[i].value_);
2386 _profile(Package$parse$Value)
2387 value.set(pool_, start, end - start);
2393 _profile(Package$parse$Tagline)
2394 const char *start, *end;
2395 if (parser->ShortDesc(start, end)) {
2396 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2399 while (stop != start && stop[-1] == '\r')
2401 parsed->tagline_.set(pool_, start, stop - start);
2405 _profile(Package$parse$Retain)
2406 if (parsed->homepage_.empty())
2407 parsed->homepage_ = website;
2408 if (parsed->homepage_ == parsed->depiction_)
2409 parsed->homepage_.clear();
2414 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2415 if ((self = [super init]) != nil) {
2416 _profile(Package$initWithVersion)
2419 database_ = database;
2420 era_ = [database era];
2424 pkgCache::PkgIterator iterator(version.ParentPkg());
2425 iterator_ = iterator;
2427 _profile(Package$initWithVersion$Version)
2428 if (!version_.end())
2429 file_ = version_.FileList();
2431 pkgCache &cache([database_ cache]);
2432 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2436 _profile(Package$initWithVersion$Cache)
2437 name_.set(NULL, iterator.Display());
2439 latest_.set(NULL, StripVersion_(version_.VerStr()));
2441 pkgCache::VerIterator current(iterator.CurrentVer());
2443 installed_.set(NULL, StripVersion_(current.VerStr()));
2446 _profile(Package$initWithVersion$Tags)
2447 pkgCache::TagIterator tag(iterator.TagList());
2449 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2451 const char *name(tag.Name());
2452 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2454 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2455 if (strcmp(name + 6, "enduser") == 0)
2457 else if (strcmp(name + 6, "hacker") == 0)
2459 else if (strcmp(name + 6, "developer") == 0)
2461 else if (strcmp(name + 6, "cydia") == 0)
2467 if (strncmp(name, "cydia::", 7) == 0) {
2468 if (strcmp(name + 7, "essential") == 0)
2470 else if (strcmp(name + 7, "obsolete") == 0)
2475 } while (!tag.end());
2479 _profile(Package$initWithVersion$Metadata)
2480 const char *mixed(iterator.Name());
2481 size_t size(strlen(mixed));
2482 char lower[size + 1];
2484 for (size_t i(0); i != size; ++i)
2485 lower[i] = mixed[i] | 0x20;
2488 PackageValue *metadata(PackageFind(lower, size));
2489 metadata_ = metadata;
2491 id_.set(NULL, metadata->name_, size);
2493 const char *latest(version_.VerStr());
2494 size_t length(strlen(latest));
2496 uint16_t vhash(hashlittle(latest, length));
2498 size_t capped(std::min<size_t>(8, length));
2499 latest = latest + length - capped;
2501 if (metadata->first_ == 0)
2502 metadata->first_ = now_;
2504 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2505 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2506 metadata->vhash_ = vhash;
2507 metadata->last_ = now_;
2508 } else if (metadata->last_ == 0)
2509 metadata->last_ = metadata->first_;
2512 _profile(Package$initWithVersion$Section)
2513 section_ = iterator.Section();
2516 _profile(Package$initWithVersion$Flags)
2517 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2518 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2523 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2524 pkgCache::VerIterator version;
2526 _profile(Package$packageWithIterator$GetCandidateVer)
2527 version = [database policy]->GetCandidateVer(iterator);
2535 _profile(Package$packageWithIterator$Allocate)
2536 package = [Package allocWithZone:zone];
2539 _profile(Package$packageWithIterator$Initialize)
2541 initWithVersion:version
2548 _profile(Package$packageWithIterator$Autorelease)
2549 package = [package autorelease];
2555 - (pkgCache::PkgIterator) iterator {
2559 - (NSString *) section {
2560 if (section$_ == nil) {
2561 if (section_ == NULL)
2564 _profile(Package$section$mappedSectionForPointer)
2565 section$_ = [database_ mappedSectionForPointer:section_];
2570 - (NSString *) simpleSection {
2571 if (NSString *section = [self section])
2572 return Simplify(section);
2577 - (NSString *) longSection {
2578 return LocalizeSection([self section]);
2581 - (NSString *) shortSection {
2582 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2585 - (NSString *) uri {
2588 pkgIndexFile *index;
2589 pkgCache::PkgFileIterator file(file_.File());
2590 if (![database_ list].FindIndex(file, index))
2592 return [NSString stringWithUTF8String:iterator_->Path];
2593 //return [NSString stringWithUTF8String:file.Site()];
2594 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2598 - (Address *) maintainer {
2599 @synchronized (database_) {
2600 if ([database_ era] != era_ || file_.end())
2603 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2604 const std::string &maintainer(parser->Maintainer());
2605 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2609 @synchronized (database_) {
2610 if ([database_ era] != era_ || version_.end())
2613 return version_->InstalledSize;
2616 - (NSString *) longDescription {
2617 @synchronized (database_) {
2618 if ([database_ era] != era_ || file_.end())
2621 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2622 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2624 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2625 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2626 if ([lines count] < 2)
2629 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2630 for (size_t i(1), e([lines count]); i != e; ++i) {
2631 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2632 [trimmed addObject:trim];
2635 return [trimmed componentsJoinedByString:@"\n"];
2638 - (NSString *) shortDescription {
2639 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2643 _profile(Package$index)
2644 CFStringRef name((CFStringRef) [self name]);
2645 if (CFStringGetLength(name) == 0)
2647 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2648 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2650 return toupper(character);
2654 - (PackageValue *) metadata {
2659 PackageValue *metadata([self metadata]);
2660 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2663 - (bool) subscribed {
2664 return [self metadata]->subscribed_;
2667 - (bool) setSubscribed:(bool)subscribed {
2668 PackageValue *metadata([self metadata]);
2669 if (metadata->subscribed_ == subscribed)
2671 metadata->subscribed_ = subscribed;
2679 - (NSString *) latest {
2683 - (NSString *) installed {
2687 - (BOOL) uninstalled {
2688 return installed_.empty();
2692 return !version_.end();
2695 - (BOOL) upgradableAndEssential:(BOOL)essential {
2696 _profile(Package$upgradableAndEssential)
2697 pkgCache::VerIterator current(iterator_.CurrentVer());
2699 return essential && essential_;
2701 return !version_.end() && version_ != current;
2705 - (BOOL) essential {
2710 return [database_ cache][iterator_].InstBroken();
2713 - (BOOL) unfiltered {
2714 _profile(Package$unfiltered$obsolete)
2715 if (_unlikely(obsolete_))
2719 _profile(Package$unfiltered$hasSupportingRole)
2720 if (_unlikely(![self hasSupportingRole]))
2728 if (![self unfiltered])
2733 _profile(Package$visible$section)
2734 section = [self section];
2737 _profile(Package$visible$isSectionVisible)
2738 if (!isSectionVisible(section))
2746 unsigned char current(iterator_->CurrentState);
2747 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2750 - (BOOL) halfConfigured {
2751 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2754 - (BOOL) halfInstalled {
2755 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2759 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2760 return state.Mode != pkgDepCache::ModeKeep;
2763 - (NSString *) mode {
2764 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2766 switch (state.Mode) {
2767 case pkgDepCache::ModeDelete:
2768 if ((state.iFlags & pkgDepCache::Purge) != 0)
2772 case pkgDepCache::ModeKeep:
2773 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2774 return @"REINSTALL";
2775 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2779 case pkgDepCache::ModeInstall:
2780 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2781 return @"REINSTALL";
2782 else*/ switch (state.Status) {
2784 return @"DOWNGRADE";
2790 return @"NEW_INSTALL";
2801 - (NSString *) name {
2802 return name_.empty() ? id_ : name_;
2805 - (UIImage *) icon {
2806 NSString *section = [self simpleSection];
2809 if (parsed_ != NULL)
2810 if (NSString *href = parsed_->icon_)
2811 if ([href hasPrefix:@"file:///"])
2812 // XXX: correct escaping
2813 icon = [UIImage imageAtPath:[href substringFromIndex:7]];
2814 if (icon == nil) if (section != nil)
2815 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2816 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2817 if ([dicon hasPrefix:@"file:///"])
2818 // XXX: correct escaping
2819 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2821 icon = [UIImage applicationImageNamed:@"unknown.png"];
2825 - (NSString *) homepage {
2826 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2829 - (NSString *) depiction {
2830 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2833 - (Address *) sponsor {
2834 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [Address addressWithString:parsed_->sponsor_];
2837 - (Address *) author {
2838 return parsed_ == NULL || parsed_->author_.empty() ? nil : [Address addressWithString:parsed_->author_];
2841 - (NSString *) support {
2842 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2845 - (NSArray *) files {
2846 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2847 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2850 fin.open([path UTF8String]);
2855 while (std::getline(fin, line))
2856 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2861 - (NSArray *) warnings {
2862 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2863 const char *name(iterator_.Name());
2865 size_t length(strlen(name));
2866 if (length < 2) invalid:
2867 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2868 else for (size_t i(0); i != length; ++i)
2870 /* XXX: technically this is not allowed */
2871 (name[i] < 'A' || name[i] > 'Z') &&
2872 (name[i] < 'a' || name[i] > 'z') &&
2873 (name[i] < '0' || name[i] > '9') &&
2874 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2877 if (strcmp(name, "cydia") != 0) {
2880 bool _private = false;
2883 bool repository = [[self section] isEqualToString:@"Repositories"];
2885 if (NSArray *files = [self files])
2886 for (NSString *file in files)
2887 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2889 else if (!user && [file isEqualToString:@"/User"])
2891 else if (!_private && [file isEqualToString:@"/private"])
2893 else if (!stash && [file isEqualToString:@"/var/stash"])
2896 /* XXX: this is not sensitive enough. only some folders are valid. */
2897 if (cydia && !repository)
2898 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2900 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2902 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2904 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2907 return [warnings count] == 0 ? nil : warnings;
2910 - (NSArray *) applications {
2911 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2913 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2915 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2916 if (NSArray *files = [self files])
2917 for (NSString *file in files)
2918 if (application_r(file)) {
2919 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2920 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2921 if ([id isEqualToString:me])
2924 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2926 display = application_r[1];
2928 NSString *bundle([file stringByDeletingLastPathComponent]);
2929 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2930 if (icon == nil || [icon length] == 0)
2932 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2934 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2935 [applications addObject:application];
2937 [application addObject:id];
2938 [application addObject:display];
2939 [application addObject:url];
2942 return [applications count] == 0 ? nil : applications;
2945 - (Source *) source {
2946 if (source_ == nil) {
2947 @synchronized (database_) {
2948 if ([database_ era] != era_ || file_.end())
2949 source_ = (Source *) [NSNull null];
2951 source_ = [([database_ getSource:file_.File()] ?: (Source *) [NSNull null]) retain];
2955 return source_ == (Source *) [NSNull null] ? nil : source_;
2958 - (BOOL) matches:(NSString *)text {
2964 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2965 if (range.location != NSNotFound)
2968 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2969 if (range.location != NSNotFound)
2974 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2975 if (range.location != NSNotFound)
2981 - (bool) hasSupportingRole {
2986 if ([Role_ isEqualToString:@"User"])
2990 if ([Role_ isEqualToString:@"Hacker"])
2994 if ([Role_ isEqualToString:@"Developer"])
2999 - (BOOL) hasTag:(NSString *)tag {
3000 return tags_ == nil ? NO : [tags_ containsObject:tag];
3003 - (NSString *) primaryPurpose {
3004 for (NSString *tag in tags_)
3005 if ([tag hasPrefix:@"purpose::"])
3006 return [tag substringFromIndex:9];
3010 - (NSArray *) purposes {
3011 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
3012 for (NSString *tag in tags_)
3013 if ([tag hasPrefix:@"purpose::"])
3014 [purposes addObject:[tag substringFromIndex:9]];
3015 return [purposes count] == 0 ? nil : purposes;
3018 - (bool) isCommercial {
3019 return [self hasTag:@"cydia::commercial"];
3022 - (void) setIndex:(size_t)index {
3023 if (metadata_->index_ != index)
3024 metadata_->index_ = index;
3027 - (CYString &) cyname {
3028 return name_.empty() ? id_ : name_;
3031 - (uint32_t) compareBySection:(NSArray *)sections {
3032 NSString *section([self section]);
3033 for (size_t i(0), e([sections count]); i != e; ++i) {
3034 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3038 return _not(uint32_t);
3042 @synchronized (database_) {
3043 pkgProblemResolver *resolver = [database_ resolver];
3044 resolver->Clear(iterator_);
3046 pkgCacheFile &cache([database_ cache]);
3047 cache->SetReInstall(iterator_, false);
3048 cache->MarkKeep(iterator_, false);
3052 @synchronized (database_) {
3053 pkgProblemResolver *resolver = [database_ resolver];
3054 resolver->Clear(iterator_);
3055 resolver->Protect(iterator_);
3057 pkgCacheFile &cache([database_ cache]);
3058 cache->SetReInstall(iterator_, false);
3059 cache->MarkInstall(iterator_, false);
3061 pkgDepCache::StateCache &state((*cache)[iterator_]);
3062 if (!state.Install())
3063 cache->SetReInstall(iterator_, true);
3067 @synchronized (database_) {
3068 pkgProblemResolver *resolver = [database_ resolver];
3069 resolver->Clear(iterator_);
3070 resolver->Remove(iterator_);
3071 resolver->Protect(iterator_);
3073 pkgCacheFile &cache([database_ cache]);
3074 cache->SetReInstall(iterator_, false);
3075 cache->MarkDelete(iterator_, true);
3078 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
3079 _profile(Package$isUnfilteredAndSearchedForBy)
3082 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
3083 value &= [self unfiltered];
3086 _profile(Package$isUnfilteredAndSearchedForBy$Match)
3087 value &= [self matches:search];
3094 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
3095 if ([search length] == 0)
3098 _profile(Package$isUnfilteredAndSelectedForBy)
3101 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
3102 value &= [self unfiltered];
3105 _profile(Package$isUnfilteredAndSelectedForBy$Match)
3106 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
3113 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
3114 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
3117 - (bool) isVisibleInSection:(NSString *)name {
3118 NSString *section([self section]);
3122 section == nil && [name length] == 0 ||
3123 [name isEqualToString:section]
3124 ) && [self visible];
3127 - (bool) isVisibleInSource:(Source *)source {
3128 return [self source] == source && [self visible];
3133 /* Section Class {{{ */
3134 @interface Section : NSObject {
3139 NSString *localized_;
3142 - (NSComparisonResult) compareByLocalized:(Section *)section;
3143 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3144 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3145 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3146 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
3147 - (NSString *) name;
3154 - (void) addToCount;
3156 - (void) setCount:(size_t)count;
3157 - (NSString *) localized;
3161 @implementation Section
3165 if (localized_ != nil)
3166 [localized_ release];
3170 - (NSComparisonResult) compareByLocalized:(Section *)section {
3171 NSString *lhs(localized_);
3172 NSString *rhs([section localized]);
3174 /*if ([lhs length] != 0 && [rhs length] != 0) {
3175 unichar lhc = [lhs characterAtIndex:0];
3176 unichar rhc = [rhs characterAtIndex:0];
3178 if (isalpha(lhc) && !isalpha(rhc))
3179 return NSOrderedAscending;
3180 else if (!isalpha(lhc) && isalpha(rhc))
3181 return NSOrderedDescending;
3184 return [lhs compare:rhs options:LaxCompareOptions_];
3187 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3188 if ((self = [self initWithName:name localize:NO]) != nil) {
3189 if (localized != nil)
3190 localized_ = [localized retain];
3194 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3195 return [self initWithName:name row:0 localize:localize];
3198 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3199 if ((self = [super init]) != nil) {
3200 name_ = [name retain];
3204 localized_ = [LocalizeSection(name_) retain];
3208 /* XXX: localize the index thingees */
3209 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
3210 if ((self = [super init]) != nil) {
3211 name_ = [[NSString stringWithCharacters:&index length:1] retain];
3217 - (NSString *) name {
3237 - (void) addToCount {
3241 - (void) setCount:(size_t)count {
3245 - (NSString *) localized {
3252 static NSString *Colon_;
3253 static NSString *Elision_;
3254 static NSString *Error_;
3255 static NSString *Warning_;
3257 /* Database Implementation {{{ */
3258 @implementation Database
3260 + (Database *) sharedInstance {
3261 static Database *instance;
3262 if (instance == nil)
3263 instance = [[Database alloc] init];
3271 - (void) releasePackages {
3272 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3273 CFArrayRemoveAllValues(packages_);
3277 // XXX: actually implement this thing
3279 [sourceList_ release];
3280 [self releasePackages];
3281 apr_pool_destroy(pool_);
3282 NSRecycleZone(zone_);
3286 - (void) _readCydia:(NSNumber *)fd { _pooled
3287 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3288 std::istream is(&ib);
3291 static Pcre finish_r("^finish:([^:]*)$");
3293 while (std::getline(is, line)) {
3294 const char *data(line.c_str());
3295 size_t size = line.size();
3296 lprintf("C:%s\n", data);
3298 if (finish_r(data, size)) {
3299 NSString *finish = finish_r[1];
3300 int index = [Finishes_ indexOfObject:finish];
3301 if (index != INT_MAX && index > Finish_)
3309 - (void) _readStatus:(NSNumber *)fd { _pooled
3310 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3311 std::istream is(&ib);
3314 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3315 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3317 while (std::getline(is, line)) {
3318 const char *data(line.c_str());
3319 size_t size(line.size());
3320 lprintf("S:%s\n", data);
3322 if (conffile_r(data, size))
3323 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3324 else if (strncmp(data, "status: ", 8) == 0) {
3325 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:@"STATUS"]);
3326 [progress_ performSelectorOnMainThread:@selector(addProgressEvent) withObject:event waitUntilDone:YES];
3327 } else if (pmstatus_r(data, size)) {
3328 std::string type([pmstatus_r[1] UTF8String]);
3329 NSString *package = pmstatus_r[2];
3331 float percent([pmstatus_r[3] floatValue]);
3332 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3334 NSString *string = pmstatus_r[4];
3336 if (type == "pmerror") {
3337 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:@"ERROR" forPackage:package]);
3338 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3339 } else if (type == "pmstatus") {
3340 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:@"STATUS" forPackage:package]);
3341 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3342 } else if (type == "pmconffile")
3343 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3345 lprintf("E:unknown pmstatus\n");
3347 lprintf("E:unknown status\n");
3353 - (void) _readOutput:(NSNumber *)fd { _pooled
3354 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3355 std::istream is(&ib);
3358 while (std::getline(is, line)) {
3359 lprintf("O:%s\n", line.c_str());
3361 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:@"INFORMATION"]);
3362 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3372 - (Package *) packageWithName:(NSString *)name {
3373 @synchronized (self) {
3374 if (static_cast<pkgDepCache *>(cache_) == NULL)
3376 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3377 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3381 if ((self = [super init]) != nil) {
3388 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3389 apr_pool_create(&pool_, NULL);
3391 size_t capacity(MetaFile_->active_);
3397 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3398 sourceList_ = [[NSMutableArray alloc] initWithCapacity:16];
3402 _assert(pipe(fds) != -1);
3405 _config->Set("APT::Keep-Fds::", cydiafd_);
3406 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3409 detachNewThreadSelector:@selector(_readCydia:)
3411 withObject:[NSNumber numberWithInt:fds[0]]
3414 _assert(pipe(fds) != -1);
3418 detachNewThreadSelector:@selector(_readStatus:)
3420 withObject:[NSNumber numberWithInt:fds[0]]
3423 _assert(pipe(fds) != -1);
3424 _assert(dup2(fds[0], 0) != -1);
3425 _assert(close(fds[0]) != -1);
3427 input_ = fdopen(fds[1], "a");
3429 _assert(pipe(fds) != -1);
3430 _assert(dup2(fds[1], 1) != -1);
3431 _assert(close(fds[1]) != -1);
3434 detachNewThreadSelector:@selector(_readOutput:)
3436 withObject:[NSNumber numberWithInt:fds[0]]
3441 - (pkgCacheFile &) cache {
3445 - (pkgDepCache::Policy *) policy {
3449 - (pkgRecords *) records {
3453 - (pkgProblemResolver *) resolver {
3457 - (pkgAcquire &) fetcher {
3461 - (pkgSourceList &) list {
3465 - (NSArray *) packages {
3466 return (NSArray *) packages_;
3469 - (NSArray *) sources {
3473 - (Source *) sourceWithKey:(NSString *)key {
3474 for (Source *source in [self sources]) {
3475 if ([[source key] isEqualToString:key])
3480 - (bool) popErrorWithTitle:(NSString *)title {
3483 while (!_error->empty()) {
3485 bool warning(!_error->PopMessage(error));
3490 size_t size(error.size());
3491 if (size == 0 || error[size - 1] != '\n')
3493 error.resize(size - 1);
3496 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3498 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? @"WARNING" : @"ERROR")] forTask:title];
3504 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3505 return [self popErrorWithTitle:title] || !success;
3508 - (void) reloadDataWithInvocation:(NSInvocation *)invocation { CYPoolStart() {
3509 @synchronized (self) {
3512 [self releasePackages];
3515 [sourceList_ removeAllObjects];
3535 apr_pool_clear(pool_);
3537 NSRecycleZone(zone_);
3538 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3540 int chk(creat("/tmp/cydia.chk", 0644));
3544 if (invocation != nil)
3545 [invocation invoke];
3547 NSString *title(UCLocalize("DATABASE"));
3550 OpProgress progress;
3551 while (!cache_.Open(progress, true)) { pop:
3553 bool warning(!_error->PopMessage(error));
3554 lprintf("cache_.Open():[%s]\n", error.c_str());
3556 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3557 [delegate_ repairWithSelector:@selector(configure)];
3558 else if (error == "The package lists or status file could not be parsed or opened.")
3559 [delegate_ repairWithSelector:@selector(update)];
3560 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3561 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3562 // else if (error == "The list of sources could not be read.")
3564 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? @"WARNING" : @"ERROR")] forTask:title];
3574 unlink("/tmp/cydia.chk");
3576 now_ = [[NSDate date] timeIntervalSince1970];
3578 policy_ = new pkgDepCache::Policy();
3579 records_ = new pkgRecords(cache_);
3580 resolver_ = new pkgProblemResolver(cache_);
3581 fetcher_ = new pkgAcquire(&status_);
3584 list_ = new pkgSourceList();
3585 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3588 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3589 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:@"ERROR"] forTask:title];
3593 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3596 if (cache_->BrokenCount() != 0) {
3597 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3600 if (cache_->BrokenCount() != 0) {
3601 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:@"ERROR"] forTask:title];
3605 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3609 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3610 Source *object([[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease]);
3611 [sourceList_ addObject:object];
3613 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3614 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3615 // XXX: this could be more intelligent
3616 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3617 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3619 sourceMap_[cached->ID] = object;
3624 /*std::vector<Package *> packages;
3625 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3626 [packages_ release];
3631 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3632 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3633 //packages.push_back(package);
3634 CFArrayAppendValue(packages_, [package retain]);
3638 /*if (packages.empty())
3639 packages_ = [[NSArray alloc] init];
3641 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3644 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3645 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3646 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3654 /*if (!packages.empty())
3655 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3656 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3658 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3660 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3662 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3666 size_t count(CFArrayGetCount(packages_));
3667 MetaFile_->active_ = count;
3669 for (size_t index(0); index != count; ++index)
3670 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3674 } } CYPoolEnd() _trace(); }
3677 @synchronized (self) {
3679 resolver_ = new pkgProblemResolver(cache_);
3681 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3682 if (!cache_[iterator].Keep())
3683 cache_->MarkKeep(iterator, false);
3684 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3685 cache_->SetReInstall(iterator, false);
3688 - (void) configure {
3689 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3691 system([dpkg UTF8String]);
3696 // XXX: I don't remember this condition
3701 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3703 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3705 if ([self popErrorWithTitle:title])
3709 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3712 public pkgArchiveCleaner
3715 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3720 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3727 fetcher_->Shutdown();
3729 pkgRecords records(cache_);
3731 lock_ = new FileFd();
3732 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3734 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3736 if ([self popErrorWithTitle:title])
3740 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3743 manager_ = (_system->CreatePM(cache_));
3744 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3751 bool substrate(RestartSubstrate_);
3752 RestartSubstrate_ = false;
3754 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3756 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3758 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3760 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3761 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3764 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3766 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3768 [self popErrorWithTitle:title];
3772 bool failed = false;
3773 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3774 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3776 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3782 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3790 RestartSubstrate_ = true;
3793 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3795 if (_error->PendingError()) {
3800 if (result == pkgPackageManager::Failed) {
3805 if (result != pkgPackageManager::Completed) {
3810 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3812 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3814 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3815 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3818 if (![before isEqualToArray:after])
3823 NSString *title(UCLocalize("UPGRADE"));
3824 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3830 [self updateWithStatus:status_];
3833 - (void) updateWithStatus:(Status &)status {
3834 NSString *title(UCLocalize("REFRESHING_DATA"));
3837 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3841 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3842 if ([self popErrorWithTitle:title])
3845 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3846 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */
3847 /* XXX: why the hell is an empty if statement a clang error? */ (void) 0;
3849 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3853 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3854 delegate_ = delegate;
3857 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3858 progress_ = delegate;
3859 status_.setDelegate(delegate);
3862 - (NSObject<ProgressDelegate> *) progressDelegate {
3866 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3867 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3868 return i == sourceMap_.end() ? nil : i->second;
3871 - (NSString *) mappedSectionForPointer:(const char *)section {
3872 _H<NSString> *mapped;
3874 _profile(Database$mappedSectionForPointer$Cache)
3875 mapped = §ions_[section];
3878 if (*mapped == NULL) {
3879 size_t length(strlen(section));
3880 char spaced[length + 1];
3882 _profile(Database$mappedSectionForPointer$Replace)
3883 for (size_t index(0); index != length; ++index)
3884 spaced[index] = section[index] == '_' ? ' ' : section[index];
3885 spaced[length] = '\0';
3890 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3891 string = [NSString stringWithUTF8String:spaced];
3894 _profile(Database$mappedSectionForPointer$Map)
3895 string = [SectionMap_ objectForKey:string] ?: string;
3905 /* Web Scripting {{{ */
3906 @interface CydiaObject : NSObject {
3908 _transient id delegate_;
3911 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3915 @implementation CydiaObject
3918 [indirect_ release];
3922 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3923 if ((self = [super init]) != nil) {
3924 indirect_ = [indirect retain];
3928 - (void) setDelegate:(id)delegate {
3929 delegate_ = delegate;
3932 + (NSArray *) _attributeKeys {
3933 return [NSArray arrayWithObjects:
3943 - (NSArray *) attributeKeys {
3944 return [[self class] _attributeKeys];
3947 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3948 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3951 - (NSString *) device {
3952 return [[UIDevice currentDevice] uniqueIdentifier];
3955 - (NSString *) plmn {
3959 - (NSString *) ecid {
3963 - (NSString *) serial {
3964 return SerialNumber_;
3967 - (NSString *) role {
3971 - (NSString *) model {
3972 return [NSString stringWithUTF8String:Machine_];
3975 + (NSString *) webScriptNameForSelector:(SEL)selector {
3977 else if (selector == @selector(addTrivialSource:))
3978 return @"addTrivialSource";
3979 else if (selector == @selector(close))
3981 else if (selector == @selector(du:))
3983 else if (selector == @selector(stringWithFormat:arguments:))
3985 else if (selector == @selector(getAllSources))
3986 return @"getAllSourcs";
3987 else if (selector == @selector(getKernelNumber:))
3988 return @"getKernelNumber";
3989 else if (selector == @selector(getKernelString:))
3990 return @"getKernelString";
3991 else if (selector == @selector(getInstalledPackages))
3992 return @"getInstalledPackages";
3993 else if (selector == @selector(getPackageById:))
3994 return @"getPackageById";
3995 else if (selector == @selector(installPackages:))
3996 return @"installPackages";
3997 else if (selector == @selector(localizedStringForKey:value:table:))
3999 else if (selector == @selector(refreshSources))
4000 return @"refreshSources";
4001 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4002 return @"setButtonImage";
4003 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4004 return @"setButtonTitle";
4005 else if (selector == @selector(setPopupHook:))
4006 return @"setPopupHook";
4007 else if (selector == @selector(setToken:))
4009 else if (selector == @selector(setViewportWidth:))
4010 return @"setViewportWidth";
4011 else if (selector == @selector(statfs:))
4013 else if (selector == @selector(supports:))
4019 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4020 return [self webScriptNameForSelector:selector] == nil;
4023 - (BOOL) supports:(NSString *)feature {
4024 return [feature isEqualToString:@"window.open"];
4027 - (NSNumber *) getKernelNumber:(NSString *)name {
4028 const char *string([name UTF8String]);
4031 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4032 return (id) [NSNull null];
4034 if (size != sizeof(int))
4035 return (id) [NSNull null];
4038 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4039 return (id) [NSNull null];
4041 return [NSNumber numberWithInt:value];
4044 - (NSString *) getKernelString:(NSString *)name {
4045 const char *string([name UTF8String]);
4048 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4049 return (id) [NSNull null];
4051 char value[size + 1];
4052 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4053 return (id) [NSNull null];
4055 // XXX: just in case you request something ludicrous
4058 return [NSString stringWithCString:value];
4061 - (void) addTrivialSource:(NSString *)href {
4062 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4065 - (void) refreshSources {
4066 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4069 - (NSArray *) getAllSources {
4070 return [[Database sharedInstance] sources];
4073 - (NSArray *) getInstalledPackages {
4074 Database *database([Database sharedInstance]);
4075 @synchronized (database) {
4076 NSArray *packages([database packages]);
4077 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4078 for (Package *package in packages)
4079 if (![package uninstalled])
4080 [installed addObject:package];
4084 - (Package *) getPackageById:(NSString *)id {
4085 Package *package([[Database sharedInstance] packageWithName:id]);
4090 - (NSArray *) statfs:(NSString *)path {
4093 if (path == nil || statfs([path UTF8String], &stat) == -1)
4096 return [NSArray arrayWithObjects:
4097 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4098 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4099 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4103 - (NSNumber *) du:(NSString *)path {
4104 NSNumber *value(nil);
4107 _assert(pipe(fds) != -1);
4109 pid_t pid(ExecFork());
4111 _assert(dup2(fds[1], 1) != -1);
4112 _assert(close(fds[0]) != -1);
4113 _assert(close(fds[1]) != -1);
4114 /* XXX: this should probably not use du */
4115 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4120 _assert(close(fds[1]) != -1);
4122 if (FILE *du = fdopen(fds[0], "r")) {
4124 while (fgets(line, sizeof(line), du) != NULL) {
4125 size_t length(strlen(line));
4126 while (length != 0 && line[length - 1] == '\n')
4127 line[--length] = '\0';
4128 if (char *tab = strchr(line, '\t')) {
4130 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4135 } else _assert(close(fds[0]));
4139 if (waitpid(pid, &status, 0) == -1)
4142 else _assert(false);
4148 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4151 - (void) installPackages:(NSArray *)packages {
4152 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4155 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4156 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4159 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4160 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4163 - (void) _setToken:(NSString *)token {
4166 Token_ = [token retain];
4168 [Metadata_ setObject:Token_ forKey:@"Token"];
4172 - (void) setToken:(NSString *)token {
4173 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4176 - (void) setPopupHook:(id)function {
4177 [indirect_ setPopupHook:function];
4180 - (void) setViewportWidth:(float)width {
4181 [indirect_ setViewportWidthOnMainThread:width];
4184 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4185 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4186 unsigned count([arguments count]);
4188 for (unsigned i(0); i != count; ++i)
4189 values[i] = [arguments objectAtIndex:i];
4190 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4193 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4194 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4196 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4198 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4204 /* @ Loading... Indicator {{{ */
4205 @interface CYLoadingIndicator : UIView {
4206 _H<UIActivityIndicatorView> spinner_;
4208 _H<UIView> container_;
4211 @property (readonly, nonatomic) UILabel *label;
4212 @property (readonly, nonatomic) UIActivityIndicatorView *activityIndicatorView;
4216 @implementation CYLoadingIndicator
4218 - (id) initWithFrame:(CGRect)frame {
4219 if ((self = [super initWithFrame:frame]) != nil) {
4220 container_ = [[[UIView alloc] init] autorelease];
4221 [container_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
4223 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
4224 [spinner_ startAnimating];
4225 [container_ addSubview:spinner_];
4227 label_ = [[[UILabel alloc] init] autorelease];
4228 [label_ setFont:[UIFont boldSystemFontOfSize:15.0f]];
4229 [label_ setBackgroundColor:[UIColor clearColor]];
4230 [label_ setTextColor:[UIColor blackColor]];
4231 [label_ setShadowColor:[UIColor whiteColor]];
4232 [label_ setShadowOffset:CGSizeMake(0, 1)];
4233 [label_ setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
4234 [container_ addSubview:label_];
4236 CGSize viewsize = frame.size;
4237 CGSize spinnersize = [spinner_ bounds].size;
4238 CGSize textsize = [[label_ text] sizeWithFont:[label_ font]];
4239 float bothwidth = spinnersize.width + textsize.width + 5.0f;
4241 CGRect containrect = {
4242 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
4243 CGSizeMake(bothwidth, spinnersize.height)
4246 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
4254 [container_ setFrame:containrect];
4255 [spinner_ setFrame:spinrect];
4256 [label_ setFrame:textrect];
4257 [self addSubview:container_];
4261 - (UILabel *) label {
4265 - (UIActivityIndicatorView *) activityIndicatorView {
4271 /* Emulated Loading Controller {{{ */
4272 @interface CYEmulatedLoadingController : CYViewController {
4273 _transient Database *database_;
4274 _H<CYLoadingIndicator> indicator_;
4275 _H<UITabBar> tabbar_;
4276 _H<UINavigationBar> navbar_;
4281 @implementation CYEmulatedLoadingController
4283 - (id) initWithDatabase:(Database *)database {
4284 if ((self = [super init]) != nil) {
4285 database_ = database;
4290 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
4291 [[self view] setBackgroundColor:[UIColor pinStripeColor]];
4293 indicator_ = [[[CYLoadingIndicator alloc] initWithFrame:[[self view] bounds]] autorelease];
4294 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4295 [[self view] addSubview:indicator_];
4297 tabbar_ = [[[UITabBar alloc] initWithFrame:CGRectMake(0, 0, 0, 49.0f)] autorelease];
4298 [tabbar_ setFrame:CGRectMake(0.0f, [[self view] bounds].size.height - [tabbar_ bounds].size.height, [[self view] bounds].size.width, [tabbar_ bounds].size.height)];
4299 [tabbar_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth];
4300 [[self view] addSubview:tabbar_];
4302 navbar_ = [[[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 0, 44.0f)] autorelease];
4303 [navbar_ setFrame:CGRectMake(0.0f, 0.0f, [[self view] bounds].size.width, [navbar_ bounds].size.height)];
4304 [navbar_ setAutoresizingMask:UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth];
4305 [[self view] addSubview:navbar_];
4308 - (void) releaseSubviews {
4317 /* Cydia Browser Controller {{{ */
4318 @interface CYBrowserController : BrowserController {
4319 CydiaObject *cydia_;
4324 @implementation CYBrowserController
4331 - (NSURL *) navigationURL {
4332 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[[webview_ request] URL] absoluteString]]];
4335 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
4338 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4339 [super webView:view didClearWindowObject:window forFrame:frame];
4341 WebDataSource *source([frame dataSource]);
4342 NSURLResponse *response([source response]);
4344 NSURL *url([response URL]);
4345 NSString *scheme([url scheme]);
4346 NSString *host([url host]);
4348 if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
4349 NSHTTPURLResponse *http((NSHTTPURLResponse *) response);
4350 NSDictionary *headers([http allHeaderFields]);
4351 [self setHeaders:headers forHost:host];
4355 [host isEqualToString:@"cydia.saurik.com"] ||
4356 [host hasSuffix:@".cydia.saurik.com"] ||
4357 [scheme isEqualToString:@"file"]
4359 [window setValue:cydia_ forKey:@"cydia"];
4362 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
4363 if (System_ != NULL)
4364 [request setValue:System_ forHTTPHeaderField:@"X-System"];
4365 if (Machine_ != NULL)
4366 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4368 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4370 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
4373 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4374 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4375 [self _setMoreHeaders:copy];
4379 - (void) setDelegate:(id)delegate {
4380 [super setDelegate:delegate];
4381 [cydia_ setDelegate:delegate];
4385 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
4386 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
4388 WebView *webview([[webview_ _documentView] webView]);
4390 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
4392 NSString *application = package == nil ? @"Cydia" : [NSString
4393 stringWithFormat:@"Cydia/%@",
4398 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4400 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4401 if (Product_ != nil)
4402 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4404 [webview setApplicationNameForUserAgent:application];
4412 @interface NSObject (CydiaScript)
4413 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4416 @implementation NSObject (CydiaScript)
4418 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4424 @implementation NSArray (CydiaScript)
4426 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4427 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4428 for (size_t i(0), e([self count]); i != e; ++i)
4429 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4435 @implementation NSDictionary (CydiaScript)
4437 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4438 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4440 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4447 /* Confirmation Controller {{{ */
4448 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4449 if (!iterator.end())
4450 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4451 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4453 pkgCache::PkgIterator package(dep.TargetPkg());
4456 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4463 @protocol ConfirmationControllerDelegate
4464 - (void) cancelAndClear:(bool)clear;
4465 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4469 @interface ConfirmationController : CYBrowserController {
4470 _transient Database *database_;
4472 UIAlertView *essential_;
4474 NSDictionary *changes_;
4475 NSMutableArray *issues_;
4476 NSDictionary *sizes_;
4481 - (id) initWithDatabase:(Database *)database;
4485 @implementation ConfirmationController
4492 if (essential_ != nil)
4493 [essential_ release];
4500 RestartSubstrate_ = true;
4501 [delegate_ confirmWithNavigationController:[self navigationController]];
4504 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4505 NSString *context([alert context]);
4507 if ([context isEqualToString:@"remove"]) {
4508 if (button == [alert cancelButtonIndex])
4509 [self dismissModalViewControllerAnimated:YES];
4510 else if (button == [alert firstOtherButtonIndex]) {
4514 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4515 } else if ([context isEqualToString:@"unable"]) {
4516 [self dismissModalViewControllerAnimated:YES];
4517 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4519 [super alertView:alert clickedButtonAtIndex:button];
4523 - (void) _doContinue {
4524 [self dismissModalViewControllerAnimated:YES];
4525 [delegate_ cancelAndClear:NO];
4528 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4529 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4533 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4534 [super webView:view didClearWindowObject:window forFrame:frame];
4536 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4537 changes_, @"changes",
4541 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4544 - (id) initWithDatabase:(Database *)database {
4545 if ((self = [super init]) != nil) {
4546 database_ = database;
4548 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4549 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4550 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4551 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4552 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4556 pkgCacheFile &cache([database_ cache]);
4557 NSArray *packages([database_ packages]);
4558 pkgDepCache::Policy *policy([database_ policy]);
4560 issues_ = [[NSMutableArray arrayWithCapacity:4] retain];
4562 for (Package *package in packages) {
4563 pkgCache::PkgIterator iterator([package iterator]);
4564 NSString *name([package id]);
4566 if ([package broken]) {
4567 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4569 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4571 reasons, @"reasons",
4574 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4578 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4579 pkgCache::DepIterator start;
4580 pkgCache::DepIterator end;
4581 dep.GlobOr(start, end); // ++dep
4583 if (!cache->IsImportantDep(end))
4585 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4588 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4590 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4591 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4592 clauses, @"clauses",
4596 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4598 pkgCache::PkgIterator target(start.TargetPkg());
4599 if (target->ProvidesList != 0)
4600 reason = @"missing";
4602 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4604 reason = @"installed";
4605 installed = [NSString stringWithUTF8String:ver.VerStr()];
4606 } else if (!cache[target].CandidateVerIter(cache).end())
4607 reason = @"uninstalled";
4608 else if (target->ProvidesList == 0)
4609 reason = @"uninstallable";
4611 reason = @"virtual";
4614 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4615 [NSString stringWithUTF8String:start.CompType()], @"operator",
4616 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4619 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4620 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4621 version, @"version",
4623 installed, @"installed",
4626 // yes, seriously. (wtf?)
4634 pkgDepCache::StateCache &state(cache[iterator]);
4636 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4638 if (state.NewInstall())
4639 [installs addObject:name];
4640 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4641 [reinstalls addObject:name];
4642 else if (state.Upgrade())
4643 [upgrades addObject:name];
4644 else if (state.Downgrade())
4645 [downgrades addObject:name];
4646 else if (!state.Delete())
4648 else if (special_r(name))
4649 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4650 [NSNull null], @"package",
4651 [NSArray arrayWithObjects:
4652 [NSDictionary dictionaryWithObjectsAndKeys:
4653 @"Conflicts", @"relationship",
4654 [NSArray arrayWithObjects:
4655 [NSDictionary dictionaryWithObjectsAndKeys:
4657 [NSNull null], @"version",
4658 @"installed", @"reason",
4665 if ([package essential])
4667 [removes addObject:name];
4670 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4671 substrate_ |= DepSubstrate(iterator.CurrentVer());
4676 else if (Advanced_) {
4677 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4679 essential_ = [[UIAlertView alloc]
4680 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4681 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4683 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4685 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4689 [essential_ setContext:@"remove"];
4691 essential_ = [[UIAlertView alloc]
4692 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4693 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4695 cancelButtonTitle:UCLocalize("OKAY")
4696 otherButtonTitles:nil
4699 [essential_ setContext:@"unable"];
4702 changes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
4703 installs, @"installs",
4704 reinstalls, @"reinstalls",
4705 upgrades, @"upgrades",
4706 downgrades, @"downgrades",
4707 removes, @"removes",
4710 sizes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
4711 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4712 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4715 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/confirm/", UI_]]];
4717 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
4718 initWithTitle:UCLocalize("CANCEL")
4719 style:UIBarButtonItemStylePlain
4721 action:@selector(cancelButtonClicked)
4727 - (void) applyRightButton {
4728 if ([issues_ count] == 0 && ![self isLoading])
4729 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4730 initWithTitle:UCLocalize("CONFIRM")
4731 style:UIBarButtonItemStyleDone
4733 action:@selector(confirmButtonClicked)
4736 [[self navigationItem] setRightBarButtonItem:nil];
4740 - (void) cancelButtonClicked {
4741 [self dismissModalViewControllerAnimated:YES];
4742 [delegate_ cancelAndClear:YES];
4746 - (void) confirmButtonClicked {
4747 if (essential_ != nil)
4757 /* Progress Controller {{{ */
4758 @interface ProgressController : CYViewController <
4761 _transient Database *database_;
4762 UIProgressBar *progress_;
4763 UITextView *output_;
4764 UITextLabel *status_;
4765 UIPushButton *close_;
4767 SHA1SumValue springlist_;
4768 SHA1SumValue notifyconf_;
4769 _H<NSString> title_;
4772 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4774 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
4776 - (void) setTitle:(NSString *)title;
4782 @implementation ProgressController
4785 [database_ setProgressDelegate:nil];
4786 [progress_ release];
4793 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4794 if ((self = [super init]) != nil) {
4795 database_ = database;
4796 delegate_ = delegate;
4798 [database_ setProgressDelegate:self];
4800 [[self view] setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
4802 progress_ = [[UIProgressBar alloc] init];
4803 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4804 [progress_ setStyle:0];
4806 status_ = [[UITextLabel alloc] init];
4807 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4808 [status_ setColor:[UIColor whiteColor]];
4809 [status_ setBackgroundColor:[UIColor clearColor]];
4810 [status_ setCentersHorizontally:YES];
4811 //[status_ setFont:font];
4813 output_ = [[UITextView alloc] init];
4814 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4815 //[output_ setTextFont:@"Courier New"];
4816 [output_ setFont:[[output_ font] fontWithSize:12]];
4817 [output_ setTextColor:[UIColor whiteColor]];
4818 [output_ setBackgroundColor:[UIColor clearColor]];
4819 [output_ setMarginTop:0];
4820 [output_ setAllowsRubberBanding:YES];
4821 [output_ setEditable:NO];
4822 [[self view] addSubview:output_];
4824 close_ = [[UIPushButton alloc] init];
4825 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4826 [close_ setAutosizesToFit:NO];
4827 [close_ setDrawsShadow:YES];
4828 [close_ setStretchBackground:YES];
4829 [close_ setEnabled:YES];
4830 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
4831 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4832 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4833 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4837 - (void) positionViews {
4838 CGRect bounds = [[self view] bounds];
4839 CGSize prgsize = [UIProgressBar defaultSize];
4842 (bounds.size.width - prgsize.width) / 2,
4843 bounds.size.height - prgsize.height - 20
4846 float closewidth = std::min(bounds.size.width - 20, 300.0f);
4848 [progress_ setFrame:prgrect];
4849 [status_ setFrame:CGRectMake(
4851 bounds.size.height - prgsize.height - 50,
4852 bounds.size.width - 20,
4855 [output_ setFrame:CGRectMake(
4858 bounds.size.width - 20,
4859 bounds.size.height - 96
4861 [close_ setFrame:CGRectMake(
4862 (bounds.size.width - closewidth) / 2,
4863 bounds.size.height - prgsize.height - 50,
4869 - (void) viewWillAppear:(BOOL)animated {
4870 [super viewDidAppear:animated];
4871 [[self navigationItem] setHidesBackButton:YES];
4872 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4874 [self positionViews];
4877 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4878 [self positionViews];
4881 - (void) closeButtonPushed {
4884 UpdateExternalStatus(0);
4888 [self dismissModalViewControllerAnimated:YES];
4892 [delegate_ terminateWithSuccess];
4893 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4894 [delegate_ suspendWithAnimation:YES];
4896 [delegate_ suspend];*/
4908 system("/usr/bin/sbreload");
4914 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
4915 SBReboot(SBSSpringBoardServerPort());
4917 reboot2(RB_AUTOBOOT);
4922 - (void) setTitle:(NSString *)title {
4924 [[self navigationItem] setTitle:title];
4927 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
4928 UpdateExternalStatus(1);
4930 [self setTitle:title];
4932 [status_ setText:nil];
4933 [output_ setText:@""];
4934 [progress_ setProgress:0];
4936 [close_ removeFromSuperview];
4937 [[self view] addSubview:progress_];
4938 [[self view] addSubview:status_];
4940 [delegate_ retainNetworkActivityIndicator];
4945 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4948 MMap mmap(file, MMap::ReadOnly);
4950 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4951 notifyconf_ = sha1.Result();
4957 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4960 MMap mmap(file, MMap::ReadOnly);
4962 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4963 springlist_ = sha1.Result();
4967 if (invocation != nil) {
4968 [invocation yieldToSelector:@selector(invoke)];
4969 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
4972 [[self view] addSubview:close_];
4973 [progress_ removeFromSuperview];
4974 [status_ removeFromSuperview];
4978 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4981 MMap mmap(file, MMap::ReadOnly);
4983 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4984 if (!(notifyconf_ == sha1.Result()))
4991 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4994 MMap mmap(file, MMap::ReadOnly);
4996 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4997 if (!(springlist_ == sha1.Result()))
5003 if (RestartSubstrate_)
5007 RestartSubstrate_ = false;
5010 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5011 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
5012 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
5013 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5014 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
5018 system("su -c /usr/bin/uicache mobile");
5021 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
5023 [delegate_ releaseNetworkActivityIndicator];
5026 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5027 NSString *type([event type]);
5029 if ([type isEqualToString:@"ERROR"] || [type isEqualToString:@"WARNING"]) {
5030 CYAlertView *sheet([[[CYAlertView alloc]
5031 initWithTitle:[event compoundTitle]
5032 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
5033 defaultButtonIndex:0
5036 [sheet setMessage:[event message]];
5037 [sheet yieldToPopupAlertAnimated:YES];
5039 } else if ([type isEqualToString:@"INFORMATION"]) {
5040 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], [event message]]];
5041 CGSize size = [output_ contentSize];
5042 CGPoint offset = [output_ contentOffset];
5043 if (size.height - offset.y < [output_ frame].size.height + 20.f) {
5044 CGRect rect = {{0, size.height-1}, {size.width, 1}};
5045 [output_ scrollRectToVisible:rect animated:YES];
5047 } else if ([type isEqualToString:@"STATUS"]) {
5048 NSMutableArray *words([[[event message] componentsSeparatedByString:@" "] mutableCopy]);
5049 for (size_t i(0), e([words count]); i != e; ++i) {
5050 NSString *word([words objectAtIndex:i]);
5051 if (Package *package = [database_ packageWithName:word])
5052 [words replaceObjectAtIndex:i withObject:[package name]];
5055 [status_ setText:[words componentsJoinedByString:@" "]];
5056 } else _assert(false);
5059 - (bool) isProgressCancelled {
5063 - (void) setProgressPercent:(NSNumber *)percent {
5064 [progress_ setProgress:[percent floatValue]];
5067 - (BOOL) isRunning {
5074 /* Cell Content View {{{ */
5075 @protocol ContentDelegate
5076 - (void) drawContentRect:(CGRect)rect;
5079 @interface ContentView : UIView {
5080 _transient id<ContentDelegate> delegate_;
5085 @implementation ContentView
5087 - (id) initWithFrame:(CGRect)frame {
5088 if ((self = [super initWithFrame:frame]) != nil) {
5089 [self setNeedsDisplayOnBoundsChange:YES];
5093 - (void) setDelegate:(id<ContentDelegate>)delegate {
5094 delegate_ = delegate;
5097 - (void) drawRect:(CGRect)rect {
5098 [super drawRect:rect];
5099 [delegate_ drawContentRect:rect];
5104 /* Cydia TableView Cell {{{ */
5105 @interface CYTableViewCell : UITableViewCell {
5106 ContentView *content_;
5112 @implementation CYTableViewCell
5119 - (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
5120 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
5122 if (view == content_) {
5123 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
5124 highlighted_ = highlighted;
5127 [super _updateHighlightColorsForView:view highlighted:highlighted];
5130 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
5131 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
5132 highlighted_ = selected;
5134 [super setSelected:selected animated:animated];
5135 [content_ setNeedsDisplay];
5141 /* Package Cell {{{ */
5142 @interface PackageCell : CYTableViewCell <
5147 NSString *description_;
5155 - (PackageCell *) init;
5156 - (void) setPackage:(Package *)package;
5158 - (void) drawContentRect:(CGRect)rect;
5162 @implementation PackageCell
5164 - (void) clearPackage {
5175 if (description_ != nil) {
5176 [description_ release];
5180 if (source_ != nil) {
5185 if (badge_ != nil) {
5190 if (placard_ != nil) {
5200 [self clearPackage];
5204 - (PackageCell *) init {
5205 CGRect frame(CGRectMake(0, 0, 320, 74));
5206 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5207 UIView *content([self contentView]);
5208 CGRect bounds([content bounds]);
5210 content_ = [[ContentView alloc] initWithFrame:bounds];
5211 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5212 [content addSubview:content_];
5214 [content_ setDelegate:self];
5215 [content_ setOpaque:YES];
5219 - (NSString *) accessibilityLabel {
5220 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), name_, description_];
5223 - (void) setPackage:(Package *)package {
5224 [self clearPackage];
5227 Source *source = [package source];
5229 icon_ = [[package icon] retain];
5230 name_ = [[package name] retain];
5233 description_ = [package longDescription];
5234 if (description_ == nil)
5235 description_ = [package shortDescription];
5236 if (description_ != nil)
5237 description_ = [description_ retain];
5239 commercial_ = [package isCommercial];
5241 package_ = [package retain];
5243 NSString *label = nil;
5244 bool trusted = false;
5246 if (source != nil) {
5247 label = [source label];
5248 trusted = [source trusted];
5249 } else if ([[package id] isEqualToString:@"firmware"])
5250 label = UCLocalize("APPLE");
5252 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5254 NSString *from(label);
5256 NSString *section = [package simpleSection];
5257 if (section != nil && ![section isEqualToString:label]) {
5258 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5259 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5262 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
5263 source_ = [from retain];
5265 if (NSString *purpose = [package primaryPurpose])
5266 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
5267 badge_ = [badge_ retain];
5272 if (NSString *mode = [package_ mode]) {
5273 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5274 color = RemovingColor_;
5275 //placard = @"removing";
5277 color = InstallingColor_;
5278 //placard = @"installing";
5281 // XXX: the removing/installing placards are not @2x
5284 color = [UIColor whiteColor];
5286 if ([package installed] != nil)
5287 placard = @"installed";
5292 [content_ setBackgroundColor:color];
5295 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]]) != nil)
5296 placard_ = [placard_ retain];
5298 [self setNeedsDisplay];
5299 [content_ setNeedsDisplay];
5302 - (void) drawContentRect:(CGRect)rect {
5303 bool highlighted(highlighted_);
5304 float width([self bounds].size.width);
5307 CGContextRef context(UIGraphicsGetCurrentContext());
5308 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
5309 CGContextFillRect(context, rect);
5314 rect.size = [icon_ size];
5316 rect.size.width /= 2;
5317 rect.size.height /= 2;
5319 rect.origin.x = 25 - rect.size.width / 2;
5320 rect.origin.y = 25 - rect.size.height / 2;
5322 [icon_ drawInRect:rect];
5325 if (badge_ != nil) {
5327 rect.size = [badge_ size];
5329 rect.size.width /= 2;
5330 rect.size.height /= 2;
5332 rect.origin.x = 36 - rect.size.width / 2;
5333 rect.origin.y = 36 - rect.size.height / 2;
5335 [badge_ drawInRect:rect];
5342 UISetColor(commercial_ ? Purple_ : Black_);
5343 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5344 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5347 UISetColor(commercial_ ? Purplish_ : Gray_);
5348 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5350 if (placard_ != nil)
5351 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5356 /* Section Cell {{{ */
5357 @interface SectionCell : CYTableViewCell <
5369 - (void) setSection:(Section *)section editing:(BOOL)editing;
5373 @implementation SectionCell
5375 - (void) clearSection {
5376 if (basic_ != nil) {
5381 if (section_ != nil) {
5391 if (count_ != nil) {
5398 [self clearSection];
5404 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5405 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5406 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
5407 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
5408 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5410 UIView *content([self contentView]);
5411 CGRect bounds([content bounds]);
5413 content_ = [[ContentView alloc] initWithFrame:bounds];
5414 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5415 [content addSubview:content_];
5416 [content_ setBackgroundColor:[UIColor whiteColor]];
5418 [content_ setDelegate:self];
5422 - (void) onSwitch:(id)sender {
5423 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5424 if (metadata == nil) {
5425 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5426 [Sections_ setObject:metadata forKey:basic_];
5429 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5433 - (void) setSection:(Section *)section editing:(BOOL)editing {
5434 if (editing != editing_) {
5436 [switch_ removeFromSuperview];
5438 [self addSubview:switch_];
5442 [self clearSection];
5444 if (section == nil) {
5445 name_ = [UCLocalize("ALL_PACKAGES") retain];
5448 basic_ = [section name];
5450 basic_ = [basic_ retain];
5452 section_ = [section localized];
5453 if (section_ != nil)
5454 section_ = [section_ retain];
5456 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
5457 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
5460 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5463 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5464 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5466 [content_ setNeedsDisplay];
5469 - (void) setFrame:(CGRect)frame {
5470 [super setFrame:frame];
5472 CGRect rect([switch_ frame]);
5473 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5476 - (NSString *) accessibilityLabel {
5480 - (void) drawContentRect:(CGRect)rect {
5481 bool highlighted(highlighted_ && !editing_);
5483 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5488 float width(rect.size.width);
5494 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5496 CGSize size = [count_ sizeWithFont:Font14_];
5500 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5506 /* File Table {{{ */
5507 @interface FileTable : CYViewController <
5508 UITableViewDataSource,
5511 _transient Database *database_;
5514 NSMutableArray *files_;
5518 - (id) initWithDatabase:(Database *)database;
5519 - (void) setPackage:(Package *)package;
5523 @implementation FileTable
5526 [self releaseSubviews];
5535 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5536 return files_ == nil ? 0 : [files_ count];
5539 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5543 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5544 static NSString *reuseIdentifier = @"Cell";
5546 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5548 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5549 [cell setFont:[UIFont systemFontOfSize:16]];
5551 [cell setText:[files_ objectAtIndex:indexPath.row]];
5552 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5557 - (NSURL *) navigationURL {
5558 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5562 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5564 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5565 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5566 [list_ setRowHeight:24.0f];
5567 [list_ setDataSource:self];
5568 [list_ setDelegate:self];
5569 [[self view] addSubview:list_];
5572 - (void) viewDidLoad {
5573 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5576 - (void) releaseSubviews {
5581 - (id) initWithDatabase:(Database *)database {
5582 if ((self = [super init]) != nil) {
5583 database_ = database;
5585 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5589 - (void) setPackage:(Package *)package {
5590 if (package_ != nil) {
5591 [package_ autorelease];
5600 [files_ removeAllObjects];
5602 if (package != nil) {
5603 package_ = [package retain];
5604 name_ = [[package id] retain];
5606 if (NSArray *files = [package files])
5607 [files_ addObjectsFromArray:files];
5609 if ([files_ count] != 0) {
5610 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5611 [files_ removeObjectAtIndex:0];
5612 [files_ sortUsingSelector:@selector(compareByPath:)];
5614 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5615 [stack addObject:@"/"];
5617 for (int i(0), e([files_ count]); i != e; ++i) {
5618 NSString *file = [files_ objectAtIndex:i];
5619 while (![file hasPrefix:[stack lastObject]])
5620 [stack removeLastObject];
5621 NSString *directory = [stack lastObject];
5622 [stack addObject:[file stringByAppendingString:@"/"]];
5623 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5624 ([stack count] - 2) * 3, "",
5625 [file substringFromIndex:[directory length]]
5634 - (void) reloadData {
5637 [self setPackage:[database_ packageWithName:name_]];
5642 /* Package Controller {{{ */
5643 @interface CYPackageController : CYBrowserController <
5644 UIActionSheetDelegate
5646 _transient Database *database_;
5650 NSMutableArray *buttons_;
5651 UIBarButtonItem *button_;
5654 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5658 @implementation CYPackageController
5661 if (package_ != nil)
5674 - (NSURL *) navigationURL {
5675 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", name_]];
5678 /* XXX: this is not safe at all... localization of /fail/ */
5679 - (void) _clickButtonWithName:(NSString *)name {
5680 if ([name isEqualToString:UCLocalize("CLEAR")])
5681 [delegate_ clearPackage:package_];
5682 else if ([name isEqualToString:UCLocalize("INSTALL")])
5683 [delegate_ installPackage:package_];
5684 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5685 [delegate_ installPackage:package_];
5686 else if ([name isEqualToString:UCLocalize("REMOVE")])
5687 [delegate_ removePackage:package_];
5688 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5689 [delegate_ installPackage:package_];
5690 else _assert(false);
5693 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5694 NSString *context([sheet context]);
5696 if ([context isEqualToString:@"modify"]) {
5697 if (button != [sheet cancelButtonIndex]) {
5698 NSString *buttonName = [buttons_ objectAtIndex:button];
5699 [self _clickButtonWithName:buttonName];
5702 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5706 - (bool) _allowJavaScriptPanel {
5711 - (void) _customButtonClicked {
5712 int count([buttons_ count]);
5717 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5719 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5720 [buttons addObjectsFromArray:buttons_];
5722 UIActionSheet *sheet = [[[UIActionSheet alloc]
5725 cancelButtonTitle:nil
5726 destructiveButtonTitle:nil
5727 otherButtonTitles:nil
5730 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5732 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5733 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5735 [sheet setContext:@"modify"];
5737 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5741 // We don't want to allow non-commercial packages to do custom things to the install button,
5742 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5743 - (void) customButtonClicked {
5745 [super customButtonClicked];
5747 [self _customButtonClicked];
5750 - (void) reloadButtonClicked {
5751 // Don't reload a commerical package by tapping the loading button,
5752 // but if it's not an Install button, we should forward it on.
5753 if (![package_ uninstalled])
5754 [self _customButtonClicked];
5757 - (void) applyLoadingTitle {
5758 // Don't show "Loading" as the title. Ever.
5761 - (UIBarButtonItem *) rightButton {
5766 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
5767 if ((self = [super init]) != nil) {
5768 database_ = database;
5769 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5770 name_ = [[NSString alloc] initWithString:name];
5771 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/package/#!/%@", UI_, name_]]];
5775 - (void) reloadData {
5776 if (package_ != nil)
5777 [package_ autorelease];
5778 package_ = [database_ packageWithName:name_];
5780 [buttons_ removeAllObjects];
5782 if (package_ != nil) {
5785 package_ = [package_ retain];
5786 commercial_ = [package_ isCommercial];
5788 if ([package_ mode] != nil)
5789 [buttons_ addObject:UCLocalize("CLEAR")];
5790 if ([package_ source] == nil);
5791 else if ([package_ upgradableAndEssential:NO])
5792 [buttons_ addObject:UCLocalize("UPGRADE")];
5793 else if ([package_ uninstalled])
5794 [buttons_ addObject:UCLocalize("INSTALL")];
5796 [buttons_ addObject:UCLocalize("REINSTALL")];
5797 if (![package_ uninstalled])
5798 [buttons_ addObject:UCLocalize("REMOVE")];
5805 switch ([buttons_ count]) {
5806 case 0: title = nil; break;
5807 case 1: title = [buttons_ objectAtIndex:0]; break;
5808 default: title = UCLocalize("MODIFY"); break;
5811 button_ = [[UIBarButtonItem alloc]
5813 style:UIBarButtonItemStylePlain
5815 action:@selector(customButtonClicked)
5821 - (bool) isLoading {
5822 return commercial_ ? [super isLoading] : false;
5828 /* Package List Controller {{{ */
5829 @interface PackageListController : CYViewController <
5830 UITableViewDataSource,
5833 _transient Database *database_;
5835 NSMutableArray *packages_;
5836 NSMutableArray *sections_;
5838 NSMutableArray *index_;
5839 NSMutableDictionary *indices_;
5843 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
5844 - (void) setDelegate:(id)delegate;
5845 - (void) resetCursor;
5849 @implementation PackageListController
5852 [packages_ release];
5853 [sections_ release];
5862 - (void) deselectWithAnimation:(BOOL)animated {
5863 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5866 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
5867 CGRect base = [[self view] bounds];
5868 base.size.height -= bounds.size.height;
5869 base.origin = [list_ frame].origin;
5871 [UIView beginAnimations:nil context:NULL];
5872 [UIView setAnimationBeginsFromCurrentState:YES];
5873 [UIView setAnimationCurve:curve];
5874 [UIView setAnimationDuration:duration];
5875 [list_ setFrame:base];
5876 [UIView commitAnimations];
5879 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
5880 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
5883 - (void) resizeForKeyboardBounds:(CGRect)bounds {
5884 [self resizeForKeyboardBounds:bounds duration:0];
5887 - (void) keyboardWillShow:(NSNotification *)notification {
5890 NSTimeInterval duration;
5891 UIViewAnimationCurve curve;
5892 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
5893 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
5894 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
5895 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
5897 CGRect kbframe = CGRectMake(round(center.x - bounds.size.width / 2.0), round(center.y - bounds.size.height / 2.0), bounds.size.width, bounds.size.height);
5898 UIViewController *base = self;
5899 while ([base parentViewController] != nil)
5900 base = [base parentViewController];
5901 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
5902 CGRect intersection = CGRectIntersection(viewframe, kbframe);
5904 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
5907 - (void) keyboardWillHide:(NSNotification *)notification {
5908 NSTimeInterval duration;
5909 UIViewAnimationCurve curve;
5910 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
5911 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
5913 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
5916 - (void) viewWillAppear:(BOOL)animated {
5917 [super viewWillAppear:animated];
5919 [self resizeForKeyboardBounds:CGRectZero];
5920 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
5921 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
5924 - (void) viewWillDisappear:(BOOL)animated {
5925 [super viewWillDisappear:animated];
5927 [self resizeForKeyboardBounds:CGRectZero];
5928 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
5929 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
5932 - (void) viewDidAppear:(BOOL)animated {
5933 [super viewDidAppear:animated];
5934 [self deselectWithAnimation:animated];
5937 - (void) didSelectPackage:(Package *)package {
5938 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
5939 [view setDelegate:delegate_];
5940 [[self navigationController] pushViewController:view animated:YES];
5943 #if TryIndexedCollation
5944 + (BOOL) hasIndexedCollation {
5945 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
5949 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5950 NSInteger count([sections_ count]);
5951 return count == 0 ? 1 : count;
5954 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5955 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
5957 return [[sections_ objectAtIndex:section] name];
5960 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5961 if ([sections_ count] == 0)
5963 return [[sections_ objectAtIndex:section] count];
5966 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5967 @synchronized (database_) {
5968 if ([database_ era] != era_)
5971 Section *section([sections_ objectAtIndex:[path section]]);
5972 NSInteger row([path row]);
5973 Package *package([packages_ objectAtIndex:([section row] + row)]);
5974 return [[package retain] autorelease];
5977 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5978 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5980 cell = [[[PackageCell alloc] init] autorelease];
5981 [cell setPackage:[self packageAtIndexPath:path]];
5985 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
5986 Package *package([self packageAtIndexPath:path]);
5987 package = [database_ packageWithName:[package id]];
5988 [self didSelectPackage:package];
5991 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5992 // XXX: is 20 the most optimal number here?
5993 return [packages_ count] > 20 ? index_ : nil;
5996 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5997 #if TryIndexedCollation
5998 if ([[self class] hasIndexedCollation]) {
5999 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6006 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6007 if ((self = [super init]) != nil) {
6008 database_ = database;
6009 title_ = [title copy];
6010 [[self navigationItem] setTitle:title_];
6012 #if TryIndexedCollation
6013 if ([[self class] hasIndexedCollation])
6014 index_ = [[[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles] retain]
6017 index_ = [[NSMutableArray alloc] initWithCapacity:32];
6019 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
6021 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6022 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6024 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6025 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6026 [list_ setRowHeight:73];
6027 [[self view] addSubview:list_];
6029 [list_ setDataSource:self];
6030 [list_ setDelegate:self];
6034 - (void) setDelegate:(id)delegate {
6035 delegate_ = delegate;
6038 - (bool) hasPackage:(Package *)package {
6042 - (void) reloadData {
6045 era_ = [database_ era];
6046 NSArray *packages = [database_ packages];
6048 [packages_ removeAllObjects];
6049 [sections_ removeAllObjects];
6051 _profile(PackageTable$reloadData$Filter)
6052 for (Package *package in packages)
6053 if ([self hasPackage:package])
6054 [packages_ addObject:package];
6057 [indices_ removeAllObjects];
6059 Section *section = nil;
6061 #if TryIndexedCollation
6062 if ([[self class] hasIndexedCollation]) {
6063 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6064 NSArray *titles = [collation sectionIndexTitles];
6067 _profile(PackageTable$reloadData$Section)
6068 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6072 _profile(PackageTable$reloadData$Section$Package)
6073 package = [packages_ objectAtIndex:offset];
6074 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6077 while (secidx < index) {
6080 _profile(PackageTable$reloadData$Section$Allocate)
6081 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6084 _profile(PackageTable$reloadData$Section$Add)
6085 [sections_ addObject:section];
6089 [section addToCount];
6095 [index_ removeAllObjects];
6097 _profile(PackageTable$reloadData$Section)
6098 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6102 _profile(PackageTable$reloadData$Section$Package)
6103 package = [packages_ objectAtIndex:offset];
6104 index = [package index];
6107 if (section == nil || [section index] != index) {
6108 _profile(PackageTable$reloadData$Section$Allocate)
6109 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6112 [index_ addObject:[section name]];
6113 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6115 _profile(PackageTable$reloadData$Section$Add)
6116 [sections_ addObject:section];
6120 [section addToCount];
6125 _profile(PackageTable$reloadData$List)
6130 - (void) resetCursor {
6131 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
6136 /* Filtered Package List Controller {{{ */
6137 @interface FilteredPackageListController : PackageListController {
6143 - (void) setObject:(id)object;
6144 - (void) setObject:(id)object forFilter:(SEL)filter;
6146 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6150 @implementation FilteredPackageListController
6158 - (void) setFilter:(SEL)filter {
6161 /* XXX: this is an unsafe optimization of doomy hell */
6162 Method method(class_getInstanceMethod([Package class], filter));
6163 _assert(method != NULL);
6164 imp_ = method_getImplementation(method);
6165 _assert(imp_ != NULL);
6168 - (void) setObject:(id)object {
6174 object_ = [object retain];
6177 - (void) setObject:(id)object forFilter:(SEL)filter {
6178 [self setFilter:filter];
6179 [self setObject:object];
6182 - (bool) hasPackage:(Package *)package {
6183 _profile(FilteredPackageTable$hasPackage)
6184 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
6188 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6189 if ((self = [super initWithDatabase:database title:title]) != nil) {
6190 [self setFilter:filter];
6191 [self setObject:object];
6198 /* Home Controller {{{ */
6199 @interface HomeController : CYBrowserController {
6204 @implementation HomeController
6206 + (BOOL) shouldHideNavigationBar {
6210 - (NSURL *) navigationURL {
6211 return [NSURL URLWithString:@"cydia://home"];
6214 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6215 [super _setMoreHeaders:request];
6218 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6219 if (UniqueID_ != nil)
6220 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6222 [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"];
6225 - (void) aboutButtonClicked {
6226 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6228 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6229 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6230 [alert setCancelButtonIndex:0];
6233 @"Copyright (C) 2008-2011\n"
6234 "Jay Freeman (saurik)\n"
6235 "saurik@saurik.com\n"
6236 "http://www.saurik.com/"
6242 - (void) viewWillDisappear:(BOOL)animated {
6243 [super viewWillDisappear:animated];
6245 if ([[self class] shouldHideNavigationBar])
6246 [[self navigationController] setNavigationBarHidden:NO animated:animated];
6249 - (void) viewWillAppear:(BOOL)animated {
6250 if (![self hasLoaded])
6251 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/home/", UI_]]];
6253 [super viewWillAppear:animated];
6255 if ([[self class] shouldHideNavigationBar])
6256 [[self navigationController] setNavigationBarHidden:YES animated:animated];
6259 - (void) viewDidLoad {
6260 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6261 initWithTitle:UCLocalize("ABOUT")
6262 style:UIBarButtonItemStylePlain
6264 action:@selector(aboutButtonClicked)
6270 /* Manage Controller {{{ */
6271 @interface ManageController : CYBrowserController {
6274 - (void) queueStatusDidChange;
6278 @implementation ManageController
6280 - (NSURL *) navigationURL {
6281 return [NSURL URLWithString:@"cydia://manage"];
6284 - (void) viewWillAppear:(BOOL)animated {
6285 if (![self hasLoaded])
6286 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/manage/", UI_]]];
6288 [super viewWillAppear:animated];
6291 - (void) viewDidLoad {
6292 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6293 initWithTitle:UCLocalize("SETTINGS")
6294 style:UIBarButtonItemStylePlain
6296 action:@selector(settingsButtonClicked)
6299 [self queueStatusDidChange];
6302 - (void) settingsButtonClicked {
6303 [delegate_ showSettings];
6307 - (void) queueButtonClicked {
6311 - (void) applyLoadingTitle {
6312 // Disable "Loading" title.
6315 - (void) applyRightButton {
6316 // Disable right button.
6320 - (void) queueStatusDidChange {
6322 if (!IsWildcat_ && Queuing_) {
6323 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6324 initWithTitle:UCLocalize("QUEUE")
6325 style:UIBarButtonItemStyleDone
6327 action:@selector(queueButtonClicked)
6330 [[self navigationItem] setRightBarButtonItem:nil];
6335 - (bool) isLoading {
6336 // Never show as loading.
6343 /* Refresh Bar {{{ */
6344 @interface RefreshBar : UINavigationBar {
6345 UIProgressIndicator *indicator_;
6346 UITextLabel *prompt_;
6347 UIProgressBar *progress_;
6348 UINavigationButton *cancel_;
6353 @implementation RefreshBar
6356 [indicator_ release];
6358 [progress_ release];
6363 - (void) positionViews {
6364 CGRect frame = [cancel_ frame];
6365 frame.size = [cancel_ sizeThatFits:frame.size];
6366 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6367 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6368 [cancel_ setFrame:frame];
6370 CGSize prgsize = {75, 100};
6372 [self frame].size.width - prgsize.width - 10,
6373 ([self frame].size.height - prgsize.height) / 2
6375 [progress_ setFrame:prgrect];
6377 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6378 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6379 CGRect indrect = {{indoffset, indoffset}, indsize};
6380 [indicator_ setFrame:indrect];
6382 CGSize prmsize = {215, indsize.height + 4};
6384 indoffset * 2 + indsize.width,
6385 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6387 [prompt_ setFrame:prmrect];
6390 - (void) setFrame:(CGRect)frame {
6391 [super setFrame:frame];
6392 [self positionViews];
6395 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6396 if ((self = [super initWithFrame:frame]) != nil) {
6397 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6399 [self setBarStyle:UIBarStyleBlack];
6401 UIBarStyle barstyle([self _barStyle:NO]);
6402 bool ugly(barstyle == UIBarStyleDefault);
6404 UIProgressIndicatorStyle style = ugly ?
6405 UIProgressIndicatorStyleMediumBrown :
6406 UIProgressIndicatorStyleMediumWhite;
6408 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6409 [indicator_ setStyle:style];
6410 [indicator_ startAnimation];
6411 [self addSubview:indicator_];
6413 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6414 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6415 [prompt_ setBackgroundColor:[UIColor clearColor]];
6416 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6417 [self addSubview:prompt_];
6419 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6420 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6421 [progress_ setStyle:0];
6422 [self addSubview:progress_];
6424 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6425 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6426 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6427 [cancel_ setBarStyle:barstyle];
6429 [self positionViews];
6434 [cancel_ removeFromSuperview];
6438 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6439 [progress_ setProgress:0];
6440 [self addSubview:cancel_];
6444 [cancel_ removeFromSuperview];
6447 - (void) setPrompt:(NSString *)prompt {
6448 [prompt_ setText:prompt];
6451 - (void) setProgress:(float)progress {
6452 [progress_ setProgress:progress];
6458 @class CYNavigationController;
6460 /* Cydia Tab Bar Controller {{{ */
6461 @interface CYTabBarController : UITabBarController <
6462 UITabBarControllerDelegate,
6465 _transient Database *database_;
6466 RefreshBar *refreshbar_;
6470 // XXX: ok, "updatedelegate_"?...
6471 _transient NSObject<CydiaDelegate> *updatedelegate_;
6474 UIViewController *remembered_;
6475 _transient UIViewController *transient_;
6478 - (NSArray *) navigationURLCollection;
6479 - (void) dropBar:(BOOL)animated;
6480 - (void) beginUpdate;
6481 - (void) raiseBar:(BOOL)animated;
6486 @implementation CYTabBarController
6488 - (void) setUnselectedViewController:(UIViewController *)transient {
6489 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6490 if (transient != nil) {
6491 if (transient_ == nil)
6492 remembered_ = [[controllers objectAtIndex:0] retain];
6493 transient_ = transient;
6494 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6495 [controllers replaceObjectAtIndex:0 withObject:transient_];
6496 [self setSelectedIndex:0];
6497 [self setViewControllers:controllers];
6498 [self concealTabBarSelection];
6499 } else if (remembered_ != nil) {
6500 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6501 transient_ = transient;
6502 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6503 [remembered_ release];
6505 [self setViewControllers:controllers];
6506 [self revealTabBarSelection];
6510 - (UIViewController *) unselectedViewController {
6514 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6515 if ([self unselectedViewController])
6516 [self setUnselectedViewController:nil];
6519 - (NSArray *) navigationURLCollection {
6520 NSMutableArray *items([NSMutableArray array]);
6522 // XXX: Should this deal with transient view controllers?
6523 for (id navigation in [self viewControllers]) {
6524 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6526 [items addObject:stack];
6532 - (void) reloadData {
6533 for (CYViewController *controller in [self viewControllers])
6534 [controller reloadData];
6536 [(CYNavigationController *)[self unselectedViewController] reloadData];
6540 [refreshbar_ release];
6541 [[NSNotificationCenter defaultCenter] removeObserver:self];
6546 - (id) initWithDatabase:(Database *)database {
6547 if ((self = [super init]) != nil) {
6548 database_ = database;
6549 [self setDelegate:self];
6551 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6552 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6554 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
6558 - (void) setUpdate:(NSDate *)date {
6562 - (void) beginUpdate {
6563 [refreshbar_ start];
6566 [updatedelegate_ retainNetworkActivityIndicator];
6570 detachNewThreadSelector:@selector(performUpdate)
6576 - (void) performUpdate { _pooled
6578 status.setDelegate(self);
6579 [database_ updateWithStatus:status];
6582 performSelectorOnMainThread:@selector(completeUpdate)
6588 - (void) stopUpdateWithSelector:(SEL)selector {
6590 [updatedelegate_ releaseNetworkActivityIndicator];
6592 [self raiseBar:YES];
6595 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6598 - (void) completeUpdate {
6601 [self stopUpdateWithSelector:@selector(reloadData)];
6604 - (void) cancelUpdate {
6605 [self stopUpdateWithSelector:@selector(updateData)];
6608 - (void) cancelPressed {
6609 [self cancelUpdate];
6616 - (void) addProgressEvent:(CydiaProgressEvent *)event {
6617 [refreshbar_ setPrompt:[event compoundMessage]];
6620 - (bool) isProgressCancelled {
6624 - (void) setProgressPercent:(NSNumber *)percent {
6625 [refreshbar_ setProgress:[percent floatValue]];
6628 - (void) setUpdateDelegate:(id)delegate {
6629 updatedelegate_ = delegate;
6632 - (CGFloat) statusBarHeight {
6633 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
6634 return [[UIApplication sharedApplication] statusBarFrame].size.height;
6636 return [[UIApplication sharedApplication] statusBarFrame].size.width;
6640 - (UIView *) transitionView {
6641 if ([self respondsToSelector:@selector(_transitionView)])
6642 return [self _transitionView];
6644 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6647 - (void) dropBar:(BOOL)animated {
6652 UIView *transition([self transitionView]);
6653 [[self view] addSubview:refreshbar_];
6655 CGRect barframe([refreshbar_ frame]);
6657 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6658 barframe.origin.y = [self statusBarHeight];
6660 barframe.origin.y = 0;
6662 [refreshbar_ setFrame:barframe];
6665 [UIView beginAnimations:nil context:NULL];
6667 CGRect viewframe = [transition frame];
6668 viewframe.origin.y += barframe.size.height;
6669 viewframe.size.height -= barframe.size.height;
6670 [transition setFrame:viewframe];
6673 [UIView commitAnimations];
6675 // Ensure bar has the proper width for our view, it might have changed
6676 barframe.size.width = viewframe.size.width;
6677 [refreshbar_ setFrame:barframe];
6679 // XXX: fix Apple's layout bug
6680 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6683 - (void) raiseBar:(BOOL)animated {
6688 UIView *transition([self transitionView]);
6689 [refreshbar_ removeFromSuperview];
6691 CGRect barframe([refreshbar_ frame]);
6694 [UIView beginAnimations:nil context:NULL];
6696 CGRect viewframe = [transition frame];
6697 viewframe.origin.y -= barframe.size.height;
6698 viewframe.size.height += barframe.size.height;
6699 [transition setFrame:viewframe];
6702 [UIView commitAnimations];
6704 // XXX: fix Apple's layout bug
6705 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6709 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
6710 // XXX: fix Apple's layout bug
6711 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6715 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6716 bool dropped(dropped_);
6721 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6726 // XXX: fix Apple's layout bug
6727 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6730 - (void) statusBarFrameChanged:(NSNotification *)notification {
6739 /* Cydia Navigation Controller {{{ */
6740 @interface CYNavigationController : UINavigationController {
6741 _transient Database *database_;
6742 _transient id<UINavigationControllerDelegate> delegate_;
6745 - (NSArray *) navigationURLCollection;
6746 - (id) initWithDatabase:(Database *)database;
6747 - (void) reloadData;
6752 @implementation CYNavigationController
6754 - (NSArray *) navigationURLCollection {
6755 NSMutableArray *stack([NSMutableArray array]);
6757 for (CYViewController *controller in [self viewControllers]) {
6758 NSString *url = [[controller navigationURL] absoluteString];
6760 [stack addObject:url];
6766 - (void) reloadData {
6767 for (CYViewController *page in [self viewControllers]) {
6768 // Only reload controllers that have already loaded.
6769 // This prevents a page from accidentally loading too
6770 // early if it hasn't been shown on the screen yet.
6771 if ([page hasLoaded])
6776 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
6777 delegate_ = delegate;
6780 - (id) initWithDatabase:(Database *)database {
6781 if ((self = [super init]) != nil) {
6782 database_ = database;
6789 /* Cydia:// Protocol {{{ */
6790 @interface CydiaURLProtocol : NSURLProtocol {
6795 @implementation CydiaURLProtocol
6797 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6798 NSURL *url([request URL]);
6801 NSString *scheme([[url scheme] lowercaseString]);
6802 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6807 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6811 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6812 id<NSURLProtocolClient> client([self client]);
6814 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6816 NSData *data(UIImagePNGRepresentation(icon));
6818 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6819 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6820 [client URLProtocol:self didLoadData:data];
6821 [client URLProtocolDidFinishLoading:self];
6825 - (void) startLoading {
6826 id<NSURLProtocolClient> client([self client]);
6827 NSURLRequest *request([self request]);
6829 NSURL *url([request URL]);
6830 NSString *href([url absoluteString]);
6832 NSString *path([href substringFromIndex:8]);
6833 NSRange slash([path rangeOfString:@"/"]);
6836 if (slash.location == NSNotFound) {
6840 command = [path substringToIndex:slash.location];
6841 path = [path substringFromIndex:(slash.location + 1)];
6844 Database *database([Database sharedInstance]);
6846 if ([command isEqualToString:@"package-icon"]) {
6849 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6850 Package *package([database packageWithName:path]);
6853 UIImage *icon([package icon]);
6854 [self _returnPNGWithImage:icon forRequest:request];
6855 } else if ([command isEqualToString:@"source-icon"]) {
6858 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6859 NSString *source(Simplify(path));
6860 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6862 icon = [UIImage applicationImageNamed:@"unknown.png"];
6863 [self _returnPNGWithImage:icon forRequest:request];
6864 } else if ([command isEqualToString:@"uikit-image"]) {
6867 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6868 UIImage *icon(_UIImageWithName(path));
6869 [self _returnPNGWithImage:icon forRequest:request];
6870 } else if ([command isEqualToString:@"section-icon"]) {
6873 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6874 NSString *section(Simplify(path));
6875 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6877 icon = [UIImage applicationImageNamed:@"unknown.png"];
6878 [self _returnPNGWithImage:icon forRequest:request];
6880 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6884 - (void) stopLoading {
6890 /* Section Controller {{{ */
6891 @interface SectionController : FilteredPackageListController {
6895 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
6899 @implementation SectionController
6901 - (NSURL *) navigationURL {
6902 NSString *name = section_;
6906 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
6909 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
6912 title = UCLocalize("ALL_PACKAGES");
6913 else if (![name isEqual:@""])
6914 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6916 title = UCLocalize("NO_SECTION");
6918 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
6925 /* Sections Controller {{{ */
6926 @interface SectionsController : CYViewController <
6927 UITableViewDataSource,
6930 _transient Database *database_;
6931 NSMutableArray *sections_;
6932 NSMutableArray *filtered_;
6937 - (id) initWithDatabase:(Database *)database;
6938 - (void) editButtonClicked;
6942 @implementation SectionsController
6945 [self releaseSubviews];
6946 [sections_ release];
6947 [filtered_ release];
6952 - (NSURL *) navigationURL {
6953 return [NSURL URLWithString:@"cydia://sections"];
6956 - (void) updateNavigationItem {
6957 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6958 if ([sections_ count] == 0) {
6959 [[self navigationItem] setRightBarButtonItem:nil];
6961 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
6962 initWithBarButtonSystemItem:(editing_ ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
6964 action:@selector(editButtonClicked)
6965 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
6969 - (BOOL) isEditing {
6973 - (void) setEditing:(BOOL)editing {
6974 if ((editing_ = editing))
6977 [delegate_ updateData];
6979 [self updateNavigationItem];
6982 - (void) viewDidAppear:(BOOL)animated {
6983 [super viewDidAppear:animated];
6984 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6987 - (void) viewWillDisappear:(BOOL)animated {
6988 [super viewWillDisappear:animated];
6989 if (editing_) [self setEditing:NO];
6992 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
6993 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
6997 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6998 return editing_ ? [sections_ count] : [filtered_ count] + 1;
7001 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7005 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7006 static NSString *reuseIdentifier = @"SectionCell";
7008 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7010 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7012 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
7017 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7021 Section *section = [self sectionAtIndexPath:indexPath];
7023 SectionController *controller = [[[SectionController alloc]
7024 initWithDatabase:database_
7025 section:[section name]
7027 [controller setDelegate:delegate_];
7029 [[self navigationController] pushViewController:controller animated:YES];
7033 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7035 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
7036 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7037 [list_ setRowHeight:45.0f];
7038 [list_ setDataSource:self];
7039 [list_ setDelegate:self];
7040 [[self view] addSubview:list_];
7043 - (void) viewDidLoad {
7044 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7047 - (void) releaseSubviews {
7052 - (id) initWithDatabase:(Database *)database {
7053 if ((self = [super init]) != nil) {
7054 database_ = database;
7056 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7057 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
7061 - (void) reloadData {
7064 NSArray *packages = [database_ packages];
7066 [sections_ removeAllObjects];
7067 [filtered_ removeAllObjects];
7069 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7072 for (Package *package in packages) {
7073 NSString *name([package section]);
7074 NSString *key(name == nil ? @"" : name);
7078 _profile(SectionsView$reloadData$Section)
7079 section = [sections objectForKey:key];
7080 if (section == nil) {
7081 _profile(SectionsView$reloadData$Section$Allocate)
7082 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7083 [sections setObject:section forKey:key];
7088 [section addToCount];
7090 _profile(SectionsView$reloadData$Filter)
7091 if (![package valid] || ![package visible])
7099 [sections_ addObjectsFromArray:[sections allValues]];
7101 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7103 for (Section *section in sections_) {
7104 size_t count([section row]);
7108 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7109 [section setCount:count];
7110 [filtered_ addObject:section];
7113 [self updateNavigationItem];
7118 - (void) editButtonClicked {
7119 [self setEditing:(!editing_)];
7125 /* Changes Controller {{{ */
7126 @interface ChangesController : CYViewController <
7127 UITableViewDataSource,
7130 _transient Database *database_;
7132 CFMutableArrayRef packages_;
7133 NSMutableArray *sections_;
7136 BOOL hasSentFirstLoad_;
7139 - (id) initWithDatabase:(Database *)database;
7143 @implementation ChangesController
7146 [self releaseSubviews];
7147 CFRelease(packages_);
7148 [sections_ release];
7153 - (NSURL *) navigationURL {
7154 return [NSURL URLWithString:@"cydia://changes"];
7157 - (void) viewWillAppear:(BOOL)animated {
7158 // Loads after it appears, so don't load beforehand.
7160 [super viewWillAppear:animated];
7163 - (void) viewDidAppear:(BOOL)animated {
7164 [super viewDidAppear:animated];
7166 if (!hasSentFirstLoad_) {
7167 hasSentFirstLoad_ = YES;
7168 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
7170 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7174 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7175 NSInteger count([sections_ count]);
7176 return count == 0 ? 1 : count;
7179 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7180 if ([sections_ count] == 0)
7182 return [[sections_ objectAtIndex:section] name];
7185 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7186 if ([sections_ count] == 0)
7188 return [[sections_ objectAtIndex:section] count];
7191 - (Package *) packageAtIndex:(NSUInteger)index {
7192 return (Package *) CFArrayGetValueAtIndex(packages_, index);
7195 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7196 @synchronized (database_) {
7197 if ([database_ era] != era_)
7200 NSUInteger sectionIndex([path section]);
7201 if (sectionIndex >= [sections_ count])
7203 Section *section([sections_ objectAtIndex:sectionIndex]);
7204 NSInteger row([path row]);
7205 return [[[self packageAtIndex:([section row] + row)] retain] autorelease];
7208 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7209 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7211 cell = [[[PackageCell alloc] init] autorelease];
7212 [cell setPackage:[self packageAtIndexPath:path]];
7216 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7217 Package *package([self packageAtIndexPath:path]);
7218 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7219 [view setDelegate:delegate_];
7220 [[self navigationController] pushViewController:view animated:YES];
7224 - (void) refreshButtonClicked {
7225 [delegate_ beginUpdate];
7226 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7229 - (void) upgradeButtonClicked {
7230 [delegate_ distUpgrade];
7234 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7236 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7237 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7238 [list_ setRowHeight:73];
7239 [list_ setDataSource:self];
7240 [list_ setDelegate:self];
7241 [[self view] addSubview:list_];
7244 - (void) viewDidLoad {
7245 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7248 - (void) releaseSubviews {
7253 - (id) initWithDatabase:(Database *)database {
7254 if ((self = [super init]) != nil) {
7255 database_ = database;
7257 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7258 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7262 // this mostly works because reloadData (below) is @synchronized (database_)
7263 // XXX: that said, I've been running into problems with NSRangeExceptions :(
7264 - (void) _reloadPackages:(NSArray *)packages {
7265 CFRelease(packages_);
7266 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, [packages count], NULL);
7269 _profile(ChangesController$_reloadPackages$Filter)
7270 for (Package *package in packages)
7271 if ([package upgradableAndEssential:YES] || [package visible])
7272 CFArrayAppendValue(packages_, package);
7275 _profile(ChangesController$_reloadPackages$radixSort)
7276 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7281 - (void) reloadData {
7282 @synchronized (database_) {
7283 era_ = [database_ era];
7284 NSArray *packages = [database_ packages];
7286 [sections_ removeAllObjects];
7289 UIProgressHUD *hud([delegate_ addProgressHUD]);
7290 [hud setText:UCLocalize("LOADING")];
7291 //NSLog(@"HUD:%@::%@", delegate_, hud);
7292 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7293 [delegate_ removeProgressHUD:hud];
7295 [self _reloadPackages:packages];
7298 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7299 Section *ignored = nil;
7300 Section *section = nil;
7304 bool unseens = false;
7306 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7308 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7309 Package *package = [self packageAtIndex:offset];
7311 BOOL uae = [package upgradableAndEssential:YES];
7315 time_t seen([package seen]);
7317 if (section == nil || last != seen) {
7321 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7324 _profile(ChangesController$reloadData$Allocate)
7325 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7326 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7327 [sections_ addObject:section];
7331 [section addToCount];
7332 } else if ([package ignored]) {
7333 if (ignored == nil) {
7334 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7336 [ignored addToCount];
7339 [upgradable addToCount];
7344 CFRelease(formatter);
7347 Section *last = [sections_ lastObject];
7348 size_t count = [last count];
7349 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7350 [sections_ removeLastObject];
7353 if ([ignored count] != 0)
7354 [sections_ insertObject:ignored atIndex:0];
7356 [sections_ insertObject:upgradable atIndex:0];
7361 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7362 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7363 style:UIBarButtonItemStylePlain
7365 action:@selector(upgradeButtonClicked)
7368 if (![delegate_ updating])
7369 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7370 initWithTitle:UCLocalize("REFRESH")
7371 style:UIBarButtonItemStylePlain
7373 action:@selector(refreshButtonClicked)
7381 /* Search Controller {{{ */
7382 @interface SearchController : FilteredPackageListController <
7385 UISearchBar *search_;
7389 - (id) initWithDatabase:(Database *)database;
7390 - (void) setSearchTerm:(NSString *)term;
7391 - (void) reloadData;
7395 @implementation SearchController
7402 - (NSURL *) navigationURL {
7403 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7404 return [NSURL URLWithString:@"cydia://search"];
7406 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7409 - (void) setSearchTerm:(NSString *)searchTerm {
7410 [search_ setText:searchTerm];
7414 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7415 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7416 [search_ resignFirstResponder];
7420 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7421 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7425 - (id) initWithDatabase:(Database *)database {
7426 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil])) {
7427 search_ = [[UISearchBar alloc] init];
7431 - (void) viewDidAppear:(BOOL)animated {
7432 [super viewDidAppear:animated];
7434 if (!searchloaded_) {
7435 searchloaded_ = YES;
7436 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7437 [search_ layoutSubviews];
7438 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7440 UITextField *textField;
7441 if ([search_ respondsToSelector:@selector(searchField)])
7442 textField = [search_ searchField];
7444 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7446 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7447 [search_ setDelegate:self];
7448 [textField setEnablesReturnKeyAutomatically:NO];
7449 [[self navigationItem] setTitleView:textField];
7453 - (void) reloadData {
7454 [self setObject:[search_ text]];
7459 - (void) didSelectPackage:(Package *)package {
7460 [search_ resignFirstResponder];
7461 [super didSelectPackage:package];
7466 /* Package Settings Controller {{{ */
7467 @interface PackageSettingsController : CYViewController <
7468 UITableViewDataSource,
7471 _transient Database *database_;
7474 UITableView *table_;
7475 UISwitch *subscribedSwitch_;
7476 UISwitch *ignoredSwitch_;
7477 UITableViewCell *subscribedCell_;
7478 UITableViewCell *ignoredCell_;
7481 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7485 @implementation PackageSettingsController
7488 [self releaseSubviews];
7495 - (NSURL *) navigationURL {
7496 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", [package_ id]]];
7499 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7500 if (package_ == nil)
7503 if ([package_ installed] == nil)
7509 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7510 if (package_ == nil)
7513 // both sections contain just one item right now.
7517 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7521 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7523 return UCLocalize("SHOW_ALL_CHANGES_EX");
7525 return UCLocalize("IGNORE_UPGRADES_EX");
7528 - (void) onSubscribed:(id)control {
7529 bool value([control isOn]);
7530 if (package_ == nil)
7532 if ([package_ setSubscribed:value])
7533 [delegate_ updateData];
7536 - (void) _updateIgnored {
7537 const char *package([name_ UTF8String]);
7538 bool on([ignoredSwitch_ isOn]);
7540 pid_t pid(ExecFork());
7542 FILE *dpkg(popen("dpkg --set-selections", "w"));
7543 fwrite(package, strlen(package), 1, dpkg);
7546 fwrite(" hold\n", 6, 1, dpkg);
7548 fwrite(" install\n", 9, 1, dpkg);
7558 int result(waitpid(pid, &status, 0));
7561 _assert(result == pid);
7567 - (void) onIgnored:(id)control {
7568 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7569 [invocation setTarget:self];
7570 [invocation setSelector:@selector(_updateIgnored)];
7572 [delegate_ reloadDataWithInvocation:invocation];
7575 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7576 if (package_ == nil)
7579 switch ([indexPath section]) {
7580 case 0: return subscribedCell_;
7581 case 1: return ignoredCell_;
7590 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7592 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7593 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7594 [table_ setDataSource:self];
7595 [table_ setDelegate:self];
7596 [[self view] addSubview:table_];
7598 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7599 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7600 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7602 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7603 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7604 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7606 subscribedCell_ = [[UITableViewCell alloc] init];
7607 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7608 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7609 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7611 ignoredCell_ = [[UITableViewCell alloc] init];
7612 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7613 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7614 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7617 - (void) viewDidLoad {
7618 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7621 - (void) releaseSubviews {
7622 [ignoredCell_ release];
7625 [subscribedCell_ release];
7626 subscribedCell_ = nil;
7631 [ignoredSwitch_ release];
7632 ignoredSwitch_ = nil;
7634 [subscribedSwitch_ release];
7635 subscribedSwitch_ = nil;
7638 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7639 if ((self = [super init]) != nil) {
7640 database_ = database;
7641 name_ = [package retain];
7645 - (void) reloadData {
7648 if (package_ != nil)
7649 [package_ autorelease];
7650 package_ = [database_ packageWithName:name_];
7652 if (package_ != nil) {
7653 package_ = [package_ retain];
7654 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7655 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7656 } // XXX: what now, G?
7658 [table_ reloadData];
7664 /* Installed Controller {{{ */
7665 @interface InstalledController : FilteredPackageListController {
7669 - (id) initWithDatabase:(Database *)database;
7671 - (void) updateRoleButton;
7672 - (void) queueStatusDidChange;
7676 @implementation InstalledController
7682 - (NSURL *) navigationURL {
7683 return [NSURL URLWithString:@"cydia://installed"];
7686 - (id) initWithDatabase:(Database *)database {
7687 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7688 [self updateRoleButton];
7689 [self queueStatusDidChange];
7694 - (void) queueButtonClicked {
7699 - (void) queueStatusDidChange {
7703 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7704 initWithTitle:UCLocalize("QUEUE")
7705 style:UIBarButtonItemStyleDone
7707 action:@selector(queueButtonClicked)
7710 [[self navigationItem] setLeftBarButtonItem:nil];
7716 - (void) updateRoleButton {
7717 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7718 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7719 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7720 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7722 action:@selector(roleButtonClicked)
7726 - (void) roleButtonClicked {
7727 [self setObject:[NSNumber numberWithBool:expert_]];
7731 [self updateRoleButton];
7737 /* Source Cell {{{ */
7738 @interface SourceCell : CYTableViewCell <
7746 - (void) setSource:(Source *)source;
7750 @implementation SourceCell
7752 - (void) clearSource {
7762 - (void) setSource:(Source *)source {
7766 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
7768 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
7769 icon_ = [icon_ retain];
7771 origin_ = [[source name] retain];
7772 label_ = [[source uri] retain];
7774 [content_ setNeedsDisplay];
7782 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
7783 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
7784 UIView *content([self contentView]);
7785 CGRect bounds([content bounds]);
7787 content_ = [[ContentView alloc] initWithFrame:bounds];
7788 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7789 [content_ setBackgroundColor:[UIColor whiteColor]];
7790 [content addSubview:content_];
7792 [content_ setDelegate:self];
7793 [content_ setOpaque:YES];
7797 - (NSString *) accessibilityLabel {
7801 - (void) drawContentRect:(CGRect)rect {
7802 bool highlighted(highlighted_);
7803 float width(rect.size.width);
7806 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
7813 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
7817 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
7822 /* Source Controller {{{ */
7823 @interface SourceController : FilteredPackageListController {
7824 _transient Source *source_;
7828 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7832 @implementation SourceController
7834 - (NSURL *) navigationURL {
7835 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [source_ name]]];
7838 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7839 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
7841 key_ = [[source key] retain];
7845 - (void) reloadData {
7846 source_ = [database_ sourceWithKey:key_];
7848 key_ = [[source_ key] retain];
7849 [self setObject:source_];
7850 [[self navigationItem] setTitle:[source_ label]];
7857 /* Sources Controller {{{ */
7858 @interface SourcesController : CYViewController <
7859 UITableViewDataSource,
7862 _transient Database *database_;
7864 NSMutableArray *sources_;
7868 UIProgressHUD *hud_;
7871 //NSURLConnection *installer_;
7872 NSURLConnection *trivial_;
7873 NSURLConnection *trivial_bz2_;
7874 NSURLConnection *trivial_gz_;
7875 //NSURLConnection *automatic_;
7880 - (id) initWithDatabase:(Database *)database;
7881 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
7885 @implementation SourcesController
7887 - (void) _releaseConnection:(NSURLConnection *)connection {
7888 if (connection != nil) {
7889 [connection cancel];
7890 //[connection setDelegate:nil];
7891 [connection release];
7896 [self releaseSubviews];
7902 //[self _releaseConnection:installer_];
7903 [self _releaseConnection:trivial_];
7904 [self _releaseConnection:trivial_gz_];
7905 [self _releaseConnection:trivial_bz2_];
7906 //[self _releaseConnection:automatic_];
7912 - (NSURL *) navigationURL {
7913 return [NSURL URLWithString:@"cydia://sources"];
7916 - (void) viewDidAppear:(BOOL)animated {
7917 [super viewDidAppear:animated];
7918 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7921 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7922 return offset_ == 0 ? 1 : 2;
7925 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7926 switch (section + (offset_ == 0 ? 1 : 0)) {
7927 case 0: return UCLocalize("ENTERED_BY_USER");
7928 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
7934 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7935 int count = [sources_ count];
7937 case 0: return (offset_ == 0 ? count : offset_);
7938 case 1: return count - offset_;
7944 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
7946 switch (indexPath.section) {
7947 case 0: idx = indexPath.row; break;
7948 case 1: idx = indexPath.row + offset_; break;
7952 return [sources_ objectAtIndex:idx];
7955 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7956 static NSString *cellIdentifier = @"SourceCell";
7958 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
7959 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
7960 [cell setSource:[self sourceAtIndexPath:indexPath]];
7961 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
7966 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7967 Source *source = [self sourceAtIndexPath:indexPath];
7969 SourceController *controller = [[[SourceController alloc]
7970 initWithDatabase:database_
7974 [controller setDelegate:delegate_];
7976 [[self navigationController] pushViewController:controller animated:YES];
7979 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
7980 Source *source = [self sourceAtIndexPath:indexPath];
7981 return [source record] != nil;
7984 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
7985 Source *source = [self sourceAtIndexPath:indexPath];
7986 [Sources_ removeObjectForKey:[source key]];
7987 [delegate_ syncData];
7991 [delegate_ addTrivialSource:href_];
7992 [delegate_ syncData];
7995 - (NSString *) getWarning {
7996 NSString *href(href_);
7997 NSRange colon([href rangeOfString:@"://"]);
7998 if (colon.location != NSNotFound)
7999 href = [href substringFromIndex:(colon.location + 3)];
8000 href = [href stringByAddingPercentEscapes];
8001 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8002 href = [href stringByCachingURLWithCurrentCDN];
8004 NSURL *url([NSURL URLWithString:href]);
8006 NSStringEncoding encoding;
8007 NSError *error(nil);
8009 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8010 return [warning length] == 0 ? nil : warning;
8014 - (void) _endConnection:(NSURLConnection *)connection {
8015 // XXX: the memory management in this method is horribly awkward
8017 NSURLConnection **field = NULL;
8018 if (connection == trivial_)
8020 else if (connection == trivial_bz2_)
8021 field = &trivial_bz2_;
8022 else if (connection == trivial_gz_)
8023 field = &trivial_gz_;
8024 _assert(field != NULL);
8025 [connection release];
8030 trivial_bz2_ == nil &&
8036 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
8039 UIAlertView *alert = [[[UIAlertView alloc]
8040 initWithTitle:UCLocalize("SOURCE_WARNING")
8043 cancelButtonTitle:UCLocalize("CANCEL")
8045 UCLocalize("ADD_ANYWAY"),
8049 [alert setContext:@"warning"];
8050 [alert setNumberOfRows:1];
8054 } else if (error_ != nil) {
8055 UIAlertView *alert = [[[UIAlertView alloc]
8056 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8057 message:[error_ localizedDescription]
8059 cancelButtonTitle:UCLocalize("OK")
8060 otherButtonTitles:nil
8063 [alert setContext:@"urlerror"];
8066 UIAlertView *alert = [[[UIAlertView alloc]
8067 initWithTitle:UCLocalize("NOT_REPOSITORY")
8068 message:UCLocalize("NOT_REPOSITORY_EX")
8070 cancelButtonTitle:UCLocalize("OK")
8071 otherButtonTitles:nil
8074 [alert setContext:@"trivial"];
8078 [delegate_ releaseNetworkActivityIndicator];
8080 [delegate_ removeProgressHUD:hud_];
8089 if (error_ != nil) {
8096 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8097 switch ([response statusCode]) {
8103 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8104 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8106 error_ = [error retain];
8107 [self _endConnection:connection];
8110 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8111 [self _endConnection:connection];
8114 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8115 NSMutableURLRequest *request = [NSMutableURLRequest
8116 requestWithURL:[NSURL URLWithString:href]
8117 cachePolicy:NSURLRequestUseProtocolCachePolicy
8118 timeoutInterval:120.0
8121 [request setHTTPMethod:method];
8123 if (Machine_ != NULL)
8124 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8125 if (UniqueID_ != nil)
8126 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8128 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
8130 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8133 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8134 NSString *context([alert context]);
8136 if ([context isEqualToString:@"source"]) {
8139 NSString *href = [[alert textField] text];
8141 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8143 if (![href hasSuffix:@"/"])
8144 href_ = [href stringByAppendingString:@"/"];
8147 href_ = [href_ retain];
8149 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8150 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8151 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8152 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8156 // XXX: this is stupid
8157 hud_ = [[delegate_ addProgressHUD] retain];
8158 [hud_ setText:UCLocalize("VERIFYING_URL")];
8159 [delegate_ retainNetworkActivityIndicator];
8168 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8169 } else if ([context isEqualToString:@"trivial"])
8170 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8171 else if ([context isEqualToString:@"urlerror"])
8172 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8173 else if ([context isEqualToString:@"warning"]) {
8188 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8193 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8195 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
8196 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8197 [list_ setRowHeight:56];
8198 [list_ setDataSource:self];
8199 [list_ setDelegate:self];
8200 [[self view] addSubview:list_];
8203 - (void) viewDidLoad {
8204 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8205 [self updateButtonsForEditingStatus:NO animated:NO];
8208 - (void) releaseSubviews {
8213 - (id) initWithDatabase:(Database *)database {
8214 if ((self = [super init]) != nil) {
8215 database_ = database;
8216 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
8220 - (void) reloadData {
8224 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8227 [sources_ removeAllObjects];
8228 [sources_ addObjectsFromArray:[database_ sources]];
8230 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8233 int count([sources_ count]);
8235 for (int i = 0; i != count; i++) {
8236 if ([[sources_ objectAtIndex:i] record] == nil)
8241 [list_ setEditing:NO];
8242 [self updateButtonsForEditingStatus:NO animated:NO];
8246 - (void) showAddSourcePrompt {
8247 UIAlertView *alert = [[[UIAlertView alloc]
8248 initWithTitle:UCLocalize("ENTER_APT_URL")
8251 cancelButtonTitle:UCLocalize("CANCEL")
8253 UCLocalize("ADD_SOURCE"),
8257 [alert setContext:@"source"];
8258 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
8260 [alert setNumberOfRows:1];
8261 [alert addTextFieldWithValue:@"http://" label:@""];
8263 UITextInputTraits *traits = [[alert textField] textInputTraits];
8264 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8265 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8266 [traits setKeyboardType:UIKeyboardTypeURL];
8267 // XXX: UIReturnKeyDone
8268 [traits setReturnKeyType:UIReturnKeyNext];
8273 - (void) addButtonClicked {
8274 [self showAddSourcePrompt];
8277 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8278 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8279 initWithTitle:UCLocalize("ADD")
8280 style:UIBarButtonItemStylePlain
8282 action:@selector(addButtonClicked)
8283 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8285 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8286 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8287 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8289 action:@selector(editButtonClicked)
8290 ] autorelease] animated:animated];
8292 if (IsWildcat_ && !editing)
8293 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8294 initWithTitle:UCLocalize("SETTINGS")
8295 style:UIBarButtonItemStylePlain
8297 action:@selector(settingsButtonClicked)
8301 - (void) settingsButtonClicked {
8302 [delegate_ showSettings];
8305 - (void) editButtonClicked {
8306 [list_ setEditing:![list_ isEditing] animated:YES];
8308 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8314 /* Settings Controller {{{ */
8315 @interface SettingsController : CYViewController <
8316 UITableViewDataSource,
8319 _transient Database *database_;
8320 // XXX: ok, "roledelegate_"?...
8321 _transient id roledelegate_;
8322 UITableView *table_;
8323 UISegmentedControl *segment_;
8327 - (void) showDoneButton;
8328 - (void) resizeSegmentedControl;
8332 @implementation SettingsController
8335 [self releaseSubviews];
8341 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8343 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
8344 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8345 [table_ setDelegate:self];
8346 [table_ setDataSource:self];
8347 [[self view] addSubview:table_];
8349 NSArray *items = [NSArray arrayWithObjects:
8351 UCLocalize("HACKER"),
8352 UCLocalize("DEVELOPER"),
8354 segment_ = [[UISegmentedControl alloc] initWithItems:items];
8355 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
8356 [container_ addSubview:segment_];
8359 - (void) viewDidLoad {
8360 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8363 if ([Role_ isEqualToString:@"User"]) index = 0;
8364 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8365 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8367 [segment_ setSelectedSegmentIndex:index];
8368 [self showDoneButton];
8371 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8372 [self resizeSegmentedControl];
8375 - (void) releaseSubviews {
8382 [container_ release];
8386 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8387 if ((self = [super init]) != nil) {
8388 database_ = database;
8389 roledelegate_ = delegate;
8393 - (void) resizeSegmentedControl {
8394 CGFloat width = [[self view] frame].size.width;
8395 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8398 - (void) viewWillAppear:(BOOL)animated {
8399 [super viewWillAppear:animated];
8401 [self resizeSegmentedControl];
8404 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8405 [self resizeSegmentedControl];
8408 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8409 [self resizeSegmentedControl];
8413 NSString *role(nil);
8415 switch ([segment_ selectedSegmentIndex]) {
8416 case 0: role = @"User"; break;
8417 case 1: role = @"Hacker"; break;
8418 case 2: role = @"Developer"; break;
8423 if (![role isEqualToString:Role_]) {
8424 bool rolling(Role_ == nil);
8427 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8431 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8435 [roledelegate_ loadData];
8437 [roledelegate_ updateData];
8441 - (void) segmentChanged:(UISegmentedControl *)control {
8442 [self showDoneButton];
8445 - (void) saveAndClose {
8448 [[self navigationItem] setRightBarButtonItem:nil];
8449 [[self navigationController] dismissModalViewControllerAnimated:YES];
8452 - (void) doneButtonClicked {
8453 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8454 [spinner startAnimating];
8455 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8456 [[self navigationItem] setRightBarButtonItem:spinItem];
8458 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8461 - (void) showDoneButton {
8462 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8463 initWithTitle:UCLocalize("DONE")
8464 style:UIBarButtonItemStyleDone
8466 action:@selector(doneButtonClicked)
8467 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8470 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8471 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8475 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8479 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8480 return nil; // This method is required by the protocol.
8483 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8485 return UCLocalize("ROLE_EX");
8487 return [NSString stringWithFormat:
8488 @"%@: %@\n%@: %@\n%@: %@",
8489 UCLocalize("USER"), UCLocalize("USER_EX"),
8490 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8491 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8496 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8497 return section == 3 ? 44.0f : 0;
8500 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8501 return section == 3 ? container_ : nil;
8504 - (void) reloadData {
8506 [table_ reloadData];
8511 /* Stash Controller {{{ */
8512 @interface StashController : CYViewController {
8513 UIActivityIndicatorView *spinner_;
8520 @implementation StashController
8523 [self releaseSubviews];
8529 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8530 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8532 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8533 CGRect spinrect = [spinner_ frame];
8534 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8535 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8536 [spinner_ setFrame:spinrect];
8537 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8538 [[self view] addSubview:spinner_];
8539 [spinner_ startAnimating];
8542 captrect.size.width = [[self view] frame].size.width;
8543 captrect.size.height = 40.0f;
8544 captrect.origin.x = 0;
8545 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8546 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8547 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8548 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8549 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8550 [caption_ setTextColor:[UIColor whiteColor]];
8551 [caption_ setBackgroundColor:[UIColor clearColor]];
8552 [caption_ setShadowColor:[UIColor blackColor]];
8553 [caption_ setTextAlignment:UITextAlignmentCenter];
8554 [[self view] addSubview:caption_];
8557 statusrect.size.width = [[self view] frame].size.width;
8558 statusrect.size.height = 30.0f;
8559 statusrect.origin.x = 0;
8560 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8561 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8562 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8563 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8564 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8565 [status_ setTextColor:[UIColor whiteColor]];
8566 [status_ setBackgroundColor:[UIColor clearColor]];
8567 [status_ setShadowColor:[UIColor blackColor]];
8568 [status_ setTextAlignment:UITextAlignmentCenter];
8569 [[self view] addSubview:status_];
8572 - (void) releaseSubviews {
8586 @interface Cydia : UIApplication <
8587 ConfirmationControllerDelegate,
8590 UINavigationControllerDelegate,
8591 UITabBarControllerDelegate
8593 // XXX: evaluate all fields for _transient
8596 CYTabBarController *tabbar_;
8597 CYEmulatedLoadingController *emulated_;
8599 NSMutableArray *essential_;
8600 NSMutableArray *broken_;
8602 Database *database_;
8609 StashController *stash_;
8618 @implementation Cydia
8620 - (void) beginUpdate {
8621 [tabbar_ beginUpdate];
8625 return [tabbar_ updating];
8629 if ([broken_ count] != 0) {
8630 int count = [broken_ count];
8632 UIAlertView *alert = [[[UIAlertView alloc]
8633 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8634 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8636 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8638 UCLocalize("TEMPORARY_IGNORE"),
8642 [alert setContext:@"fixhalf"];
8644 } else if (!Ignored_ && [essential_ count] != 0) {
8645 int count = [essential_ count];
8647 UIAlertView *alert = [[[UIAlertView alloc]
8648 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8649 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8651 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8653 UCLocalize("UPGRADE_ESSENTIAL"),
8654 UCLocalize("COMPLETE_UPGRADE"),
8658 [alert setContext:@"upgrade"];
8663 - (void) _saveConfig {
8669 NSString *error(nil);
8671 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8673 NSError *error(nil);
8674 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8675 NSLog(@"failure to save metadata data: %@", error);
8680 NSLog(@"failure to serialize metadata: %@", error);
8685 // Navigation controller for the queuing badge.
8686 - (CYNavigationController *) queueNavigationController {
8687 NSArray *controllers = [tabbar_ viewControllers];
8688 return [controllers objectAtIndex:3];
8691 - (void) _updateData {
8694 [tabbar_ reloadData];
8696 CYNavigationController *navigation = [self queueNavigationController];
8698 id queuedelegate = nil;
8699 if ([[navigation viewControllers] count] > 0)
8700 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8702 [queuedelegate queueStatusDidChange];
8703 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8706 - (void) _refreshIfPossible:(NSDate *)update {
8707 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8709 bool recently = false;
8710 if (update != nil) {
8711 NSTimeInterval interval([update timeIntervalSinceNow]);
8712 if (interval <= 0 && interval > -(15*60))
8716 // Don't automatic refresh if:
8717 // - We already refreshed recently.
8718 // - We already auto-refreshed this launch.
8719 // - Auto-refresh is disabled.
8720 if (recently || loaded_ || ManualRefresh) {
8721 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8723 // If we are cancelling, we need to make sure it knows it's already loaded.
8727 // We are going to load, so remember that.
8731 SCNetworkReachabilityFlags flags; {
8732 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8733 SCNetworkReachabilityGetFlags(reachability, &flags);
8734 CFRelease(reachability);
8737 // XXX: this elaborate mess is what Apple is using to determine this? :(
8738 // XXX: do we care if the user has to intervene? maybe that's ok?
8740 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8741 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8742 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8743 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8744 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8745 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8749 // If we can reach the server, auto-refresh!
8751 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8756 - (void) refreshIfPossible {
8757 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
8760 - (void) _reloadDataWithInvocation:(NSInvocation *)invocation {
8761 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8762 [hud setText:UCLocalize("RELOADING_DATA")];
8764 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
8767 [self removeProgressHUD:hud];
8771 [essential_ removeAllObjects];
8772 [broken_ removeAllObjects];
8774 NSArray *packages([database_ packages]);
8775 for (Package *package in packages) {
8777 [broken_ addObject:package];
8778 if ([package upgradableAndEssential:NO]) {
8779 if ([package essential])
8780 [essential_ addObject:package];
8785 NSLog(@"changes:#%u", changes);
8787 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
8790 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8791 [changesItem setBadgeValue:badge];
8792 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8793 [self setApplicationIconBadgeNumber:changes];
8796 [changesItem setBadgeValue:nil];
8797 [changesItem setAnimatedBadge:NO];
8798 [self setApplicationIconBadgeNumber:0];
8803 [self refreshIfPossible];
8806 - (void) updateData {
8815 @synchronized (self) {
8816 [self _reloadDataWithInvocation:nil];
8820 - (void) presentModalViewController:(UIViewController *)controller {
8821 UINavigationController *navigation([[[CYNavigationController alloc] initWithRootViewController:controller] autorelease]);
8823 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8824 [((UIViewController *) emulated_ ?: tabbar_) presentModalViewController:navigation animated:YES];
8827 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
8828 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
8830 if (navigation != nil)
8831 [navigation pushViewController:progress animated:YES];
8833 [self presentModalViewController:progress];
8835 [progress invoke:invocation withTitle:title];
8839 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
8840 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
8843 - (void) repairWithInvocation:(NSInvocation *)invocation {
8845 [self invokeNewProgress:invocation forController:nil withTitle:UCLocalize("REPAIRING")];
8849 - (void) repairWithSelector:(SEL)selector {
8850 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
8856 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8857 _assert(file != NULL);
8859 for (NSString *key in [Sources_ allKeys]) {
8860 NSDictionary *source([Sources_ objectForKey:key]);
8862 fprintf(file, "%s %s %s\n",
8863 [[source objectForKey:@"Type"] UTF8String],
8864 [[source objectForKey:@"URI"] UTF8String],
8865 [[source objectForKey:@"Distribution"] UTF8String]
8871 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:UCLocalize("UPDATING_SOURCES")];
8876 - (void) addTrivialSource:(NSString *)href {
8877 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
8880 @"./", @"Distribution",
8881 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href]];
8886 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
8887 @synchronized (self) {
8888 [self _reloadDataWithInvocation:invocation];
8892 - (void) reloadData {
8893 [self reloadDataWithInvocation:nil];
8897 pkgProblemResolver *resolver = [database_ resolver];
8899 resolver->InstallProtect();
8900 if (!resolver->Resolve(true))
8905 // XXX: this is a really crappy way of doing this.
8906 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
8907 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
8908 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
8909 if ([tabbar_ updating])
8910 [tabbar_ cancelUpdate];
8912 if (![database_ prepare])
8915 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8916 [page setDelegate:self];
8917 CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]);
8918 [confirm_ setDelegate:self];
8921 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8922 [tabbar_ presentModalViewController:confirm_ animated:YES];
8928 @synchronized (self) {
8933 - (void) clearPackage:(Package *)package {
8934 @synchronized (self) {
8941 - (void) installPackages:(NSArray *)packages {
8942 @synchronized (self) {
8943 for (Package *package in packages)
8950 - (void) installPackage:(Package *)package {
8951 @synchronized (self) {
8958 - (void) removePackage:(Package *)package {
8959 @synchronized (self) {
8966 - (void) distUpgrade {
8967 @synchronized (self) {
8968 if (![database_ upgrade])
8974 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8977 [self detachNewProgressSelector:@selector(perform) toTarget:database_ forController:navigation title:UCLocalize("RUNNING")];
8982 - (void) showSettings {
8983 SettingsController *role = [[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease];
8984 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
8986 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
8987 [tabbar_ presentModalViewController:nav animated:YES];
8990 - (void) retainNetworkActivityIndicator {
8991 if (activity_++ == 0)
8992 [self setNetworkActivityIndicatorVisible:YES];
8995 - (void) releaseNetworkActivityIndicator {
8996 if (--activity_ == 0)
8997 [self setNetworkActivityIndicatorVisible:NO];
9000 - (void) cancelAndClear:(bool)clear {
9001 @synchronized (self) {
9013 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9014 NSString *context([alert context]);
9016 if ([context isEqualToString:@"conffile"]) {
9017 FILE *input = [database_ input];
9018 if (button == [alert cancelButtonIndex])
9019 fprintf(input, "N\n");
9020 else if (button == [alert firstOtherButtonIndex])
9021 fprintf(input, "Y\n");
9024 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9025 } else if ([context isEqualToString:@"fixhalf"]) {
9026 if (button == [alert cancelButtonIndex]) {
9027 @synchronized (self) {
9028 for (Package *broken in broken_) {
9031 NSString *id = [broken id];
9032 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9033 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9034 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9035 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9041 } else if (button == [alert firstOtherButtonIndex]) {
9042 [broken_ removeAllObjects];
9046 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9047 } else if ([context isEqualToString:@"upgrade"]) {
9048 if (button == [alert firstOtherButtonIndex]) {
9049 @synchronized (self) {
9050 for (Package *essential in essential_)
9051 [essential install];
9056 } else if (button == [alert firstOtherButtonIndex] + 1) {
9058 } else if (button == [alert cancelButtonIndex]) {
9062 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9066 - (void) system:(NSString *)command { _pooled
9068 system([command UTF8String]);
9072 - (void) applicationWillSuspend {
9074 [super applicationWillSuspend];
9077 - (BOOL) isSafeToSuspend {
9078 // Use external process status API internally.
9079 // This is probably a really bad idea.
9080 // XXX: what is the point of this? does this solve anything at all?
9081 uint64_t status = 0;
9083 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9084 notify_get_state(notify_token, &status);
9085 notify_cancel(notify_token);
9088 return locked_ == 0 && status == 0;
9091 - (void) applicationSuspend:(__GSEvent *)event {
9092 if ([self isSafeToSuspend])
9093 [super applicationSuspend:event];
9096 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9097 if ([self isSafeToSuspend])
9098 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9101 - (void) _setSuspended:(BOOL)value {
9102 if ([self isSafeToSuspend])
9103 [super _setSuspended:value];
9106 - (UIProgressHUD *) addProgressHUD {
9107 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
9108 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9110 [window_ setUserInteractionEnabled:NO];
9113 UIViewController *target = tabbar_;
9114 while ([target modalViewController] != nil) target = [target modalViewController];
9115 [[target view] addSubview:hud];
9121 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9123 [hud removeFromSuperview];
9124 [window_ setUserInteractionEnabled:YES];
9128 - (CYViewController *) pageForPackage:(NSString *)name {
9129 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9132 - (CYViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9133 NSString *scheme([[url scheme] lowercaseString]);
9134 if ([[url absoluteString] length] <= [scheme length] + 3)
9136 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9137 NSArray *components([path pathComponents]);
9139 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9140 return [self pageForPackage:[components objectAtIndex:1]];
9142 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9145 NSString *base([components objectAtIndex:0]);
9147 CYViewController *controller = nil;
9149 if ([base isEqualToString:@"url"]) {
9150 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9151 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9152 controller = [[[CYBrowserController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9153 } else if (!external && [components count] == 1) {
9154 if ([base isEqualToString:@"manage"]) {
9155 controller = [[[ManageController alloc] init] autorelease];
9158 if ([base isEqualToString:@"sources"]) {
9159 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9162 if ([base isEqualToString:@"home"]) {
9163 controller = [[[HomeController alloc] init] autorelease];
9166 if ([base isEqualToString:@"sections"]) {
9167 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9170 if ([base isEqualToString:@"search"]) {
9171 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9174 if ([base isEqualToString:@"changes"]) {
9175 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9178 if ([base isEqualToString:@"installed"]) {
9179 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9181 } else if ([components count] == 2) {
9182 NSString *argument = [components objectAtIndex:1];
9184 if ([base isEqualToString:@"package"]) {
9185 controller = [self pageForPackage:argument];
9188 if (!external && [base isEqualToString:@"search"]) {
9189 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9190 [(SearchController *)controller setSearchTerm:argument];
9193 if (!external && [base isEqualToString:@"sections"]) {
9194 if ([argument isEqualToString:@"all"])
9196 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9199 if (!external && [base isEqualToString:@"sources"]) {
9200 if ([argument isEqualToString:@"add"]) {
9201 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9202 [(SourcesController *)controller showAddSourcePrompt];
9204 Source *source = [database_ sourceWithKey:argument];
9205 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9209 if (!external && [base isEqualToString:@"launch"]) {
9210 [self launchApplicationWithIdentifier:argument suspended:NO];
9213 } else if (!external && [components count] == 3) {
9214 NSString *arg1 = [components objectAtIndex:1];
9215 NSString *arg2 = [components objectAtIndex:2];
9217 if ([base isEqualToString:@"package"]) {
9218 if ([arg2 isEqualToString:@"settings"]) {
9219 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9220 } else if ([arg2 isEqualToString:@"files"]) {
9221 if (Package *package = [database_ packageWithName:arg1]) {
9222 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9223 [(FileTable *)controller setPackage:package];
9229 [controller setDelegate:self];
9233 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9234 CYViewController *page([self pageForURL:url forExternal:external]);
9237 CYNavigationController *nav = [[[CYNavigationController alloc] init] autorelease];
9238 [nav setViewControllers:[NSArray arrayWithObject:page]];
9239 [tabbar_ setUnselectedViewController:nav];
9245 - (void) applicationOpenURL:(NSURL *)url {
9246 [super applicationOpenURL:url];
9248 if (!loaded_) starturl_ = [url retain];
9249 else [self openCydiaURL:url forExternal:YES];
9252 - (void) applicationWillResignActive:(UIApplication *)application {
9253 // Stop refreshing if you get a phone call or lock the device.
9254 if ([tabbar_ updating])
9255 [tabbar_ cancelUpdate];
9257 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9258 [super applicationWillResignActive:application];
9261 - (void) applicationWillTerminate:(UIApplication *)application {
9263 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9264 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9265 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9270 - (void) setConfigurationData:(NSString *)data {
9271 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9273 if (!conffile_r(data)) {
9274 lprintf("E:invalid conffile\n");
9278 NSString *ofile = conffile_r[1];
9279 //NSString *nfile = conffile_r[2];
9281 UIAlertView *alert = [[[UIAlertView alloc]
9282 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9283 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9285 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9287 UCLocalize("ACCEPT_NEW_COPY"),
9288 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9292 [alert setContext:@"conffile"];
9296 - (void) addStashController {
9298 stash_ = [[StashController alloc] init];
9299 [window_ addSubview:[stash_ view]];
9302 - (void) removeStashController {
9303 [[stash_ view] removeFromSuperview];
9309 [self setIdleTimerDisabled:YES];
9311 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9312 UpdateExternalStatus(1);
9313 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9314 UpdateExternalStatus(0);
9316 [self removeStashController];
9318 if (ExecFork() == 0) {
9319 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9320 perror("launchctl stop");
9324 - (void) setupViewControllers {
9325 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
9327 NSMutableArray *items([NSMutableArray arrayWithObjects:
9328 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9329 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9330 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9331 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9335 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9336 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9338 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9341 NSMutableArray *controllers([NSMutableArray array]);
9342 for (UITabBarItem *item in items) {
9343 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
9344 [controller setTabBarItem:item];
9345 [controllers addObject:controller];
9347 [tabbar_ setViewControllers:controllers];
9349 [tabbar_ setUpdateDelegate:self];
9352 - (void) applicationDidFinishLaunching:(id)unused {
9354 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9355 [self setApplicationSupportsShakeToEdit:NO];
9357 [NSURLCache setSharedURLCache:[[[SDURLCache alloc]
9358 initWithMemoryCapacity:524288
9359 diskCapacity:10485760
9360 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9363 [CYBrowserController _initialize];
9365 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9367 Font12_ = [[UIFont systemFontOfSize:12] retain];
9368 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
9369 Font14_ = [[UIFont systemFontOfSize:14] retain];
9370 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
9371 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
9373 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
9374 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
9376 window_ = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
9377 [window_ orderFront:self];
9378 [window_ makeKey:self];
9379 [window_ setHidden:NO];
9382 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9383 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9384 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9385 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9386 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9387 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9388 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9389 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9390 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9393 [self addStashController];
9394 // XXX: this would be much cleaner as a yieldToSelector:
9395 // that way the removeStashController could happen right here inline
9396 // we also could no longer require the useless stash_ field anymore
9397 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9401 database_ = [Database sharedInstance];
9402 [database_ setDelegate:self];
9404 [window_ setUserInteractionEnabled:NO];
9405 [self setupViewControllers];
9407 emulated_ = [[CYEmulatedLoadingController alloc] initWithDatabase:database_];
9408 [window_ addSubview:[emulated_ view]];
9410 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9417 [window_ setUserInteractionEnabled:YES];
9418 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease]];
9421 if ([emulated_ modalViewController] != nil)
9422 [emulated_ dismissModalViewControllerAnimated:YES];
9423 [window_ setUserInteractionEnabled:NO];
9429 [window_ addSubview:[tabbar_ view]];
9431 [[emulated_ view] removeFromSuperview];
9432 [emulated_ release];
9435 [window_ setUserInteractionEnabled:YES];
9437 int selectedIndex = 0;
9438 NSMutableArray *items = nil;
9440 bool recently = false;
9441 NSDate *closed([Metadata_ objectForKey:@"LastClosed"]);
9442 if (closed != nil) {
9443 NSTimeInterval interval([closed timeIntervalSinceNow]);
9444 // XXX: Is 15 minutes the optimal time here?
9445 if (interval <= 0 && interval > -(15*60))
9449 items = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9450 selectedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9453 for (NSArray *entry in items)
9454 if ([entry count] <= 0)
9457 if (!recently || !items || !enough) {
9459 items = [NSMutableArray array];
9460 [items addObject:[NSArray arrayWithObject:@"cydia://home"]];
9461 [items addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9462 [items addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9464 [items addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9466 [items addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9467 [items addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9469 [items addObject:[NSArray arrayWithObject:@"cydia://search"]];
9472 [tabbar_ setSelectedIndex:selectedIndex];
9473 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9474 NSArray *stack = [items objectAtIndex:tab];
9475 CYNavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9476 NSMutableArray *current = [NSMutableArray array];
9478 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9479 NSString *addr = [stack objectAtIndex:nav];
9480 NSURL *url = [NSURL URLWithString:addr];
9481 CYViewController *page = [self pageForURL:url forExternal:NO];
9483 [current addObject:page];
9486 [navigation setViewControllers:current];
9489 // (Try to) show the startup URL.
9490 if (starturl_ != nil) {
9491 [self openCydiaURL:starturl_ forExternal:NO];
9492 [starturl_ release];
9497 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9498 if (item != nil && IsWildcat_) {
9499 [sheet showFromBarButtonItem:item animated:YES];
9501 [sheet showInView:window_];
9505 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9506 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9507 [progress setTitle:task];
9508 [progress addProgressEvent:event];
9511 - (void) addProgressEventForTask:(NSArray *)data {
9512 CydiaProgressEvent *event([data objectAtIndex:0]);
9513 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9514 [self addProgressEvent:event forTask:task];
9517 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9518 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9524 id Alloc_(id self, SEL selector) {
9525 id object = alloc_(self, selector);
9526 lprintf("[%s]A-%p\n", self->isa->name, object);
9531 id Dealloc_(id self, SEL selector) {
9532 id object = dealloc_(self, selector);
9533 lprintf("[%s]D-%p\n", self->isa->name, object);
9537 Class $WebDefaultUIKitDelegate;
9539 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9540 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9541 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9542 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9545 static NSNumber *shouldPlayKeyboardSounds;
9549 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
9551 case 1104: // Keyboard Button Clicked
9552 case 1105: // Keyboard Delete Repeated
9553 if (shouldPlayKeyboardSounds == nil) {
9554 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
9555 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
9558 if (![shouldPlayKeyboardSounds boolValue])
9562 _UIHardware$_playSystemSound$(self, _cmd, sound);
9566 Class $UIApplication;
9568 MSHook(void, UIApplication$_updateApplicationAccessibility, UIApplication *self, SEL _cmd) {
9569 static BOOL initialized = NO;
9570 static BOOL started = NO;
9572 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.Accessibility.plist"] autorelease]);
9573 BOOL enabled = [[dict objectForKey:@"VoiceOverTouchEnabled"] boolValue] || [[dict objectForKey:@"VoiceOverTouchEnabledByiTunes"] boolValue];
9575 if ([self respondsToSelector:@selector(_accessibilityBundlePrincipalClass)]) {
9576 id bundle = [self performSelector:@selector(_accessibilityBundlePrincipalClass)];
9577 if (![bundle respondsToSelector:@selector(_accessibilityStopServer)]) return;
9578 if (![bundle respondsToSelector:@selector(_accessibilityStartServer)]) return;
9580 if (initialized && !enabled) {
9582 [bundle performSelector:@selector(_accessibilityStopServer)];
9583 } else if (enabled) {
9587 [bundle performSelector:@selector(_accessibilityStartServer)];
9593 int main(int argc, char *argv[]) { _pooled
9596 UpdateExternalStatus(0);
9598 if (Class $UIDevice = objc_getClass("UIDevice")) {
9599 UIDevice *device([$UIDevice currentDevice]);
9600 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
9604 UIScreen *screen([UIScreen mainScreen]);
9605 if ([screen respondsToSelector:@selector(scale)])
9606 ScreenScale_ = [screen scale];
9610 NSMutableArray *parts([NSMutableArray arrayWithCapacity:2]);
9611 if (ScreenScale_ > 1)
9612 [parts addObject:@"@2x"];
9613 [parts addObject:(IsWildcat_ ? @"~ipad" : @"~iphone")];
9614 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios%@", [parts componentsJoinedByString:@""]]);
9616 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9618 /* Library Hacks {{{ */
9619 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
9621 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
9622 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
9623 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
9624 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
9625 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
9628 $UIHardware = objc_getClass("UIHardware");
9629 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
9630 if (UIHardware$_playSystemSound$ != NULL) {
9631 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
9632 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
9635 $UIApplication = objc_getClass("UIApplication");
9636 Method UIApplication$_updateApplicationAccessibility(class_getInstanceMethod($UIApplication, @selector(_updateApplicationAccessibility)));
9637 if (UIApplication$_updateApplicationAccessibility != NULL) {
9638 _UIApplication$_updateApplicationAccessibility = reinterpret_cast<void (*)(UIApplication *, SEL)>(method_getImplementation(UIApplication$_updateApplicationAccessibility));
9639 method_setImplementation(UIApplication$_updateApplicationAccessibility, reinterpret_cast<IMP>(&$UIApplication$_updateApplicationAccessibility));
9642 /* Set Locale {{{ */
9643 Locale_ = CFLocaleCopyCurrent();
9644 Languages_ = [NSLocale preferredLanguages];
9645 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
9646 //NSLog(@"%@", [Languages_ description]);
9649 if (Languages_ == nil || [Languages_ count] == 0)
9650 // XXX: consider just setting to C and then falling through?
9653 lang = [[Languages_ objectAtIndex:0] UTF8String];
9654 setenv("LANG", lang, true);
9657 //std::setlocale(LC_ALL, lang);
9658 NSLog(@"Setting Language: %s", lang);
9661 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
9663 /* Parse Arguments {{{ */
9664 bool substrate(false);
9670 for (int argi(1); argi != argc; ++argi)
9671 if (strcmp(argv[argi], "--") == 0) {
9673 argv[argi] = argv[0];
9679 for (int argi(1); argi != arge; ++argi)
9680 if (strcmp(args[argi], "--substrate") == 0)
9683 fprintf(stderr, "unknown argument: %s\n", args[argi]);
9687 App_ = [[NSBundle mainBundle] bundlePath];
9688 Home_ = NSHomeDirectory();
9694 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
9695 alloc_ = alloc->method_imp;
9696 alloc->method_imp = (IMP) &Alloc_;*/
9698 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
9699 dealloc_ = dealloc->method_imp;
9700 dealloc->method_imp = (IMP) &Dealloc_;*/
9702 /* System Information {{{ */
9706 size = sizeof(maxproc);
9707 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9708 perror("sysctlbyname(\"kern.maxproc\", ?)");
9709 else if (maxproc < 64) {
9711 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9712 perror("sysctlbyname(\"kern.maxproc\", #)");
9715 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
9716 char *osversion = new char[size];
9717 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
9718 perror("sysctlbyname(\"kern.osversion\", ?)");
9720 System_ = [NSString stringWithUTF8String:osversion];
9722 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
9723 char *machine = new char[size];
9724 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
9725 perror("sysctlbyname(\"hw.machine\", ?)");
9729 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
9730 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
9731 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
9732 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
9736 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
9737 NSData *data((NSData *) ecid);
9738 size_t length([data length]);
9739 uint8_t bytes[length];
9740 [data getBytes:bytes];
9741 char string[length * 2 + 1];
9742 for (size_t i(0); i != length; ++i)
9743 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
9744 ChipID_ = [NSString stringWithUTF8String:string];
9748 IOObjectRelease(service);
9752 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
9754 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
9755 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9756 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
9758 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
9759 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9760 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
9762 if (mcc != NULL && mnc != NULL)
9763 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9770 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9771 Build_ = [system objectForKey:@"ProductBuildVersion"];
9772 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9773 Product_ = [info objectForKey:@"SafariProductVersion"];
9774 Safari_ = [info objectForKey:@"CFBundleVersion"];
9777 /* Load Database {{{ */
9779 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9781 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9783 if (Metadata_ == NULL)
9784 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9786 Settings_ = [Metadata_ objectForKey:@"Settings"];
9788 Packages_ = [Metadata_ objectForKey:@"Packages"];
9789 Sections_ = [Metadata_ objectForKey:@"Sections"];
9790 Sources_ = [Metadata_ objectForKey:@"Sources"];
9792 Token_ = [Metadata_ objectForKey:@"Token"];
9795 if (Settings_ != nil)
9796 Role_ = [Settings_ objectForKey:@"Role"];
9798 if (Sections_ == nil) {
9799 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9800 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9803 if (Sources_ == nil) {
9804 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9805 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9810 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
9813 if (Packages_ != nil) {
9815 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
9819 [Metadata_ removeObjectForKey:@"Packages"];
9825 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9827 #define MobileSubstrate_(name) \
9828 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) \
9829 dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL);
9831 MobileSubstrate_(Activator)
9832 MobileSubstrate_(libstatusbar)
9833 MobileSubstrate_(SimulatedKeyEvents)
9834 MobileSubstrate_(WinterBoard)
9836 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9837 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9839 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9841 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9842 unlink("/tmp/.cydia.fw");
9844 } else if (access("/User", F_OK) != 0 || version < 2) {
9847 system("/usr/libexec/cydia/firmware.sh");
9851 _assert([[NSFileManager defaultManager]
9852 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9853 withIntermediateDirectories:YES
9858 if (access("/tmp/cydia.chk", F_OK) == 0) {
9859 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9860 _assert(errno == ENOENT);
9861 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9862 _assert(errno == ENOENT);
9865 /* APT Initialization {{{ */
9866 _assert(pkgInitConfig(*_config));
9867 _assert(pkgInitSystem(*_config, _system));
9870 _config->Set("APT::Acquire::Translation", lang);
9872 // XXX: this timeout might be important :(
9873 //_config->Set("Acquire::http::Timeout", 15);
9875 _config->Set("Acquire::http::MaxParallel", 3);
9877 /* Color Choices {{{ */
9878 space_ = CGColorSpaceCreateDeviceRGB();
9880 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9881 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9882 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9883 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9884 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9885 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9886 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9887 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9888 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9890 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9891 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9893 /* UIKit Configuration {{{ */
9894 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9895 if ($GSFontSetUseLegacyFontMetrics != NULL)
9896 $GSFontSetUseLegacyFontMetrics(YES);
9898 // XXX: I have a feeling this was important
9899 //UIKeyboardDisableAutomaticAppearance();
9902 Colon_ = UCLocalize("COLON_DELIMITED");
9903 Elision_ = UCLocalize("ELISION");
9904 Error_ = UCLocalize("ERROR");
9905 Warning_ = UCLocalize("WARNING");
9908 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9910 CGColorSpaceRelease(space_);