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 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1370 if ((self = [super init]) != nil) {
1376 - (NSString *) message {
1380 - (NSString *) type {
1384 - (NSString *) package {
1388 - (NSString *) uri {
1392 - (void) setPackage:(NSString *)package {
1396 - (NSString *) compound:(NSString *)value {
1398 NSString *mode(nil); {
1399 NSString *type([self type]);
1400 if ([type isEqualToString:@"ERROR"])
1401 mode = UCLocalize("ERROR");
1402 else if ([type isEqualToString:@"WARNING"])
1403 mode = UCLocalize("WARNING");
1407 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1413 - (NSString *) compoundMessage {
1414 return [self compound:[self message]];
1417 - (NSString *) compoundTitle {
1420 if (package_ != nil) {
1421 if (Package *package = [[Database sharedInstance] packageWithName:package_])
1422 title = [package name];
1429 return [self compound:title];
1435 // Cytore Definitions {{{
1436 struct PackageValue :
1439 Cytore::Offset<PackageValue> next_;
1441 uint32_t index_ : 23;
1442 uint32_t subscribed_ : 1;
1459 Cytore::Offset<PackageValue> packages_[1 << 16];
1462 static Cytore::File<MetaValue> MetaFile_;
1464 // Cytore Helper Functions {{{
1465 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1466 SplitHash nhash = { hashlittle(name, length) };
1468 PackageValue *metadata;
1470 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1471 offset: if (offset->IsNull()) {
1472 *offset = MetaFile_.New<PackageValue>(length + 1);
1473 metadata = &MetaFile_.Get(*offset);
1475 if (metadata == NULL) {
1479 metadata = new PackageValue();
1480 memset(metadata, 0, sizeof(*metadata));
1483 memcpy(metadata->name_, name, length + 1);
1484 metadata->nhash_ = nhash.u16[1];
1486 metadata = &MetaFile_.Get(*offset);
1488 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1489 offset = &metadata->next_;
1497 static void PackageImport(const void *key, const void *value, void *context) {
1498 bool &fail(*reinterpret_cast<bool *>(context));
1501 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1502 NSLog(@"failed to import package %@", key);
1506 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1507 NSDictionary *package((NSDictionary *) value);
1509 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1510 if ([subscribed boolValue] && !metadata->subscribed_)
1511 metadata->subscribed_ = true;
1513 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1514 time_t time([date timeIntervalSince1970]);
1515 if (metadata->first_ > time || metadata->first_ == 0)
1516 metadata->first_ = time;
1519 NSDate *date([package objectForKey:@"LastSeen"]);
1520 NSString *version([package objectForKey:@"LastVersion"]);
1522 if (date != nil && version != nil) {
1523 time_t time([date timeIntervalSince1970]);
1524 if (metadata->last_ < time || metadata->last_ == 0)
1525 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1526 size_t length(strlen(buffer));
1527 uint16_t vhash(hashlittle(buffer, length));
1529 size_t capped(std::min<size_t>(8, length));
1530 char *latest(buffer + length - capped);
1532 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1533 metadata->vhash_ = vhash;
1535 metadata->last_ = time;
1541 /* Source Class {{{ */
1542 @interface Source : NSObject {
1543 CYString depiction_;
1544 CYString description_;
1550 CYString distribution_;
1555 NSString *authority_;
1557 CYString defaultIcon_;
1559 NSDictionary *record_;
1563 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1565 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1567 - (NSString *) depictionForPackage:(NSString *)package;
1568 - (NSString *) supportForPackage:(NSString *)package;
1570 - (NSDictionary *) record;
1574 - (NSString *) distribution;
1575 - (NSString *) type;
1577 - (NSString *) host;
1579 - (NSString *) name;
1580 - (NSString *) description;
1581 - (NSString *) label;
1582 - (NSString *) origin;
1583 - (NSString *) version;
1585 - (NSString *) defaultIcon;
1589 @implementation Source
1593 distribution_.clear();
1596 description_.clear();
1602 defaultIcon_.clear();
1604 if (record_ != nil) {
1614 if (authority_ != nil) {
1615 [authority_ release];
1621 // XXX: this is a very inefficient way to call these deconstructors
1626 + (NSArray *) _attributeKeys {
1627 return [NSArray arrayWithObjects:
1642 - (NSArray *) attributeKeys {
1643 return [[self class] _attributeKeys];
1646 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1647 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1650 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1653 trusted_ = index->IsTrusted();
1655 uri_.set(pool, index->GetURI());
1656 distribution_.set(pool, index->GetDist());
1657 type_.set(pool, index->GetType());
1659 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1660 if (dindex != NULL) {
1662 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1665 pkgTagFile tags(&fd);
1667 pkgTagSection section;
1674 {"default-icon", &defaultIcon_},
1675 {"depiction", &depiction_},
1676 {"description", &description_},
1678 {"origin", &origin_},
1679 {"support", &support_},
1680 {"version", &version_},
1683 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1684 const char *start, *end;
1686 if (section.Find(names[i].name_, start, end)) {
1687 CYString &value(*names[i].value_);
1688 value.set(pool, start, end - start);
1694 record_ = [Sources_ objectForKey:[self key]];
1696 record_ = [record_ retain];
1698 NSURL *url([NSURL URLWithString:uri_]);
1702 host_ = [[host_ lowercaseString] retain];
1707 authority_ = [url path];
1709 if (authority_ != nil)
1710 authority_ = [authority_ retain];
1713 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1714 if ((self = [super init]) != nil) {
1715 [self setMetaIndex:index inPool:pool];
1719 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1720 NSDictionary *lhr = [self record];
1721 NSDictionary *rhr = [source record];
1724 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1726 NSString *lhs = [self name];
1727 NSString *rhs = [source name];
1729 if ([lhs length] != 0 && [rhs length] != 0) {
1730 unichar lhc = [lhs characterAtIndex:0];
1731 unichar rhc = [rhs characterAtIndex:0];
1733 if (isalpha(lhc) && !isalpha(rhc))
1734 return NSOrderedAscending;
1735 else if (!isalpha(lhc) && isalpha(rhc))
1736 return NSOrderedDescending;
1739 return [lhs compare:rhs options:LaxCompareOptions_];
1742 - (NSString *) depictionForPackage:(NSString *)package {
1743 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1746 - (NSString *) supportForPackage:(NSString *)package {
1747 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1750 - (NSDictionary *) record {
1758 - (NSString *) uri {
1762 - (NSString *) distribution {
1763 return distribution_;
1766 - (NSString *) type {
1770 - (NSString *) key {
1771 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1774 - (NSString *) host {
1778 - (NSString *) name {
1779 return origin_.empty() ? authority_ : origin_;
1782 - (NSString *) description {
1783 return description_;
1786 - (NSString *) label {
1787 return label_.empty() ? authority_ : label_;
1790 - (NSString *) origin {
1794 - (NSString *) version {
1798 - (NSString *) defaultIcon {
1799 return defaultIcon_;
1804 /* CydiaOperation Class {{{ */
1805 @interface CydiaOperation : NSObject {
1806 NSString *operator_;
1810 - (NSString *) operator;
1811 - (NSString *) value;
1815 @implementation CydiaOperation
1818 [operator_ release];
1823 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1824 if ((self = [super init]) != nil) {
1825 operator_ = [[NSString alloc] initWithUTF8String:_operator];
1826 value_ = [[NSString alloc] initWithUTF8String:value];
1830 + (NSArray *) _attributeKeys {
1831 return [NSArray arrayWithObjects:
1837 - (NSArray *) attributeKeys {
1838 return [[self class] _attributeKeys];
1841 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1842 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1845 - (NSString *) operator {
1849 - (NSString *) value {
1855 /* CydiaClause Class {{{ */
1856 @interface CydiaClause : NSObject {
1858 CydiaOperation *version_;
1861 - (NSString *) package;
1862 - (CydiaOperation *) version;
1866 @implementation CydiaClause
1874 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1875 if ((self = [super init]) != nil) {
1876 package_ = [[NSString alloc] initWithUTF8String:dep.TargetPkg().Name()];
1878 if (const char *version = dep.TargetVer())
1879 version_ = [[CydiaOperation alloc] initWithOperator:dep.CompType() value:version];
1881 version_ = [[NSNull null] retain];
1885 + (NSArray *) _attributeKeys {
1886 return [NSArray arrayWithObjects:
1892 - (NSArray *) attributeKeys {
1893 return [[self class] _attributeKeys];
1896 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1897 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1900 - (NSString *) package {
1904 - (CydiaOperation *) version {
1910 /* CydiaRelation Class {{{ */
1911 @interface CydiaRelation : NSObject {
1912 NSString *relationship_;
1913 NSMutableArray *clauses_;
1916 - (NSString *) relationship;
1917 - (NSArray *) clauses;
1921 @implementation CydiaRelation
1924 [relationship_ release];
1929 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1930 if ((self = [super init]) != nil) {
1931 relationship_ = [[NSString alloc] initWithUTF8String:dep.DepType()];
1932 clauses_ = [[NSMutableArray alloc] initWithCapacity:8];
1934 pkgCache::DepIterator start;
1935 pkgCache::DepIterator end;
1936 dep.GlobOr(start, end); // ++dep
1939 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1941 // yes, seriously. (wtf?)
1949 + (NSArray *) _attributeKeys {
1950 return [NSArray arrayWithObjects:
1956 - (NSArray *) attributeKeys {
1957 return [[self class] _attributeKeys];
1960 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1961 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1964 - (NSString *) relationship {
1965 return relationship_;
1968 - (NSArray *) clauses {
1972 - (void) addClause:(CydiaClause *)clause {
1973 [clauses_ addObject:clause];
1978 /* Package Class {{{ */
1979 struct ParsedPackage {
1984 CYString depiction_;
1994 @interface Package : NSObject {
1997 uint32_t essential_ : 1;
1998 uint32_t obsolete_ : 1;
1999 uint32_t ignored_ : 1;
2003 _transient Database *database_;
2005 pkgCache::VerIterator version_;
2006 pkgCache::PkgIterator iterator_;
2007 pkgCache::VerFileIterator file_;
2013 CYString installed_;
2015 const char *section_;
2016 _transient NSString *section$_;
2020 PackageValue *metadata_;
2021 ParsedPackage *parsed_;
2023 NSMutableArray *tags_;
2026 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
2027 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
2029 - (pkgCache::PkgIterator) iterator;
2032 - (NSString *) section;
2033 - (NSString *) simpleSection;
2035 - (NSString *) longSection;
2036 - (NSString *) shortSection;
2040 - (Address *) maintainer;
2042 - (NSString *) longDescription;
2043 - (NSString *) shortDescription;
2046 - (PackageValue *) metadata;
2049 - (bool) subscribed;
2050 - (bool) setSubscribed:(bool)subscribed;
2054 - (NSString *) latest;
2055 - (NSString *) installed;
2056 - (BOOL) uninstalled;
2059 - (BOOL) upgradableAndEssential:(BOOL)essential;
2062 - (BOOL) unfiltered;
2066 - (BOOL) halfConfigured;
2067 - (BOOL) halfInstalled;
2069 - (NSString *) mode;
2072 - (NSString *) name;
2074 - (NSString *) homepage;
2075 - (NSString *) depiction;
2076 - (Address *) author;
2078 - (NSString *) support;
2080 - (NSArray *) files;
2081 - (NSArray *) warnings;
2082 - (NSArray *) applications;
2084 - (Source *) source;
2086 - (BOOL) matches:(NSString *)text;
2088 - (bool) hasSupportingRole;
2089 - (BOOL) hasTag:(NSString *)tag;
2090 - (NSString *) primaryPurpose;
2091 - (NSArray *) purposes;
2092 - (bool) isCommercial;
2094 - (void) setIndex:(size_t)index;
2096 - (CYString &) cyname;
2098 - (uint32_t) compareBySection:(NSArray *)sections;
2103 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
2104 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
2105 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
2106 - (bool) isVisibleInSection:(NSString *)section;
2107 - (bool) isVisibleInSource:(Source *)source;
2111 uint32_t PackageChangesRadix(Package *self, void *) {
2116 uint32_t timestamp : 30;
2117 uint32_t ignored : 1;
2118 uint32_t upgradable : 1;
2122 bool upgradable([self upgradableAndEssential:YES]);
2123 value.bits.upgradable = upgradable ? 1 : 0;
2126 value.bits.timestamp = 0;
2127 value.bits.ignored = [self ignored] ? 0 : 1;
2128 value.bits.upgradable = 1;
2130 value.bits.timestamp = [self seen] >> 2;
2131 value.bits.ignored = 0;
2132 value.bits.upgradable = 0;
2135 return _not(uint32_t) - value.key;
2138 uint32_t PackagePrefixRadix(Package *self, void *context) {
2139 size_t offset(reinterpret_cast<size_t>(context));
2140 CYString &name([self cyname]);
2142 size_t size(name.size());
2145 char *text(name.data());
2148 if (!isdigit(text[0]))
2152 while (size != digits && isdigit(text[digits]))
2160 if (offset == 0 && zeros != 0) {
2161 memset(data, '0', zeros);
2162 memcpy(data + zeros, text, 4 - zeros);
2164 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2165 if (size <= offset - zeros)
2168 text += offset - zeros;
2169 size -= offset - zeros;
2172 memcpy(data, text, 4);
2174 memcpy(data, text, size);
2175 memset(data + size, 0, 4 - size);
2178 for (size_t i(0); i != 4; ++i)
2179 if (isalpha(data[i]))
2187 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2189 /* XXX: ntohl may be more honest */
2190 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2193 CYString &(*PackageName)(Package *self, SEL sel);
2195 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2196 _profile(PackageNameCompare)
2197 CYString &lhi(PackageName(lhs, @selector(cyname)));
2198 CYString &rhi(PackageName(rhs, @selector(cyname)));
2199 CFStringRef lhn(lhi), rhn(rhi);
2202 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2203 else if (rhn == NULL)
2204 return NSOrderedDescending;
2206 _profile(PackageNameCompare$NumbersLast)
2207 if (!lhi.empty() && !rhi.empty()) {
2208 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2209 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2210 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2211 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2212 return lha ? NSOrderedAscending : NSOrderedDescending;
2216 CFIndex length = CFStringGetLength(lhn);
2218 _profile(PackageNameCompare$Compare)
2219 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2224 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2225 return PackageNameCompare(*lhs, *rhs, context);
2228 struct PackageNameOrdering :
2229 std::binary_function<Package *, Package *, bool>
2231 _finline bool operator ()(Package *lhs, Package *rhs) const {
2232 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2236 @implementation Package
2238 - (NSString *) description {
2239 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2243 if (parsed_ != NULL)
2252 + (NSString *) webScriptNameForSelector:(SEL)selector {
2254 else if (selector == @selector(clear))
2256 else if (selector == @selector(getField:))
2258 else if (selector == @selector(hasTag:))
2260 else if (selector == @selector(install))
2262 else if (selector == @selector(remove))
2268 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2269 return [self webScriptNameForSelector:selector] == nil;
2272 + (NSArray *) _attributeKeys {
2273 return [NSArray arrayWithObjects:
2291 @"shortDescription",
2302 - (NSArray *) attributeKeys {
2303 return [[self class] _attributeKeys];
2306 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2307 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2310 - (NSArray *) relations {
2311 @synchronized (database_) {
2312 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2313 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2314 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2318 - (NSString *) getField:(NSString *)name {
2319 @synchronized (database_) {
2320 if ([database_ era] != era_ || file_.end())
2323 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2325 const char *start, *end;
2326 if (!parser.Find([name UTF8String], start, end))
2327 return (NSString *) [NSNull null];
2329 return [(NSString *) CYStringCreate(start, end - start) autorelease];
2333 if (parsed_ != NULL)
2335 @synchronized (database_) {
2336 if ([database_ era] != era_ || file_.end())
2339 ParsedPackage *parsed(new ParsedPackage);
2342 _profile(Package$parse)
2343 pkgRecords::Parser *parser;
2345 _profile(Package$parse$Lookup)
2346 parser = &[database_ records]->Lookup(file_);
2351 _profile(Package$parse$Find)
2356 {"icon", &parsed->icon_},
2357 {"depiction", &parsed->depiction_},
2358 {"homepage", &parsed->homepage_},
2359 {"website", &website},
2360 {"bugs", &parsed->bugs_},
2361 {"support", &parsed->support_},
2362 {"sponsor", &parsed->sponsor_},
2363 {"author", &parsed->author_},
2366 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2367 const char *start, *end;
2369 if (parser->Find(names[i].name_, start, end)) {
2370 CYString &value(*names[i].value_);
2371 _profile(Package$parse$Value)
2372 value.set(pool_, start, end - start);
2378 _profile(Package$parse$Tagline)
2379 const char *start, *end;
2380 if (parser->ShortDesc(start, end)) {
2381 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2384 while (stop != start && stop[-1] == '\r')
2386 parsed->tagline_.set(pool_, start, stop - start);
2390 _profile(Package$parse$Retain)
2391 if (parsed->homepage_.empty())
2392 parsed->homepage_ = website;
2393 if (parsed->homepage_ == parsed->depiction_)
2394 parsed->homepage_.clear();
2399 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2400 if ((self = [super init]) != nil) {
2401 _profile(Package$initWithVersion)
2404 database_ = database;
2405 era_ = [database era];
2409 pkgCache::PkgIterator iterator(version.ParentPkg());
2410 iterator_ = iterator;
2412 _profile(Package$initWithVersion$Version)
2413 if (!version_.end())
2414 file_ = version_.FileList();
2416 pkgCache &cache([database_ cache]);
2417 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2421 _profile(Package$initWithVersion$Cache)
2422 name_.set(NULL, iterator.Display());
2424 latest_.set(NULL, StripVersion_(version_.VerStr()));
2426 pkgCache::VerIterator current(iterator.CurrentVer());
2428 installed_.set(NULL, StripVersion_(current.VerStr()));
2431 _profile(Package$initWithVersion$Tags)
2432 pkgCache::TagIterator tag(iterator.TagList());
2434 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2436 const char *name(tag.Name());
2437 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2439 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2440 if (strcmp(name + 6, "enduser") == 0)
2442 else if (strcmp(name + 6, "hacker") == 0)
2444 else if (strcmp(name + 6, "developer") == 0)
2446 else if (strcmp(name + 6, "cydia") == 0)
2452 if (strncmp(name, "cydia::", 7) == 0) {
2453 if (strcmp(name + 7, "essential") == 0)
2455 else if (strcmp(name + 7, "obsolete") == 0)
2460 } while (!tag.end());
2464 _profile(Package$initWithVersion$Metadata)
2465 const char *mixed(iterator.Name());
2466 size_t size(strlen(mixed));
2467 char lower[size + 1];
2469 for (size_t i(0); i != size; ++i)
2470 lower[i] = mixed[i] | 0x20;
2473 PackageValue *metadata(PackageFind(lower, size));
2474 metadata_ = metadata;
2476 id_.set(NULL, metadata->name_, size);
2478 const char *latest(version_.VerStr());
2479 size_t length(strlen(latest));
2481 uint16_t vhash(hashlittle(latest, length));
2483 size_t capped(std::min<size_t>(8, length));
2484 latest = latest + length - capped;
2486 if (metadata->first_ == 0)
2487 metadata->first_ = now_;
2489 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2490 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2491 metadata->vhash_ = vhash;
2492 metadata->last_ = now_;
2493 } else if (metadata->last_ == 0)
2494 metadata->last_ = metadata->first_;
2497 _profile(Package$initWithVersion$Section)
2498 section_ = iterator.Section();
2501 _profile(Package$initWithVersion$Flags)
2502 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2503 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2508 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2509 pkgCache::VerIterator version;
2511 _profile(Package$packageWithIterator$GetCandidateVer)
2512 version = [database policy]->GetCandidateVer(iterator);
2520 _profile(Package$packageWithIterator$Allocate)
2521 package = [Package allocWithZone:zone];
2524 _profile(Package$packageWithIterator$Initialize)
2526 initWithVersion:version
2533 _profile(Package$packageWithIterator$Autorelease)
2534 package = [package autorelease];
2540 - (pkgCache::PkgIterator) iterator {
2544 - (NSString *) section {
2545 if (section$_ == nil) {
2546 if (section_ == NULL)
2549 _profile(Package$section$mappedSectionForPointer)
2550 section$_ = [database_ mappedSectionForPointer:section_];
2555 - (NSString *) simpleSection {
2556 if (NSString *section = [self section])
2557 return Simplify(section);
2562 - (NSString *) longSection {
2563 return LocalizeSection([self section]);
2566 - (NSString *) shortSection {
2567 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2570 - (NSString *) uri {
2573 pkgIndexFile *index;
2574 pkgCache::PkgFileIterator file(file_.File());
2575 if (![database_ list].FindIndex(file, index))
2577 return [NSString stringWithUTF8String:iterator_->Path];
2578 //return [NSString stringWithUTF8String:file.Site()];
2579 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2583 - (Address *) maintainer {
2584 @synchronized (database_) {
2585 if ([database_ era] != era_ || file_.end())
2588 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2589 const std::string &maintainer(parser->Maintainer());
2590 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2594 @synchronized (database_) {
2595 if ([database_ era] != era_ || version_.end())
2598 return version_->InstalledSize;
2601 - (NSString *) longDescription {
2602 @synchronized (database_) {
2603 if ([database_ era] != era_ || file_.end())
2606 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2607 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2609 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2610 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2611 if ([lines count] < 2)
2614 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2615 for (size_t i(1), e([lines count]); i != e; ++i) {
2616 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2617 [trimmed addObject:trim];
2620 return [trimmed componentsJoinedByString:@"\n"];
2623 - (NSString *) shortDescription {
2624 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2628 _profile(Package$index)
2629 CFStringRef name((CFStringRef) [self name]);
2630 if (CFStringGetLength(name) == 0)
2632 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2633 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2635 return toupper(character);
2639 - (PackageValue *) metadata {
2644 PackageValue *metadata([self metadata]);
2645 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2648 - (bool) subscribed {
2649 return [self metadata]->subscribed_;
2652 - (bool) setSubscribed:(bool)subscribed {
2653 PackageValue *metadata([self metadata]);
2654 if (metadata->subscribed_ == subscribed)
2656 metadata->subscribed_ = subscribed;
2664 - (NSString *) latest {
2668 - (NSString *) installed {
2672 - (BOOL) uninstalled {
2673 return installed_.empty();
2677 return !version_.end();
2680 - (BOOL) upgradableAndEssential:(BOOL)essential {
2681 _profile(Package$upgradableAndEssential)
2682 pkgCache::VerIterator current(iterator_.CurrentVer());
2684 return essential && essential_;
2686 return !version_.end() && version_ != current;
2690 - (BOOL) essential {
2695 return [database_ cache][iterator_].InstBroken();
2698 - (BOOL) unfiltered {
2699 _profile(Package$unfiltered$obsolete)
2700 if (_unlikely(obsolete_))
2704 _profile(Package$unfiltered$hasSupportingRole)
2705 if (_unlikely(![self hasSupportingRole]))
2713 if (![self unfiltered])
2718 _profile(Package$visible$section)
2719 section = [self section];
2722 _profile(Package$visible$isSectionVisible)
2723 if (!isSectionVisible(section))
2731 unsigned char current(iterator_->CurrentState);
2732 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2735 - (BOOL) halfConfigured {
2736 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2739 - (BOOL) halfInstalled {
2740 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2744 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2745 return state.Mode != pkgDepCache::ModeKeep;
2748 - (NSString *) mode {
2749 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2751 switch (state.Mode) {
2752 case pkgDepCache::ModeDelete:
2753 if ((state.iFlags & pkgDepCache::Purge) != 0)
2757 case pkgDepCache::ModeKeep:
2758 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2759 return @"REINSTALL";
2760 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2764 case pkgDepCache::ModeInstall:
2765 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2766 return @"REINSTALL";
2767 else*/ switch (state.Status) {
2769 return @"DOWNGRADE";
2775 return @"NEW_INSTALL";
2786 - (NSString *) name {
2787 return name_.empty() ? id_ : name_;
2790 - (UIImage *) icon {
2791 NSString *section = [self simpleSection];
2794 if (parsed_ != NULL)
2795 if (NSString *href = parsed_->icon_)
2796 if ([href hasPrefix:@"file:///"])
2797 // XXX: correct escaping
2798 icon = [UIImage imageAtPath:[href substringFromIndex:7]];
2799 if (icon == nil) if (section != nil)
2800 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2801 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2802 if ([dicon hasPrefix:@"file:///"])
2803 // XXX: correct escaping
2804 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2806 icon = [UIImage applicationImageNamed:@"unknown.png"];
2810 - (NSString *) homepage {
2811 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2814 - (NSString *) depiction {
2815 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2818 - (Address *) sponsor {
2819 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [Address addressWithString:parsed_->sponsor_];
2822 - (Address *) author {
2823 return parsed_ == NULL || parsed_->author_.empty() ? nil : [Address addressWithString:parsed_->author_];
2826 - (NSString *) support {
2827 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2830 - (NSArray *) files {
2831 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2832 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2835 fin.open([path UTF8String]);
2840 while (std::getline(fin, line))
2841 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2846 - (NSArray *) warnings {
2847 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2848 const char *name(iterator_.Name());
2850 size_t length(strlen(name));
2851 if (length < 2) invalid:
2852 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2853 else for (size_t i(0); i != length; ++i)
2855 /* XXX: technically this is not allowed */
2856 (name[i] < 'A' || name[i] > 'Z') &&
2857 (name[i] < 'a' || name[i] > 'z') &&
2858 (name[i] < '0' || name[i] > '9') &&
2859 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2862 if (strcmp(name, "cydia") != 0) {
2865 bool _private = false;
2868 bool repository = [[self section] isEqualToString:@"Repositories"];
2870 if (NSArray *files = [self files])
2871 for (NSString *file in files)
2872 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2874 else if (!user && [file isEqualToString:@"/User"])
2876 else if (!_private && [file isEqualToString:@"/private"])
2878 else if (!stash && [file isEqualToString:@"/var/stash"])
2881 /* XXX: this is not sensitive enough. only some folders are valid. */
2882 if (cydia && !repository)
2883 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2885 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2887 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2889 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2892 return [warnings count] == 0 ? nil : warnings;
2895 - (NSArray *) applications {
2896 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2898 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2900 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2901 if (NSArray *files = [self files])
2902 for (NSString *file in files)
2903 if (application_r(file)) {
2904 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2905 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2906 if ([id isEqualToString:me])
2909 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2911 display = application_r[1];
2913 NSString *bundle([file stringByDeletingLastPathComponent]);
2914 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2915 if (icon == nil || [icon length] == 0)
2917 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2919 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2920 [applications addObject:application];
2922 [application addObject:id];
2923 [application addObject:display];
2924 [application addObject:url];
2927 return [applications count] == 0 ? nil : applications;
2930 - (Source *) source {
2931 if (source_ == nil) {
2932 @synchronized (database_) {
2933 if ([database_ era] != era_ || file_.end())
2934 source_ = (Source *) [NSNull null];
2936 source_ = [([database_ getSource:file_.File()] ?: (Source *) [NSNull null]) retain];
2940 return source_ == (Source *) [NSNull null] ? nil : source_;
2943 - (BOOL) matches:(NSString *)text {
2949 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2950 if (range.location != NSNotFound)
2953 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2954 if (range.location != NSNotFound)
2959 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2960 if (range.location != NSNotFound)
2966 - (bool) hasSupportingRole {
2971 if ([Role_ isEqualToString:@"User"])
2975 if ([Role_ isEqualToString:@"Hacker"])
2979 if ([Role_ isEqualToString:@"Developer"])
2984 - (BOOL) hasTag:(NSString *)tag {
2985 return tags_ == nil ? NO : [tags_ containsObject:tag];
2988 - (NSString *) primaryPurpose {
2989 for (NSString *tag in tags_)
2990 if ([tag hasPrefix:@"purpose::"])
2991 return [tag substringFromIndex:9];
2995 - (NSArray *) purposes {
2996 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2997 for (NSString *tag in tags_)
2998 if ([tag hasPrefix:@"purpose::"])
2999 [purposes addObject:[tag substringFromIndex:9]];
3000 return [purposes count] == 0 ? nil : purposes;
3003 - (bool) isCommercial {
3004 return [self hasTag:@"cydia::commercial"];
3007 - (void) setIndex:(size_t)index {
3008 if (metadata_->index_ != index)
3009 metadata_->index_ = index;
3012 - (CYString &) cyname {
3013 return name_.empty() ? id_ : name_;
3016 - (uint32_t) compareBySection:(NSArray *)sections {
3017 NSString *section([self section]);
3018 for (size_t i(0), e([sections count]); i != e; ++i) {
3019 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3023 return _not(uint32_t);
3027 @synchronized (database_) {
3028 pkgProblemResolver *resolver = [database_ resolver];
3029 resolver->Clear(iterator_);
3031 pkgCacheFile &cache([database_ cache]);
3032 cache->SetReInstall(iterator_, false);
3033 cache->MarkKeep(iterator_, false);
3037 @synchronized (database_) {
3038 pkgProblemResolver *resolver = [database_ resolver];
3039 resolver->Clear(iterator_);
3040 resolver->Protect(iterator_);
3042 pkgCacheFile &cache([database_ cache]);
3043 cache->SetReInstall(iterator_, false);
3044 cache->MarkInstall(iterator_, false);
3046 pkgDepCache::StateCache &state((*cache)[iterator_]);
3047 if (!state.Install())
3048 cache->SetReInstall(iterator_, true);
3052 @synchronized (database_) {
3053 pkgProblemResolver *resolver = [database_ resolver];
3054 resolver->Clear(iterator_);
3055 resolver->Remove(iterator_);
3056 resolver->Protect(iterator_);
3058 pkgCacheFile &cache([database_ cache]);
3059 cache->SetReInstall(iterator_, false);
3060 cache->MarkDelete(iterator_, true);
3063 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
3064 _profile(Package$isUnfilteredAndSearchedForBy)
3067 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
3068 value &= [self unfiltered];
3071 _profile(Package$isUnfilteredAndSearchedForBy$Match)
3072 value &= [self matches:search];
3079 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
3080 if ([search length] == 0)
3083 _profile(Package$isUnfilteredAndSelectedForBy)
3086 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
3087 value &= [self unfiltered];
3090 _profile(Package$isUnfilteredAndSelectedForBy$Match)
3091 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
3098 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
3099 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
3102 - (bool) isVisibleInSection:(NSString *)name {
3103 NSString *section([self section]);
3107 section == nil && [name length] == 0 ||
3108 [name isEqualToString:section]
3109 ) && [self visible];
3112 - (bool) isVisibleInSource:(Source *)source {
3113 return [self source] == source && [self visible];
3118 /* Section Class {{{ */
3119 @interface Section : NSObject {
3124 NSString *localized_;
3127 - (NSComparisonResult) compareByLocalized:(Section *)section;
3128 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3129 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3130 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3131 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
3132 - (NSString *) name;
3139 - (void) addToCount;
3141 - (void) setCount:(size_t)count;
3142 - (NSString *) localized;
3146 @implementation Section
3150 if (localized_ != nil)
3151 [localized_ release];
3155 - (NSComparisonResult) compareByLocalized:(Section *)section {
3156 NSString *lhs(localized_);
3157 NSString *rhs([section localized]);
3159 /*if ([lhs length] != 0 && [rhs length] != 0) {
3160 unichar lhc = [lhs characterAtIndex:0];
3161 unichar rhc = [rhs characterAtIndex:0];
3163 if (isalpha(lhc) && !isalpha(rhc))
3164 return NSOrderedAscending;
3165 else if (!isalpha(lhc) && isalpha(rhc))
3166 return NSOrderedDescending;
3169 return [lhs compare:rhs options:LaxCompareOptions_];
3172 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3173 if ((self = [self initWithName:name localize:NO]) != nil) {
3174 if (localized != nil)
3175 localized_ = [localized retain];
3179 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3180 return [self initWithName:name row:0 localize:localize];
3183 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3184 if ((self = [super init]) != nil) {
3185 name_ = [name retain];
3189 localized_ = [LocalizeSection(name_) retain];
3193 /* XXX: localize the index thingees */
3194 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
3195 if ((self = [super init]) != nil) {
3196 name_ = [[NSString stringWithCharacters:&index length:1] retain];
3202 - (NSString *) name {
3222 - (void) addToCount {
3226 - (void) setCount:(size_t)count {
3230 - (NSString *) localized {
3237 static NSString *Colon_;
3238 static NSString *Elision_;
3239 static NSString *Error_;
3240 static NSString *Warning_;
3242 /* Database Implementation {{{ */
3243 @implementation Database
3245 + (Database *) sharedInstance {
3246 static Database *instance;
3247 if (instance == nil)
3248 instance = [[Database alloc] init];
3256 - (void) releasePackages {
3257 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3258 CFArrayRemoveAllValues(packages_);
3262 // XXX: actually implement this thing
3264 [sourceList_ release];
3265 [self releasePackages];
3266 apr_pool_destroy(pool_);
3267 NSRecycleZone(zone_);
3271 - (void) _readCydia:(NSNumber *)fd { _pooled
3272 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3273 std::istream is(&ib);
3276 static Pcre finish_r("^finish:([^:]*)$");
3278 while (std::getline(is, line)) {
3279 const char *data(line.c_str());
3280 size_t size = line.size();
3281 lprintf("C:%s\n", data);
3283 if (finish_r(data, size)) {
3284 NSString *finish = finish_r[1];
3285 int index = [Finishes_ indexOfObject:finish];
3286 if (index != INT_MAX && index > Finish_)
3294 - (void) _readStatus:(NSNumber *)fd { _pooled
3295 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3296 std::istream is(&ib);
3299 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3300 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3302 while (std::getline(is, line)) {
3303 const char *data(line.c_str());
3304 size_t size(line.size());
3305 lprintf("S:%s\n", data);
3307 if (conffile_r(data, size))
3308 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3309 else if (strncmp(data, "status: ", 8) == 0) {
3310 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:@"STATUS"]);
3311 [progress_ performSelectorOnMainThread:@selector(addProgressEvent) withObject:event waitUntilDone:YES];
3312 } else if (pmstatus_r(data, size)) {
3313 std::string type([pmstatus_r[1] UTF8String]);
3314 NSString *package = pmstatus_r[2];
3316 float percent([pmstatus_r[3] floatValue]);
3317 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3319 NSString *string = pmstatus_r[4];
3321 if (type == "pmerror") {
3322 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:@"ERROR" forPackage:package]);
3323 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3324 } else if (type == "pmstatus") {
3325 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:@"STATUS" forPackage:package]);
3326 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3327 } else if (type == "pmconffile")
3328 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3330 lprintf("E:unknown pmstatus\n");
3332 lprintf("E:unknown status\n");
3338 - (void) _readOutput:(NSNumber *)fd { _pooled
3339 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3340 std::istream is(&ib);
3343 while (std::getline(is, line)) {
3344 lprintf("O:%s\n", line.c_str());
3346 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:@"INFORMATION"]);
3347 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3357 - (Package *) packageWithName:(NSString *)name {
3358 @synchronized (self) {
3359 if (static_cast<pkgDepCache *>(cache_) == NULL)
3361 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3362 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3366 if ((self = [super init]) != nil) {
3373 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3374 apr_pool_create(&pool_, NULL);
3376 size_t capacity(MetaFile_->active_);
3382 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3383 sourceList_ = [[NSMutableArray alloc] initWithCapacity:16];
3387 _assert(pipe(fds) != -1);
3390 _config->Set("APT::Keep-Fds::", cydiafd_);
3391 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3394 detachNewThreadSelector:@selector(_readCydia:)
3396 withObject:[NSNumber numberWithInt:fds[0]]
3399 _assert(pipe(fds) != -1);
3403 detachNewThreadSelector:@selector(_readStatus:)
3405 withObject:[NSNumber numberWithInt:fds[0]]
3408 _assert(pipe(fds) != -1);
3409 _assert(dup2(fds[0], 0) != -1);
3410 _assert(close(fds[0]) != -1);
3412 input_ = fdopen(fds[1], "a");
3414 _assert(pipe(fds) != -1);
3415 _assert(dup2(fds[1], 1) != -1);
3416 _assert(close(fds[1]) != -1);
3419 detachNewThreadSelector:@selector(_readOutput:)
3421 withObject:[NSNumber numberWithInt:fds[0]]
3426 - (pkgCacheFile &) cache {
3430 - (pkgDepCache::Policy *) policy {
3434 - (pkgRecords *) records {
3438 - (pkgProblemResolver *) resolver {
3442 - (pkgAcquire &) fetcher {
3446 - (pkgSourceList &) list {
3450 - (NSArray *) packages {
3451 return (NSArray *) packages_;
3454 - (NSArray *) sources {
3458 - (Source *) sourceWithKey:(NSString *)key {
3459 for (Source *source in [self sources]) {
3460 if ([[source key] isEqualToString:key])
3465 - (bool) popErrorWithTitle:(NSString *)title {
3468 while (!_error->empty()) {
3470 bool warning(!_error->PopMessage(error));
3475 size_t size(error.size());
3476 if (size == 0 || error[size - 1] != '\n')
3478 error.resize(size - 1);
3481 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3483 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? @"WARNING" : @"ERROR")] forTask:title];
3489 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3490 return [self popErrorWithTitle:title] || !success;
3493 - (void) reloadDataWithInvocation:(NSInvocation *)invocation { CYPoolStart() {
3494 @synchronized (self) {
3497 [self releasePackages];
3500 [sourceList_ removeAllObjects];
3520 apr_pool_clear(pool_);
3522 NSRecycleZone(zone_);
3523 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3525 int chk(creat("/tmp/cydia.chk", 0644));
3529 if (invocation != nil)
3530 [invocation invoke];
3532 NSString *title(UCLocalize("DATABASE"));
3535 OpProgress progress;
3536 while (!cache_.Open(progress, true)) { pop:
3538 bool warning(!_error->PopMessage(error));
3539 lprintf("cache_.Open():[%s]\n", error.c_str());
3541 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3542 [delegate_ repairWithSelector:@selector(configure)];
3543 else if (error == "The package lists or status file could not be parsed or opened.")
3544 [delegate_ repairWithSelector:@selector(update)];
3545 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3546 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3547 // else if (error == "The list of sources could not be read.")
3549 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? @"WARNING" : @"ERROR")] forTask:title];
3559 unlink("/tmp/cydia.chk");
3561 now_ = [[NSDate date] timeIntervalSince1970];
3563 policy_ = new pkgDepCache::Policy();
3564 records_ = new pkgRecords(cache_);
3565 resolver_ = new pkgProblemResolver(cache_);
3566 fetcher_ = new pkgAcquire(&status_);
3569 list_ = new pkgSourceList();
3570 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3573 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3574 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:@"ERROR"] forTask:title];
3578 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3581 if (cache_->BrokenCount() != 0) {
3582 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3585 if (cache_->BrokenCount() != 0) {
3586 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:@"ERROR"] forTask:title];
3590 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3594 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3595 Source *object([[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease]);
3596 [sourceList_ addObject:object];
3598 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3599 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3600 // XXX: this could be more intelligent
3601 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3602 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3604 sourceMap_[cached->ID] = object;
3609 /*std::vector<Package *> packages;
3610 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3611 [packages_ release];
3616 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3617 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3618 //packages.push_back(package);
3619 CFArrayAppendValue(packages_, [package retain]);
3623 /*if (packages.empty())
3624 packages_ = [[NSArray alloc] init];
3626 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3629 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3630 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3631 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3639 /*if (!packages.empty())
3640 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3641 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3643 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3645 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3647 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3651 size_t count(CFArrayGetCount(packages_));
3652 MetaFile_->active_ = count;
3654 for (size_t index(0); index != count; ++index)
3655 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3659 } } CYPoolEnd() _trace(); }
3662 @synchronized (self) {
3664 resolver_ = new pkgProblemResolver(cache_);
3666 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3667 if (!cache_[iterator].Keep())
3668 cache_->MarkKeep(iterator, false);
3669 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3670 cache_->SetReInstall(iterator, false);
3673 - (void) configure {
3674 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3676 system([dpkg UTF8String]);
3681 // XXX: I don't remember this condition
3686 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3688 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3690 if ([self popErrorWithTitle:title])
3694 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3697 public pkgArchiveCleaner
3700 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3705 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3712 fetcher_->Shutdown();
3714 pkgRecords records(cache_);
3716 lock_ = new FileFd();
3717 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3719 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3721 if ([self popErrorWithTitle:title])
3725 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3728 manager_ = (_system->CreatePM(cache_));
3729 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3736 bool substrate(RestartSubstrate_);
3737 RestartSubstrate_ = false;
3739 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3741 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3743 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3745 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3746 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3749 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3751 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3753 [self popErrorWithTitle:title];
3757 bool failed = false;
3758 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3759 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3761 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3767 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3775 RestartSubstrate_ = true;
3778 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3780 if (_error->PendingError()) {
3785 if (result == pkgPackageManager::Failed) {
3790 if (result != pkgPackageManager::Completed) {
3795 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3797 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3799 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3800 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3803 if (![before isEqualToArray:after])
3808 NSString *title(UCLocalize("UPGRADE"));
3809 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3815 [self updateWithStatus:status_];
3818 - (void) updateWithStatus:(Status &)status {
3819 NSString *title(UCLocalize("REFRESHING_DATA"));
3822 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3826 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3827 if ([self popErrorWithTitle:title])
3830 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3831 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */
3832 /* XXX: why the hell is an empty if statement a clang error? */ (void) 0;
3834 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3838 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3839 delegate_ = delegate;
3842 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3843 progress_ = delegate;
3844 status_.setDelegate(delegate);
3847 - (NSObject<ProgressDelegate> *) progressDelegate {
3851 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3852 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3853 return i == sourceMap_.end() ? nil : i->second;
3856 - (NSString *) mappedSectionForPointer:(const char *)section {
3857 _H<NSString> *mapped;
3859 _profile(Database$mappedSectionForPointer$Cache)
3860 mapped = §ions_[section];
3863 if (*mapped == NULL) {
3864 size_t length(strlen(section));
3865 char spaced[length + 1];
3867 _profile(Database$mappedSectionForPointer$Replace)
3868 for (size_t index(0); index != length; ++index)
3869 spaced[index] = section[index] == '_' ? ' ' : section[index];
3870 spaced[length] = '\0';
3875 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3876 string = [NSString stringWithUTF8String:spaced];
3879 _profile(Database$mappedSectionForPointer$Map)
3880 string = [SectionMap_ objectForKey:string] ?: string;
3890 /* Web Scripting {{{ */
3891 @interface CydiaObject : NSObject {
3893 _transient id delegate_;
3896 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3900 @implementation CydiaObject
3903 [indirect_ release];
3907 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3908 if ((self = [super init]) != nil) {
3909 indirect_ = [indirect retain];
3913 - (void) setDelegate:(id)delegate {
3914 delegate_ = delegate;
3917 + (NSArray *) _attributeKeys {
3918 return [NSArray arrayWithObjects:
3928 - (NSArray *) attributeKeys {
3929 return [[self class] _attributeKeys];
3932 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3933 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3936 - (NSString *) device {
3937 return [[UIDevice currentDevice] uniqueIdentifier];
3940 - (NSString *) plmn {
3944 - (NSString *) ecid {
3948 - (NSString *) serial {
3949 return SerialNumber_;
3952 - (NSString *) role {
3956 - (NSString *) model {
3957 return [NSString stringWithUTF8String:Machine_];
3960 + (NSString *) webScriptNameForSelector:(SEL)selector {
3962 else if (selector == @selector(addTrivialSource:))
3963 return @"addTrivialSource";
3964 else if (selector == @selector(close))
3966 else if (selector == @selector(du:))
3968 else if (selector == @selector(stringWithFormat:arguments:))
3970 else if (selector == @selector(getAllSources))
3971 return @"getAllSourcs";
3972 else if (selector == @selector(getKernelNumber:))
3973 return @"getKernelNumber";
3974 else if (selector == @selector(getKernelString:))
3975 return @"getKernelString";
3976 else if (selector == @selector(getInstalledPackages))
3977 return @"getInstalledPackages";
3978 else if (selector == @selector(getPackageById:))
3979 return @"getPackageById";
3980 else if (selector == @selector(installPackages:))
3981 return @"installPackages";
3982 else if (selector == @selector(localizedStringForKey:value:table:))
3984 else if (selector == @selector(refreshSources))
3985 return @"refreshSources";
3986 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3987 return @"setButtonImage";
3988 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3989 return @"setButtonTitle";
3990 else if (selector == @selector(setPopupHook:))
3991 return @"setPopupHook";
3992 else if (selector == @selector(setToken:))
3994 else if (selector == @selector(setViewportWidth:))
3995 return @"setViewportWidth";
3996 else if (selector == @selector(statfs:))
3998 else if (selector == @selector(supports:))
4004 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4005 return [self webScriptNameForSelector:selector] == nil;
4008 - (BOOL) supports:(NSString *)feature {
4009 return [feature isEqualToString:@"window.open"];
4012 - (NSNumber *) getKernelNumber:(NSString *)name {
4013 const char *string([name UTF8String]);
4016 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4017 return (id) [NSNull null];
4019 if (size != sizeof(int))
4020 return (id) [NSNull null];
4023 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4024 return (id) [NSNull null];
4026 return [NSNumber numberWithInt:value];
4029 - (NSString *) getKernelString:(NSString *)name {
4030 const char *string([name UTF8String]);
4033 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4034 return (id) [NSNull null];
4036 char value[size + 1];
4037 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4038 return (id) [NSNull null];
4040 // XXX: just in case you request something ludicrous
4043 return [NSString stringWithCString:value];
4046 - (void) addTrivialSource:(NSString *)href {
4047 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4050 - (void) refreshSources {
4051 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4054 - (NSArray *) getAllSources {
4055 return [[Database sharedInstance] sources];
4058 - (NSArray *) getInstalledPackages {
4059 Database *database([Database sharedInstance]);
4060 @synchronized (database) {
4061 NSArray *packages([database packages]);
4062 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4063 for (Package *package in packages)
4064 if (![package uninstalled])
4065 [installed addObject:package];
4069 - (Package *) getPackageById:(NSString *)id {
4070 Package *package([[Database sharedInstance] packageWithName:id]);
4075 - (NSArray *) statfs:(NSString *)path {
4078 if (path == nil || statfs([path UTF8String], &stat) == -1)
4081 return [NSArray arrayWithObjects:
4082 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4083 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4084 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4088 - (NSNumber *) du:(NSString *)path {
4089 NSNumber *value(nil);
4092 _assert(pipe(fds) != -1);
4094 pid_t pid(ExecFork());
4096 _assert(dup2(fds[1], 1) != -1);
4097 _assert(close(fds[0]) != -1);
4098 _assert(close(fds[1]) != -1);
4099 /* XXX: this should probably not use du */
4100 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4105 _assert(close(fds[1]) != -1);
4107 if (FILE *du = fdopen(fds[0], "r")) {
4109 while (fgets(line, sizeof(line), du) != NULL) {
4110 size_t length(strlen(line));
4111 while (length != 0 && line[length - 1] == '\n')
4112 line[--length] = '\0';
4113 if (char *tab = strchr(line, '\t')) {
4115 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4120 } else _assert(close(fds[0]));
4124 if (waitpid(pid, &status, 0) == -1)
4127 else _assert(false);
4133 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4136 - (void) installPackages:(NSArray *)packages {
4137 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4140 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4141 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4144 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4145 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4148 - (void) _setToken:(NSString *)token {
4151 Token_ = [token retain];
4153 [Metadata_ setObject:Token_ forKey:@"Token"];
4157 - (void) setToken:(NSString *)token {
4158 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4161 - (void) setPopupHook:(id)function {
4162 [indirect_ setPopupHook:function];
4165 - (void) setViewportWidth:(float)width {
4166 [indirect_ setViewportWidthOnMainThread:width];
4169 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4170 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4171 unsigned count([arguments count]);
4173 for (unsigned i(0); i != count; ++i)
4174 values[i] = [arguments objectAtIndex:i];
4175 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4178 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4179 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4181 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4183 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4189 /* @ Loading... Indicator {{{ */
4190 @interface CYLoadingIndicator : UIView {
4191 UIActivityIndicatorView *spinner_;
4196 @property (readonly, nonatomic) UILabel *label;
4197 @property (readonly, nonatomic) UIActivityIndicatorView *activityIndicatorView;
4201 @implementation CYLoadingIndicator
4203 - (id) initWithFrame:(CGRect)frame {
4204 if ((self = [super initWithFrame:frame]) != nil) {
4205 container_ = [[[UIView alloc] init] autorelease];
4206 [container_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
4208 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
4209 [spinner_ startAnimating];
4210 [container_ addSubview:spinner_];
4212 label_ = [[[UILabel alloc] init] autorelease];
4213 [label_ setFont:[UIFont boldSystemFontOfSize:15.0f]];
4214 [label_ setBackgroundColor:[UIColor clearColor]];
4215 [label_ setTextColor:[UIColor blackColor]];
4216 [label_ setShadowColor:[UIColor whiteColor]];
4217 [label_ setShadowOffset:CGSizeMake(0, 1)];
4218 [label_ setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
4219 [container_ addSubview:label_];
4221 CGSize viewsize = frame.size;
4222 CGSize spinnersize = [spinner_ bounds].size;
4223 CGSize textsize = [[label_ text] sizeWithFont:[label_ font]];
4224 float bothwidth = spinnersize.width + textsize.width + 5.0f;
4226 CGRect containrect = {
4227 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
4228 CGSizeMake(bothwidth, spinnersize.height)
4231 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
4239 [container_ setFrame:containrect];
4240 [spinner_ setFrame:spinrect];
4241 [label_ setFrame:textrect];
4242 [self addSubview:container_];
4246 - (UILabel *) label {
4250 - (UIActivityIndicatorView *) activityIndicatorView {
4256 /* Emulated Loading Controller {{{ */
4257 @interface CYEmulatedLoadingController : CYViewController {
4258 _transient Database *database_;
4259 CYLoadingIndicator *indicator_;
4261 UINavigationBar *navbar_;
4266 @implementation CYEmulatedLoadingController
4269 [self releaseSubviews];
4273 - (id) initWithDatabase:(Database *)database {
4274 if ((self = [super init]) != nil) {
4275 database_ = database;
4280 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
4281 [[self view] setBackgroundColor:[UIColor pinStripeColor]];
4283 indicator_ = [[CYLoadingIndicator alloc] initWithFrame:[[self view] bounds]];
4284 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4285 [[self view] addSubview:indicator_];
4287 tabbar_ = [[UITabBar alloc] initWithFrame:CGRectMake(0, 0, 0, 49.0f)];
4288 [tabbar_ setFrame:CGRectMake(0.0f, [[self view] bounds].size.height - [tabbar_ bounds].size.height, [[self view] bounds].size.width, [tabbar_ bounds].size.height)];
4289 [tabbar_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth];
4290 [[self view] addSubview:tabbar_];
4292 navbar_ = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 0, 44.0f)];
4293 [navbar_ setFrame:CGRectMake(0.0f, 0.0f, [[self view] bounds].size.width, [navbar_ bounds].size.height)];
4294 [navbar_ setAutoresizingMask:UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth];
4295 [[self view] addSubview:navbar_];
4298 - (void) releaseSubviews {
4299 [indicator_ release];
4312 /* Cydia Browser Controller {{{ */
4313 @interface CYBrowserController : BrowserController {
4314 CydiaObject *cydia_;
4319 @implementation CYBrowserController
4326 - (NSURL *) navigationURL {
4327 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[[webview_ request] URL] absoluteString]]];
4330 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
4333 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4334 [super webView:view didClearWindowObject:window forFrame:frame];
4336 WebDataSource *source([frame dataSource]);
4337 NSURLResponse *response([source response]);
4339 NSURL *url([response URL]);
4340 NSString *scheme([url scheme]);
4341 NSString *host([url host]);
4343 if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
4344 NSHTTPURLResponse *http((NSHTTPURLResponse *) response);
4345 NSDictionary *headers([http allHeaderFields]);
4346 [self setHeaders:headers forHost:host];
4350 [host isEqualToString:@"cydia.saurik.com"] ||
4351 [host hasSuffix:@".cydia.saurik.com"] ||
4352 [scheme isEqualToString:@"file"]
4354 [window setValue:cydia_ forKey:@"cydia"];
4357 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
4358 if (System_ != NULL)
4359 [request setValue:System_ forHTTPHeaderField:@"X-System"];
4360 if (Machine_ != NULL)
4361 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4363 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4365 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
4368 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4369 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4370 [self _setMoreHeaders:copy];
4374 - (void) setDelegate:(id)delegate {
4375 [super setDelegate:delegate];
4376 [cydia_ setDelegate:delegate];
4380 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
4381 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
4383 WebView *webview([[webview_ _documentView] webView]);
4385 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
4387 NSString *application = package == nil ? @"Cydia" : [NSString
4388 stringWithFormat:@"Cydia/%@",
4393 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4395 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4396 if (Product_ != nil)
4397 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4399 [webview setApplicationNameForUserAgent:application];
4407 @interface NSObject (CydiaScript)
4408 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4411 @implementation NSObject (CydiaScript)
4413 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4419 @implementation NSArray (CydiaScript)
4421 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4422 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4423 for (size_t i(0), e([self count]); i != e; ++i)
4424 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4430 @implementation NSDictionary (CydiaScript)
4432 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4433 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4435 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4442 /* Confirmation Controller {{{ */
4443 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4444 if (!iterator.end())
4445 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4446 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4448 pkgCache::PkgIterator package(dep.TargetPkg());
4451 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4458 @protocol ConfirmationControllerDelegate
4459 - (void) cancelAndClear:(bool)clear;
4460 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4464 @interface ConfirmationController : CYBrowserController {
4465 _transient Database *database_;
4467 UIAlertView *essential_;
4469 NSDictionary *changes_;
4470 NSMutableArray *issues_;
4471 NSDictionary *sizes_;
4476 - (id) initWithDatabase:(Database *)database;
4480 @implementation ConfirmationController
4487 if (essential_ != nil)
4488 [essential_ release];
4495 RestartSubstrate_ = true;
4496 [delegate_ confirmWithNavigationController:[self navigationController]];
4499 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4500 NSString *context([alert context]);
4502 if ([context isEqualToString:@"remove"]) {
4503 if (button == [alert cancelButtonIndex])
4504 [self dismissModalViewControllerAnimated:YES];
4505 else if (button == [alert firstOtherButtonIndex]) {
4509 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4510 } else if ([context isEqualToString:@"unable"]) {
4511 [self dismissModalViewControllerAnimated:YES];
4512 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4514 [super alertView:alert clickedButtonAtIndex:button];
4518 - (void) _doContinue {
4519 [self dismissModalViewControllerAnimated:YES];
4520 [delegate_ cancelAndClear:NO];
4523 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4524 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4528 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4529 [super webView:view didClearWindowObject:window forFrame:frame];
4531 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4532 changes_, @"changes",
4536 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4539 - (id) initWithDatabase:(Database *)database {
4540 if ((self = [super init]) != nil) {
4541 database_ = database;
4543 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4544 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4545 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4546 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4547 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4551 pkgCacheFile &cache([database_ cache]);
4552 NSArray *packages([database_ packages]);
4553 pkgDepCache::Policy *policy([database_ policy]);
4555 issues_ = [[NSMutableArray arrayWithCapacity:4] retain];
4557 for (Package *package in packages) {
4558 pkgCache::PkgIterator iterator([package iterator]);
4559 NSString *name([package id]);
4561 if ([package broken]) {
4562 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4564 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4566 reasons, @"reasons",
4569 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4573 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4574 pkgCache::DepIterator start;
4575 pkgCache::DepIterator end;
4576 dep.GlobOr(start, end); // ++dep
4578 if (!cache->IsImportantDep(end))
4580 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4583 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4585 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4586 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4587 clauses, @"clauses",
4591 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4593 pkgCache::PkgIterator target(start.TargetPkg());
4594 if (target->ProvidesList != 0)
4595 reason = @"missing";
4597 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4599 reason = @"installed";
4600 installed = [NSString stringWithUTF8String:ver.VerStr()];
4601 } else if (!cache[target].CandidateVerIter(cache).end())
4602 reason = @"uninstalled";
4603 else if (target->ProvidesList == 0)
4604 reason = @"uninstallable";
4606 reason = @"virtual";
4609 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4610 [NSString stringWithUTF8String:start.CompType()], @"operator",
4611 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4614 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4615 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4616 version, @"version",
4618 installed, @"installed",
4621 // yes, seriously. (wtf?)
4629 pkgDepCache::StateCache &state(cache[iterator]);
4631 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4633 if (state.NewInstall())
4634 [installs addObject:name];
4635 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4636 [reinstalls addObject:name];
4637 else if (state.Upgrade())
4638 [upgrades addObject:name];
4639 else if (state.Downgrade())
4640 [downgrades addObject:name];
4641 else if (!state.Delete())
4643 else if (special_r(name))
4644 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4645 [NSNull null], @"package",
4646 [NSArray arrayWithObjects:
4647 [NSDictionary dictionaryWithObjectsAndKeys:
4648 @"Conflicts", @"relationship",
4649 [NSArray arrayWithObjects:
4650 [NSDictionary dictionaryWithObjectsAndKeys:
4652 [NSNull null], @"version",
4653 @"installed", @"reason",
4660 if ([package essential])
4662 [removes addObject:name];
4665 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4666 substrate_ |= DepSubstrate(iterator.CurrentVer());
4671 else if (Advanced_) {
4672 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4674 essential_ = [[UIAlertView alloc]
4675 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4676 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4678 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4680 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4684 [essential_ setContext:@"remove"];
4686 essential_ = [[UIAlertView alloc]
4687 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4688 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4690 cancelButtonTitle:UCLocalize("OKAY")
4691 otherButtonTitles:nil
4694 [essential_ setContext:@"unable"];
4697 changes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
4698 installs, @"installs",
4699 reinstalls, @"reinstalls",
4700 upgrades, @"upgrades",
4701 downgrades, @"downgrades",
4702 removes, @"removes",
4705 sizes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
4706 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4707 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4710 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/confirm/", UI_]]];
4712 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
4713 initWithTitle:UCLocalize("CANCEL")
4714 style:UIBarButtonItemStylePlain
4716 action:@selector(cancelButtonClicked)
4722 - (void) applyRightButton {
4723 if ([issues_ count] == 0 && ![self isLoading])
4724 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4725 initWithTitle:UCLocalize("CONFIRM")
4726 style:UIBarButtonItemStyleDone
4728 action:@selector(confirmButtonClicked)
4731 [[self navigationItem] setRightBarButtonItem:nil];
4735 - (void) cancelButtonClicked {
4736 [self dismissModalViewControllerAnimated:YES];
4737 [delegate_ cancelAndClear:YES];
4741 - (void) confirmButtonClicked {
4742 if (essential_ != nil)
4752 /* Progress Controller {{{ */
4753 @interface ProgressController : CYViewController <
4756 _transient Database *database_;
4757 UIProgressBar *progress_;
4758 UITextView *output_;
4759 UITextLabel *status_;
4760 UIPushButton *close_;
4762 SHA1SumValue springlist_;
4763 SHA1SumValue notifyconf_;
4764 _H<NSString> title_;
4767 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4769 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
4771 - (void) setTitle:(NSString *)title;
4777 @implementation ProgressController
4780 [database_ setProgressDelegate:nil];
4781 [progress_ release];
4788 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4789 if ((self = [super init]) != nil) {
4790 database_ = database;
4791 delegate_ = delegate;
4793 [database_ setProgressDelegate:self];
4795 [[self view] setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
4797 progress_ = [[UIProgressBar alloc] init];
4798 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4799 [progress_ setStyle:0];
4801 status_ = [[UITextLabel alloc] init];
4802 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4803 [status_ setColor:[UIColor whiteColor]];
4804 [status_ setBackgroundColor:[UIColor clearColor]];
4805 [status_ setCentersHorizontally:YES];
4806 //[status_ setFont:font];
4808 output_ = [[UITextView alloc] init];
4809 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4810 //[output_ setTextFont:@"Courier New"];
4811 [output_ setFont:[[output_ font] fontWithSize:12]];
4812 [output_ setTextColor:[UIColor whiteColor]];
4813 [output_ setBackgroundColor:[UIColor clearColor]];
4814 [output_ setMarginTop:0];
4815 [output_ setAllowsRubberBanding:YES];
4816 [output_ setEditable:NO];
4817 [[self view] addSubview:output_];
4819 close_ = [[UIPushButton alloc] init];
4820 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4821 [close_ setAutosizesToFit:NO];
4822 [close_ setDrawsShadow:YES];
4823 [close_ setStretchBackground:YES];
4824 [close_ setEnabled:YES];
4825 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
4826 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4827 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4828 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4832 - (void) positionViews {
4833 CGRect bounds = [[self view] bounds];
4834 CGSize prgsize = [UIProgressBar defaultSize];
4837 (bounds.size.width - prgsize.width) / 2,
4838 bounds.size.height - prgsize.height - 20
4841 float closewidth = std::min(bounds.size.width - 20, 300.0f);
4843 [progress_ setFrame:prgrect];
4844 [status_ setFrame:CGRectMake(
4846 bounds.size.height - prgsize.height - 50,
4847 bounds.size.width - 20,
4850 [output_ setFrame:CGRectMake(
4853 bounds.size.width - 20,
4854 bounds.size.height - 96
4856 [close_ setFrame:CGRectMake(
4857 (bounds.size.width - closewidth) / 2,
4858 bounds.size.height - prgsize.height - 50,
4864 - (void) viewWillAppear:(BOOL)animated {
4865 [super viewDidAppear:animated];
4866 [[self navigationItem] setHidesBackButton:YES];
4867 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4869 [self positionViews];
4872 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4873 [self positionViews];
4876 - (void) closeButtonPushed {
4879 UpdateExternalStatus(0);
4883 [self dismissModalViewControllerAnimated:YES];
4887 [delegate_ terminateWithSuccess];
4888 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4889 [delegate_ suspendWithAnimation:YES];
4891 [delegate_ suspend];*/
4903 system("/usr/bin/sbreload");
4909 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
4910 SBReboot(SBSSpringBoardServerPort());
4912 reboot2(RB_AUTOBOOT);
4917 - (void) setTitle:(NSString *)title {
4919 [[self navigationItem] setTitle:title];
4922 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
4923 UpdateExternalStatus(1);
4925 [self setTitle:title];
4927 [status_ setText:nil];
4928 [output_ setText:@""];
4929 [progress_ setProgress:0];
4931 [close_ removeFromSuperview];
4932 [[self view] addSubview:progress_];
4933 [[self view] addSubview:status_];
4935 [delegate_ retainNetworkActivityIndicator];
4940 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4943 MMap mmap(file, MMap::ReadOnly);
4945 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4946 notifyconf_ = sha1.Result();
4952 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4955 MMap mmap(file, MMap::ReadOnly);
4957 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4958 springlist_ = sha1.Result();
4962 if (invocation != nil) {
4963 [invocation yieldToSelector:@selector(invoke)];
4964 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
4967 [[self view] addSubview:close_];
4968 [progress_ removeFromSuperview];
4969 [status_ removeFromSuperview];
4973 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4976 MMap mmap(file, MMap::ReadOnly);
4978 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4979 if (!(notifyconf_ == sha1.Result()))
4986 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4989 MMap mmap(file, MMap::ReadOnly);
4991 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4992 if (!(springlist_ == sha1.Result()))
4998 if (RestartSubstrate_)
5002 RestartSubstrate_ = false;
5005 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5006 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
5007 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
5008 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5009 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
5013 system("su -c /usr/bin/uicache mobile");
5016 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
5018 [delegate_ releaseNetworkActivityIndicator];
5021 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5022 NSString *type([event type]);
5024 if ([type isEqualToString:@"ERROR"] || [type isEqualToString:@"WARNING"]) {
5025 CYAlertView *sheet([[[CYAlertView alloc]
5026 initWithTitle:[event compoundTitle]
5027 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
5028 defaultButtonIndex:0
5031 [sheet setMessage:[event message]];
5032 [sheet yieldToPopupAlertAnimated:YES];
5034 } else if ([type isEqualToString:@"INFORMATION"]) {
5035 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], [event message]]];
5036 CGSize size = [output_ contentSize];
5037 CGPoint offset = [output_ contentOffset];
5038 if (size.height - offset.y < [output_ frame].size.height + 20.f) {
5039 CGRect rect = {{0, size.height-1}, {size.width, 1}};
5040 [output_ scrollRectToVisible:rect animated:YES];
5042 } else if ([type isEqualToString:@"STATUS"]) {
5043 NSMutableArray *words([[[event message] componentsSeparatedByString:@" "] mutableCopy]);
5044 for (size_t i(0), e([words count]); i != e; ++i) {
5045 NSString *word([words objectAtIndex:i]);
5046 if (Package *package = [database_ packageWithName:word])
5047 [words replaceObjectAtIndex:i withObject:[package name]];
5050 [status_ setText:[words componentsJoinedByString:@" "]];
5051 } else _assert(false);
5054 - (bool) isProgressCancelled {
5058 - (void) setProgressPercent:(NSNumber *)percent {
5059 [progress_ setProgress:[percent floatValue]];
5062 - (BOOL) isRunning {
5069 /* Cell Content View {{{ */
5070 @protocol ContentDelegate
5071 - (void) drawContentRect:(CGRect)rect;
5074 @interface ContentView : UIView {
5075 _transient id<ContentDelegate> delegate_;
5080 @implementation ContentView
5082 - (id) initWithFrame:(CGRect)frame {
5083 if ((self = [super initWithFrame:frame]) != nil) {
5084 [self setNeedsDisplayOnBoundsChange:YES];
5088 - (void) setDelegate:(id<ContentDelegate>)delegate {
5089 delegate_ = delegate;
5092 - (void) drawRect:(CGRect)rect {
5093 [super drawRect:rect];
5094 [delegate_ drawContentRect:rect];
5099 /* Cydia TableView Cell {{{ */
5100 @interface CYTableViewCell : UITableViewCell {
5101 ContentView *content_;
5107 @implementation CYTableViewCell
5114 - (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
5115 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
5117 if (view == content_) {
5118 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
5119 highlighted_ = highlighted;
5122 [super _updateHighlightColorsForView:view highlighted:highlighted];
5125 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
5126 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
5127 highlighted_ = selected;
5129 [super setSelected:selected animated:animated];
5130 [content_ setNeedsDisplay];
5136 /* Package Cell {{{ */
5137 @interface PackageCell : CYTableViewCell <
5142 NSString *description_;
5150 - (PackageCell *) init;
5151 - (void) setPackage:(Package *)package;
5153 - (void) drawContentRect:(CGRect)rect;
5157 @implementation PackageCell
5159 - (void) clearPackage {
5170 if (description_ != nil) {
5171 [description_ release];
5175 if (source_ != nil) {
5180 if (badge_ != nil) {
5185 if (placard_ != nil) {
5195 [self clearPackage];
5199 - (PackageCell *) init {
5200 CGRect frame(CGRectMake(0, 0, 320, 74));
5201 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5202 UIView *content([self contentView]);
5203 CGRect bounds([content bounds]);
5205 content_ = [[ContentView alloc] initWithFrame:bounds];
5206 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5207 [content addSubview:content_];
5209 [content_ setDelegate:self];
5210 [content_ setOpaque:YES];
5214 - (NSString *) accessibilityLabel {
5215 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), name_, description_];
5218 - (void) setPackage:(Package *)package {
5219 [self clearPackage];
5222 Source *source = [package source];
5224 icon_ = [[package icon] retain];
5225 name_ = [[package name] retain];
5228 description_ = [package longDescription];
5229 if (description_ == nil)
5230 description_ = [package shortDescription];
5231 if (description_ != nil)
5232 description_ = [description_ retain];
5234 commercial_ = [package isCommercial];
5236 package_ = [package retain];
5238 NSString *label = nil;
5239 bool trusted = false;
5241 if (source != nil) {
5242 label = [source label];
5243 trusted = [source trusted];
5244 } else if ([[package id] isEqualToString:@"firmware"])
5245 label = UCLocalize("APPLE");
5247 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5249 NSString *from(label);
5251 NSString *section = [package simpleSection];
5252 if (section != nil && ![section isEqualToString:label]) {
5253 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5254 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5257 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
5258 source_ = [from retain];
5260 if (NSString *purpose = [package primaryPurpose])
5261 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
5262 badge_ = [badge_ retain];
5267 if (NSString *mode = [package_ mode]) {
5268 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5269 color = RemovingColor_;
5270 //placard = @"removing";
5272 color = InstallingColor_;
5273 //placard = @"installing";
5276 // XXX: the removing/installing placards are not @2x
5279 color = [UIColor whiteColor];
5281 if ([package installed] != nil)
5282 placard = @"installed";
5287 [content_ setBackgroundColor:color];
5290 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]]) != nil)
5291 placard_ = [placard_ retain];
5293 [self setNeedsDisplay];
5294 [content_ setNeedsDisplay];
5297 - (void) drawContentRect:(CGRect)rect {
5298 bool highlighted(highlighted_);
5299 float width([self bounds].size.width);
5302 CGContextRef context(UIGraphicsGetCurrentContext());
5303 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
5304 CGContextFillRect(context, rect);
5309 rect.size = [icon_ size];
5311 rect.size.width /= 2;
5312 rect.size.height /= 2;
5314 rect.origin.x = 25 - rect.size.width / 2;
5315 rect.origin.y = 25 - rect.size.height / 2;
5317 [icon_ drawInRect:rect];
5320 if (badge_ != nil) {
5322 rect.size = [badge_ size];
5324 rect.size.width /= 2;
5325 rect.size.height /= 2;
5327 rect.origin.x = 36 - rect.size.width / 2;
5328 rect.origin.y = 36 - rect.size.height / 2;
5330 [badge_ drawInRect:rect];
5337 UISetColor(commercial_ ? Purple_ : Black_);
5338 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5339 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5342 UISetColor(commercial_ ? Purplish_ : Gray_);
5343 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5345 if (placard_ != nil)
5346 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5351 /* Section Cell {{{ */
5352 @interface SectionCell : CYTableViewCell <
5364 - (void) setSection:(Section *)section editing:(BOOL)editing;
5368 @implementation SectionCell
5370 - (void) clearSection {
5371 if (basic_ != nil) {
5376 if (section_ != nil) {
5386 if (count_ != nil) {
5393 [self clearSection];
5399 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5400 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5401 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
5402 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
5403 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5405 UIView *content([self contentView]);
5406 CGRect bounds([content bounds]);
5408 content_ = [[ContentView alloc] initWithFrame:bounds];
5409 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5410 [content addSubview:content_];
5411 [content_ setBackgroundColor:[UIColor whiteColor]];
5413 [content_ setDelegate:self];
5417 - (void) onSwitch:(id)sender {
5418 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5419 if (metadata == nil) {
5420 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5421 [Sections_ setObject:metadata forKey:basic_];
5424 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5428 - (void) setSection:(Section *)section editing:(BOOL)editing {
5429 if (editing != editing_) {
5431 [switch_ removeFromSuperview];
5433 [self addSubview:switch_];
5437 [self clearSection];
5439 if (section == nil) {
5440 name_ = [UCLocalize("ALL_PACKAGES") retain];
5443 basic_ = [section name];
5445 basic_ = [basic_ retain];
5447 section_ = [section localized];
5448 if (section_ != nil)
5449 section_ = [section_ retain];
5451 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
5452 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
5455 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5458 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5459 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5461 [content_ setNeedsDisplay];
5464 - (void) setFrame:(CGRect)frame {
5465 [super setFrame:frame];
5467 CGRect rect([switch_ frame]);
5468 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5471 - (NSString *) accessibilityLabel {
5475 - (void) drawContentRect:(CGRect)rect {
5476 bool highlighted(highlighted_ && !editing_);
5478 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5483 float width(rect.size.width);
5489 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5491 CGSize size = [count_ sizeWithFont:Font14_];
5495 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5501 /* File Table {{{ */
5502 @interface FileTable : CYViewController <
5503 UITableViewDataSource,
5506 _transient Database *database_;
5509 NSMutableArray *files_;
5513 - (id) initWithDatabase:(Database *)database;
5514 - (void) setPackage:(Package *)package;
5518 @implementation FileTable
5521 [self releaseSubviews];
5530 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5531 return files_ == nil ? 0 : [files_ count];
5534 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5538 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5539 static NSString *reuseIdentifier = @"Cell";
5541 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5543 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5544 [cell setFont:[UIFont systemFontOfSize:16]];
5546 [cell setText:[files_ objectAtIndex:indexPath.row]];
5547 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5552 - (NSURL *) navigationURL {
5553 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5557 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5559 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5560 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5561 [list_ setRowHeight:24.0f];
5562 [list_ setDataSource:self];
5563 [list_ setDelegate:self];
5564 [[self view] addSubview:list_];
5567 - (void) viewDidLoad {
5568 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5571 - (void) releaseSubviews {
5576 - (id) initWithDatabase:(Database *)database {
5577 if ((self = [super init]) != nil) {
5578 database_ = database;
5580 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5584 - (void) setPackage:(Package *)package {
5585 if (package_ != nil) {
5586 [package_ autorelease];
5595 [files_ removeAllObjects];
5597 if (package != nil) {
5598 package_ = [package retain];
5599 name_ = [[package id] retain];
5601 if (NSArray *files = [package files])
5602 [files_ addObjectsFromArray:files];
5604 if ([files_ count] != 0) {
5605 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5606 [files_ removeObjectAtIndex:0];
5607 [files_ sortUsingSelector:@selector(compareByPath:)];
5609 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5610 [stack addObject:@"/"];
5612 for (int i(0), e([files_ count]); i != e; ++i) {
5613 NSString *file = [files_ objectAtIndex:i];
5614 while (![file hasPrefix:[stack lastObject]])
5615 [stack removeLastObject];
5616 NSString *directory = [stack lastObject];
5617 [stack addObject:[file stringByAppendingString:@"/"]];
5618 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5619 ([stack count] - 2) * 3, "",
5620 [file substringFromIndex:[directory length]]
5629 - (void) reloadData {
5632 [self setPackage:[database_ packageWithName:name_]];
5637 /* Package Controller {{{ */
5638 @interface CYPackageController : CYBrowserController <
5639 UIActionSheetDelegate
5641 _transient Database *database_;
5645 NSMutableArray *buttons_;
5646 UIBarButtonItem *button_;
5649 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5653 @implementation CYPackageController
5656 if (package_ != nil)
5669 - (NSURL *) navigationURL {
5670 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", name_]];
5673 /* XXX: this is not safe at all... localization of /fail/ */
5674 - (void) _clickButtonWithName:(NSString *)name {
5675 if ([name isEqualToString:UCLocalize("CLEAR")])
5676 [delegate_ clearPackage:package_];
5677 else if ([name isEqualToString:UCLocalize("INSTALL")])
5678 [delegate_ installPackage:package_];
5679 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5680 [delegate_ installPackage:package_];
5681 else if ([name isEqualToString:UCLocalize("REMOVE")])
5682 [delegate_ removePackage:package_];
5683 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5684 [delegate_ installPackage:package_];
5685 else _assert(false);
5688 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5689 NSString *context([sheet context]);
5691 if ([context isEqualToString:@"modify"]) {
5692 if (button != [sheet cancelButtonIndex]) {
5693 NSString *buttonName = [buttons_ objectAtIndex:button];
5694 [self _clickButtonWithName:buttonName];
5697 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5701 - (bool) _allowJavaScriptPanel {
5706 - (void) _customButtonClicked {
5707 int count([buttons_ count]);
5712 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5714 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5715 [buttons addObjectsFromArray:buttons_];
5717 UIActionSheet *sheet = [[[UIActionSheet alloc]
5720 cancelButtonTitle:nil
5721 destructiveButtonTitle:nil
5722 otherButtonTitles:nil
5725 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5727 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5728 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5730 [sheet setContext:@"modify"];
5732 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5736 // We don't want to allow non-commercial packages to do custom things to the install button,
5737 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5738 - (void) customButtonClicked {
5740 [super customButtonClicked];
5742 [self _customButtonClicked];
5745 - (void) reloadButtonClicked {
5746 // Don't reload a commerical package by tapping the loading button,
5747 // but if it's not an Install button, we should forward it on.
5748 if (![package_ uninstalled])
5749 [self _customButtonClicked];
5752 - (void) applyLoadingTitle {
5753 // Don't show "Loading" as the title. Ever.
5756 - (UIBarButtonItem *) rightButton {
5761 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
5762 if ((self = [super init]) != nil) {
5763 database_ = database;
5764 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5765 name_ = [[NSString alloc] initWithString:name];
5766 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/package/#!/%@", UI_, name_]]];
5770 - (void) reloadData {
5771 if (package_ != nil)
5772 [package_ autorelease];
5773 package_ = [database_ packageWithName:name_];
5775 [buttons_ removeAllObjects];
5777 if (package_ != nil) {
5780 package_ = [package_ retain];
5781 commercial_ = [package_ isCommercial];
5783 if ([package_ mode] != nil)
5784 [buttons_ addObject:UCLocalize("CLEAR")];
5785 if ([package_ source] == nil);
5786 else if ([package_ upgradableAndEssential:NO])
5787 [buttons_ addObject:UCLocalize("UPGRADE")];
5788 else if ([package_ uninstalled])
5789 [buttons_ addObject:UCLocalize("INSTALL")];
5791 [buttons_ addObject:UCLocalize("REINSTALL")];
5792 if (![package_ uninstalled])
5793 [buttons_ addObject:UCLocalize("REMOVE")];
5800 switch ([buttons_ count]) {
5801 case 0: title = nil; break;
5802 case 1: title = [buttons_ objectAtIndex:0]; break;
5803 default: title = UCLocalize("MODIFY"); break;
5806 button_ = [[UIBarButtonItem alloc]
5808 style:UIBarButtonItemStylePlain
5810 action:@selector(customButtonClicked)
5816 - (bool) isLoading {
5817 return commercial_ ? [super isLoading] : false;
5823 /* Package List Controller {{{ */
5824 @interface PackageListController : CYViewController <
5825 UITableViewDataSource,
5828 _transient Database *database_;
5830 NSMutableArray *packages_;
5831 NSMutableArray *sections_;
5833 NSMutableArray *index_;
5834 NSMutableDictionary *indices_;
5838 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
5839 - (void) setDelegate:(id)delegate;
5840 - (void) resetCursor;
5844 @implementation PackageListController
5847 [packages_ release];
5848 [sections_ release];
5857 - (void) deselectWithAnimation:(BOOL)animated {
5858 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5861 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
5862 CGRect base = [[self view] bounds];
5863 base.size.height -= bounds.size.height;
5864 base.origin = [list_ frame].origin;
5866 [UIView beginAnimations:nil context:NULL];
5867 [UIView setAnimationBeginsFromCurrentState:YES];
5868 [UIView setAnimationCurve:curve];
5869 [UIView setAnimationDuration:duration];
5870 [list_ setFrame:base];
5871 [UIView commitAnimations];
5874 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
5875 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
5878 - (void) resizeForKeyboardBounds:(CGRect)bounds {
5879 [self resizeForKeyboardBounds:bounds duration:0];
5882 - (void) keyboardWillShow:(NSNotification *)notification {
5885 NSTimeInterval duration;
5886 UIViewAnimationCurve curve;
5887 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
5888 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
5889 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
5890 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
5892 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);
5893 UIViewController *base = self;
5894 while ([base parentViewController] != nil)
5895 base = [base parentViewController];
5896 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
5897 CGRect intersection = CGRectIntersection(viewframe, kbframe);
5899 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
5902 - (void) keyboardWillHide:(NSNotification *)notification {
5903 NSTimeInterval duration;
5904 UIViewAnimationCurve curve;
5905 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
5906 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
5908 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
5911 - (void) viewWillAppear:(BOOL)animated {
5912 [super viewWillAppear:animated];
5914 [self resizeForKeyboardBounds:CGRectZero];
5915 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
5916 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
5919 - (void) viewWillDisappear:(BOOL)animated {
5920 [super viewWillDisappear:animated];
5922 [self resizeForKeyboardBounds:CGRectZero];
5923 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
5924 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
5927 - (void) viewDidAppear:(BOOL)animated {
5928 [super viewDidAppear:animated];
5929 [self deselectWithAnimation:animated];
5932 - (void) didSelectPackage:(Package *)package {
5933 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
5934 [view setDelegate:delegate_];
5935 [[self navigationController] pushViewController:view animated:YES];
5938 #if TryIndexedCollation
5939 + (BOOL) hasIndexedCollation {
5940 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
5944 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5945 NSInteger count([sections_ count]);
5946 return count == 0 ? 1 : count;
5949 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5950 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
5952 return [[sections_ objectAtIndex:section] name];
5955 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5956 if ([sections_ count] == 0)
5958 return [[sections_ objectAtIndex:section] count];
5961 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5962 @synchronized (database_) {
5963 if ([database_ era] != era_)
5966 Section *section([sections_ objectAtIndex:[path section]]);
5967 NSInteger row([path row]);
5968 Package *package([packages_ objectAtIndex:([section row] + row)]);
5969 return [[package retain] autorelease];
5972 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5973 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5975 cell = [[[PackageCell alloc] init] autorelease];
5976 [cell setPackage:[self packageAtIndexPath:path]];
5980 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
5981 Package *package([self packageAtIndexPath:path]);
5982 package = [database_ packageWithName:[package id]];
5983 [self didSelectPackage:package];
5986 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5987 // XXX: is 20 the most optimal number here?
5988 return [packages_ count] > 20 ? index_ : nil;
5991 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5992 #if TryIndexedCollation
5993 if ([[self class] hasIndexedCollation]) {
5994 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6001 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6002 if ((self = [super init]) != nil) {
6003 database_ = database;
6004 title_ = [title copy];
6005 [[self navigationItem] setTitle:title_];
6007 #if TryIndexedCollation
6008 if ([[self class] hasIndexedCollation])
6009 index_ = [[[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles] retain]
6012 index_ = [[NSMutableArray alloc] initWithCapacity:32];
6014 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
6016 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6017 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6019 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6020 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6021 [list_ setRowHeight:73];
6022 [[self view] addSubview:list_];
6024 [list_ setDataSource:self];
6025 [list_ setDelegate:self];
6029 - (void) setDelegate:(id)delegate {
6030 delegate_ = delegate;
6033 - (bool) hasPackage:(Package *)package {
6037 - (void) reloadData {
6040 era_ = [database_ era];
6041 NSArray *packages = [database_ packages];
6043 [packages_ removeAllObjects];
6044 [sections_ removeAllObjects];
6046 _profile(PackageTable$reloadData$Filter)
6047 for (Package *package in packages)
6048 if ([self hasPackage:package])
6049 [packages_ addObject:package];
6052 [indices_ removeAllObjects];
6054 Section *section = nil;
6056 #if TryIndexedCollation
6057 if ([[self class] hasIndexedCollation]) {
6058 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6059 NSArray *titles = [collation sectionIndexTitles];
6062 _profile(PackageTable$reloadData$Section)
6063 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6067 _profile(PackageTable$reloadData$Section$Package)
6068 package = [packages_ objectAtIndex:offset];
6069 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6072 while (secidx < index) {
6075 _profile(PackageTable$reloadData$Section$Allocate)
6076 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6079 _profile(PackageTable$reloadData$Section$Add)
6080 [sections_ addObject:section];
6084 [section addToCount];
6090 [index_ removeAllObjects];
6092 _profile(PackageTable$reloadData$Section)
6093 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6097 _profile(PackageTable$reloadData$Section$Package)
6098 package = [packages_ objectAtIndex:offset];
6099 index = [package index];
6102 if (section == nil || [section index] != index) {
6103 _profile(PackageTable$reloadData$Section$Allocate)
6104 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6107 [index_ addObject:[section name]];
6108 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6110 _profile(PackageTable$reloadData$Section$Add)
6111 [sections_ addObject:section];
6115 [section addToCount];
6120 _profile(PackageTable$reloadData$List)
6125 - (void) resetCursor {
6126 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
6131 /* Filtered Package List Controller {{{ */
6132 @interface FilteredPackageListController : PackageListController {
6138 - (void) setObject:(id)object;
6139 - (void) setObject:(id)object forFilter:(SEL)filter;
6141 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6145 @implementation FilteredPackageListController
6153 - (void) setFilter:(SEL)filter {
6156 /* XXX: this is an unsafe optimization of doomy hell */
6157 Method method(class_getInstanceMethod([Package class], filter));
6158 _assert(method != NULL);
6159 imp_ = method_getImplementation(method);
6160 _assert(imp_ != NULL);
6163 - (void) setObject:(id)object {
6169 object_ = [object retain];
6172 - (void) setObject:(id)object forFilter:(SEL)filter {
6173 [self setFilter:filter];
6174 [self setObject:object];
6177 - (bool) hasPackage:(Package *)package {
6178 _profile(FilteredPackageTable$hasPackage)
6179 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
6183 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6184 if ((self = [super initWithDatabase:database title:title]) != nil) {
6185 [self setFilter:filter];
6186 [self setObject:object];
6193 /* Home Controller {{{ */
6194 @interface HomeController : CYBrowserController {
6199 @implementation HomeController
6201 + (BOOL) shouldHideNavigationBar {
6205 - (NSURL *) navigationURL {
6206 return [NSURL URLWithString:@"cydia://home"];
6209 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
6210 [super _setMoreHeaders:request];
6213 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
6214 if (UniqueID_ != nil)
6215 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
6217 [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"];
6220 - (void) aboutButtonClicked {
6221 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6223 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6224 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6225 [alert setCancelButtonIndex:0];
6228 @"Copyright (C) 2008-2011\n"
6229 "Jay Freeman (saurik)\n"
6230 "saurik@saurik.com\n"
6231 "http://www.saurik.com/"
6237 - (void) viewWillDisappear:(BOOL)animated {
6238 [super viewWillDisappear:animated];
6240 if ([[self class] shouldHideNavigationBar])
6241 [[self navigationController] setNavigationBarHidden:NO animated:animated];
6244 - (void) viewWillAppear:(BOOL)animated {
6245 if (![self hasLoaded])
6246 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/home/", UI_]]];
6248 [super viewWillAppear:animated];
6250 if ([[self class] shouldHideNavigationBar])
6251 [[self navigationController] setNavigationBarHidden:YES animated:animated];
6254 - (void) viewDidLoad {
6255 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6256 initWithTitle:UCLocalize("ABOUT")
6257 style:UIBarButtonItemStylePlain
6259 action:@selector(aboutButtonClicked)
6265 /* Manage Controller {{{ */
6266 @interface ManageController : CYBrowserController {
6269 - (void) queueStatusDidChange;
6273 @implementation ManageController
6275 - (NSURL *) navigationURL {
6276 return [NSURL URLWithString:@"cydia://manage"];
6279 - (void) viewWillAppear:(BOOL)animated {
6280 if (![self hasLoaded])
6281 [self loadURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/manage/", UI_]]];
6283 [super viewWillAppear:animated];
6286 - (void) viewDidLoad {
6287 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6288 initWithTitle:UCLocalize("SETTINGS")
6289 style:UIBarButtonItemStylePlain
6291 action:@selector(settingsButtonClicked)
6294 [self queueStatusDidChange];
6297 - (void) settingsButtonClicked {
6298 [delegate_ showSettings];
6302 - (void) queueButtonClicked {
6306 - (void) applyLoadingTitle {
6307 // Disable "Loading" title.
6310 - (void) applyRightButton {
6311 // Disable right button.
6315 - (void) queueStatusDidChange {
6317 if (!IsWildcat_ && Queuing_) {
6318 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6319 initWithTitle:UCLocalize("QUEUE")
6320 style:UIBarButtonItemStyleDone
6322 action:@selector(queueButtonClicked)
6325 [[self navigationItem] setRightBarButtonItem:nil];
6330 - (bool) isLoading {
6331 // Never show as loading.
6338 /* Refresh Bar {{{ */
6339 @interface RefreshBar : UINavigationBar {
6340 UIProgressIndicator *indicator_;
6341 UITextLabel *prompt_;
6342 UIProgressBar *progress_;
6343 UINavigationButton *cancel_;
6348 @implementation RefreshBar
6351 [indicator_ release];
6353 [progress_ release];
6358 - (void) positionViews {
6359 CGRect frame = [cancel_ frame];
6360 frame.size = [cancel_ sizeThatFits:frame.size];
6361 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6362 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6363 [cancel_ setFrame:frame];
6365 CGSize prgsize = {75, 100};
6367 [self frame].size.width - prgsize.width - 10,
6368 ([self frame].size.height - prgsize.height) / 2
6370 [progress_ setFrame:prgrect];
6372 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6373 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6374 CGRect indrect = {{indoffset, indoffset}, indsize};
6375 [indicator_ setFrame:indrect];
6377 CGSize prmsize = {215, indsize.height + 4};
6379 indoffset * 2 + indsize.width,
6380 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6382 [prompt_ setFrame:prmrect];
6385 - (void) setFrame:(CGRect)frame {
6386 [super setFrame:frame];
6387 [self positionViews];
6390 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6391 if ((self = [super initWithFrame:frame]) != nil) {
6392 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6394 [self setBarStyle:UIBarStyleBlack];
6396 UIBarStyle barstyle([self _barStyle:NO]);
6397 bool ugly(barstyle == UIBarStyleDefault);
6399 UIProgressIndicatorStyle style = ugly ?
6400 UIProgressIndicatorStyleMediumBrown :
6401 UIProgressIndicatorStyleMediumWhite;
6403 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6404 [indicator_ setStyle:style];
6405 [indicator_ startAnimation];
6406 [self addSubview:indicator_];
6408 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6409 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6410 [prompt_ setBackgroundColor:[UIColor clearColor]];
6411 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6412 [self addSubview:prompt_];
6414 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6415 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6416 [progress_ setStyle:0];
6417 [self addSubview:progress_];
6419 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6420 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6421 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6422 [cancel_ setBarStyle:barstyle];
6424 [self positionViews];
6429 [cancel_ removeFromSuperview];
6433 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6434 [progress_ setProgress:0];
6435 [self addSubview:cancel_];
6439 [cancel_ removeFromSuperview];
6442 - (void) setPrompt:(NSString *)prompt {
6443 [prompt_ setText:prompt];
6446 - (void) setProgress:(float)progress {
6447 [progress_ setProgress:progress];
6453 @class CYNavigationController;
6455 /* Cydia Tab Bar Controller {{{ */
6456 @interface CYTabBarController : UITabBarController <
6457 UITabBarControllerDelegate,
6460 _transient Database *database_;
6461 RefreshBar *refreshbar_;
6465 // XXX: ok, "updatedelegate_"?...
6466 _transient NSObject<CydiaDelegate> *updatedelegate_;
6469 UIViewController *remembered_;
6470 _transient UIViewController *transient_;
6473 - (NSArray *) navigationURLCollection;
6474 - (void) dropBar:(BOOL)animated;
6475 - (void) beginUpdate;
6476 - (void) raiseBar:(BOOL)animated;
6481 @implementation CYTabBarController
6483 - (void) setUnselectedViewController:(UIViewController *)transient {
6484 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6485 if (transient != nil) {
6486 if (transient_ == nil)
6487 remembered_ = [[controllers objectAtIndex:0] retain];
6488 transient_ = transient;
6489 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6490 [controllers replaceObjectAtIndex:0 withObject:transient_];
6491 [self setSelectedIndex:0];
6492 [self setViewControllers:controllers];
6493 [self concealTabBarSelection];
6494 } else if (remembered_ != nil) {
6495 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6496 transient_ = transient;
6497 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6498 [remembered_ release];
6500 [self setViewControllers:controllers];
6501 [self revealTabBarSelection];
6505 - (UIViewController *) unselectedViewController {
6509 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6510 if ([self unselectedViewController])
6511 [self setUnselectedViewController:nil];
6514 - (NSArray *) navigationURLCollection {
6515 NSMutableArray *items([NSMutableArray array]);
6517 // XXX: Should this deal with transient view controllers?
6518 for (id navigation in [self viewControllers]) {
6519 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6521 [items addObject:stack];
6527 - (void) reloadData {
6528 for (CYViewController *controller in [self viewControllers])
6529 [controller reloadData];
6531 [(CYNavigationController *)[self unselectedViewController] reloadData];
6535 [refreshbar_ release];
6536 [[NSNotificationCenter defaultCenter] removeObserver:self];
6541 - (id) initWithDatabase:(Database *)database {
6542 if ((self = [super init]) != nil) {
6543 database_ = database;
6544 [self setDelegate:self];
6546 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6547 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6549 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
6553 - (void) setUpdate:(NSDate *)date {
6557 - (void) beginUpdate {
6558 [refreshbar_ start];
6561 [updatedelegate_ retainNetworkActivityIndicator];
6565 detachNewThreadSelector:@selector(performUpdate)
6571 - (void) performUpdate { _pooled
6573 status.setDelegate(self);
6574 [database_ updateWithStatus:status];
6577 performSelectorOnMainThread:@selector(completeUpdate)
6583 - (void) stopUpdateWithSelector:(SEL)selector {
6585 [updatedelegate_ releaseNetworkActivityIndicator];
6587 [self raiseBar:YES];
6590 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6593 - (void) completeUpdate {
6596 [self stopUpdateWithSelector:@selector(reloadData)];
6599 - (void) cancelUpdate {
6600 [self stopUpdateWithSelector:@selector(updateData)];
6603 - (void) cancelPressed {
6604 [self cancelUpdate];
6611 - (void) addProgressEvent:(CydiaProgressEvent *)event {
6612 [refreshbar_ setPrompt:[event compoundMessage]];
6615 - (bool) isProgressCancelled {
6619 - (void) setProgressPercent:(NSNumber *)percent {
6620 [refreshbar_ setProgress:[percent floatValue]];
6623 - (void) setUpdateDelegate:(id)delegate {
6624 updatedelegate_ = delegate;
6627 - (CGFloat) statusBarHeight {
6628 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
6629 return [[UIApplication sharedApplication] statusBarFrame].size.height;
6631 return [[UIApplication sharedApplication] statusBarFrame].size.width;
6635 - (UIView *) transitionView {
6636 if ([self respondsToSelector:@selector(_transitionView)])
6637 return [self _transitionView];
6639 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6642 - (void) dropBar:(BOOL)animated {
6647 UIView *transition([self transitionView]);
6648 [[self view] addSubview:refreshbar_];
6650 CGRect barframe([refreshbar_ frame]);
6652 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6653 barframe.origin.y = [self statusBarHeight];
6655 barframe.origin.y = 0;
6657 [refreshbar_ setFrame:barframe];
6660 [UIView beginAnimations:nil context:NULL];
6662 CGRect viewframe = [transition frame];
6663 viewframe.origin.y += barframe.size.height;
6664 viewframe.size.height -= barframe.size.height;
6665 [transition setFrame:viewframe];
6668 [UIView commitAnimations];
6670 // Ensure bar has the proper width for our view, it might have changed
6671 barframe.size.width = viewframe.size.width;
6672 [refreshbar_ setFrame:barframe];
6674 // XXX: fix Apple's layout bug
6675 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6678 - (void) raiseBar:(BOOL)animated {
6683 UIView *transition([self transitionView]);
6684 [refreshbar_ removeFromSuperview];
6686 CGRect barframe([refreshbar_ frame]);
6689 [UIView beginAnimations:nil context:NULL];
6691 CGRect viewframe = [transition frame];
6692 viewframe.origin.y -= barframe.size.height;
6693 viewframe.size.height += barframe.size.height;
6694 [transition setFrame:viewframe];
6697 [UIView commitAnimations];
6699 // XXX: fix Apple's layout bug
6700 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6704 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
6705 // XXX: fix Apple's layout bug
6706 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6710 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6711 bool dropped(dropped_);
6716 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6721 // XXX: fix Apple's layout bug
6722 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6725 - (void) statusBarFrameChanged:(NSNotification *)notification {
6734 /* Cydia Navigation Controller {{{ */
6735 @interface CYNavigationController : UINavigationController {
6736 _transient Database *database_;
6737 _transient id<UINavigationControllerDelegate> delegate_;
6740 - (NSArray *) navigationURLCollection;
6741 - (id) initWithDatabase:(Database *)database;
6742 - (void) reloadData;
6747 @implementation CYNavigationController
6749 - (NSArray *) navigationURLCollection {
6750 NSMutableArray *stack([NSMutableArray array]);
6752 for (CYViewController *controller in [self viewControllers]) {
6753 NSString *url = [[controller navigationURL] absoluteString];
6755 [stack addObject:url];
6761 - (void) reloadData {
6762 for (CYViewController *page in [self viewControllers]) {
6763 // Only reload controllers that have already loaded.
6764 // This prevents a page from accidentally loading too
6765 // early if it hasn't been shown on the screen yet.
6766 if ([page hasLoaded])
6771 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
6772 delegate_ = delegate;
6775 - (id) initWithDatabase:(Database *)database {
6776 if ((self = [super init]) != nil) {
6777 database_ = database;
6784 /* Cydia:// Protocol {{{ */
6785 @interface CydiaURLProtocol : NSURLProtocol {
6790 @implementation CydiaURLProtocol
6792 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6793 NSURL *url([request URL]);
6796 NSString *scheme([[url scheme] lowercaseString]);
6797 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6802 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6806 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6807 id<NSURLProtocolClient> client([self client]);
6809 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6811 NSData *data(UIImagePNGRepresentation(icon));
6813 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6814 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6815 [client URLProtocol:self didLoadData:data];
6816 [client URLProtocolDidFinishLoading:self];
6820 - (void) startLoading {
6821 id<NSURLProtocolClient> client([self client]);
6822 NSURLRequest *request([self request]);
6824 NSURL *url([request URL]);
6825 NSString *href([url absoluteString]);
6827 NSString *path([href substringFromIndex:8]);
6828 NSRange slash([path rangeOfString:@"/"]);
6831 if (slash.location == NSNotFound) {
6835 command = [path substringToIndex:slash.location];
6836 path = [path substringFromIndex:(slash.location + 1)];
6839 Database *database([Database sharedInstance]);
6841 if ([command isEqualToString:@"package-icon"]) {
6844 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6845 Package *package([database packageWithName:path]);
6848 UIImage *icon([package icon]);
6849 [self _returnPNGWithImage:icon forRequest:request];
6850 } else if ([command isEqualToString:@"source-icon"]) {
6853 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6854 NSString *source(Simplify(path));
6855 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6857 icon = [UIImage applicationImageNamed:@"unknown.png"];
6858 [self _returnPNGWithImage:icon forRequest:request];
6859 } else if ([command isEqualToString:@"uikit-image"]) {
6862 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6863 UIImage *icon(_UIImageWithName(path));
6864 [self _returnPNGWithImage:icon forRequest:request];
6865 } else if ([command isEqualToString:@"section-icon"]) {
6868 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6869 NSString *section(Simplify(path));
6870 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6872 icon = [UIImage applicationImageNamed:@"unknown.png"];
6873 [self _returnPNGWithImage:icon forRequest:request];
6875 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6879 - (void) stopLoading {
6885 /* Section Controller {{{ */
6886 @interface SectionController : FilteredPackageListController {
6890 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
6894 @implementation SectionController
6896 - (NSURL *) navigationURL {
6897 NSString *name = section_;
6901 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
6904 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
6907 title = UCLocalize("ALL_PACKAGES");
6908 else if (![name isEqual:@""])
6909 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6911 title = UCLocalize("NO_SECTION");
6913 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
6920 /* Sections Controller {{{ */
6921 @interface SectionsController : CYViewController <
6922 UITableViewDataSource,
6925 _transient Database *database_;
6926 NSMutableArray *sections_;
6927 NSMutableArray *filtered_;
6932 - (id) initWithDatabase:(Database *)database;
6933 - (void) editButtonClicked;
6937 @implementation SectionsController
6940 [self releaseSubviews];
6941 [sections_ release];
6942 [filtered_ release];
6947 - (NSURL *) navigationURL {
6948 return [NSURL URLWithString:@"cydia://sections"];
6951 - (void) updateNavigationItem {
6952 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6953 if ([sections_ count] == 0) {
6954 [[self navigationItem] setRightBarButtonItem:nil];
6956 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
6957 initWithBarButtonSystemItem:(editing_ ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
6959 action:@selector(editButtonClicked)
6960 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
6964 - (BOOL) isEditing {
6968 - (void) setEditing:(BOOL)editing {
6969 if ((editing_ = editing))
6972 [delegate_ updateData];
6974 [self updateNavigationItem];
6977 - (void) viewDidAppear:(BOOL)animated {
6978 [super viewDidAppear:animated];
6979 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6982 - (void) viewWillDisappear:(BOOL)animated {
6983 [super viewWillDisappear:animated];
6984 if (editing_) [self setEditing:NO];
6987 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
6988 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
6992 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6993 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6996 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7000 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7001 static NSString *reuseIdentifier = @"SectionCell";
7003 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7005 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7007 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
7012 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7016 Section *section = [self sectionAtIndexPath:indexPath];
7018 SectionController *controller = [[[SectionController alloc]
7019 initWithDatabase:database_
7020 section:[section name]
7022 [controller setDelegate:delegate_];
7024 [[self navigationController] pushViewController:controller animated:YES];
7028 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7030 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
7031 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7032 [list_ setRowHeight:45.0f];
7033 [list_ setDataSource:self];
7034 [list_ setDelegate:self];
7035 [[self view] addSubview:list_];
7038 - (void) viewDidLoad {
7039 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7042 - (void) releaseSubviews {
7047 - (id) initWithDatabase:(Database *)database {
7048 if ((self = [super init]) != nil) {
7049 database_ = database;
7051 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7052 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
7056 - (void) reloadData {
7059 NSArray *packages = [database_ packages];
7061 [sections_ removeAllObjects];
7062 [filtered_ removeAllObjects];
7064 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7067 for (Package *package in packages) {
7068 NSString *name([package section]);
7069 NSString *key(name == nil ? @"" : name);
7073 _profile(SectionsView$reloadData$Section)
7074 section = [sections objectForKey:key];
7075 if (section == nil) {
7076 _profile(SectionsView$reloadData$Section$Allocate)
7077 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7078 [sections setObject:section forKey:key];
7083 [section addToCount];
7085 _profile(SectionsView$reloadData$Filter)
7086 if (![package valid] || ![package visible])
7094 [sections_ addObjectsFromArray:[sections allValues]];
7096 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7098 for (Section *section in sections_) {
7099 size_t count([section row]);
7103 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7104 [section setCount:count];
7105 [filtered_ addObject:section];
7108 [self updateNavigationItem];
7113 - (void) editButtonClicked {
7114 [self setEditing:(!editing_)];
7120 /* Changes Controller {{{ */
7121 @interface ChangesController : CYViewController <
7122 UITableViewDataSource,
7125 _transient Database *database_;
7127 CFMutableArrayRef packages_;
7128 NSMutableArray *sections_;
7131 BOOL hasSentFirstLoad_;
7134 - (id) initWithDatabase:(Database *)database;
7138 @implementation ChangesController
7141 [self releaseSubviews];
7142 CFRelease(packages_);
7143 [sections_ release];
7148 - (NSURL *) navigationURL {
7149 return [NSURL URLWithString:@"cydia://changes"];
7152 - (void) viewWillAppear:(BOOL)animated {
7153 // Loads after it appears, so don't load beforehand.
7155 [super viewWillAppear:animated];
7158 - (void) viewDidAppear:(BOOL)animated {
7159 [super viewDidAppear:animated];
7161 if (!hasSentFirstLoad_) {
7162 hasSentFirstLoad_ = YES;
7163 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
7165 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7169 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7170 NSInteger count([sections_ count]);
7171 return count == 0 ? 1 : count;
7174 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7175 if ([sections_ count] == 0)
7177 return [[sections_ objectAtIndex:section] name];
7180 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7181 if ([sections_ count] == 0)
7183 return [[sections_ objectAtIndex:section] count];
7186 - (Package *) packageAtIndex:(NSUInteger)index {
7187 return (Package *) CFArrayGetValueAtIndex(packages_, index);
7190 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7191 @synchronized (database_) {
7192 if ([database_ era] != era_)
7195 NSUInteger sectionIndex([path section]);
7196 if (sectionIndex >= [sections_ count])
7198 Section *section([sections_ objectAtIndex:sectionIndex]);
7199 NSInteger row([path row]);
7200 return [[[self packageAtIndex:([section row] + row)] retain] autorelease];
7203 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7204 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7206 cell = [[[PackageCell alloc] init] autorelease];
7207 [cell setPackage:[self packageAtIndexPath:path]];
7211 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7212 Package *package([self packageAtIndexPath:path]);
7213 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7214 [view setDelegate:delegate_];
7215 [[self navigationController] pushViewController:view animated:YES];
7219 - (void) refreshButtonClicked {
7220 [delegate_ beginUpdate];
7221 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7224 - (void) upgradeButtonClicked {
7225 [delegate_ distUpgrade];
7229 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7231 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7232 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7233 [list_ setRowHeight:73];
7234 [list_ setDataSource:self];
7235 [list_ setDelegate:self];
7236 [[self view] addSubview:list_];
7239 - (void) viewDidLoad {
7240 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7243 - (void) releaseSubviews {
7248 - (id) initWithDatabase:(Database *)database {
7249 if ((self = [super init]) != nil) {
7250 database_ = database;
7252 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7253 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7257 // this mostly works because reloadData (below) is @synchronized (database_)
7258 // XXX: that said, I've been running into problems with NSRangeExceptions :(
7259 - (void) _reloadPackages:(NSArray *)packages {
7260 CFRelease(packages_);
7261 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, [packages count], NULL);
7264 _profile(ChangesController$_reloadPackages$Filter)
7265 for (Package *package in packages)
7266 if ([package upgradableAndEssential:YES] || [package visible])
7267 CFArrayAppendValue(packages_, package);
7270 _profile(ChangesController$_reloadPackages$radixSort)
7271 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7276 - (void) reloadData {
7277 @synchronized (database_) {
7278 era_ = [database_ era];
7279 NSArray *packages = [database_ packages];
7281 [sections_ removeAllObjects];
7284 UIProgressHUD *hud([delegate_ addProgressHUD]);
7285 [hud setText:UCLocalize("LOADING")];
7286 //NSLog(@"HUD:%@::%@", delegate_, hud);
7287 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7288 [delegate_ removeProgressHUD:hud];
7290 [self _reloadPackages:packages];
7293 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7294 Section *ignored = nil;
7295 Section *section = nil;
7299 bool unseens = false;
7301 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7303 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7304 Package *package = [self packageAtIndex:offset];
7306 BOOL uae = [package upgradableAndEssential:YES];
7310 time_t seen([package seen]);
7312 if (section == nil || last != seen) {
7316 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7319 _profile(ChangesController$reloadData$Allocate)
7320 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7321 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7322 [sections_ addObject:section];
7326 [section addToCount];
7327 } else if ([package ignored]) {
7328 if (ignored == nil) {
7329 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7331 [ignored addToCount];
7334 [upgradable addToCount];
7339 CFRelease(formatter);
7342 Section *last = [sections_ lastObject];
7343 size_t count = [last count];
7344 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7345 [sections_ removeLastObject];
7348 if ([ignored count] != 0)
7349 [sections_ insertObject:ignored atIndex:0];
7351 [sections_ insertObject:upgradable atIndex:0];
7356 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7357 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7358 style:UIBarButtonItemStylePlain
7360 action:@selector(upgradeButtonClicked)
7363 if (![delegate_ updating])
7364 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7365 initWithTitle:UCLocalize("REFRESH")
7366 style:UIBarButtonItemStylePlain
7368 action:@selector(refreshButtonClicked)
7376 /* Search Controller {{{ */
7377 @interface SearchController : FilteredPackageListController <
7380 UISearchBar *search_;
7384 - (id) initWithDatabase:(Database *)database;
7385 - (void) setSearchTerm:(NSString *)term;
7386 - (void) reloadData;
7390 @implementation SearchController
7397 - (NSURL *) navigationURL {
7398 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7399 return [NSURL URLWithString:@"cydia://search"];
7401 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7404 - (void) setSearchTerm:(NSString *)searchTerm {
7405 [search_ setText:searchTerm];
7409 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7410 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7411 [search_ resignFirstResponder];
7415 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7416 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7420 - (id) initWithDatabase:(Database *)database {
7421 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil])) {
7422 search_ = [[UISearchBar alloc] init];
7426 - (void) viewDidAppear:(BOOL)animated {
7427 [super viewDidAppear:animated];
7429 if (!searchloaded_) {
7430 searchloaded_ = YES;
7431 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7432 [search_ layoutSubviews];
7433 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7435 UITextField *textField;
7436 if ([search_ respondsToSelector:@selector(searchField)])
7437 textField = [search_ searchField];
7439 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7441 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7442 [search_ setDelegate:self];
7443 [textField setEnablesReturnKeyAutomatically:NO];
7444 [[self navigationItem] setTitleView:textField];
7448 - (void) reloadData {
7449 [self setObject:[search_ text]];
7454 - (void) didSelectPackage:(Package *)package {
7455 [search_ resignFirstResponder];
7456 [super didSelectPackage:package];
7461 /* Package Settings Controller {{{ */
7462 @interface PackageSettingsController : CYViewController <
7463 UITableViewDataSource,
7466 _transient Database *database_;
7469 UITableView *table_;
7470 UISwitch *subscribedSwitch_;
7471 UISwitch *ignoredSwitch_;
7472 UITableViewCell *subscribedCell_;
7473 UITableViewCell *ignoredCell_;
7476 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7480 @implementation PackageSettingsController
7483 [self releaseSubviews];
7490 - (NSURL *) navigationURL {
7491 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", [package_ id]]];
7494 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7495 if (package_ == nil)
7498 if ([package_ installed] == nil)
7504 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7505 if (package_ == nil)
7508 // both sections contain just one item right now.
7512 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7516 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7518 return UCLocalize("SHOW_ALL_CHANGES_EX");
7520 return UCLocalize("IGNORE_UPGRADES_EX");
7523 - (void) onSubscribed:(id)control {
7524 bool value([control isOn]);
7525 if (package_ == nil)
7527 if ([package_ setSubscribed:value])
7528 [delegate_ updateData];
7531 - (void) _updateIgnored {
7532 const char *package([name_ UTF8String]);
7533 bool on([ignoredSwitch_ isOn]);
7535 pid_t pid(ExecFork());
7537 FILE *dpkg(popen("dpkg --set-selections", "w"));
7538 fwrite(package, strlen(package), 1, dpkg);
7541 fwrite(" hold\n", 6, 1, dpkg);
7543 fwrite(" install\n", 9, 1, dpkg);
7553 int result(waitpid(pid, &status, 0));
7556 _assert(result == pid);
7562 - (void) onIgnored:(id)control {
7563 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7564 [invocation setTarget:self];
7565 [invocation setSelector:@selector(_updateIgnored)];
7567 [delegate_ reloadDataWithInvocation:invocation];
7570 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7571 if (package_ == nil)
7574 switch ([indexPath section]) {
7575 case 0: return subscribedCell_;
7576 case 1: return ignoredCell_;
7585 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7587 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7588 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7589 [table_ setDataSource:self];
7590 [table_ setDelegate:self];
7591 [[self view] addSubview:table_];
7593 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7594 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7595 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7597 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7598 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7599 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7601 subscribedCell_ = [[UITableViewCell alloc] init];
7602 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7603 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7604 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7606 ignoredCell_ = [[UITableViewCell alloc] init];
7607 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7608 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7609 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7612 - (void) viewDidLoad {
7613 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7616 - (void) releaseSubviews {
7617 [ignoredCell_ release];
7620 [subscribedCell_ release];
7621 subscribedCell_ = nil;
7626 [ignoredSwitch_ release];
7627 ignoredSwitch_ = nil;
7629 [subscribedSwitch_ release];
7630 subscribedSwitch_ = nil;
7633 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7634 if ((self = [super init]) != nil) {
7635 database_ = database;
7636 name_ = [package retain];
7640 - (void) reloadData {
7643 if (package_ != nil)
7644 [package_ autorelease];
7645 package_ = [database_ packageWithName:name_];
7647 if (package_ != nil) {
7648 package_ = [package_ retain];
7649 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7650 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7651 } // XXX: what now, G?
7653 [table_ reloadData];
7659 /* Installed Controller {{{ */
7660 @interface InstalledController : FilteredPackageListController {
7664 - (id) initWithDatabase:(Database *)database;
7666 - (void) updateRoleButton;
7667 - (void) queueStatusDidChange;
7671 @implementation InstalledController
7677 - (NSURL *) navigationURL {
7678 return [NSURL URLWithString:@"cydia://installed"];
7681 - (id) initWithDatabase:(Database *)database {
7682 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7683 [self updateRoleButton];
7684 [self queueStatusDidChange];
7689 - (void) queueButtonClicked {
7694 - (void) queueStatusDidChange {
7698 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7699 initWithTitle:UCLocalize("QUEUE")
7700 style:UIBarButtonItemStyleDone
7702 action:@selector(queueButtonClicked)
7705 [[self navigationItem] setLeftBarButtonItem:nil];
7711 - (void) updateRoleButton {
7712 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7713 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7714 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7715 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7717 action:@selector(roleButtonClicked)
7721 - (void) roleButtonClicked {
7722 [self setObject:[NSNumber numberWithBool:expert_]];
7726 [self updateRoleButton];
7732 /* Source Cell {{{ */
7733 @interface SourceCell : CYTableViewCell <
7741 - (void) setSource:(Source *)source;
7745 @implementation SourceCell
7747 - (void) clearSource {
7757 - (void) setSource:(Source *)source {
7761 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
7763 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
7764 icon_ = [icon_ retain];
7766 origin_ = [[source name] retain];
7767 label_ = [[source uri] retain];
7769 [content_ setNeedsDisplay];
7777 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
7778 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
7779 UIView *content([self contentView]);
7780 CGRect bounds([content bounds]);
7782 content_ = [[ContentView alloc] initWithFrame:bounds];
7783 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7784 [content_ setBackgroundColor:[UIColor whiteColor]];
7785 [content addSubview:content_];
7787 [content_ setDelegate:self];
7788 [content_ setOpaque:YES];
7792 - (NSString *) accessibilityLabel {
7796 - (void) drawContentRect:(CGRect)rect {
7797 bool highlighted(highlighted_);
7798 float width(rect.size.width);
7801 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
7808 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
7812 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
7817 /* Source Controller {{{ */
7818 @interface SourceController : FilteredPackageListController {
7819 _transient Source *source_;
7823 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7827 @implementation SourceController
7829 - (NSURL *) navigationURL {
7830 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [source_ name]]];
7833 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7834 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
7836 key_ = [[source key] retain];
7840 - (void) reloadData {
7841 source_ = [database_ sourceWithKey:key_];
7843 key_ = [[source_ key] retain];
7844 [self setObject:source_];
7845 [[self navigationItem] setTitle:[source_ label]];
7852 /* Sources Controller {{{ */
7853 @interface SourcesController : CYViewController <
7854 UITableViewDataSource,
7857 _transient Database *database_;
7859 NSMutableArray *sources_;
7863 UIProgressHUD *hud_;
7866 //NSURLConnection *installer_;
7867 NSURLConnection *trivial_;
7868 NSURLConnection *trivial_bz2_;
7869 NSURLConnection *trivial_gz_;
7870 //NSURLConnection *automatic_;
7875 - (id) initWithDatabase:(Database *)database;
7876 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
7880 @implementation SourcesController
7882 - (void) _releaseConnection:(NSURLConnection *)connection {
7883 if (connection != nil) {
7884 [connection cancel];
7885 //[connection setDelegate:nil];
7886 [connection release];
7891 [self releaseSubviews];
7897 //[self _releaseConnection:installer_];
7898 [self _releaseConnection:trivial_];
7899 [self _releaseConnection:trivial_gz_];
7900 [self _releaseConnection:trivial_bz2_];
7901 //[self _releaseConnection:automatic_];
7907 - (NSURL *) navigationURL {
7908 return [NSURL URLWithString:@"cydia://sources"];
7911 - (void) viewDidAppear:(BOOL)animated {
7912 [super viewDidAppear:animated];
7913 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7916 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7917 return offset_ == 0 ? 1 : 2;
7920 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7921 switch (section + (offset_ == 0 ? 1 : 0)) {
7922 case 0: return UCLocalize("ENTERED_BY_USER");
7923 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
7929 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7930 int count = [sources_ count];
7932 case 0: return (offset_ == 0 ? count : offset_);
7933 case 1: return count - offset_;
7939 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
7941 switch (indexPath.section) {
7942 case 0: idx = indexPath.row; break;
7943 case 1: idx = indexPath.row + offset_; break;
7947 return [sources_ objectAtIndex:idx];
7950 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7951 static NSString *cellIdentifier = @"SourceCell";
7953 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
7954 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
7955 [cell setSource:[self sourceAtIndexPath:indexPath]];
7956 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
7961 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7962 Source *source = [self sourceAtIndexPath:indexPath];
7964 SourceController *controller = [[[SourceController alloc]
7965 initWithDatabase:database_
7969 [controller setDelegate:delegate_];
7971 [[self navigationController] pushViewController:controller animated:YES];
7974 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
7975 Source *source = [self sourceAtIndexPath:indexPath];
7976 return [source record] != nil;
7979 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
7980 Source *source = [self sourceAtIndexPath:indexPath];
7981 [Sources_ removeObjectForKey:[source key]];
7982 [delegate_ syncData];
7986 [delegate_ addTrivialSource:href_];
7987 [delegate_ syncData];
7990 - (NSString *) getWarning {
7991 NSString *href(href_);
7992 NSRange colon([href rangeOfString:@"://"]);
7993 if (colon.location != NSNotFound)
7994 href = [href substringFromIndex:(colon.location + 3)];
7995 href = [href stringByAddingPercentEscapes];
7996 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
7997 href = [href stringByCachingURLWithCurrentCDN];
7999 NSURL *url([NSURL URLWithString:href]);
8001 NSStringEncoding encoding;
8002 NSError *error(nil);
8004 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8005 return [warning length] == 0 ? nil : warning;
8009 - (void) _endConnection:(NSURLConnection *)connection {
8010 // XXX: the memory management in this method is horribly awkward
8012 NSURLConnection **field = NULL;
8013 if (connection == trivial_)
8015 else if (connection == trivial_bz2_)
8016 field = &trivial_bz2_;
8017 else if (connection == trivial_gz_)
8018 field = &trivial_gz_;
8019 _assert(field != NULL);
8020 [connection release];
8025 trivial_bz2_ == nil &&
8031 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
8034 UIAlertView *alert = [[[UIAlertView alloc]
8035 initWithTitle:UCLocalize("SOURCE_WARNING")
8038 cancelButtonTitle:UCLocalize("CANCEL")
8040 UCLocalize("ADD_ANYWAY"),
8044 [alert setContext:@"warning"];
8045 [alert setNumberOfRows:1];
8049 } else if (error_ != nil) {
8050 UIAlertView *alert = [[[UIAlertView alloc]
8051 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8052 message:[error_ localizedDescription]
8054 cancelButtonTitle:UCLocalize("OK")
8055 otherButtonTitles:nil
8058 [alert setContext:@"urlerror"];
8061 UIAlertView *alert = [[[UIAlertView alloc]
8062 initWithTitle:UCLocalize("NOT_REPOSITORY")
8063 message:UCLocalize("NOT_REPOSITORY_EX")
8065 cancelButtonTitle:UCLocalize("OK")
8066 otherButtonTitles:nil
8069 [alert setContext:@"trivial"];
8073 [delegate_ releaseNetworkActivityIndicator];
8075 [delegate_ removeProgressHUD:hud_];
8084 if (error_ != nil) {
8091 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8092 switch ([response statusCode]) {
8098 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8099 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8101 error_ = [error retain];
8102 [self _endConnection:connection];
8105 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8106 [self _endConnection:connection];
8109 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8110 NSMutableURLRequest *request = [NSMutableURLRequest
8111 requestWithURL:[NSURL URLWithString:href]
8112 cachePolicy:NSURLRequestUseProtocolCachePolicy
8113 timeoutInterval:120.0
8116 [request setHTTPMethod:method];
8118 if (Machine_ != NULL)
8119 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8120 if (UniqueID_ != nil)
8121 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8123 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
8125 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8128 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8129 NSString *context([alert context]);
8131 if ([context isEqualToString:@"source"]) {
8134 NSString *href = [[alert textField] text];
8136 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8138 if (![href hasSuffix:@"/"])
8139 href_ = [href stringByAppendingString:@"/"];
8142 href_ = [href_ retain];
8144 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8145 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8146 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8147 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8151 // XXX: this is stupid
8152 hud_ = [[delegate_ addProgressHUD] retain];
8153 [hud_ setText:UCLocalize("VERIFYING_URL")];
8154 [delegate_ retainNetworkActivityIndicator];
8163 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8164 } else if ([context isEqualToString:@"trivial"])
8165 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8166 else if ([context isEqualToString:@"urlerror"])
8167 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8168 else if ([context isEqualToString:@"warning"]) {
8183 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8188 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8190 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
8191 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8192 [list_ setRowHeight:56];
8193 [list_ setDataSource:self];
8194 [list_ setDelegate:self];
8195 [[self view] addSubview:list_];
8198 - (void) viewDidLoad {
8199 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8200 [self updateButtonsForEditingStatus:NO animated:NO];
8203 - (void) releaseSubviews {
8208 - (id) initWithDatabase:(Database *)database {
8209 if ((self = [super init]) != nil) {
8210 database_ = database;
8211 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
8215 - (void) reloadData {
8219 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8222 [sources_ removeAllObjects];
8223 [sources_ addObjectsFromArray:[database_ sources]];
8225 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8228 int count([sources_ count]);
8230 for (int i = 0; i != count; i++) {
8231 if ([[sources_ objectAtIndex:i] record] == nil)
8236 [list_ setEditing:NO];
8237 [self updateButtonsForEditingStatus:NO animated:NO];
8241 - (void) showAddSourcePrompt {
8242 UIAlertView *alert = [[[UIAlertView alloc]
8243 initWithTitle:UCLocalize("ENTER_APT_URL")
8246 cancelButtonTitle:UCLocalize("CANCEL")
8248 UCLocalize("ADD_SOURCE"),
8252 [alert setContext:@"source"];
8253 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
8255 [alert setNumberOfRows:1];
8256 [alert addTextFieldWithValue:@"http://" label:@""];
8258 UITextInputTraits *traits = [[alert textField] textInputTraits];
8259 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8260 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8261 [traits setKeyboardType:UIKeyboardTypeURL];
8262 // XXX: UIReturnKeyDone
8263 [traits setReturnKeyType:UIReturnKeyNext];
8268 - (void) addButtonClicked {
8269 [self showAddSourcePrompt];
8272 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8273 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8274 initWithTitle:UCLocalize("ADD")
8275 style:UIBarButtonItemStylePlain
8277 action:@selector(addButtonClicked)
8278 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8280 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8281 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8282 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8284 action:@selector(editButtonClicked)
8285 ] autorelease] animated:animated];
8287 if (IsWildcat_ && !editing)
8288 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8289 initWithTitle:UCLocalize("SETTINGS")
8290 style:UIBarButtonItemStylePlain
8292 action:@selector(settingsButtonClicked)
8296 - (void) settingsButtonClicked {
8297 [delegate_ showSettings];
8300 - (void) editButtonClicked {
8301 [list_ setEditing:![list_ isEditing] animated:YES];
8303 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8309 /* Settings Controller {{{ */
8310 @interface SettingsController : CYViewController <
8311 UITableViewDataSource,
8314 _transient Database *database_;
8315 // XXX: ok, "roledelegate_"?...
8316 _transient id roledelegate_;
8317 UITableView *table_;
8318 UISegmentedControl *segment_;
8322 - (void) showDoneButton;
8323 - (void) resizeSegmentedControl;
8327 @implementation SettingsController
8330 [self releaseSubviews];
8336 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8338 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
8339 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8340 [table_ setDelegate:self];
8341 [table_ setDataSource:self];
8342 [[self view] addSubview:table_];
8344 NSArray *items = [NSArray arrayWithObjects:
8346 UCLocalize("HACKER"),
8347 UCLocalize("DEVELOPER"),
8349 segment_ = [[UISegmentedControl alloc] initWithItems:items];
8350 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
8351 [container_ addSubview:segment_];
8354 - (void) viewDidLoad {
8355 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8358 if ([Role_ isEqualToString:@"User"]) index = 0;
8359 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8360 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8362 [segment_ setSelectedSegmentIndex:index];
8363 [self showDoneButton];
8366 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8367 [self resizeSegmentedControl];
8370 - (void) releaseSubviews {
8377 [container_ release];
8381 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8382 if ((self = [super init]) != nil) {
8383 database_ = database;
8384 roledelegate_ = delegate;
8388 - (void) resizeSegmentedControl {
8389 CGFloat width = [[self view] frame].size.width;
8390 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8393 - (void) viewWillAppear:(BOOL)animated {
8394 [super viewWillAppear:animated];
8396 [self resizeSegmentedControl];
8399 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8400 [self resizeSegmentedControl];
8403 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8404 [self resizeSegmentedControl];
8408 NSString *role(nil);
8410 switch ([segment_ selectedSegmentIndex]) {
8411 case 0: role = @"User"; break;
8412 case 1: role = @"Hacker"; break;
8413 case 2: role = @"Developer"; break;
8418 if (![role isEqualToString:Role_]) {
8419 bool rolling(Role_ == nil);
8422 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8426 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8430 [roledelegate_ loadData];
8432 [roledelegate_ updateData];
8436 - (void) segmentChanged:(UISegmentedControl *)control {
8437 [self showDoneButton];
8440 - (void) saveAndClose {
8443 [[self navigationItem] setRightBarButtonItem:nil];
8444 [[self navigationController] dismissModalViewControllerAnimated:YES];
8447 - (void) doneButtonClicked {
8448 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8449 [spinner startAnimating];
8450 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8451 [[self navigationItem] setRightBarButtonItem:spinItem];
8453 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8456 - (void) showDoneButton {
8457 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8458 initWithTitle:UCLocalize("DONE")
8459 style:UIBarButtonItemStyleDone
8461 action:@selector(doneButtonClicked)
8462 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8465 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8466 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8470 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8474 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8475 return nil; // This method is required by the protocol.
8478 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8480 return UCLocalize("ROLE_EX");
8482 return [NSString stringWithFormat:
8483 @"%@: %@\n%@: %@\n%@: %@",
8484 UCLocalize("USER"), UCLocalize("USER_EX"),
8485 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8486 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8491 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8492 return section == 3 ? 44.0f : 0;
8495 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8496 return section == 3 ? container_ : nil;
8499 - (void) reloadData {
8501 [table_ reloadData];
8506 /* Stash Controller {{{ */
8507 @interface StashController : CYViewController {
8508 UIActivityIndicatorView *spinner_;
8515 @implementation StashController
8518 [self releaseSubviews];
8524 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8525 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8527 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8528 CGRect spinrect = [spinner_ frame];
8529 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8530 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8531 [spinner_ setFrame:spinrect];
8532 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8533 [[self view] addSubview:spinner_];
8534 [spinner_ startAnimating];
8537 captrect.size.width = [[self view] frame].size.width;
8538 captrect.size.height = 40.0f;
8539 captrect.origin.x = 0;
8540 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8541 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8542 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8543 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8544 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8545 [caption_ setTextColor:[UIColor whiteColor]];
8546 [caption_ setBackgroundColor:[UIColor clearColor]];
8547 [caption_ setShadowColor:[UIColor blackColor]];
8548 [caption_ setTextAlignment:UITextAlignmentCenter];
8549 [[self view] addSubview:caption_];
8552 statusrect.size.width = [[self view] frame].size.width;
8553 statusrect.size.height = 30.0f;
8554 statusrect.origin.x = 0;
8555 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8556 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8557 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8558 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8559 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8560 [status_ setTextColor:[UIColor whiteColor]];
8561 [status_ setBackgroundColor:[UIColor clearColor]];
8562 [status_ setShadowColor:[UIColor blackColor]];
8563 [status_ setTextAlignment:UITextAlignmentCenter];
8564 [[self view] addSubview:status_];
8567 - (void) releaseSubviews {
8581 @interface Cydia : UIApplication <
8582 ConfirmationControllerDelegate,
8585 UINavigationControllerDelegate,
8586 UITabBarControllerDelegate
8588 // XXX: evaluate all fields for _transient
8591 CYTabBarController *tabbar_;
8592 CYEmulatedLoadingController *emulated_;
8594 NSMutableArray *essential_;
8595 NSMutableArray *broken_;
8597 Database *database_;
8604 StashController *stash_;
8613 @implementation Cydia
8615 - (void) beginUpdate {
8616 [tabbar_ beginUpdate];
8620 return [tabbar_ updating];
8624 if ([broken_ count] != 0) {
8625 int count = [broken_ count];
8627 UIAlertView *alert = [[[UIAlertView alloc]
8628 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8629 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8631 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8633 UCLocalize("TEMPORARY_IGNORE"),
8637 [alert setContext:@"fixhalf"];
8639 } else if (!Ignored_ && [essential_ count] != 0) {
8640 int count = [essential_ count];
8642 UIAlertView *alert = [[[UIAlertView alloc]
8643 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8644 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8646 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8648 UCLocalize("UPGRADE_ESSENTIAL"),
8649 UCLocalize("COMPLETE_UPGRADE"),
8653 [alert setContext:@"upgrade"];
8658 - (void) _saveConfig {
8664 NSString *error(nil);
8666 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8668 NSError *error(nil);
8669 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8670 NSLog(@"failure to save metadata data: %@", error);
8675 NSLog(@"failure to serialize metadata: %@", error);
8680 // Navigation controller for the queuing badge.
8681 - (CYNavigationController *) queueNavigationController {
8682 NSArray *controllers = [tabbar_ viewControllers];
8683 return [controllers objectAtIndex:3];
8686 - (void) _updateData {
8689 [tabbar_ reloadData];
8691 CYNavigationController *navigation = [self queueNavigationController];
8693 id queuedelegate = nil;
8694 if ([[navigation viewControllers] count] > 0)
8695 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8697 [queuedelegate queueStatusDidChange];
8698 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8701 - (void) _refreshIfPossible:(NSDate *)update {
8702 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8704 bool recently = false;
8705 if (update != nil) {
8706 NSTimeInterval interval([update timeIntervalSinceNow]);
8707 if (interval <= 0 && interval > -(15*60))
8711 // Don't automatic refresh if:
8712 // - We already refreshed recently.
8713 // - We already auto-refreshed this launch.
8714 // - Auto-refresh is disabled.
8715 if (recently || loaded_ || ManualRefresh) {
8716 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8718 // If we are cancelling, we need to make sure it knows it's already loaded.
8722 // We are going to load, so remember that.
8726 SCNetworkReachabilityFlags flags; {
8727 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8728 SCNetworkReachabilityGetFlags(reachability, &flags);
8729 CFRelease(reachability);
8732 // XXX: this elaborate mess is what Apple is using to determine this? :(
8733 // XXX: do we care if the user has to intervene? maybe that's ok?
8735 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8736 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8737 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8738 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8739 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8740 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8744 // If we can reach the server, auto-refresh!
8746 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8751 - (void) refreshIfPossible {
8752 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
8755 - (void) _reloadDataWithInvocation:(NSInvocation *)invocation {
8756 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8757 [hud setText:UCLocalize("RELOADING_DATA")];
8759 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
8762 [self removeProgressHUD:hud];
8766 [essential_ removeAllObjects];
8767 [broken_ removeAllObjects];
8769 NSArray *packages([database_ packages]);
8770 for (Package *package in packages) {
8772 [broken_ addObject:package];
8773 if ([package upgradableAndEssential:NO]) {
8774 if ([package essential])
8775 [essential_ addObject:package];
8780 NSLog(@"changes:#%u", changes);
8782 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
8785 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8786 [changesItem setBadgeValue:badge];
8787 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8788 [self setApplicationIconBadgeNumber:changes];
8791 [changesItem setBadgeValue:nil];
8792 [changesItem setAnimatedBadge:NO];
8793 [self setApplicationIconBadgeNumber:0];
8798 [self refreshIfPossible];
8801 - (void) updateData {
8810 @synchronized (self) {
8811 [self _reloadDataWithInvocation:nil];
8815 - (void) presentModalViewController:(UIViewController *)controller {
8816 UINavigationController *navigation([[[CYNavigationController alloc] initWithRootViewController:controller] autorelease]);
8818 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8819 [((UIViewController *) emulated_ ?: tabbar_) presentModalViewController:navigation animated:YES];
8822 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
8823 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
8825 if (navigation != nil)
8826 [navigation pushViewController:progress animated:YES];
8828 [self presentModalViewController:progress];
8830 [progress invoke:invocation withTitle:title];
8834 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
8835 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
8838 - (void) repairWithInvocation:(NSInvocation *)invocation {
8840 [self invokeNewProgress:invocation forController:nil withTitle:UCLocalize("REPAIRING")];
8844 - (void) repairWithSelector:(SEL)selector {
8845 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
8851 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8852 _assert(file != NULL);
8854 for (NSString *key in [Sources_ allKeys]) {
8855 NSDictionary *source([Sources_ objectForKey:key]);
8857 fprintf(file, "%s %s %s\n",
8858 [[source objectForKey:@"Type"] UTF8String],
8859 [[source objectForKey:@"URI"] UTF8String],
8860 [[source objectForKey:@"Distribution"] UTF8String]
8866 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:UCLocalize("UPDATING_SOURCES")];
8871 - (void) addTrivialSource:(NSString *)href {
8872 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
8875 @"./", @"Distribution",
8876 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href]];
8881 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
8882 @synchronized (self) {
8883 [self _reloadDataWithInvocation:invocation];
8887 - (void) reloadData {
8888 [self reloadDataWithInvocation:nil];
8892 pkgProblemResolver *resolver = [database_ resolver];
8894 resolver->InstallProtect();
8895 if (!resolver->Resolve(true))
8900 // XXX: this is a really crappy way of doing this.
8901 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
8902 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
8903 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
8904 if ([tabbar_ updating])
8905 [tabbar_ cancelUpdate];
8907 if (![database_ prepare])
8910 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8911 [page setDelegate:self];
8912 CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]);
8913 [confirm_ setDelegate:self];
8916 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8917 [tabbar_ presentModalViewController:confirm_ animated:YES];
8923 @synchronized (self) {
8928 - (void) clearPackage:(Package *)package {
8929 @synchronized (self) {
8936 - (void) installPackages:(NSArray *)packages {
8937 @synchronized (self) {
8938 for (Package *package in packages)
8945 - (void) installPackage:(Package *)package {
8946 @synchronized (self) {
8953 - (void) removePackage:(Package *)package {
8954 @synchronized (self) {
8961 - (void) distUpgrade {
8962 @synchronized (self) {
8963 if (![database_ upgrade])
8969 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8972 [self detachNewProgressSelector:@selector(perform) toTarget:database_ forController:navigation title:UCLocalize("RUNNING")];
8977 - (void) showSettings {
8978 SettingsController *role = [[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease];
8979 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
8981 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
8982 [tabbar_ presentModalViewController:nav animated:YES];
8985 - (void) retainNetworkActivityIndicator {
8986 if (activity_++ == 0)
8987 [self setNetworkActivityIndicatorVisible:YES];
8990 - (void) releaseNetworkActivityIndicator {
8991 if (--activity_ == 0)
8992 [self setNetworkActivityIndicatorVisible:NO];
8995 - (void) cancelAndClear:(bool)clear {
8996 @synchronized (self) {
9008 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9009 NSString *context([alert context]);
9011 if ([context isEqualToString:@"conffile"]) {
9012 FILE *input = [database_ input];
9013 if (button == [alert cancelButtonIndex])
9014 fprintf(input, "N\n");
9015 else if (button == [alert firstOtherButtonIndex])
9016 fprintf(input, "Y\n");
9019 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9020 } else if ([context isEqualToString:@"fixhalf"]) {
9021 if (button == [alert cancelButtonIndex]) {
9022 @synchronized (self) {
9023 for (Package *broken in broken_) {
9026 NSString *id = [broken id];
9027 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9028 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9029 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9030 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9036 } else if (button == [alert firstOtherButtonIndex]) {
9037 [broken_ removeAllObjects];
9041 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9042 } else if ([context isEqualToString:@"upgrade"]) {
9043 if (button == [alert firstOtherButtonIndex]) {
9044 @synchronized (self) {
9045 for (Package *essential in essential_)
9046 [essential install];
9051 } else if (button == [alert firstOtherButtonIndex] + 1) {
9053 } else if (button == [alert cancelButtonIndex]) {
9057 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9061 - (void) system:(NSString *)command { _pooled
9063 system([command UTF8String]);
9067 - (void) applicationWillSuspend {
9069 [super applicationWillSuspend];
9072 - (BOOL) isSafeToSuspend {
9073 // Use external process status API internally.
9074 // This is probably a really bad idea.
9075 // XXX: what is the point of this? does this solve anything at all?
9076 uint64_t status = 0;
9078 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9079 notify_get_state(notify_token, &status);
9080 notify_cancel(notify_token);
9083 return locked_ == 0 && status == 0;
9086 - (void) applicationSuspend:(__GSEvent *)event {
9087 if ([self isSafeToSuspend])
9088 [super applicationSuspend:event];
9091 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9092 if ([self isSafeToSuspend])
9093 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9096 - (void) _setSuspended:(BOOL)value {
9097 if ([self isSafeToSuspend])
9098 [super _setSuspended:value];
9101 - (UIProgressHUD *) addProgressHUD {
9102 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
9103 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9105 [window_ setUserInteractionEnabled:NO];
9108 UIViewController *target = tabbar_;
9109 while ([target modalViewController] != nil) target = [target modalViewController];
9110 [[target view] addSubview:hud];
9116 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9118 [hud removeFromSuperview];
9119 [window_ setUserInteractionEnabled:YES];
9123 - (CYViewController *) pageForPackage:(NSString *)name {
9124 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9127 - (CYViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9128 NSString *scheme([[url scheme] lowercaseString]);
9129 if ([[url absoluteString] length] <= [scheme length] + 3)
9131 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9132 NSArray *components([path pathComponents]);
9134 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9135 return [self pageForPackage:[components objectAtIndex:1]];
9137 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9140 NSString *base([components objectAtIndex:0]);
9142 CYViewController *controller = nil;
9144 if ([base isEqualToString:@"url"]) {
9145 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9146 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9147 controller = [[[CYBrowserController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9148 } else if (!external && [components count] == 1) {
9149 if ([base isEqualToString:@"manage"]) {
9150 controller = [[[ManageController alloc] init] autorelease];
9153 if ([base isEqualToString:@"sources"]) {
9154 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9157 if ([base isEqualToString:@"home"]) {
9158 controller = [[[HomeController alloc] init] autorelease];
9161 if ([base isEqualToString:@"sections"]) {
9162 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9165 if ([base isEqualToString:@"search"]) {
9166 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9169 if ([base isEqualToString:@"changes"]) {
9170 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9173 if ([base isEqualToString:@"installed"]) {
9174 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9176 } else if ([components count] == 2) {
9177 NSString *argument = [components objectAtIndex:1];
9179 if ([base isEqualToString:@"package"]) {
9180 controller = [self pageForPackage:argument];
9183 if (!external && [base isEqualToString:@"search"]) {
9184 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
9185 [(SearchController *)controller setSearchTerm:argument];
9188 if (!external && [base isEqualToString:@"sections"]) {
9189 if ([argument isEqualToString:@"all"])
9191 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9194 if (!external && [base isEqualToString:@"sources"]) {
9195 if ([argument isEqualToString:@"add"]) {
9196 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9197 [(SourcesController *)controller showAddSourcePrompt];
9199 Source *source = [database_ sourceWithKey:argument];
9200 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9204 if (!external && [base isEqualToString:@"launch"]) {
9205 [self launchApplicationWithIdentifier:argument suspended:NO];
9208 } else if (!external && [components count] == 3) {
9209 NSString *arg1 = [components objectAtIndex:1];
9210 NSString *arg2 = [components objectAtIndex:2];
9212 if ([base isEqualToString:@"package"]) {
9213 if ([arg2 isEqualToString:@"settings"]) {
9214 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9215 } else if ([arg2 isEqualToString:@"files"]) {
9216 if (Package *package = [database_ packageWithName:arg1]) {
9217 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9218 [(FileTable *)controller setPackage:package];
9224 [controller setDelegate:self];
9228 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9229 CYViewController *page([self pageForURL:url forExternal:external]);
9232 CYNavigationController *nav = [[[CYNavigationController alloc] init] autorelease];
9233 [nav setViewControllers:[NSArray arrayWithObject:page]];
9234 [tabbar_ setUnselectedViewController:nav];
9240 - (void) applicationOpenURL:(NSURL *)url {
9241 [super applicationOpenURL:url];
9243 if (!loaded_) starturl_ = [url retain];
9244 else [self openCydiaURL:url forExternal:YES];
9247 - (void) applicationWillResignActive:(UIApplication *)application {
9248 // Stop refreshing if you get a phone call or lock the device.
9249 if ([tabbar_ updating])
9250 [tabbar_ cancelUpdate];
9252 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9253 [super applicationWillResignActive:application];
9256 - (void) applicationWillTerminate:(UIApplication *)application {
9258 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9259 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9260 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9265 - (void) setConfigurationData:(NSString *)data {
9266 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9268 if (!conffile_r(data)) {
9269 lprintf("E:invalid conffile\n");
9273 NSString *ofile = conffile_r[1];
9274 //NSString *nfile = conffile_r[2];
9276 UIAlertView *alert = [[[UIAlertView alloc]
9277 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9278 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9280 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9282 UCLocalize("ACCEPT_NEW_COPY"),
9283 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9287 [alert setContext:@"conffile"];
9291 - (void) addStashController {
9293 stash_ = [[StashController alloc] init];
9294 [window_ addSubview:[stash_ view]];
9297 - (void) removeStashController {
9298 [[stash_ view] removeFromSuperview];
9304 [self setIdleTimerDisabled:YES];
9306 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9307 UpdateExternalStatus(1);
9308 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9309 UpdateExternalStatus(0);
9311 [self removeStashController];
9313 if (ExecFork() == 0) {
9314 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9315 perror("launchctl stop");
9319 - (void) setupViewControllers {
9320 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
9322 NSMutableArray *items([NSMutableArray arrayWithObjects:
9323 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9324 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9325 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9326 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9330 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9331 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9333 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9336 NSMutableArray *controllers([NSMutableArray array]);
9337 for (UITabBarItem *item in items) {
9338 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
9339 [controller setTabBarItem:item];
9340 [controllers addObject:controller];
9342 [tabbar_ setViewControllers:controllers];
9344 [tabbar_ setUpdateDelegate:self];
9347 - (void) applicationDidFinishLaunching:(id)unused {
9349 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9350 [self setApplicationSupportsShakeToEdit:NO];
9352 [NSURLCache setSharedURLCache:[[[SDURLCache alloc]
9353 initWithMemoryCapacity:524288
9354 diskCapacity:10485760
9355 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9358 [CYBrowserController _initialize];
9360 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9362 Font12_ = [[UIFont systemFontOfSize:12] retain];
9363 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
9364 Font14_ = [[UIFont systemFontOfSize:14] retain];
9365 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
9366 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
9368 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
9369 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
9371 window_ = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
9372 [window_ orderFront:self];
9373 [window_ makeKey:self];
9374 [window_ setHidden:NO];
9377 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9378 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9379 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9380 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9381 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9382 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9383 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9384 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9385 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9388 [self addStashController];
9389 // XXX: this would be much cleaner as a yieldToSelector:
9390 // that way the removeStashController could happen right here inline
9391 // we also could no longer require the useless stash_ field anymore
9392 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9396 database_ = [Database sharedInstance];
9397 [database_ setDelegate:self];
9399 [window_ setUserInteractionEnabled:NO];
9400 [self setupViewControllers];
9402 emulated_ = [[CYEmulatedLoadingController alloc] initWithDatabase:database_];
9403 [window_ addSubview:[emulated_ view]];
9405 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9412 [window_ setUserInteractionEnabled:YES];
9413 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease]];
9416 if ([emulated_ modalViewController] != nil)
9417 [emulated_ dismissModalViewControllerAnimated:YES];
9418 [window_ setUserInteractionEnabled:NO];
9424 [window_ addSubview:[tabbar_ view]];
9426 [[emulated_ view] removeFromSuperview];
9427 [emulated_ release];
9430 [window_ setUserInteractionEnabled:YES];
9432 int selectedIndex = 0;
9433 NSMutableArray *items = nil;
9435 bool recently = false;
9436 NSDate *closed([Metadata_ objectForKey:@"LastClosed"]);
9437 if (closed != nil) {
9438 NSTimeInterval interval([closed timeIntervalSinceNow]);
9439 // XXX: Is 15 minutes the optimal time here?
9440 if (interval <= 0 && interval > -(15*60))
9444 items = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9445 selectedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9448 for (NSArray *entry in items)
9449 if ([entry count] <= 0)
9452 if (!recently || !items || !enough) {
9454 items = [NSMutableArray array];
9455 [items addObject:[NSArray arrayWithObject:@"cydia://home"]];
9456 [items addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9457 [items addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9459 [items addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9461 [items addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9462 [items addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9464 [items addObject:[NSArray arrayWithObject:@"cydia://search"]];
9467 [tabbar_ setSelectedIndex:selectedIndex];
9468 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9469 NSArray *stack = [items objectAtIndex:tab];
9470 CYNavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9471 NSMutableArray *current = [NSMutableArray array];
9473 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9474 NSString *addr = [stack objectAtIndex:nav];
9475 NSURL *url = [NSURL URLWithString:addr];
9476 CYViewController *page = [self pageForURL:url forExternal:NO];
9478 [current addObject:page];
9481 [navigation setViewControllers:current];
9484 // (Try to) show the startup URL.
9485 if (starturl_ != nil) {
9486 [self openCydiaURL:starturl_ forExternal:NO];
9487 [starturl_ release];
9492 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9493 if (item != nil && IsWildcat_) {
9494 [sheet showFromBarButtonItem:item animated:YES];
9496 [sheet showInView:window_];
9500 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9501 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9502 [progress setTitle:task];
9503 [progress addProgressEvent:event];
9506 - (void) addProgressEventForTask:(NSArray *)data {
9507 CydiaProgressEvent *event([data objectAtIndex:0]);
9508 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9509 [self addProgressEvent:event forTask:task];
9512 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9513 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9519 id Alloc_(id self, SEL selector) {
9520 id object = alloc_(self, selector);
9521 lprintf("[%s]A-%p\n", self->isa->name, object);
9526 id Dealloc_(id self, SEL selector) {
9527 id object = dealloc_(self, selector);
9528 lprintf("[%s]D-%p\n", self->isa->name, object);
9532 Class $WebDefaultUIKitDelegate;
9534 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9535 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9536 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9537 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9540 static NSNumber *shouldPlayKeyboardSounds;
9544 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
9546 case 1104: // Keyboard Button Clicked
9547 case 1105: // Keyboard Delete Repeated
9548 if (shouldPlayKeyboardSounds == nil) {
9549 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
9550 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
9553 if (![shouldPlayKeyboardSounds boolValue])
9557 _UIHardware$_playSystemSound$(self, _cmd, sound);
9561 Class $UIApplication;
9563 MSHook(void, UIApplication$_updateApplicationAccessibility, UIApplication *self, SEL _cmd) {
9564 static BOOL initialized = NO;
9565 static BOOL started = NO;
9567 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.Accessibility.plist"] autorelease]);
9568 BOOL enabled = [[dict objectForKey:@"VoiceOverTouchEnabled"] boolValue] || [[dict objectForKey:@"VoiceOverTouchEnabledByiTunes"] boolValue];
9570 if ([self respondsToSelector:@selector(_accessibilityBundlePrincipalClass)]) {
9571 id bundle = [self performSelector:@selector(_accessibilityBundlePrincipalClass)];
9572 if (![bundle respondsToSelector:@selector(_accessibilityStopServer)]) return;
9573 if (![bundle respondsToSelector:@selector(_accessibilityStartServer)]) return;
9575 if (initialized && !enabled) {
9577 [bundle performSelector:@selector(_accessibilityStopServer)];
9578 } else if (enabled) {
9582 [bundle performSelector:@selector(_accessibilityStartServer)];
9588 int main(int argc, char *argv[]) { _pooled
9591 UpdateExternalStatus(0);
9593 if (Class $UIDevice = objc_getClass("UIDevice")) {
9594 UIDevice *device([$UIDevice currentDevice]);
9595 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
9599 UIScreen *screen([UIScreen mainScreen]);
9600 if ([screen respondsToSelector:@selector(scale)])
9601 ScreenScale_ = [screen scale];
9605 NSMutableArray *parts([NSMutableArray arrayWithCapacity:2]);
9606 if (ScreenScale_ > 1)
9607 [parts addObject:@"@2x"];
9608 [parts addObject:(IsWildcat_ ? @"~ipad" : @"~iphone")];
9609 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios%@", [parts componentsJoinedByString:@""]]);
9611 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9613 /* Library Hacks {{{ */
9614 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
9616 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
9617 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
9618 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
9619 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
9620 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
9623 $UIHardware = objc_getClass("UIHardware");
9624 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
9625 if (UIHardware$_playSystemSound$ != NULL) {
9626 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
9627 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
9630 $UIApplication = objc_getClass("UIApplication");
9631 Method UIApplication$_updateApplicationAccessibility(class_getInstanceMethod($UIApplication, @selector(_updateApplicationAccessibility)));
9632 if (UIApplication$_updateApplicationAccessibility != NULL) {
9633 _UIApplication$_updateApplicationAccessibility = reinterpret_cast<void (*)(UIApplication *, SEL)>(method_getImplementation(UIApplication$_updateApplicationAccessibility));
9634 method_setImplementation(UIApplication$_updateApplicationAccessibility, reinterpret_cast<IMP>(&$UIApplication$_updateApplicationAccessibility));
9637 /* Set Locale {{{ */
9638 Locale_ = CFLocaleCopyCurrent();
9639 Languages_ = [NSLocale preferredLanguages];
9640 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
9641 //NSLog(@"%@", [Languages_ description]);
9644 if (Languages_ == nil || [Languages_ count] == 0)
9645 // XXX: consider just setting to C and then falling through?
9648 lang = [[Languages_ objectAtIndex:0] UTF8String];
9649 setenv("LANG", lang, true);
9652 //std::setlocale(LC_ALL, lang);
9653 NSLog(@"Setting Language: %s", lang);
9656 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
9658 /* Parse Arguments {{{ */
9659 bool substrate(false);
9665 for (int argi(1); argi != argc; ++argi)
9666 if (strcmp(argv[argi], "--") == 0) {
9668 argv[argi] = argv[0];
9674 for (int argi(1); argi != arge; ++argi)
9675 if (strcmp(args[argi], "--substrate") == 0)
9678 fprintf(stderr, "unknown argument: %s\n", args[argi]);
9682 App_ = [[NSBundle mainBundle] bundlePath];
9683 Home_ = NSHomeDirectory();
9689 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
9690 alloc_ = alloc->method_imp;
9691 alloc->method_imp = (IMP) &Alloc_;*/
9693 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
9694 dealloc_ = dealloc->method_imp;
9695 dealloc->method_imp = (IMP) &Dealloc_;*/
9697 /* System Information {{{ */
9701 size = sizeof(maxproc);
9702 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9703 perror("sysctlbyname(\"kern.maxproc\", ?)");
9704 else if (maxproc < 64) {
9706 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9707 perror("sysctlbyname(\"kern.maxproc\", #)");
9710 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
9711 char *osversion = new char[size];
9712 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
9713 perror("sysctlbyname(\"kern.osversion\", ?)");
9715 System_ = [NSString stringWithUTF8String:osversion];
9717 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
9718 char *machine = new char[size];
9719 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
9720 perror("sysctlbyname(\"hw.machine\", ?)");
9724 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
9725 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
9726 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
9727 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
9731 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
9732 NSData *data((NSData *) ecid);
9733 size_t length([data length]);
9734 uint8_t bytes[length];
9735 [data getBytes:bytes];
9736 char string[length * 2 + 1];
9737 for (size_t i(0); i != length; ++i)
9738 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
9739 ChipID_ = [NSString stringWithUTF8String:string];
9743 IOObjectRelease(service);
9747 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
9749 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
9750 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9751 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
9753 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
9754 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9755 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
9757 if (mcc != NULL && mnc != NULL)
9758 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9765 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9766 Build_ = [system objectForKey:@"ProductBuildVersion"];
9767 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9768 Product_ = [info objectForKey:@"SafariProductVersion"];
9769 Safari_ = [info objectForKey:@"CFBundleVersion"];
9772 /* Load Database {{{ */
9774 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9776 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9778 if (Metadata_ == NULL)
9779 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9781 Settings_ = [Metadata_ objectForKey:@"Settings"];
9783 Packages_ = [Metadata_ objectForKey:@"Packages"];
9784 Sections_ = [Metadata_ objectForKey:@"Sections"];
9785 Sources_ = [Metadata_ objectForKey:@"Sources"];
9787 Token_ = [Metadata_ objectForKey:@"Token"];
9790 if (Settings_ != nil)
9791 Role_ = [Settings_ objectForKey:@"Role"];
9793 if (Sections_ == nil) {
9794 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9795 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9798 if (Sources_ == nil) {
9799 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9800 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9805 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
9808 if (Packages_ != nil) {
9810 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
9814 [Metadata_ removeObjectForKey:@"Packages"];
9820 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9822 #define MobileSubstrate_(name) \
9823 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) \
9824 dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL);
9826 MobileSubstrate_(Activator)
9827 MobileSubstrate_(libstatusbar)
9828 MobileSubstrate_(SimulatedKeyEvents)
9829 MobileSubstrate_(WinterBoard)
9831 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9832 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9834 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9836 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9837 unlink("/tmp/.cydia.fw");
9839 } else if (access("/User", F_OK) != 0 || version < 2) {
9842 system("/usr/libexec/cydia/firmware.sh");
9846 _assert([[NSFileManager defaultManager]
9847 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9848 withIntermediateDirectories:YES
9853 if (access("/tmp/cydia.chk", F_OK) == 0) {
9854 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9855 _assert(errno == ENOENT);
9856 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9857 _assert(errno == ENOENT);
9860 /* APT Initialization {{{ */
9861 _assert(pkgInitConfig(*_config));
9862 _assert(pkgInitSystem(*_config, _system));
9865 _config->Set("APT::Acquire::Translation", lang);
9867 // XXX: this timeout might be important :(
9868 //_config->Set("Acquire::http::Timeout", 15);
9870 _config->Set("Acquire::http::MaxParallel", 3);
9872 /* Color Choices {{{ */
9873 space_ = CGColorSpaceCreateDeviceRGB();
9875 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9876 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9877 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9878 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9879 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9880 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9881 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9882 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9883 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9885 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9886 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9888 /* UIKit Configuration {{{ */
9889 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9890 if ($GSFontSetUseLegacyFontMetrics != NULL)
9891 $GSFontSetUseLegacyFontMetrics(YES);
9893 // XXX: I have a feeling this was important
9894 //UIKeyboardDisableAutomaticAppearance();
9897 Colon_ = UCLocalize("COLON_DELIMITED");
9898 Elision_ = UCLocalize("ELISION");
9899 Error_ = UCLocalize("ERROR");
9900 Warning_ = UCLocalize("WARNING");
9903 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9905 CGColorSpaceRelease(space_);