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 "CyteKit/UCPlatform.h"
45 #include "CyteKit/Localize.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>
121 #include <Cytore.hpp>
123 #include "CyteKit/PerlCompatibleRegEx.hpp"
124 #include "CyteKit/WebScriptObject-Cyte.h"
125 #include "CyteKit/WebViewController.h"
126 #include "CyteKit/stringWithUTF8Bytes.h"
128 #include "Menes/Menes.h"
130 #include "SDURLCache/SDURLCache.h"
132 #include <CydiaSubstrate/CydiaSubstrate.h>
139 #define _timestamp ({ \
141 gettimeofday(&tv, NULL); \
142 tv.tv_sec * 1000000 + tv.tv_usec; \
145 typedef std::vector<class ProfileTime *> TimeList;
155 ProfileTime(const char *name) :
159 times_.push_back(this);
162 void AddTime(uint64_t time) {
169 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
181 ProfileTimer(ProfileTime &time) :
188 time_.AddTime(_timestamp - start_);
193 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
195 std::cerr << "========" << std::endl;
198 #define _profile(name) { \
199 static ProfileTime name(#name); \
200 ProfileTimer _ ## name(name);
205 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
207 #define CYPoolStart() \
208 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
210 #define CYPoolEnd() \
214 #define Cydia_ CYDIA_VERSION
216 #define lprintf(args...) fprintf(stderr, args)
219 #define TraceLogging (1 && !ForRelease)
220 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
221 #define ProfileTimes (0 && !ForRelease)
222 #define ForSaurik (0 && !ForRelease)
223 #define LogBrowser (0 && !ForRelease)
224 #define TrackResize (0 && !ForRelease)
225 #define ManualRefresh (1 && !ForRelease)
226 #define ShowInternals (0 && !ForRelease)
227 #define AlwaysReload (0 && !ForRelease)
228 #define TryIndexedCollation (0 && !ForRelease)
232 #define _trace(args...)
237 #define _profile(name) {
240 #define PrintTimes() do {} while (false)
243 // Hash Functions/Structures {{{
244 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
252 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
254 static _finline NSString *CydiaURL(NSString *path) {
256 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
257 page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
258 page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
259 page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
260 page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
262 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
265 static _finline void UpdateExternalStatus(uint64_t newStatus) {
267 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
268 notify_set_state(notify_token, newStatus);
269 notify_cancel(notify_token);
271 notify_post("com.saurik.Cydia.status");
275 /* Cydia Alert View {{{ */
276 @interface CYAlertView : UIAlertView {
280 - (int) yieldToPopupAlertAnimated:(BOOL)animated;
284 @implementation CYAlertView
286 - (id) initWithTitle:(NSString *)title buttons:(NSArray *)buttons defaultButtonIndex:(int)index {
287 if ((self = [super init]) != nil) {
288 [self setTitle:title];
289 [self setDelegate:self];
290 for (NSString *button in buttons) [self addButtonWithTitle:button];
291 [self setCancelButtonIndex:index];
295 - (void) _updateFrameForDisplay {
296 [super _updateFrameForDisplay];
297 if ([self cancelButtonIndex] == -1) {
298 NSArray *buttons = [self buttons];
299 if ([buttons count]) {
300 UIImage *background = [[buttons objectAtIndex:0] backgroundForState:0];
301 for (UIThreePartButton *button in buttons)
302 [button setBackground:background forState:0];
307 - (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
308 button_ = buttonIndex + 1;
312 [self dismissWithClickedButtonIndex:-1 animated:YES];
315 - (int) yieldToPopupAlertAnimated:(BOOL)animated {
316 [self setRunsModal:YES];
325 /* NSForcedOrderingSearch doesn't work on the iPhone */
326 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
327 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
328 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
331 typedef uint32_t (*SKRadixFunction)(id, void *);
333 @interface NSMutableArray (Radix)
334 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
342 @implementation NSMutableArray (Radix)
344 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
345 size_t count([self count]);
346 struct RadixItem_ *swap(new RadixItem_[count * 2]);
348 for (size_t i(0); i != count; ++i) {
349 RadixItem_ &item(swap[i]);
352 id object([self objectAtIndex:i]);
353 item.key = function(object, argument);
356 struct RadixItem_ *lhs(swap), *rhs(swap + count);
358 static const size_t width = 32;
359 static const size_t bits = 11;
360 static const size_t slots = 1 << bits;
361 static const size_t passes = (width + (bits - 1)) / bits;
363 size_t *hist(new size_t[slots]);
365 for (size_t pass(0); pass != passes; ++pass) {
366 memset(hist, 0, sizeof(size_t) * slots);
368 for (size_t i(0); i != count; ++i) {
369 uint32_t key(lhs[i].key);
371 key &= _not(uint32_t) >> width - bits;
376 for (size_t i(0); i != slots; ++i) {
377 size_t local(offset);
382 for (size_t i(0); i != count; ++i) {
383 uint32_t key(lhs[i].key);
385 key &= _not(uint32_t) >> width - bits;
386 rhs[hist[key]++] = lhs[i];
389 RadixItem_ *tmp(lhs);
396 const void **values(new const void *[count]);
397 for (size_t i(0); i != count; ++i)
398 values[i] = [self objectAtIndex:lhs[i].index];
399 CFArrayReplaceValues((CFMutableArrayRef) self, CFRangeMake(0, count), values, count);
407 /* Insertion Sort {{{ */
409 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
410 const char *ptr = (const char *)list;
412 CFIndex half = count / 2;
413 const char *probe = ptr + elementSize * half;
414 CFComparisonResult cr = comparator(element, probe, context);
415 if (0 == cr) return (probe - (const char *)list) / elementSize;
416 ptr = (cr < 0) ? ptr : probe + elementSize;
417 count = (cr < 0) ? half : (half + (count & 1) - 1);
419 return (ptr - (const char *)list) / elementSize;
422 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
423 const char *ptr = (const char *)list;
425 CFIndex half = count / 2;
426 const char *probe = ptr + elementSize * half;
427 CFComparisonResult cr = comparator(element, probe, context);
428 if (0 == cr) return (probe - (const char *)list) / elementSize;
429 ptr = (cr < 0) ? ptr : probe + elementSize;
430 count = (cr < 0) ? half : (half + (count & 1) - 1);
432 return (ptr - (const char *)list) / elementSize;
435 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
436 if (range.length == 0)
438 const void **values(new const void *[range.length]);
439 CFArrayGetValues(array, range, values);
441 #if HistogramInsertionSort > 0
442 uint32_t total(0), *offsets(new uint32_t[range.length]);
445 for (CFIndex index(1); index != range.length; ++index) {
446 const void *value(values[index]);
447 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
448 CFIndex correct(index);
449 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
450 #if HistogramInsertionSort > 1
451 NSLog(@"%@ < %@", value, values[correct - 1]);
456 if (correct != index) {
457 size_t offset(index - correct);
458 #if HistogramInsertionSort
462 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
464 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
465 values[correct] = value;
469 CFArrayReplaceValues(array, range, values, range.length);
472 #if HistogramInsertionSort > 0
473 for (CFIndex index(0); index != range.length; ++index)
474 if (offsets[index] != 0)
475 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
476 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
483 /* Apple Bug Fixes {{{ */
484 @implementation UIWebDocumentView (Cydia)
486 - (void) _setScrollerOffset:(CGPoint)offset {
487 UIScroller *scroller([self _scroller]);
489 CGSize size([scroller contentSize]);
490 CGSize bounds([scroller bounds].size);
493 max.x = size.width - bounds.width;
494 max.y = size.height - bounds.height;
502 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
503 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
505 [scroller setOffset:offset];
511 @interface NSInvocation (Cydia)
512 + (NSInvocation *) invocationWithSelector:(SEL)selector forTarget:(id)target;
515 @implementation NSInvocation (Cydia)
517 + (NSInvocation *) invocationWithSelector:(SEL)selector forTarget:(id)target {
518 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[target methodSignatureForSelector:selector]]);
519 [invocation setTarget:target];
520 [invocation setSelector:selector];
526 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
527 size_t length([self length] - state->state);
530 else if (length > count)
532 for (size_t i(0); i != length; ++i)
533 objects[i] = [self item:state->state++];
534 state->itemsPtr = objects;
535 state->mutationsPtr = (unsigned long *) self;
539 /* Cydia NSString Additions {{{ */
540 @interface NSString (Cydia)
541 - (NSComparisonResult) compareByPath:(NSString *)other;
542 - (NSString *) stringByCachingURLWithCurrentCDN;
543 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
546 @implementation NSString (Cydia)
548 - (NSComparisonResult) compareByPath:(NSString *)other {
549 NSString *prefix = [self commonPrefixWithString:other options:0];
550 size_t length = [prefix length];
552 NSRange lrange = NSMakeRange(length, [self length] - length);
553 NSRange rrange = NSMakeRange(length, [other length] - length);
555 lrange = [self rangeOfString:@"/" options:0 range:lrange];
556 rrange = [other rangeOfString:@"/" options:0 range:rrange];
558 NSComparisonResult value;
560 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
561 value = NSOrderedSame;
562 else if (lrange.location == NSNotFound)
563 value = NSOrderedAscending;
564 else if (rrange.location == NSNotFound)
565 value = NSOrderedDescending;
567 value = NSOrderedSame;
569 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
570 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
571 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
572 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
574 NSComparisonResult result = [lpath compare:rpath];
575 return result == NSOrderedSame ? value : result;
578 - (NSString *) stringByCachingURLWithCurrentCDN {
580 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
581 withString:@"://cache.cydia.saurik.com/"
585 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
586 return [(id)CFURLCreateStringByAddingPercentEscapes(
591 kCFStringEncodingUTF8
598 /* C++ NSString Wrapper Cache {{{ */
599 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
600 return size == 0 ? NULL :
601 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
602 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
605 static _finline CFStringRef CYStringCreate(const char *data) {
606 return CYStringCreate(data, strlen(data));
615 _finline void clear_() {
616 if (cache_ != NULL) {
623 _finline bool empty() const {
627 _finline size_t size() const {
631 _finline char *data() const {
635 _finline void clear() {
640 _finline CYString() :
647 _finline ~CYString() {
651 void operator =(const CYString &rhs) {
655 if (rhs.cache_ == nil)
658 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
661 void copy(apr_pool_t *pool) {
662 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
663 memcpy(temp, data_, size_);
668 void set(apr_pool_t *pool, const char *data, size_t size) {
674 data_ = const_cast<char *>(data);
682 _finline void set(apr_pool_t *pool, const char *data) {
683 set(pool, data, data == NULL ? 0 : strlen(data));
686 _finline void set(apr_pool_t *pool, const std::string &rhs) {
687 set(pool, rhs.data(), rhs.size());
690 bool operator ==(const CYString &rhs) const {
691 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
694 _finline operator CFStringRef() {
696 cache_ = CYStringCreate(data_, size_);
700 _finline operator id() {
701 return (NSString *) static_cast<CFStringRef>(*this);
704 _finline operator const char *() {
705 return reinterpret_cast<const char *>(data_);
709 /* C++ NSString Algorithm Adapters {{{ */
711 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
714 struct NSStringMapHash :
715 std::unary_function<NSString *, size_t>
717 _finline size_t operator ()(NSString *value) const {
718 return CFStringHashNSString((CFStringRef) value);
722 struct NSStringMapLess :
723 std::binary_function<NSString *, NSString *, bool>
725 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
726 return [lhs compare:rhs] == NSOrderedAscending;
730 struct NSStringMapEqual :
731 std::binary_function<NSString *, NSString *, bool>
733 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
734 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
735 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
736 //[lhs isEqualToString:rhs];
741 /* Mime Addresses {{{ */
742 @interface Address : NSObject {
748 - (NSString *) address;
750 - (void) setAddress:(NSString *)address;
752 + (Address *) addressWithString:(NSString *)string;
753 - (Address *) initWithString:(NSString *)string;
757 @implementation Address
766 - (NSString *) name {
770 - (NSString *) address {
774 - (void) setAddress:(NSString *)address {
776 [address_ autorelease];
780 address_ = [address retain];
783 + (Address *) addressWithString:(NSString *)string {
784 return [[[Address alloc] initWithString:string] autorelease];
787 + (NSArray *) _attributeKeys {
788 return [NSArray arrayWithObjects:
794 - (NSArray *) attributeKeys {
795 return [[self class] _attributeKeys];
798 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
799 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
802 - (Address *) initWithString:(NSString *)string {
803 if ((self = [super init]) != nil) {
804 const char *data = [string UTF8String];
805 size_t size = [string length];
807 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
809 if (address_r(data, size)) {
810 name_ = [address_r[1] retain];
811 address_ = [address_r[2] retain];
813 name_ = [string retain];
821 /* CoreGraphics Primitives {{{ */
826 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
827 CGFloat color[] = {red, green, blue, alpha};
828 return CGColorCreate(space, color);
837 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
838 color_(Create_(space, red, green, blue, alpha))
840 Set(space, red, green, blue, alpha);
845 CGColorRelease(color_);
852 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
854 color_ = Create_(space, red, green, blue, alpha);
857 operator CGColorRef() {
863 /* Random Global Variables {{{ */
864 static const int PulseInterval_ = 50000;
866 static const NSString *UI_;
869 static bool RestartSubstrate_;
870 static NSArray *Finishes_;
872 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
873 #define NotifyConfig_ "/etc/notify.conf"
875 static bool Queuing_;
877 static CYColor Blue_;
878 static CYColor Blueish_;
879 static CYColor Black_;
881 static CYColor White_;
882 static CYColor Gray_;
883 static CYColor Green_;
884 static CYColor Purple_;
885 static CYColor Purplish_;
887 static UIColor *InstallingColor_;
888 static UIColor *RemovingColor_;
890 static NSString *App_;
892 static BOOL Advanced_;
893 static BOOL Ignored_;
895 static UIFont *Font12_;
896 static UIFont *Font12Bold_;
897 static UIFont *Font14_;
898 static UIFont *Font18Bold_;
899 static UIFont *Font22Bold_;
901 static const char *Machine_ = NULL;
902 static NSString *System_ = nil;
903 static NSString *SerialNumber_ = nil;
904 static NSString *ChipID_ = nil;
905 static _H<NSString> Token_;
906 static NSString *UniqueID_ = nil;
907 static NSString *PLMN_ = nil;
908 static NSString *Build_ = nil;
909 static NSString *Product_ = nil;
910 static NSString *Safari_ = nil;
912 static CFLocaleRef Locale_;
913 static NSArray *Languages_;
914 static CGColorSpaceRef space_;
916 static NSDictionary *SectionMap_;
917 static NSMutableDictionary *Metadata_;
918 static _transient NSMutableDictionary *Settings_;
919 static _transient NSString *Role_;
920 static _transient NSMutableDictionary *Packages_;
921 static _transient NSMutableDictionary *Sections_;
922 static _transient NSMutableDictionary *Sources_;
923 static bool Changed_;
927 static CGFloat ScreenScale_;
928 static NSString *Idiom_;
930 static NSMutableDictionary *SessionData_;
931 static NSObject *HostConfig_;
932 static NSMutableSet *BridgedHosts_;
933 static NSMutableSet *PipelinedHosts_;
935 static NSString *kCydiaProgressEventTypeError = @"Error";
936 static NSString *kCydiaProgressEventTypeInformation = @"Information";
937 static NSString *kCydiaProgressEventTypeStatus = @"Status";
938 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
941 /* Display Helpers {{{ */
942 inline float Interpolate(float begin, float end, float fraction) {
943 return (end - begin) * fraction + begin;
946 static _finline const char *StripVersion_(const char *version) {
947 const char *colon(strchr(version, ':'));
948 return colon == NULL ? version : colon + 1;
951 NSString *LocalizeSection(NSString *section) {
952 static Pcre title_r("^(.*?) \\((.*)\\)$");
953 if (title_r(section)) {
954 NSString *parent(title_r[1]);
955 NSString *child(title_r[2]);
957 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
958 LocalizeSection(parent),
959 LocalizeSection(child)
963 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
966 NSString *Simplify(NSString *title) {
967 const char *data = [title UTF8String];
968 size_t size = [title length];
970 static Pcre square_r("^\\[(.*)\\]$");
971 if (square_r(data, size))
972 return Simplify(square_r[1]);
974 static Pcre paren_r("^\\((.*)\\)$");
975 if (paren_r(data, size))
976 return Simplify(paren_r[1]);
978 static Pcre title_r("^(.*?) \\((.*)\\)$");
979 if (title_r(data, size))
980 return Simplify(title_r[1]);
986 NSString *GetLastUpdate() {
987 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
990 return UCLocalize("NEVER_OR_UNKNOWN");
992 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
993 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
995 CFRelease(formatter);
997 return [(NSString *) formatted autorelease];
1000 bool isSectionVisible(NSString *section) {
1001 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
1002 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1003 return hidden == nil || ![hidden boolValue];
1008 /* Delegate Prototypes {{{ */
1011 @class CydiaProgressEvent;
1013 @protocol DatabaseDelegate
1014 - (void) repairWithSelector:(SEL)selector;
1015 - (void) setConfigurationData:(NSString *)data;
1016 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
1019 @class CYPackageController;
1021 @protocol CydiaDelegate
1022 - (void) retainNetworkActivityIndicator;
1023 - (void) releaseNetworkActivityIndicator;
1024 - (void) clearPackage:(Package *)package;
1025 - (void) installPackage:(Package *)package;
1026 - (void) installPackages:(NSArray *)packages;
1027 - (void) removePackage:(Package *)package;
1028 - (void) beginUpdate;
1030 - (void) distUpgrade;
1032 - (void) updateData;
1034 - (void) addTrivialSource:(NSString *)href;
1035 - (void) showSettings;
1036 - (UIProgressHUD *) addProgressHUD;
1037 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1038 - (CYViewController *) pageForPackage:(NSString *)name;
1039 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
1040 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1044 /* ProgressEvent Interface/Delegate {{{ */
1045 @interface CydiaProgressEvent : NSObject {
1046 _H<NSString> message_;
1050 _H<NSString> package_;
1052 _H<NSString> version_;
1055 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type;
1056 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package;
1057 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item;
1059 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type;
1061 - (NSString *) message;
1062 - (NSString *) type;
1065 - (NSString *) package;
1067 - (NSString *) version;
1069 - (void) setItem:(NSArray *)item;
1070 - (void) setPackage:(NSString *)package;
1071 - (void) setURL:(NSString *)url;
1072 - (void) setVersion:(NSString *)version;
1074 - (NSString *) compound:(NSString *)value;
1075 - (NSString *) compoundMessage;
1076 - (NSString *) compoundTitle;
1080 @protocol ProgressDelegate
1081 - (void) addProgressEvent:(CydiaProgressEvent *)event;
1082 - (void) setProgressPercent:(NSNumber *)percent;
1083 - (void) setProgressStatus:(NSDictionary *)status;
1084 - (void) setProgressCancellable:(NSNumber *)cancellable;
1085 - (bool) isProgressCancelled;
1086 - (void) setTitle:(NSString *)title;
1089 /* Status Delegation {{{ */
1091 public pkgAcquireStatus
1094 _transient NSObject<ProgressDelegate> *delegate_;
1104 void setDelegate(NSObject<ProgressDelegate> *delegate) {
1105 delegate_ = delegate;
1108 NSObject<ProgressDelegate> *getDelegate() const {
1112 virtual bool MediaChange(std::string media, std::string drive) {
1116 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1119 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1120 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1121 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
1122 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1125 virtual void Done(pkgAcquire::ItemDesc &item) {
1128 virtual void Fail(pkgAcquire::ItemDesc &item) {
1130 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1131 item.Owner->Status == pkgAcquire::Item::StatDone
1135 std::string &error(item.Owner->ErrorText);
1139 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItem:item]);
1140 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1143 virtual bool Pulse(pkgAcquire *Owner) {
1144 bool value = pkgAcquireStatus::Pulse(Owner);
1147 double(CurrentBytes + CurrentItems) /
1148 double(TotalBytes + TotalItems)
1151 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
1152 [NSNumber numberWithDouble:percent], @"Percent",
1154 [NSNumber numberWithDouble:CurrentBytes], @"Current",
1155 [NSNumber numberWithDouble:TotalBytes], @"Total",
1156 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
1157 nil] waitUntilDone:YES];
1159 if (value && ![delegate_ isProgressCancelled])
1167 _finline bool WasCancelled() const {
1171 virtual void Start() {
1172 pkgAcquireStatus::Start();
1173 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
1176 virtual void Stop() {
1177 pkgAcquireStatus::Stop();
1178 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
1179 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
1183 /* Database Interface {{{ */
1184 typedef std::map< unsigned long, _H<Source> > SourceMap;
1186 @interface Database : NSObject {
1192 pkgCacheFile cache_;
1193 pkgDepCache::Policy *policy_;
1194 pkgRecords *records_;
1195 pkgProblemResolver *resolver_;
1196 pkgAcquire *fetcher_;
1198 SPtr<pkgPackageManager> manager_;
1199 pkgSourceList *list_;
1201 SourceMap sourceMap_;
1202 NSMutableArray *sourceList_;
1204 CFMutableArrayRef packages_;
1206 _transient NSObject<DatabaseDelegate> *delegate_;
1207 _transient NSObject<ProgressDelegate> *progress_;
1215 std::map<const char *, _H<NSString> > sections_;
1218 + (Database *) sharedInstance;
1221 - (void) _readCydia:(NSNumber *)fd;
1222 - (void) _readStatus:(NSNumber *)fd;
1223 - (void) _readOutput:(NSNumber *)fd;
1227 - (Package *) packageWithName:(NSString *)name;
1229 - (pkgCacheFile &) cache;
1230 - (pkgDepCache::Policy *) policy;
1231 - (pkgRecords *) records;
1232 - (pkgProblemResolver *) resolver;
1233 - (pkgAcquire &) fetcher;
1234 - (pkgSourceList &) list;
1235 - (NSArray *) packages;
1236 - (NSArray *) sources;
1237 - (Source *) sourceWithKey:(NSString *)key;
1238 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1246 - (void) updateWithStatus:(Status &)status;
1248 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1250 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1251 - (NSObject<ProgressDelegate> *) progressDelegate;
1253 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1255 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1259 /* ProgressEvent Implementation {{{ */
1260 @implementation CydiaProgressEvent
1262 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1263 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1266 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1267 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1268 [event setPackage:package];
1272 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item {
1273 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1275 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1276 NSArray *fields([description componentsSeparatedByString:@" "]);
1277 [event setItem:fields];
1279 if ([fields count] > 3) {
1280 [event setPackage:[fields objectAtIndex:2]];
1281 [event setVersion:[fields objectAtIndex:3]];
1284 [event setURL:[NSString stringWithUTF8String:item.URI.c_str()]];
1289 + (NSArray *) _attributeKeys {
1290 return [NSArray arrayWithObjects:
1300 - (NSArray *) attributeKeys {
1301 return [[self class] _attributeKeys];
1304 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1305 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1308 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1309 if ((self = [super init]) != nil) {
1315 - (NSString *) message {
1319 - (NSString *) type {
1323 - (NSArray *) item {
1324 return (id) item_ ?: [NSNull null];
1327 - (void) setItem:(NSArray *)item {
1331 - (NSString *) package {
1332 return (id) package_ ?: [NSNull null];
1335 - (void) setPackage:(NSString *)package {
1339 - (NSString *) url {
1340 return (id) url_ ?: [NSNull null];
1343 - (void) setURL:(NSString *)url {
1347 - (void) setVersion:(NSString *)version {
1351 - (NSString *) version {
1352 return (id) version_ ?: [NSNull null];
1355 - (NSString *) compound:(NSString *)value {
1357 NSString *mode(nil); {
1358 NSString *type([self type]);
1359 if ([type isEqualToString:kCydiaProgressEventTypeError])
1360 mode = UCLocalize("ERROR");
1361 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1362 mode = UCLocalize("WARNING");
1366 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1372 - (NSString *) compoundMessage {
1373 return [self compound:[self message]];
1376 - (NSString *) compoundTitle {
1379 if (package_ == nil)
1381 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1382 title = [package name];
1386 return [self compound:title];
1392 // Cytore Definitions {{{
1393 struct PackageValue :
1396 Cytore::Offset<PackageValue> next_;
1398 uint32_t index_ : 23;
1399 uint32_t subscribed_ : 1;
1416 Cytore::Offset<PackageValue> packages_[1 << 16];
1419 static Cytore::File<MetaValue> MetaFile_;
1421 // Cytore Helper Functions {{{
1422 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1423 SplitHash nhash = { hashlittle(name, length) };
1425 PackageValue *metadata;
1427 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1428 offset: if (offset->IsNull()) {
1429 *offset = MetaFile_.New<PackageValue>(length + 1);
1430 metadata = &MetaFile_.Get(*offset);
1432 if (metadata == NULL) {
1436 metadata = new PackageValue();
1437 memset(metadata, 0, sizeof(*metadata));
1440 memcpy(metadata->name_, name, length + 1);
1441 metadata->nhash_ = nhash.u16[1];
1443 metadata = &MetaFile_.Get(*offset);
1445 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1446 offset = &metadata->next_;
1454 static void PackageImport(const void *key, const void *value, void *context) {
1455 bool &fail(*reinterpret_cast<bool *>(context));
1458 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1459 NSLog(@"failed to import package %@", key);
1463 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1464 NSDictionary *package((NSDictionary *) value);
1466 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1467 if ([subscribed boolValue] && !metadata->subscribed_)
1468 metadata->subscribed_ = true;
1470 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1471 time_t time([date timeIntervalSince1970]);
1472 if (metadata->first_ > time || metadata->first_ == 0)
1473 metadata->first_ = time;
1476 NSDate *date([package objectForKey:@"LastSeen"]);
1477 NSString *version([package objectForKey:@"LastVersion"]);
1479 if (date != nil && version != nil) {
1480 time_t time([date timeIntervalSince1970]);
1481 if (metadata->last_ < time || metadata->last_ == 0)
1482 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1483 size_t length(strlen(buffer));
1484 uint16_t vhash(hashlittle(buffer, length));
1486 size_t capped(std::min<size_t>(8, length));
1487 char *latest(buffer + length - capped);
1489 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1490 metadata->vhash_ = vhash;
1492 metadata->last_ = time;
1498 /* Source Class {{{ */
1499 @interface Source : NSObject {
1500 CYString depiction_;
1501 CYString description_;
1507 CYString distribution_;
1512 _H<NSString> authority_;
1514 CYString defaultIcon_;
1516 _H<NSDictionary> record_;
1520 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1522 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1524 - (NSString *) depictionForPackage:(NSString *)package;
1525 - (NSString *) supportForPackage:(NSString *)package;
1527 - (NSDictionary *) record;
1531 - (NSString *) distribution;
1532 - (NSString *) type;
1534 - (NSString *) host;
1536 - (NSString *) name;
1537 - (NSString *) shortDescription;
1538 - (NSString *) label;
1539 - (NSString *) origin;
1540 - (NSString *) version;
1542 - (NSString *) defaultIcon;
1546 @implementation Source
1550 distribution_.clear();
1553 description_.clear();
1559 defaultIcon_.clear();
1567 // XXX: this is a very inefficient way to call these deconstructors
1572 + (NSArray *) _attributeKeys {
1573 return [NSArray arrayWithObjects:
1580 @"shortDescription",
1588 - (NSArray *) attributeKeys {
1589 return [[self class] _attributeKeys];
1592 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1593 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1596 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1599 trusted_ = index->IsTrusted();
1601 uri_.set(pool, index->GetURI());
1602 distribution_.set(pool, index->GetDist());
1603 type_.set(pool, index->GetType());
1605 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1606 if (dindex != NULL) {
1608 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1611 pkgTagFile tags(&fd);
1613 pkgTagSection section;
1620 {"default-icon", &defaultIcon_},
1621 {"depiction", &depiction_},
1622 {"description", &description_},
1624 {"origin", &origin_},
1625 {"support", &support_},
1626 {"version", &version_},
1629 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1630 const char *start, *end;
1632 if (section.Find(names[i].name_, start, end)) {
1633 CYString &value(*names[i].value_);
1634 value.set(pool, start, end - start);
1640 record_ = [Sources_ objectForKey:[self key]];
1642 NSURL *url([NSURL URLWithString:uri_]);
1646 host_ = [host_ lowercaseString];
1649 // XXX: this is due to a bug in _H<>
1650 authority_ = (id) host_;
1652 authority_ = [url path];
1655 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1656 if ((self = [super init]) != nil) {
1657 [self setMetaIndex:index inPool:pool];
1661 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1662 NSDictionary *lhr = [self record];
1663 NSDictionary *rhr = [source record];
1666 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1668 NSString *lhs = [self name];
1669 NSString *rhs = [source name];
1671 if ([lhs length] != 0 && [rhs length] != 0) {
1672 unichar lhc = [lhs characterAtIndex:0];
1673 unichar rhc = [rhs characterAtIndex:0];
1675 if (isalpha(lhc) && !isalpha(rhc))
1676 return NSOrderedAscending;
1677 else if (!isalpha(lhc) && isalpha(rhc))
1678 return NSOrderedDescending;
1681 return [lhs compare:rhs options:LaxCompareOptions_];
1684 - (NSString *) depictionForPackage:(NSString *)package {
1685 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1688 - (NSString *) supportForPackage:(NSString *)package {
1689 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1692 - (NSDictionary *) record {
1700 - (NSString *) uri {
1704 - (NSString *) distribution {
1705 return distribution_;
1708 - (NSString *) type {
1712 - (NSString *) key {
1713 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1716 - (NSString *) host {
1720 - (NSString *) name {
1721 return origin_.empty() ? (id) authority_ : origin_;
1724 - (NSString *) shortDescription {
1725 return description_;
1728 - (NSString *) label {
1729 return label_.empty() ? (id) authority_ : label_;
1732 - (NSString *) origin {
1736 - (NSString *) version {
1740 - (NSString *) defaultIcon {
1741 return defaultIcon_;
1746 /* CydiaOperation Class {{{ */
1747 @interface CydiaOperation : NSObject {
1748 NSString *operator_;
1752 - (NSString *) operator;
1753 - (NSString *) value;
1757 @implementation CydiaOperation
1760 [operator_ release];
1765 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1766 if ((self = [super init]) != nil) {
1767 operator_ = [[NSString alloc] initWithUTF8String:_operator];
1768 value_ = [[NSString alloc] initWithUTF8String:value];
1772 + (NSArray *) _attributeKeys {
1773 return [NSArray arrayWithObjects:
1779 - (NSArray *) attributeKeys {
1780 return [[self class] _attributeKeys];
1783 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1784 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1787 - (NSString *) operator {
1791 - (NSString *) value {
1797 /* CydiaClause Class {{{ */
1798 @interface CydiaClause : NSObject {
1800 CydiaOperation *version_;
1803 - (NSString *) package;
1804 - (CydiaOperation *) version;
1808 @implementation CydiaClause
1816 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1817 if ((self = [super init]) != nil) {
1818 package_ = [[NSString alloc] initWithUTF8String:dep.TargetPkg().Name()];
1820 if (const char *version = dep.TargetVer())
1821 version_ = [[CydiaOperation alloc] initWithOperator:dep.CompType() value:version];
1823 version_ = [[NSNull null] retain];
1827 + (NSArray *) _attributeKeys {
1828 return [NSArray arrayWithObjects:
1834 - (NSArray *) attributeKeys {
1835 return [[self class] _attributeKeys];
1838 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1839 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1842 - (NSString *) package {
1846 - (CydiaOperation *) version {
1852 /* CydiaRelation Class {{{ */
1853 @interface CydiaRelation : NSObject {
1854 NSString *relationship_;
1855 NSMutableArray *clauses_;
1858 - (NSString *) relationship;
1859 - (NSArray *) clauses;
1863 @implementation CydiaRelation
1866 [relationship_ release];
1871 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1872 if ((self = [super init]) != nil) {
1873 relationship_ = [[NSString alloc] initWithUTF8String:dep.DepType()];
1874 clauses_ = [[NSMutableArray alloc] initWithCapacity:8];
1876 pkgCache::DepIterator start;
1877 pkgCache::DepIterator end;
1878 dep.GlobOr(start, end); // ++dep
1881 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1883 // yes, seriously. (wtf?)
1891 + (NSArray *) _attributeKeys {
1892 return [NSArray arrayWithObjects:
1898 - (NSArray *) attributeKeys {
1899 return [[self class] _attributeKeys];
1902 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1903 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1906 - (NSString *) relationship {
1907 return relationship_;
1910 - (NSArray *) clauses {
1914 - (void) addClause:(CydiaClause *)clause {
1915 [clauses_ addObject:clause];
1920 /* Package Class {{{ */
1921 struct ParsedPackage {
1926 CYString depiction_;
1936 @interface Package : NSObject {
1939 uint32_t essential_ : 1;
1940 uint32_t obsolete_ : 1;
1941 uint32_t ignored_ : 1;
1945 _transient Database *database_;
1947 pkgCache::VerIterator version_;
1948 pkgCache::PkgIterator iterator_;
1949 pkgCache::VerFileIterator file_;
1955 CYString installed_;
1957 const char *section_;
1958 _transient NSString *section$_;
1962 PackageValue *metadata_;
1963 ParsedPackage *parsed_;
1965 NSMutableArray *tags_;
1968 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1969 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1971 - (pkgCache::PkgIterator) iterator;
1974 - (NSString *) section;
1975 - (NSString *) simpleSection;
1977 - (NSString *) longSection;
1978 - (NSString *) shortSection;
1982 - (Address *) maintainer;
1984 - (NSString *) longDescription;
1985 - (NSString *) shortDescription;
1988 - (PackageValue *) metadata;
1991 - (bool) subscribed;
1992 - (bool) setSubscribed:(bool)subscribed;
1996 - (NSString *) latest;
1997 - (NSString *) installed;
1998 - (BOOL) uninstalled;
2001 - (BOOL) upgradableAndEssential:(BOOL)essential;
2004 - (BOOL) unfiltered;
2008 - (BOOL) halfConfigured;
2009 - (BOOL) halfInstalled;
2011 - (NSString *) mode;
2014 - (NSString *) name;
2016 - (NSString *) homepage;
2017 - (NSString *) depiction;
2018 - (Address *) author;
2020 - (NSString *) support;
2022 - (NSArray *) files;
2023 - (NSArray *) warnings;
2024 - (NSArray *) applications;
2026 - (Source *) source;
2028 - (BOOL) matches:(NSString *)text;
2030 - (bool) hasSupportingRole;
2031 - (BOOL) hasTag:(NSString *)tag;
2032 - (NSString *) primaryPurpose;
2033 - (NSArray *) purposes;
2034 - (bool) isCommercial;
2036 - (void) setIndex:(size_t)index;
2038 - (CYString &) cyname;
2040 - (uint32_t) compareBySection:(NSArray *)sections;
2045 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
2046 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
2047 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
2048 - (bool) isVisibleInSection:(NSString *)section;
2049 - (bool) isVisibleInSource:(Source *)source;
2053 uint32_t PackageChangesRadix(Package *self, void *) {
2058 uint32_t timestamp : 30;
2059 uint32_t ignored : 1;
2060 uint32_t upgradable : 1;
2064 bool upgradable([self upgradableAndEssential:YES]);
2065 value.bits.upgradable = upgradable ? 1 : 0;
2068 value.bits.timestamp = 0;
2069 value.bits.ignored = [self ignored] ? 0 : 1;
2070 value.bits.upgradable = 1;
2072 value.bits.timestamp = [self seen] >> 2;
2073 value.bits.ignored = 0;
2074 value.bits.upgradable = 0;
2077 return _not(uint32_t) - value.key;
2080 uint32_t PackagePrefixRadix(Package *self, void *context) {
2081 size_t offset(reinterpret_cast<size_t>(context));
2082 CYString &name([self cyname]);
2084 size_t size(name.size());
2087 char *text(name.data());
2090 if (!isdigit(text[0]))
2094 while (size != digits && isdigit(text[digits]))
2102 if (offset == 0 && zeros != 0) {
2103 memset(data, '0', zeros);
2104 memcpy(data + zeros, text, 4 - zeros);
2106 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2107 if (size <= offset - zeros)
2110 text += offset - zeros;
2111 size -= offset - zeros;
2114 memcpy(data, text, 4);
2116 memcpy(data, text, size);
2117 memset(data + size, 0, 4 - size);
2120 for (size_t i(0); i != 4; ++i)
2121 if (isalpha(data[i]))
2129 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2131 /* XXX: ntohl may be more honest */
2132 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2135 CYString &(*PackageName)(Package *self, SEL sel);
2137 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2138 _profile(PackageNameCompare)
2139 CYString &lhi(PackageName(lhs, @selector(cyname)));
2140 CYString &rhi(PackageName(rhs, @selector(cyname)));
2141 CFStringRef lhn(lhi), rhn(rhi);
2144 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2145 else if (rhn == NULL)
2146 return NSOrderedDescending;
2148 _profile(PackageNameCompare$NumbersLast)
2149 if (!lhi.empty() && !rhi.empty()) {
2150 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2151 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2152 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2153 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2154 return lha ? NSOrderedAscending : NSOrderedDescending;
2158 CFIndex length = CFStringGetLength(lhn);
2160 _profile(PackageNameCompare$Compare)
2161 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2166 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2167 return PackageNameCompare(*lhs, *rhs, context);
2170 struct PackageNameOrdering :
2171 std::binary_function<Package *, Package *, bool>
2173 _finline bool operator ()(Package *lhs, Package *rhs) const {
2174 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2178 @implementation Package
2180 - (NSString *) description {
2181 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2185 if (parsed_ != NULL)
2194 + (NSString *) webScriptNameForSelector:(SEL)selector {
2196 else if (selector == @selector(clear))
2198 else if (selector == @selector(getField:))
2200 else if (selector == @selector(hasTag:))
2202 else if (selector == @selector(install))
2204 else if (selector == @selector(remove))
2210 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2211 return [self webScriptNameForSelector:selector] == nil;
2214 + (NSArray *) _attributeKeys {
2215 return [NSArray arrayWithObjects:
2234 @"shortDescription",
2247 - (NSArray *) attributeKeys {
2248 return [[self class] _attributeKeys];
2251 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2252 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2255 - (NSArray *) relations {
2256 @synchronized (database_) {
2257 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2258 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2259 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2263 - (NSString *) getField:(NSString *)name {
2264 @synchronized (database_) {
2265 if ([database_ era] != era_ || file_.end())
2268 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2270 const char *start, *end;
2271 if (!parser.Find([name UTF8String], start, end))
2272 return (NSString *) [NSNull null];
2274 return [(NSString *) CYStringCreate(start, end - start) autorelease];
2278 if (parsed_ != NULL)
2280 @synchronized (database_) {
2281 if ([database_ era] != era_ || file_.end())
2284 ParsedPackage *parsed(new ParsedPackage);
2287 _profile(Package$parse)
2288 pkgRecords::Parser *parser;
2290 _profile(Package$parse$Lookup)
2291 parser = &[database_ records]->Lookup(file_);
2296 _profile(Package$parse$Find)
2301 {"icon", &parsed->icon_},
2302 {"depiction", &parsed->depiction_},
2303 {"homepage", &parsed->homepage_},
2304 {"website", &website},
2305 {"bugs", &parsed->bugs_},
2306 {"support", &parsed->support_},
2307 {"sponsor", &parsed->sponsor_},
2308 {"author", &parsed->author_},
2311 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2312 const char *start, *end;
2314 if (parser->Find(names[i].name_, start, end)) {
2315 CYString &value(*names[i].value_);
2316 _profile(Package$parse$Value)
2317 value.set(pool_, start, end - start);
2323 _profile(Package$parse$Tagline)
2324 const char *start, *end;
2325 if (parser->ShortDesc(start, end)) {
2326 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2329 while (stop != start && stop[-1] == '\r')
2331 parsed->tagline_.set(pool_, start, stop - start);
2335 _profile(Package$parse$Retain)
2336 if (parsed->homepage_.empty())
2337 parsed->homepage_ = website;
2338 if (parsed->homepage_ == parsed->depiction_)
2339 parsed->homepage_.clear();
2344 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2345 if ((self = [super init]) != nil) {
2346 _profile(Package$initWithVersion)
2349 database_ = database;
2350 era_ = [database era];
2354 pkgCache::PkgIterator iterator(version.ParentPkg());
2355 iterator_ = iterator;
2357 _profile(Package$initWithVersion$Version)
2358 if (!version_.end())
2359 file_ = version_.FileList();
2361 pkgCache &cache([database_ cache]);
2362 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2366 _profile(Package$initWithVersion$Cache)
2367 name_.set(NULL, iterator.Display());
2369 latest_.set(NULL, StripVersion_(version_.VerStr()));
2371 pkgCache::VerIterator current(iterator.CurrentVer());
2373 installed_.set(NULL, StripVersion_(current.VerStr()));
2376 _profile(Package$initWithVersion$Tags)
2377 pkgCache::TagIterator tag(iterator.TagList());
2379 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2381 const char *name(tag.Name());
2382 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2384 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2385 if (strcmp(name + 6, "enduser") == 0)
2387 else if (strcmp(name + 6, "hacker") == 0)
2389 else if (strcmp(name + 6, "developer") == 0)
2391 else if (strcmp(name + 6, "cydia") == 0)
2397 if (strncmp(name, "cydia::", 7) == 0) {
2398 if (strcmp(name + 7, "essential") == 0)
2400 else if (strcmp(name + 7, "obsolete") == 0)
2405 } while (!tag.end());
2409 _profile(Package$initWithVersion$Metadata)
2410 const char *mixed(iterator.Name());
2411 size_t size(strlen(mixed));
2412 char lower[size + 1];
2414 for (size_t i(0); i != size; ++i)
2415 lower[i] = mixed[i] | 0x20;
2418 PackageValue *metadata(PackageFind(lower, size));
2419 metadata_ = metadata;
2421 id_.set(NULL, metadata->name_, size);
2423 const char *latest(version_.VerStr());
2424 size_t length(strlen(latest));
2426 uint16_t vhash(hashlittle(latest, length));
2428 size_t capped(std::min<size_t>(8, length));
2429 latest = latest + length - capped;
2431 if (metadata->first_ == 0)
2432 metadata->first_ = now_;
2434 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2435 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2436 metadata->vhash_ = vhash;
2437 metadata->last_ = now_;
2438 } else if (metadata->last_ == 0)
2439 metadata->last_ = metadata->first_;
2442 _profile(Package$initWithVersion$Section)
2443 section_ = iterator.Section();
2446 _profile(Package$initWithVersion$Flags)
2447 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2448 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2453 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2454 pkgCache::VerIterator version;
2456 _profile(Package$packageWithIterator$GetCandidateVer)
2457 version = [database policy]->GetCandidateVer(iterator);
2465 _profile(Package$packageWithIterator$Allocate)
2466 package = [Package allocWithZone:zone];
2469 _profile(Package$packageWithIterator$Initialize)
2471 initWithVersion:version
2478 _profile(Package$packageWithIterator$Autorelease)
2479 package = [package autorelease];
2485 - (pkgCache::PkgIterator) iterator {
2489 - (NSString *) section {
2490 if (section$_ == nil) {
2491 if (section_ == NULL)
2494 _profile(Package$section$mappedSectionForPointer)
2495 section$_ = [database_ mappedSectionForPointer:section_];
2500 - (NSString *) simpleSection {
2501 if (NSString *section = [self section])
2502 return Simplify(section);
2507 - (NSString *) longSection {
2508 return LocalizeSection([self section]);
2511 - (NSString *) shortSection {
2512 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2515 - (NSString *) uri {
2518 pkgIndexFile *index;
2519 pkgCache::PkgFileIterator file(file_.File());
2520 if (![database_ list].FindIndex(file, index))
2522 return [NSString stringWithUTF8String:iterator_->Path];
2523 //return [NSString stringWithUTF8String:file.Site()];
2524 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2528 - (Address *) maintainer {
2529 @synchronized (database_) {
2530 if ([database_ era] != era_ || file_.end())
2533 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2534 const std::string &maintainer(parser->Maintainer());
2535 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2539 @synchronized (database_) {
2540 if ([database_ era] != era_ || version_.end())
2543 return version_->InstalledSize;
2546 - (NSString *) longDescription {
2547 @synchronized (database_) {
2548 if ([database_ era] != era_ || file_.end())
2551 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2552 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2554 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2555 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2556 if ([lines count] < 2)
2559 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2560 for (size_t i(1), e([lines count]); i != e; ++i) {
2561 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2562 [trimmed addObject:trim];
2565 return [trimmed componentsJoinedByString:@"\n"];
2568 - (NSString *) shortDescription {
2569 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2573 _profile(Package$index)
2574 CFStringRef name((CFStringRef) [self name]);
2575 if (CFStringGetLength(name) == 0)
2577 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2578 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2580 return toupper(character);
2584 - (PackageValue *) metadata {
2589 PackageValue *metadata([self metadata]);
2590 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2593 - (bool) subscribed {
2594 return [self metadata]->subscribed_;
2597 - (bool) setSubscribed:(bool)subscribed {
2598 PackageValue *metadata([self metadata]);
2599 if (metadata->subscribed_ == subscribed)
2601 metadata->subscribed_ = subscribed;
2609 - (NSString *) latest {
2613 - (NSString *) installed {
2617 - (BOOL) uninstalled {
2618 return installed_.empty();
2622 return !version_.end();
2625 - (BOOL) upgradableAndEssential:(BOOL)essential {
2626 _profile(Package$upgradableAndEssential)
2627 pkgCache::VerIterator current(iterator_.CurrentVer());
2629 return essential && essential_;
2631 return !version_.end() && version_ != current;
2635 - (BOOL) essential {
2640 return [database_ cache][iterator_].InstBroken();
2643 - (BOOL) unfiltered {
2644 _profile(Package$unfiltered$obsolete)
2645 if (_unlikely(obsolete_))
2649 _profile(Package$unfiltered$hasSupportingRole)
2650 if (_unlikely(![self hasSupportingRole]))
2658 if (![self unfiltered])
2663 _profile(Package$visible$section)
2664 section = [self section];
2667 _profile(Package$visible$isSectionVisible)
2668 if (!isSectionVisible(section))
2676 unsigned char current(iterator_->CurrentState);
2677 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2680 - (BOOL) halfConfigured {
2681 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2684 - (BOOL) halfInstalled {
2685 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2689 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2690 return state.Mode != pkgDepCache::ModeKeep;
2693 - (NSString *) mode {
2694 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2696 switch (state.Mode) {
2697 case pkgDepCache::ModeDelete:
2698 if ((state.iFlags & pkgDepCache::Purge) != 0)
2702 case pkgDepCache::ModeKeep:
2703 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2704 return @"REINSTALL";
2705 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2709 case pkgDepCache::ModeInstall:
2710 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2711 return @"REINSTALL";
2712 else*/ switch (state.Status) {
2714 return @"DOWNGRADE";
2720 return @"NEW_INSTALL";
2731 - (NSString *) name {
2732 return name_.empty() ? id_ : name_;
2735 - (UIImage *) icon {
2736 NSString *section = [self simpleSection];
2739 if (parsed_ != NULL)
2740 if (NSString *href = parsed_->icon_)
2741 if ([href hasPrefix:@"file:///"])
2742 // XXX: correct escaping
2743 icon = [UIImage imageAtPath:[href substringFromIndex:7]];
2744 if (icon == nil) if (section != nil)
2745 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2746 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2747 if ([dicon hasPrefix:@"file:///"])
2748 // XXX: correct escaping
2749 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2751 icon = [UIImage applicationImageNamed:@"unknown.png"];
2755 - (NSString *) homepage {
2756 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2759 - (NSString *) depiction {
2760 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2763 - (Address *) sponsor {
2764 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [Address addressWithString:parsed_->sponsor_];
2767 - (Address *) author {
2768 return parsed_ == NULL || parsed_->author_.empty() ? nil : [Address addressWithString:parsed_->author_];
2771 - (NSString *) support {
2772 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2775 - (NSArray *) files {
2776 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2777 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2780 fin.open([path UTF8String]);
2785 while (std::getline(fin, line))
2786 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2791 - (NSString *) state {
2792 @synchronized (database_) {
2793 if ([database_ era] != era_ || file_.end())
2796 switch (iterator_->CurrentState) {
2797 case pkgCache::State::NotInstalled:
2798 return @"NotInstalled";
2799 case pkgCache::State::UnPacked:
2801 case pkgCache::State::HalfConfigured:
2802 return @"HalfConfigured";
2803 case pkgCache::State::HalfInstalled:
2804 return @"HalfInstalled";
2805 case pkgCache::State::ConfigFiles:
2806 return @"ConfigFiles";
2807 case pkgCache::State::Installed:
2808 return @"Installed";
2809 case pkgCache::State::TriggersAwaited:
2810 return @"TriggersAwaited";
2811 case pkgCache::State::TriggersPending:
2812 return @"TriggersPending";
2815 return (NSString *) [NSNull null];
2818 - (NSString *) selection {
2819 @synchronized (database_) {
2820 if ([database_ era] != era_ || file_.end())
2823 switch (iterator_->SelectedState) {
2824 case pkgCache::State::Unknown:
2826 case pkgCache::State::Install:
2828 case pkgCache::State::Hold:
2830 case pkgCache::State::DeInstall:
2831 return @"DeInstall";
2832 case pkgCache::State::Purge:
2836 return (NSString *) [NSNull null];
2839 - (NSArray *) warnings {
2840 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2841 const char *name(iterator_.Name());
2843 size_t length(strlen(name));
2844 if (length < 2) invalid:
2845 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2846 else for (size_t i(0); i != length; ++i)
2848 /* XXX: technically this is not allowed */
2849 (name[i] < 'A' || name[i] > 'Z') &&
2850 (name[i] < 'a' || name[i] > 'z') &&
2851 (name[i] < '0' || name[i] > '9') &&
2852 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2855 if (strcmp(name, "cydia") != 0) {
2858 bool _private = false;
2861 bool repository = [[self section] isEqualToString:@"Repositories"];
2863 if (NSArray *files = [self files])
2864 for (NSString *file in files)
2865 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2867 else if (!user && [file isEqualToString:@"/User"])
2869 else if (!_private && [file isEqualToString:@"/private"])
2871 else if (!stash && [file isEqualToString:@"/var/stash"])
2874 /* XXX: this is not sensitive enough. only some folders are valid. */
2875 if (cydia && !repository)
2876 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2878 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2880 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2882 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2885 return [warnings count] == 0 ? nil : warnings;
2888 - (NSArray *) applications {
2889 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2891 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2893 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2894 if (NSArray *files = [self files])
2895 for (NSString *file in files)
2896 if (application_r(file)) {
2897 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2898 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2899 if ([id isEqualToString:me])
2902 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2904 display = application_r[1];
2906 NSString *bundle([file stringByDeletingLastPathComponent]);
2907 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2908 if (icon == nil || [icon length] == 0)
2910 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2912 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2913 [applications addObject:application];
2915 [application addObject:id];
2916 [application addObject:display];
2917 [application addObject:url];
2920 return [applications count] == 0 ? nil : applications;
2923 - (Source *) source {
2924 if (source_ == nil) {
2925 @synchronized (database_) {
2926 if ([database_ era] != era_ || file_.end())
2927 source_ = (Source *) [NSNull null];
2929 source_ = [([database_ getSource:file_.File()] ?: (Source *) [NSNull null]) retain];
2933 return source_ == (Source *) [NSNull null] ? nil : source_;
2936 - (BOOL) matches:(NSString *)text {
2942 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2943 if (range.location != NSNotFound)
2946 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2947 if (range.location != NSNotFound)
2952 NSString *description([self shortDescription]);
2953 NSUInteger length([description length]);
2955 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_ range:NSMakeRange(0, std::min<NSUInteger>(length, 100))];
2956 if (range.location != NSNotFound)
2962 - (bool) hasSupportingRole {
2967 if ([Role_ isEqualToString:@"User"])
2971 if ([Role_ isEqualToString:@"Hacker"])
2975 if ([Role_ isEqualToString:@"Developer"])
2980 - (NSArray *) tags {
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 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3309 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3310 } else if (strncmp(data, "status: ", 8) == 0) {
3311 // status: <package>: {unpacked,half-configured,installed}
3312 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3313 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3314 } else if (strncmp(data, "processing: ", 12) == 0) {
3315 // processing: configure: config-test
3316 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3317 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3318 } else if (pmstatus_r(data, size)) {
3319 std::string type([pmstatus_r[1] UTF8String]);
3321 NSString *package = pmstatus_r[2];
3322 if ([package isEqualToString:@"dpkg-exec"])
3325 float percent([pmstatus_r[3] floatValue]);
3326 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3328 NSString *string = pmstatus_r[4];
3330 if (type == "pmerror") {
3331 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3332 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3333 } else if (type == "pmstatus") {
3334 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3335 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3336 } else if (type == "pmconffile")
3337 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3339 lprintf("E:unknown pmstatus\n");
3341 lprintf("E:unknown status\n");
3347 - (void) _readOutput:(NSNumber *)fd { _pooled
3348 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3349 std::istream is(&ib);
3352 while (std::getline(is, line)) {
3353 lprintf("O:%s\n", line.c_str());
3355 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3356 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3366 - (Package *) packageWithName:(NSString *)name {
3367 @synchronized (self) {
3368 if (static_cast<pkgDepCache *>(cache_) == NULL)
3370 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3371 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3375 if ((self = [super init]) != nil) {
3382 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3383 apr_pool_create(&pool_, NULL);
3385 size_t capacity(MetaFile_->active_);
3391 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3392 sourceList_ = [[NSMutableArray alloc] initWithCapacity:16];
3396 _assert(pipe(fds) != -1);
3399 _config->Set("APT::Keep-Fds::", cydiafd_);
3400 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3403 detachNewThreadSelector:@selector(_readCydia:)
3405 withObject:[NSNumber numberWithInt:fds[0]]
3408 _assert(pipe(fds) != -1);
3412 detachNewThreadSelector:@selector(_readStatus:)
3414 withObject:[NSNumber numberWithInt:fds[0]]
3417 _assert(pipe(fds) != -1);
3418 _assert(dup2(fds[0], 0) != -1);
3419 _assert(close(fds[0]) != -1);
3421 input_ = fdopen(fds[1], "a");
3423 _assert(pipe(fds) != -1);
3424 _assert(dup2(fds[1], 1) != -1);
3425 _assert(close(fds[1]) != -1);
3428 detachNewThreadSelector:@selector(_readOutput:)
3430 withObject:[NSNumber numberWithInt:fds[0]]
3435 - (pkgCacheFile &) cache {
3439 - (pkgDepCache::Policy *) policy {
3443 - (pkgRecords *) records {
3447 - (pkgProblemResolver *) resolver {
3451 - (pkgAcquire &) fetcher {
3455 - (pkgSourceList &) list {
3459 - (NSArray *) packages {
3460 return (NSArray *) packages_;
3463 - (NSArray *) sources {
3467 - (Source *) sourceWithKey:(NSString *)key {
3468 for (Source *source in [self sources]) {
3469 if ([[source key] isEqualToString:key])
3474 - (bool) popErrorWithTitle:(NSString *)title {
3477 while (!_error->empty()) {
3479 bool warning(!_error->PopMessage(error));
3484 size_t size(error.size());
3485 if (size == 0 || error[size - 1] != '\n')
3487 error.resize(size - 1);
3490 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3492 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3498 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3499 return [self popErrorWithTitle:title] || !success;
3502 - (void) reloadDataWithInvocation:(NSInvocation *)invocation { CYPoolStart() {
3503 @synchronized (self) {
3506 [self releasePackages];
3509 [sourceList_ removeAllObjects];
3529 apr_pool_clear(pool_);
3531 NSRecycleZone(zone_);
3532 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3534 int chk(creat("/tmp/cydia.chk", 0644));
3538 if (invocation != nil)
3539 [invocation invoke];
3541 NSString *title(UCLocalize("DATABASE"));
3544 OpProgress progress;
3545 while (!cache_.Open(progress, true)) { pop:
3547 bool warning(!_error->PopMessage(error));
3548 lprintf("cache_.Open():[%s]\n", error.c_str());
3550 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3551 [delegate_ repairWithSelector:@selector(configure)];
3552 else if (error == "The package lists or status file could not be parsed or opened.")
3553 [delegate_ repairWithSelector:@selector(update)];
3554 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3555 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3556 // else if (error == "Malformed Status line")
3557 // else if (error == "The list of sources could not be read.")
3559 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3569 unlink("/tmp/cydia.chk");
3571 now_ = [[NSDate date] timeIntervalSince1970];
3573 policy_ = new pkgDepCache::Policy();
3574 records_ = new pkgRecords(cache_);
3575 resolver_ = new pkgProblemResolver(cache_);
3576 fetcher_ = new pkgAcquire(&status_);
3579 list_ = new pkgSourceList();
3580 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3583 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3584 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3588 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3591 if (cache_->BrokenCount() != 0) {
3592 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3595 if (cache_->BrokenCount() != 0) {
3596 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3600 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3604 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3605 Source *object([[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease]);
3606 [sourceList_ addObject:object];
3608 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3609 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3610 // XXX: this could be more intelligent
3611 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3612 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3614 sourceMap_[cached->ID] = object;
3619 /*std::vector<Package *> packages;
3620 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3621 [packages_ release];
3626 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3627 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3628 //packages.push_back(package);
3629 CFArrayAppendValue(packages_, [package retain]);
3633 /*if (packages.empty())
3634 packages_ = [[NSArray alloc] init];
3636 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3639 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3640 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3641 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3649 /*if (!packages.empty())
3650 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3651 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3653 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3655 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3657 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3661 size_t count(CFArrayGetCount(packages_));
3662 MetaFile_->active_ = count;
3664 for (size_t index(0); index != count; ++index)
3665 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3669 } } CYPoolEnd() _trace(); }
3672 @synchronized (self) {
3674 resolver_ = new pkgProblemResolver(cache_);
3676 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3677 if (!cache_[iterator].Keep())
3678 cache_->MarkKeep(iterator, false);
3679 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3680 cache_->SetReInstall(iterator, false);
3683 - (void) configure {
3684 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3686 system([dpkg UTF8String]);
3691 // XXX: I don't remember this condition
3696 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3698 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3700 if ([self popErrorWithTitle:title])
3704 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3707 public pkgArchiveCleaner
3710 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3715 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3722 fetcher_->Shutdown();
3724 pkgRecords records(cache_);
3726 lock_ = new FileFd();
3727 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3729 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3731 if ([self popErrorWithTitle:title])
3735 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3738 manager_ = (_system->CreatePM(cache_));
3739 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3746 bool substrate(RestartSubstrate_);
3747 RestartSubstrate_ = false;
3749 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3751 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3753 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3755 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3756 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3759 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3761 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3763 [self popErrorWithTitle:title];
3767 bool failed = false;
3768 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3769 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3771 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3777 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3785 RestartSubstrate_ = true;
3788 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3790 if (_error->PendingError()) {
3795 if (result == pkgPackageManager::Failed) {
3800 if (result != pkgPackageManager::Completed) {
3805 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3807 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3809 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3810 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3813 if (![before isEqualToArray:after])
3818 NSString *title(UCLocalize("UPGRADE"));
3819 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3825 [self updateWithStatus:status_];
3828 - (void) updateWithStatus:(Status &)status {
3829 NSString *title(UCLocalize("REFRESHING_DATA"));
3832 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3836 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3837 if ([self popErrorWithTitle:title])
3840 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3842 bool success(ListUpdate(status, list, PulseInterval_));
3843 if (status.WasCancelled())
3846 [self popErrorWithTitle:title forOperation:success];
3848 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3850 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3854 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3855 delegate_ = delegate;
3858 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3859 progress_ = delegate;
3860 status_.setDelegate(delegate);
3863 - (NSObject<ProgressDelegate> *) progressDelegate {
3867 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3868 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3869 return i == sourceMap_.end() ? nil : i->second;
3872 - (NSString *) mappedSectionForPointer:(const char *)section {
3873 _H<NSString> *mapped;
3875 _profile(Database$mappedSectionForPointer$Cache)
3876 mapped = §ions_[section];
3879 if (*mapped == NULL) {
3880 size_t length(strlen(section));
3881 char spaced[length + 1];
3883 _profile(Database$mappedSectionForPointer$Replace)
3884 for (size_t index(0); index != length; ++index)
3885 spaced[index] = section[index] == '_' ? ' ' : section[index];
3886 spaced[length] = '\0';
3891 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3892 string = [NSString stringWithUTF8String:spaced];
3895 _profile(Database$mappedSectionForPointer$Map)
3896 string = [SectionMap_ objectForKey:string] ?: string;
3906 static NSMutableSet *Diversions_;
3908 @interface Diversion : NSObject {
3911 _H<NSString> format_;
3916 @implementation Diversion
3918 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
3919 if ((self = [super init]) != nil) {
3920 pattern_ = [from UTF8String];
3926 - (NSString *) divert:(NSString *)url {
3927 return !pattern_(url) ? nil : pattern_->*format_;
3930 + (NSURL *) divertURL:(NSURL *)url {
3932 NSString *href([url absoluteString]);
3934 for (Diversion *diversion in Diversions_)
3935 if (NSString *diverted = [diversion divert:href]) {
3937 NSLog(@"div: %@", diverted);
3939 url = [NSURL URLWithString:diverted];
3946 - (NSString *) key {
3950 - (NSUInteger) hash {
3954 - (BOOL) isEqual:(Diversion *)object {
3955 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
3960 @interface CydiaObject : NSObject {
3962 _transient id delegate_;
3965 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3969 @interface CydiaWebViewController : CyteWebViewController {
3970 CydiaObject *cydia_;
3973 + (void) addDiversion:(Diversion *)diversion;
3977 /* Web Scripting {{{ */
3978 @implementation CydiaObject
3981 [indirect_ release];
3985 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3986 if ((self = [super init]) != nil) {
3987 indirect_ = [indirect retain];
3991 - (void) setDelegate:(id)delegate {
3992 delegate_ = delegate;
3995 + (NSArray *) _attributeKeys {
3996 return [NSArray arrayWithObjects:
4011 - (NSArray *) attributeKeys {
4012 return [[self class] _attributeKeys];
4015 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4016 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4019 - (NSString *) version {
4023 - (NSString *) device {
4024 return [[UIDevice currentDevice] uniqueIdentifier];
4027 - (NSString *) firmware {
4028 return [[UIDevice currentDevice] systemVersion];
4031 - (NSString *) hostname {
4032 return [[UIDevice currentDevice] name];
4035 - (NSString *) idiom {
4036 return (id) Idiom_ ?: [NSNull null];
4039 - (NSString *) plmn {
4040 return (id) PLMN_ ?: [NSNull null];
4043 - (NSString *) ecid {
4044 return (id) ChipID_ ?: [NSNull null];
4047 - (NSString *) serial {
4048 return SerialNumber_;
4051 - (NSString *) role {
4052 return (id) Role_ ?: [NSNull null];
4055 - (NSString *) model {
4056 return [NSString stringWithUTF8String:Machine_];
4059 - (NSString *) token {
4060 return (id) Token_ ?: [NSNull null];
4063 + (NSString *) webScriptNameForSelector:(SEL)selector {
4065 else if (selector == @selector(addBridgedHost:))
4066 return @"addBridgedHost";
4067 else if (selector == @selector(addPipelinedHost:scheme:))
4068 return @"addPipelinedHost";
4069 else if (selector == @selector(addTrivialSource:))
4070 return @"addTrivialSource";
4071 else if (selector == @selector(close))
4073 else if (selector == @selector(divert::))
4075 else if (selector == @selector(du:))
4077 else if (selector == @selector(stringWithFormat:arguments:))
4079 else if (selector == @selector(getAllSources))
4080 return @"getAllSourcs";
4081 else if (selector == @selector(getKernelNumber:))
4082 return @"getKernelNumber";
4083 else if (selector == @selector(getKernelString:))
4084 return @"getKernelString";
4085 else if (selector == @selector(getInstalledPackages))
4086 return @"getInstalledPackages";
4087 else if (selector == @selector(getLocaleIdentifier))
4088 return @"getLocaleIdentifier";
4089 else if (selector == @selector(getPreferredLanguages))
4090 return @"getPreferredLanguages";
4091 else if (selector == @selector(getPackageById:))
4092 return @"getPackageById";
4093 else if (selector == @selector(getSessionValue:))
4094 return @"getSessionValue";
4095 else if (selector == @selector(installPackages:))
4096 return @"installPackages";
4097 else if (selector == @selector(localizedStringForKey:value:table:))
4099 else if (selector == @selector(popViewController:))
4100 return @"popViewController";
4101 else if (selector == @selector(refreshSources))
4102 return @"refreshSources";
4103 else if (selector == @selector(removeButton))
4104 return @"removeButton";
4105 else if (selector == @selector(setSessionValue::))
4106 return @"setSessionValue";
4107 else if (selector == @selector(substitutePackageNames:))
4108 return @"substitutePackageNames";
4109 else if (selector == @selector(scrollToBottom:))
4110 return @"scrollToBottom";
4111 else if (selector == @selector(setAllowsNavigationAction:))
4112 return @"setAllowsNavigationAction";
4113 else if (selector == @selector(setBadgeValue:))
4114 return @"setBadgeValue";
4115 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4116 return @"setButtonImage";
4117 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4118 return @"setButtonTitle";
4119 else if (selector == @selector(setHidesBackButton:))
4120 return @"setHidesBackButton";
4121 else if (selector == @selector(setHidesNavigationBar:))
4122 return @"setHidesNavigationBar";
4123 else if (selector == @selector(setNavigationBarStyle:))
4124 return @"setNavigationBarStyle";
4125 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4126 return @"setNavigationBarTintColor";
4127 else if (selector == @selector(setPasteboardString:))
4128 return @"setPasteboardString";
4129 else if (selector == @selector(setPasteboardURL:))
4130 return @"setPasteboardURL";
4131 else if (selector == @selector(setToken:))
4133 else if (selector == @selector(setViewportWidth:))
4134 return @"setViewportWidth";
4135 else if (selector == @selector(statfs:))
4137 else if (selector == @selector(supports:))
4143 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4144 return [self webScriptNameForSelector:selector] == nil;
4147 - (BOOL) supports:(NSString *)feature {
4148 return [feature isEqualToString:@"window.open"];
4151 - (void) divert:(NSString *)from :(NSString *)to {
4152 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4155 - (NSNumber *) getKernelNumber:(NSString *)name {
4156 const char *string([name UTF8String]);
4159 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4160 return (id) [NSNull null];
4162 if (size != sizeof(int))
4163 return (id) [NSNull null];
4166 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4167 return (id) [NSNull null];
4169 return [NSNumber numberWithInt:value];
4172 - (NSString *) getKernelString:(NSString *)name {
4173 const char *string([name UTF8String]);
4176 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4177 return (id) [NSNull null];
4179 char value[size + 1];
4180 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4181 return (id) [NSNull null];
4183 // XXX: just in case you request something ludicrous
4186 return [NSString stringWithCString:value];
4189 - (id) getSessionValue:(NSString *)key {
4190 @synchronized (SessionData_) {
4191 return [SessionData_ objectForKey:key];
4194 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4195 @synchronized (SessionData_) {
4196 if (value == (id) [WebUndefined undefined])
4197 [SessionData_ removeObjectForKey:key];
4199 [SessionData_ setObject:value forKey:key];
4202 - (void) addBridgedHost:(NSString *)host {
4203 @synchronized (HostConfig_) {
4204 [BridgedHosts_ addObject:host];
4207 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4208 @synchronized (HostConfig_) {
4209 if (scheme != (id) [WebUndefined undefined])
4210 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4212 [PipelinedHosts_ addObject:host];
4215 - (void) popViewController:(NSNumber *)value {
4216 if (value == (id) [WebUndefined undefined])
4217 value = [NSNumber numberWithBool:YES];
4218 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4221 - (void) addTrivialSource:(NSString *)href {
4222 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4225 - (void) refreshSources {
4226 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4229 - (NSArray *) getAllSources {
4230 return [[Database sharedInstance] sources];
4233 - (NSArray *) getInstalledPackages {
4234 Database *database([Database sharedInstance]);
4235 @synchronized (database) {
4236 NSArray *packages([database packages]);
4237 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4238 for (Package *package in packages)
4239 if (![package uninstalled])
4240 [installed addObject:package];
4244 - (Package *) getPackageById:(NSString *)id {
4245 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4249 return (Package *) [NSNull null];
4252 - (NSString *) getLocaleIdentifier {
4253 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4256 - (NSArray *) getPreferredLanguages {
4260 - (NSArray *) statfs:(NSString *)path {
4263 if (path == nil || statfs([path UTF8String], &stat) == -1)
4266 return [NSArray arrayWithObjects:
4267 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4268 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4269 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4273 - (NSNumber *) du:(NSString *)path {
4274 NSNumber *value(nil);
4277 _assert(pipe(fds) != -1);
4279 pid_t pid(ExecFork());
4281 _assert(dup2(fds[1], 1) != -1);
4282 _assert(close(fds[0]) != -1);
4283 _assert(close(fds[1]) != -1);
4284 /* XXX: this should probably not use du */
4285 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4290 _assert(close(fds[1]) != -1);
4292 if (FILE *du = fdopen(fds[0], "r")) {
4294 while (fgets(line, sizeof(line), du) != NULL) {
4295 size_t length(strlen(line));
4296 while (length != 0 && line[length - 1] == '\n')
4297 line[--length] = '\0';
4298 if (char *tab = strchr(line, '\t')) {
4300 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4305 } else _assert(close(fds[0]));
4309 if (waitpid(pid, &status, 0) == -1)
4312 else _assert(false);
4318 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4321 - (void) installPackages:(NSArray *)packages {
4322 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4325 - (NSString *) substitutePackageNames:(NSString *)message {
4326 NSMutableArray *words([[message componentsSeparatedByString:@" "] mutableCopy]);
4327 for (size_t i(0), e([words count]); i != e; ++i) {
4328 NSString *word([words objectAtIndex:i]);
4329 if (Package *package = [[Database sharedInstance] packageWithName:word])
4330 [words replaceObjectAtIndex:i withObject:[package name]];
4333 return [words componentsJoinedByString:@" "];
4336 - (void) removeButton {
4337 [indirect_ removeButton];
4340 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4341 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4344 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4345 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4348 - (void) setBadgeValue:(id)value {
4349 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4352 - (void) setAllowsNavigationAction:(NSString *)value {
4353 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4356 - (void) setHidesBackButton:(NSString *)value {
4357 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4360 - (void) setHidesNavigationBar:(NSString *)value {
4361 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4364 - (void) setNavigationBarStyle:(NSString *)value {
4365 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4368 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4369 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4370 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4371 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4374 - (void) setPasteboardString:(NSString *)value {
4375 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4378 - (void) setPasteboardURL:(NSString *)value {
4379 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4382 - (void) _setToken:(NSString *)token {
4386 [Metadata_ removeObjectForKey:@"Token"];
4388 [Metadata_ setObject:Token_ forKey:@"Token"];
4393 - (void) setToken:(NSString *)token {
4394 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4397 - (void) scrollToBottom:(NSNumber *)animated {
4398 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4401 - (void) setViewportWidth:(float)width {
4402 [indirect_ setViewportWidthOnMainThread:width];
4405 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4406 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4407 unsigned count([arguments count]);
4409 for (unsigned i(0); i != count; ++i)
4410 values[i] = [arguments objectAtIndex:i];
4411 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4414 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4415 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4417 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4419 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4425 /* @ Loading... Indicator {{{ */
4426 @interface CYLoadingIndicator : UIView {
4427 _H<UIActivityIndicatorView> spinner_;
4429 _H<UIView> container_;
4432 @property (readonly, nonatomic) UILabel *label;
4433 @property (readonly, nonatomic) UIActivityIndicatorView *activityIndicatorView;
4437 @implementation CYLoadingIndicator
4439 - (id) initWithFrame:(CGRect)frame {
4440 if ((self = [super initWithFrame:frame]) != nil) {
4441 container_ = [[[UIView alloc] init] autorelease];
4442 [container_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
4444 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
4445 [spinner_ startAnimating];
4446 [container_ addSubview:spinner_];
4448 label_ = [[[UILabel alloc] init] autorelease];
4449 [label_ setFont:[UIFont boldSystemFontOfSize:15.0f]];
4450 [label_ setBackgroundColor:[UIColor clearColor]];
4451 [label_ setTextColor:[UIColor blackColor]];
4452 [label_ setShadowColor:[UIColor whiteColor]];
4453 [label_ setShadowOffset:CGSizeMake(0, 1)];
4454 [label_ setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
4455 [container_ addSubview:label_];
4457 CGSize viewsize = frame.size;
4458 CGSize spinnersize = [spinner_ bounds].size;
4459 CGSize textsize = [[label_ text] sizeWithFont:[label_ font]];
4460 float bothwidth = spinnersize.width + textsize.width + 5.0f;
4462 CGRect containrect = {
4463 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
4464 CGSizeMake(bothwidth, spinnersize.height)
4467 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
4475 [container_ setFrame:containrect];
4476 [spinner_ setFrame:spinrect];
4477 [label_ setFrame:textrect];
4478 [self addSubview:container_];
4482 - (UILabel *) label {
4486 - (UIActivityIndicatorView *) activityIndicatorView {
4492 /* Emulated Loading Controller {{{ */
4493 @interface CYEmulatedLoadingController : CYViewController {
4494 _transient Database *database_;
4495 _H<CYLoadingIndicator> indicator_;
4496 _H<UITabBar> tabbar_;
4497 _H<UINavigationBar> navbar_;
4502 @implementation CYEmulatedLoadingController
4504 - (id) initWithDatabase:(Database *)database {
4505 if ((self = [super init]) != nil) {
4506 database_ = database;
4511 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
4513 UITableView *table([[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease]);
4514 [table setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4515 [[self view] addSubview:table];
4517 indicator_ = [[[CYLoadingIndicator alloc] initWithFrame:[[self view] bounds]] autorelease];
4518 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4519 [[self view] addSubview:indicator_];
4521 tabbar_ = [[[UITabBar alloc] initWithFrame:CGRectMake(0, 0, 0, 49.0f)] autorelease];
4522 [tabbar_ setFrame:CGRectMake(0.0f, [[self view] bounds].size.height - [tabbar_ bounds].size.height, [[self view] bounds].size.width, [tabbar_ bounds].size.height)];
4523 [tabbar_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth];
4524 [[self view] addSubview:tabbar_];
4526 navbar_ = [[[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 0, 44.0f)] autorelease];
4527 [navbar_ setFrame:CGRectMake(0.0f, 0.0f, [[self view] bounds].size.width, [navbar_ bounds].size.height)];
4528 [navbar_ setAutoresizingMask:UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth];
4529 [[self view] addSubview:navbar_];
4532 - (void) releaseSubviews {
4541 /* Cydia Browser Controller {{{ */
4542 @implementation CydiaWebViewController
4549 - (NSURL *) navigationURL {
4550 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4553 + (void) initialize {
4554 Diversions_ = [[NSMutableSet alloc] initWithCapacity:0];
4557 + (void) addDiversion:(Diversion *)diversion {
4558 [Diversions_ addObject:diversion];
4561 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4562 [super webView:view didClearWindowObject:window forFrame:frame];
4564 WebDataSource *source([frame dataSource]);
4565 NSURLResponse *response([source response]);
4566 NSURL *url([response URL]);
4567 NSString *scheme([[url scheme] lowercaseString]);
4569 bool bridged(false);
4571 @synchronized (HostConfig_) {
4572 if ([scheme isEqualToString:@"file"])
4574 else if ([scheme isEqualToString:@"https"])
4575 if ([BridgedHosts_ containsObject:[url host]])
4580 [window setValue:cydia_ forKey:@"cydia"];
4583 - (NSURL *) URLWithURL:(NSURL *)url {
4584 return [Diversion divertURL:url];
4587 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4588 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4590 if (System_ != NULL)
4591 [copy setValue:System_ forHTTPHeaderField:@"X-System"];
4592 if (Machine_ != NULL)
4593 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4595 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4600 - (void) setDelegate:(id)delegate {
4601 [super setDelegate:delegate];
4602 [cydia_ setDelegate:delegate];
4606 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4607 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
4609 WebView *webview([[webview_ _documentView] webView]);
4611 NSString *application([NSString stringWithFormat:@"Cydia/%@", @ Cydia_]);
4614 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4616 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4617 if (Product_ != nil)
4618 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4620 [webview setApplicationNameForUserAgent:application];
4628 @interface NSObject (CydiaScript)
4629 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4632 @implementation NSObject (CydiaScript)
4634 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4640 @implementation NSArray (CydiaScript)
4642 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4643 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4644 for (size_t i(0), e([self count]); i != e; ++i)
4645 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4651 @implementation NSDictionary (CydiaScript)
4653 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4654 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4656 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4663 /* Confirmation Controller {{{ */
4664 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4665 if (!iterator.end())
4666 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4667 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4669 pkgCache::PkgIterator package(dep.TargetPkg());
4672 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4679 @protocol ConfirmationControllerDelegate
4680 - (void) cancelAndClear:(bool)clear;
4681 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4685 @interface ConfirmationController : CydiaWebViewController {
4686 _transient Database *database_;
4688 UIAlertView *essential_;
4690 NSDictionary *changes_;
4691 NSMutableArray *issues_;
4692 NSDictionary *sizes_;
4697 - (id) initWithDatabase:(Database *)database;
4701 @implementation ConfirmationController
4708 if (essential_ != nil)
4709 [essential_ release];
4716 RestartSubstrate_ = true;
4717 [delegate_ confirmWithNavigationController:[self navigationController]];
4720 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4721 NSString *context([alert context]);
4723 if ([context isEqualToString:@"remove"]) {
4724 if (button == [alert cancelButtonIndex])
4725 [self dismissModalViewControllerAnimated:YES];
4726 else if (button == [alert firstOtherButtonIndex]) {
4730 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4731 } else if ([context isEqualToString:@"unable"]) {
4732 [self dismissModalViewControllerAnimated:YES];
4733 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4735 [super alertView:alert clickedButtonAtIndex:button];
4739 - (void) _doContinue {
4740 [self dismissModalViewControllerAnimated:YES];
4741 [delegate_ cancelAndClear:NO];
4744 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4745 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4749 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4750 [super webView:view didClearWindowObject:window forFrame:frame];
4752 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4753 changes_, @"changes",
4757 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4760 - (id) initWithDatabase:(Database *)database {
4761 if ((self = [super init]) != nil) {
4762 database_ = database;
4764 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4765 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4766 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4767 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4768 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4772 pkgCacheFile &cache([database_ cache]);
4773 NSArray *packages([database_ packages]);
4774 pkgDepCache::Policy *policy([database_ policy]);
4776 issues_ = [[NSMutableArray arrayWithCapacity:4] retain];
4778 for (Package *package in packages) {
4779 pkgCache::PkgIterator iterator([package iterator]);
4780 NSString *name([package id]);
4782 if ([package broken]) {
4783 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4785 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4787 reasons, @"reasons",
4790 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4794 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4795 pkgCache::DepIterator start;
4796 pkgCache::DepIterator end;
4797 dep.GlobOr(start, end); // ++dep
4799 if (!cache->IsImportantDep(end))
4801 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4804 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4806 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4807 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4808 clauses, @"clauses",
4812 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4814 pkgCache::PkgIterator target(start.TargetPkg());
4815 if (target->ProvidesList != 0)
4816 reason = @"missing";
4818 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4820 reason = @"installed";
4821 installed = [NSString stringWithUTF8String:ver.VerStr()];
4822 } else if (!cache[target].CandidateVerIter(cache).end())
4823 reason = @"uninstalled";
4824 else if (target->ProvidesList == 0)
4825 reason = @"uninstallable";
4827 reason = @"virtual";
4830 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4831 [NSString stringWithUTF8String:start.CompType()], @"operator",
4832 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4835 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4836 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4837 version, @"version",
4839 installed, @"installed",
4842 // yes, seriously. (wtf?)
4850 pkgDepCache::StateCache &state(cache[iterator]);
4852 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4854 if (state.NewInstall())
4855 [installs addObject:name];
4856 // XXX: else if (state.Install())
4857 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4858 [reinstalls addObject:name];
4859 // XXX: move before previous if
4860 else if (state.Upgrade())
4861 [upgrades addObject:name];
4862 else if (state.Downgrade())
4863 [downgrades addObject:name];
4864 else if (!state.Delete())
4865 // XXX: _assert(state.Keep());
4867 else if (special_r(name))
4868 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4869 [NSNull null], @"package",
4870 [NSArray arrayWithObjects:
4871 [NSDictionary dictionaryWithObjectsAndKeys:
4872 @"Conflicts", @"relationship",
4873 [NSArray arrayWithObjects:
4874 [NSDictionary dictionaryWithObjectsAndKeys:
4876 [NSNull null], @"version",
4877 @"installed", @"reason",
4884 if ([package essential])
4886 [removes addObject:name];
4889 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4890 substrate_ |= DepSubstrate(iterator.CurrentVer());
4895 else if (Advanced_) {
4896 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4898 essential_ = [[UIAlertView alloc]
4899 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4900 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4902 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4904 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4908 [essential_ setContext:@"remove"];
4910 essential_ = [[UIAlertView alloc]
4911 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4912 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4914 cancelButtonTitle:UCLocalize("OKAY")
4915 otherButtonTitles:nil
4918 [essential_ setContext:@"unable"];
4921 changes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
4922 installs, @"installs",
4923 reinstalls, @"reinstalls",
4924 upgrades, @"upgrades",
4925 downgrades, @"downgrades",
4926 removes, @"removes",
4929 sizes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
4930 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4931 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4934 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
4936 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
4937 initWithTitle:UCLocalize("CANCEL")
4938 style:UIBarButtonItemStylePlain
4940 action:@selector(cancelButtonClicked)
4946 - (void) applyRightButton {
4947 if ([issues_ count] == 0 && ![self isLoading])
4948 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4949 initWithTitle:UCLocalize("CONFIRM")
4950 style:UIBarButtonItemStyleDone
4952 action:@selector(confirmButtonClicked)
4955 [[self navigationItem] setRightBarButtonItem:nil];
4959 - (void) cancelButtonClicked {
4960 [self dismissModalViewControllerAnimated:YES];
4961 [delegate_ cancelAndClear:YES];
4965 - (void) confirmButtonClicked {
4966 if (essential_ != nil)
4976 /* Progress Data {{{ */
4977 @interface CydiaProgressData : NSObject {
4978 _transient id delegate_;
4987 _H<NSMutableArray> events_;
4988 _H<NSString> title_;
4990 _H<NSString> status_;
4991 _H<NSString> finish_;
4996 @implementation CydiaProgressData
4998 + (NSArray *) _attributeKeys {
4999 return [NSArray arrayWithObjects:
5011 - (NSArray *) attributeKeys {
5012 return [[self class] _attributeKeys];
5015 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5016 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5020 if ((self = [super init]) != nil) {
5021 events_ = [NSMutableArray arrayWithCapacity:32];
5025 - (void) setDelegate:(id)delegate {
5026 delegate_ = delegate;
5029 - (void) setPercent:(float)value {
5033 - (NSNumber *) percent {
5034 return [NSNumber numberWithFloat:percent_];
5037 - (void) setCurrent:(float)value {
5041 - (NSNumber *) current {
5042 return [NSNumber numberWithFloat:current_];
5045 - (void) setTotal:(float)value {
5049 - (NSNumber *) total {
5050 return [NSNumber numberWithFloat:total_];
5053 - (void) setSpeed:(float)value {
5057 - (NSNumber *) speed {
5058 return [NSNumber numberWithFloat:speed_];
5061 - (NSArray *) events {
5065 - (void) removeAllEvents {
5066 [events_ removeAllObjects];
5069 - (void) addEvent:(CydiaProgressEvent *)event {
5070 [events_ addObject:event];
5073 - (void) setTitle:(NSString *)text {
5077 - (NSString *) title {
5081 - (void) setFinish:(NSString *)text {
5085 - (NSString *) finish {
5086 return (id) finish_ ?: [NSNull null];
5089 - (void) setRunning:(bool)running {
5093 - (NSNumber *) running {
5094 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5099 /* Progress Controller {{{ */
5100 @interface ProgressController : CydiaWebViewController <
5103 _transient Database *database_;
5104 _H<CydiaProgressData> progress_;
5108 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5110 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5112 - (void) setTitle:(NSString *)title;
5113 - (void) setCancellable:(bool)cancellable;
5117 @implementation ProgressController
5120 [database_ setProgressDelegate:nil];
5121 [progress_ setDelegate:nil];
5125 - (void) updateCancel {
5126 [[self navigationItem] setLeftBarButtonItem:(cancel_ == 1 ? [[[UIBarButtonItem alloc]
5127 initWithTitle:UCLocalize("CANCEL")
5128 style:UIBarButtonItemStylePlain
5130 action:@selector(cancel)
5131 ] autorelease] : nil)];
5134 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5135 if ((self = [super init]) != nil) {
5136 database_ = database;
5137 delegate_ = delegate;
5139 [database_ setProgressDelegate:self];
5141 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5142 [progress_ setDelegate:self];
5144 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5146 [scroller_ setBackgroundColor:[UIColor blackColor]];
5148 [[self navigationItem] setHidesBackButton:YES];
5150 [self updateCancel];
5154 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5155 [super webView:view didClearWindowObject:window forFrame:frame];
5156 [window setValue:progress_ forKey:@"cydiaProgress"];
5159 - (void) updateProgress {
5160 [self dispatchEvent:@"CydiaProgressUpdate"];
5163 - (void) viewWillAppear:(BOOL)animated {
5164 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5165 [super viewWillAppear:animated];
5169 UpdateExternalStatus(0);
5176 [delegate_ terminateWithSuccess];
5177 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5178 [delegate_ suspendWithAnimation:YES];
5180 [delegate_ suspend];*/
5192 system("/usr/bin/sbreload");
5198 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5199 SBReboot(SBSSpringBoardServerPort());
5201 reboot2(RB_AUTOBOOT);
5208 - (void) setTitle:(NSString *)title {
5209 [progress_ setTitle:title];
5210 [self updateProgress];
5213 - (UIBarButtonItem *) rightButton {
5214 return [[progress_ running] boolValue] ? nil : [[[UIBarButtonItem alloc]
5215 initWithTitle:UCLocalize("CLOSE")
5216 style:UIBarButtonItemStylePlain
5218 action:@selector(close)
5222 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5223 UpdateExternalStatus(1);
5225 [progress_ setRunning:true];
5226 [self setTitle:title];
5227 // implicit updateProgress
5229 SHA1SumValue notifyconf; {
5231 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5234 MMap mmap(file, MMap::ReadOnly);
5236 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5237 notifyconf = sha1.Result();
5241 SHA1SumValue springlist; {
5243 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5246 MMap mmap(file, MMap::ReadOnly);
5248 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5249 springlist = sha1.Result();
5253 if (invocation != nil) {
5254 [invocation yieldToSelector:@selector(invoke)];
5255 [self setTitle:@"COMPLETE"];
5260 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5263 MMap mmap(file, MMap::ReadOnly);
5265 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5266 if (!(notifyconf == sha1.Result()))
5273 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5276 MMap mmap(file, MMap::ReadOnly);
5278 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5279 if (!(springlist == sha1.Result()))
5285 if (RestartSubstrate_)
5289 RestartSubstrate_ = false;
5292 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5293 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5294 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5295 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5296 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5300 system("su -c /usr/bin/uicache mobile");
5303 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5305 [progress_ setRunning:false];
5306 [self updateProgress];
5308 [self applyRightButton];
5311 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5312 [progress_ addEvent:event];
5313 [self updateProgress];
5316 - (bool) isProgressCancelled {
5317 return cancel_ == 2;
5322 [self updateCancel];
5325 - (void) setCancellable:(bool)cancellable {
5326 unsigned cancel(cancel_);
5330 else if (cancel_ == 0)
5333 if (cancel != cancel_)
5334 [self updateCancel];
5337 - (void) setProgressCancellable:(NSNumber *)cancellable {
5338 [self setCancellable:[cancellable boolValue]];
5341 - (void) setProgressPercent:(NSNumber *)percent {
5342 [progress_ setPercent:[percent floatValue]];
5343 [self updateProgress];
5346 - (void) setProgressStatus:(NSDictionary *)status {
5347 if (status == nil) {
5348 [progress_ setCurrent:0];
5349 [progress_ setTotal:0];
5350 [progress_ setSpeed:0];
5352 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5354 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5355 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5356 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5359 [self updateProgress];
5365 /* Cell Content View {{{ */
5366 @protocol ContentDelegate
5367 - (void) drawContentRect:(CGRect)rect;
5370 @interface ContentView : UIView {
5371 _transient id<ContentDelegate> delegate_;
5376 @implementation ContentView
5378 - (id) initWithFrame:(CGRect)frame {
5379 if ((self = [super initWithFrame:frame]) != nil) {
5380 [self setNeedsDisplayOnBoundsChange:YES];
5384 - (void) setDelegate:(id<ContentDelegate>)delegate {
5385 delegate_ = delegate;
5388 - (void) drawRect:(CGRect)rect {
5389 [super drawRect:rect];
5390 [delegate_ drawContentRect:rect];
5395 /* Cydia TableView Cell {{{ */
5396 @interface CYTableViewCell : UITableViewCell {
5397 ContentView *content_;
5403 @implementation CYTableViewCell
5410 - (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
5411 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
5413 if (view == content_) {
5414 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
5415 highlighted_ = highlighted;
5418 [super _updateHighlightColorsForView:view highlighted:highlighted];
5421 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
5422 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
5423 highlighted_ = selected;
5425 [super setSelected:selected animated:animated];
5426 [content_ setNeedsDisplay];
5432 /* Package Cell {{{ */
5433 @interface PackageCell : CYTableViewCell <
5438 NSString *description_;
5446 - (PackageCell *) init;
5447 - (void) setPackage:(Package *)package;
5449 - (void) drawContentRect:(CGRect)rect;
5453 @implementation PackageCell
5455 - (void) clearPackage {
5466 if (description_ != nil) {
5467 [description_ release];
5471 if (source_ != nil) {
5476 if (badge_ != nil) {
5481 if (placard_ != nil) {
5491 [self clearPackage];
5495 - (PackageCell *) init {
5496 CGRect frame(CGRectMake(0, 0, 320, 74));
5497 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5498 UIView *content([self contentView]);
5499 CGRect bounds([content bounds]);
5501 content_ = [[ContentView alloc] initWithFrame:bounds];
5502 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5503 [content addSubview:content_];
5505 [content_ setDelegate:self];
5506 [content_ setOpaque:YES];
5510 - (NSString *) accessibilityLabel {
5511 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), name_, description_];
5514 - (void) setPackage:(Package *)package {
5515 [self clearPackage];
5518 Source *source = [package source];
5520 icon_ = [[package icon] retain];
5521 name_ = [[package name] retain];
5524 description_ = [package longDescription];
5525 if (description_ == nil)
5526 description_ = [package shortDescription];
5527 if (description_ != nil)
5528 description_ = [description_ retain];
5530 commercial_ = [package isCommercial];
5532 package_ = [package retain];
5534 NSString *label = nil;
5535 bool trusted = false;
5537 if (source != nil) {
5538 label = [source label];
5539 trusted = [source trusted];
5540 } else if ([[package id] isEqualToString:@"firmware"])
5541 label = UCLocalize("APPLE");
5543 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5545 NSString *from(label);
5547 NSString *section = [package simpleSection];
5548 if (section != nil && ![section isEqualToString:label]) {
5549 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5550 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5553 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
5554 source_ = [from retain];
5556 if (NSString *purpose = [package primaryPurpose])
5557 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
5558 badge_ = [badge_ retain];
5563 if (NSString *mode = [package_ mode]) {
5564 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5565 color = RemovingColor_;
5566 //placard = @"removing";
5568 color = InstallingColor_;
5569 //placard = @"installing";
5572 // XXX: the removing/installing placards are not @2x
5575 color = [UIColor whiteColor];
5577 if ([package installed] != nil)
5578 placard = @"installed";
5583 [content_ setBackgroundColor:color];
5586 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]]) != nil)
5587 placard_ = [placard_ retain];
5589 [self setNeedsDisplay];
5590 [content_ setNeedsDisplay];
5593 - (void) drawContentRect:(CGRect)rect {
5594 bool highlighted(highlighted_);
5595 float width([self bounds].size.width);
5598 CGContextRef context(UIGraphicsGetCurrentContext());
5599 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
5600 CGContextFillRect(context, rect);
5605 rect.size = [icon_ size];
5607 rect.size.width /= 2;
5608 rect.size.height /= 2;
5610 rect.origin.x = 25 - rect.size.width / 2;
5611 rect.origin.y = 25 - rect.size.height / 2;
5613 [icon_ drawInRect:rect];
5616 if (badge_ != nil) {
5618 rect.size = [badge_ size];
5620 rect.size.width /= 2;
5621 rect.size.height /= 2;
5623 rect.origin.x = 36 - rect.size.width / 2;
5624 rect.origin.y = 36 - rect.size.height / 2;
5626 [badge_ drawInRect:rect];
5633 UISetColor(commercial_ ? Purple_ : Black_);
5634 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5635 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5638 UISetColor(commercial_ ? Purplish_ : Gray_);
5639 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5641 if (placard_ != nil)
5642 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5647 /* Section Cell {{{ */
5648 @interface SectionCell : CYTableViewCell <
5660 - (void) setSection:(Section *)section editing:(BOOL)editing;
5664 @implementation SectionCell
5666 - (void) clearSection {
5667 if (basic_ != nil) {
5672 if (section_ != nil) {
5682 if (count_ != nil) {
5689 [self clearSection];
5695 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5696 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5697 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
5698 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
5699 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5701 UIView *content([self contentView]);
5702 CGRect bounds([content bounds]);
5704 content_ = [[ContentView alloc] initWithFrame:bounds];
5705 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5706 [content addSubview:content_];
5707 [content_ setBackgroundColor:[UIColor whiteColor]];
5709 [content_ setDelegate:self];
5713 - (void) onSwitch:(id)sender {
5714 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5715 if (metadata == nil) {
5716 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5717 [Sections_ setObject:metadata forKey:basic_];
5720 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5724 - (void) setSection:(Section *)section editing:(BOOL)editing {
5725 if (editing != editing_) {
5727 [switch_ removeFromSuperview];
5729 [self addSubview:switch_];
5733 [self clearSection];
5735 if (section == nil) {
5736 name_ = [UCLocalize("ALL_PACKAGES") retain];
5739 basic_ = [section name];
5741 basic_ = [basic_ retain];
5743 section_ = [section localized];
5744 if (section_ != nil)
5745 section_ = [section_ retain];
5747 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
5748 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
5751 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5754 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5755 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5757 [content_ setNeedsDisplay];
5760 - (void) setFrame:(CGRect)frame {
5761 [super setFrame:frame];
5763 CGRect rect([switch_ frame]);
5764 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5767 - (NSString *) accessibilityLabel {
5771 - (void) drawContentRect:(CGRect)rect {
5772 bool highlighted(highlighted_ && !editing_);
5774 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5779 float width(rect.size.width);
5785 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5787 CGSize size = [count_ sizeWithFont:Font14_];
5791 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5797 /* File Table {{{ */
5798 @interface FileTable : CYViewController <
5799 UITableViewDataSource,
5802 _transient Database *database_;
5805 NSMutableArray *files_;
5809 - (id) initWithDatabase:(Database *)database;
5810 - (void) setPackage:(Package *)package;
5814 @implementation FileTable
5817 [self releaseSubviews];
5826 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5827 return files_ == nil ? 0 : [files_ count];
5830 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5834 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5835 static NSString *reuseIdentifier = @"Cell";
5837 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5839 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5840 [cell setFont:[UIFont systemFontOfSize:16]];
5842 [cell setText:[files_ objectAtIndex:indexPath.row]];
5843 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5848 - (NSURL *) navigationURL {
5849 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5853 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5855 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5856 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5857 [list_ setRowHeight:24.0f];
5858 [list_ setDataSource:self];
5859 [list_ setDelegate:self];
5860 [[self view] addSubview:list_];
5863 - (void) viewDidLoad {
5864 [super viewDidLoad];
5866 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5869 - (void) releaseSubviews {
5874 - (id) initWithDatabase:(Database *)database {
5875 if ((self = [super init]) != nil) {
5876 database_ = database;
5878 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5882 - (void) setPackage:(Package *)package {
5883 if (package_ != nil) {
5884 [package_ autorelease];
5893 [files_ removeAllObjects];
5895 if (package != nil) {
5896 package_ = [package retain];
5897 name_ = [[package id] retain];
5899 if (NSArray *files = [package files])
5900 [files_ addObjectsFromArray:files];
5902 if ([files_ count] != 0) {
5903 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5904 [files_ removeObjectAtIndex:0];
5905 [files_ sortUsingSelector:@selector(compareByPath:)];
5907 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5908 [stack addObject:@"/"];
5910 for (int i(0), e([files_ count]); i != e; ++i) {
5911 NSString *file = [files_ objectAtIndex:i];
5912 while (![file hasPrefix:[stack lastObject]])
5913 [stack removeLastObject];
5914 NSString *directory = [stack lastObject];
5915 [stack addObject:[file stringByAppendingString:@"/"]];
5916 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5917 ([stack count] - 2) * 3, "",
5918 [file substringFromIndex:[directory length]]
5927 - (void) reloadData {
5930 [self setPackage:[database_ packageWithName:name_]];
5935 /* Package Controller {{{ */
5936 @interface CYPackageController : CydiaWebViewController <
5937 UIActionSheetDelegate
5939 _transient Database *database_;
5940 _H<Package> package_;
5943 _H<NSMutableArray> buttons_;
5944 _H<UIBarButtonItem> button_;
5947 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5951 @implementation CYPackageController
5953 - (NSURL *) navigationURL {
5954 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
5957 /* XXX: this is not safe at all... localization of /fail/ */
5958 - (void) _clickButtonWithName:(NSString *)name {
5959 if ([name isEqualToString:UCLocalize("CLEAR")])
5960 [delegate_ clearPackage:package_];
5961 else if ([name isEqualToString:UCLocalize("INSTALL")])
5962 [delegate_ installPackage:package_];
5963 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5964 [delegate_ installPackage:package_];
5965 else if ([name isEqualToString:UCLocalize("REMOVE")])
5966 [delegate_ removePackage:package_];
5967 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5968 [delegate_ installPackage:package_];
5969 else _assert(false);
5972 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5973 NSString *context([sheet context]);
5975 if ([context isEqualToString:@"modify"]) {
5976 if (button != [sheet cancelButtonIndex]) {
5977 NSString *buttonName = [buttons_ objectAtIndex:button];
5978 [self _clickButtonWithName:buttonName];
5981 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5985 - (bool) _allowJavaScriptPanel {
5990 - (void) _customButtonClicked {
5991 int count([buttons_ count]);
5996 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5998 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5999 [buttons addObjectsFromArray:buttons_];
6001 UIActionSheet *sheet = [[[UIActionSheet alloc]
6004 cancelButtonTitle:nil
6005 destructiveButtonTitle:nil
6006 otherButtonTitles:nil
6009 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
6011 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
6012 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
6014 [sheet setContext:@"modify"];
6016 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
6020 // We don't want to allow non-commercial packages to do custom things to the install button,
6021 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
6022 - (void) customButtonClicked {
6024 [super customButtonClicked];
6026 [self _customButtonClicked];
6029 - (void) reloadButtonClicked {
6030 // Don't reload a commerical package by tapping the loading button,
6031 // but if it's not an Install button, we should forward it on.
6032 if (![package_ uninstalled])
6033 [self _customButtonClicked];
6036 - (void) applyLoadingTitle {
6037 // Don't show "Loading" as the title. Ever.
6040 - (UIBarButtonItem *) rightButton {
6045 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
6046 if ((self = [super init]) != nil) {
6047 database_ = database;
6048 buttons_ = [NSMutableArray arrayWithCapacity:4];
6049 name_ = [NSString stringWithString:name];
6050 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]]];
6054 - (void) reloadData {
6057 package_ = [database_ packageWithName:name_];
6059 [buttons_ removeAllObjects];
6061 if (package_ != nil) {
6062 [(Package *) package_ parse];
6064 commercial_ = [package_ isCommercial];
6066 if ([package_ mode] != nil)
6067 [buttons_ addObject:UCLocalize("CLEAR")];
6068 if ([package_ source] == nil);
6069 else if ([package_ upgradableAndEssential:NO])
6070 [buttons_ addObject:UCLocalize("UPGRADE")];
6071 else if ([package_ uninstalled])
6072 [buttons_ addObject:UCLocalize("INSTALL")];
6074 [buttons_ addObject:UCLocalize("REINSTALL")];
6075 if (![package_ uninstalled])
6076 [buttons_ addObject:UCLocalize("REMOVE")];
6080 switch ([buttons_ count]) {
6081 case 0: title = nil; break;
6082 case 1: title = [buttons_ objectAtIndex:0]; break;
6083 default: title = UCLocalize("MODIFY"); break;
6086 button_ = [[[UIBarButtonItem alloc]
6088 style:UIBarButtonItemStylePlain
6090 action:@selector(customButtonClicked)
6094 - (bool) isLoading {
6095 return commercial_ ? [super isLoading] : false;
6101 /* Package List Controller {{{ */
6102 @interface PackageListController : CYViewController <
6103 UITableViewDataSource,
6106 _transient Database *database_;
6108 NSMutableArray *packages_;
6109 NSMutableArray *sections_;
6111 NSMutableArray *index_;
6112 NSMutableDictionary *indices_;
6116 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6117 - (void) setDelegate:(id)delegate;
6118 - (void) resetCursor;
6122 @implementation PackageListController
6125 [packages_ release];
6126 [sections_ release];
6135 - (void) deselectWithAnimation:(BOOL)animated {
6136 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6139 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6140 CGRect base = [[self view] bounds];
6141 base.size.height -= bounds.size.height;
6142 base.origin = [list_ frame].origin;
6144 [UIView beginAnimations:nil context:NULL];
6145 [UIView setAnimationBeginsFromCurrentState:YES];
6146 [UIView setAnimationCurve:curve];
6147 [UIView setAnimationDuration:duration];
6148 [list_ setFrame:base];
6149 [UIView commitAnimations];
6152 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6153 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6156 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6157 [self resizeForKeyboardBounds:bounds duration:0];
6160 - (void) keyboardWillShow:(NSNotification *)notification {
6163 NSTimeInterval duration;
6164 UIViewAnimationCurve curve;
6165 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6166 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6167 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
6168 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
6170 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);
6171 UIViewController *base = self;
6172 while ([base parentViewController] != nil)
6173 base = [base parentViewController];
6174 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6175 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6177 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6180 - (void) keyboardWillHide:(NSNotification *)notification {
6181 NSTimeInterval duration;
6182 UIViewAnimationCurve curve;
6183 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
6184 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
6186 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6189 - (void) viewWillAppear:(BOOL)animated {
6190 [super viewWillAppear:animated];
6192 [self resizeForKeyboardBounds:CGRectZero];
6193 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6194 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6197 - (void) viewWillDisappear:(BOOL)animated {
6198 [super viewWillDisappear:animated];
6200 [self resizeForKeyboardBounds:CGRectZero];
6201 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6202 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6205 - (void) viewDidAppear:(BOOL)animated {
6206 [super viewDidAppear:animated];
6207 [self deselectWithAnimation:animated];
6210 - (void) didSelectPackage:(Package *)package {
6211 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
6212 [view setDelegate:delegate_];
6213 [[self navigationController] pushViewController:view animated:YES];
6216 #if TryIndexedCollation
6217 + (BOOL) hasIndexedCollation {
6218 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6222 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6223 NSInteger count([sections_ count]);
6224 return count == 0 ? 1 : count;
6227 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6228 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6230 return [[sections_ objectAtIndex:section] name];
6233 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6234 if ([sections_ count] == 0)
6236 return [[sections_ objectAtIndex:section] count];
6239 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6240 @synchronized (database_) {
6241 if ([database_ era] != era_)
6244 Section *section([sections_ objectAtIndex:[path section]]);
6245 NSInteger row([path row]);
6246 Package *package([packages_ objectAtIndex:([section row] + row)]);
6247 return [[package retain] autorelease];
6250 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6251 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6253 cell = [[[PackageCell alloc] init] autorelease];
6254 [cell setPackage:[self packageAtIndexPath:path]];
6258 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6259 Package *package([self packageAtIndexPath:path]);
6260 package = [database_ packageWithName:[package id]];
6261 [self didSelectPackage:package];
6264 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6265 // XXX: is 20 the most optimal number here?
6266 return [packages_ count] > 20 ? index_ : nil;
6269 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6270 #if TryIndexedCollation
6271 if ([[self class] hasIndexedCollation]) {
6272 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6279 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6280 if ((self = [super init]) != nil) {
6281 database_ = database;
6282 title_ = [title copy];
6283 [[self navigationItem] setTitle:title_];
6285 #if TryIndexedCollation
6286 if ([[self class] hasIndexedCollation])
6287 index_ = [[[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles] retain]
6290 index_ = [[NSMutableArray alloc] initWithCapacity:32];
6292 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
6294 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6295 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6297 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6298 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6299 [list_ setRowHeight:73];
6300 [[self view] addSubview:list_];
6302 [list_ setDataSource:self];
6303 [list_ setDelegate:self];
6307 - (void) setDelegate:(id)delegate {
6308 delegate_ = delegate;
6311 - (bool) hasPackage:(Package *)package {
6315 - (void) reloadData {
6318 era_ = [database_ era];
6319 NSArray *packages = [database_ packages];
6321 [packages_ removeAllObjects];
6322 [sections_ removeAllObjects];
6324 _profile(PackageTable$reloadData$Filter)
6325 for (Package *package in packages)
6326 if ([self hasPackage:package])
6327 [packages_ addObject:package];
6330 [indices_ removeAllObjects];
6332 Section *section = nil;
6334 #if TryIndexedCollation
6335 if ([[self class] hasIndexedCollation]) {
6336 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6337 NSArray *titles = [collation sectionIndexTitles];
6340 _profile(PackageTable$reloadData$Section)
6341 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6345 _profile(PackageTable$reloadData$Section$Package)
6346 package = [packages_ objectAtIndex:offset];
6347 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6350 while (secidx < index) {
6353 _profile(PackageTable$reloadData$Section$Allocate)
6354 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6357 _profile(PackageTable$reloadData$Section$Add)
6358 [sections_ addObject:section];
6362 [section addToCount];
6368 [index_ removeAllObjects];
6370 _profile(PackageTable$reloadData$Section)
6371 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6375 _profile(PackageTable$reloadData$Section$Package)
6376 package = [packages_ objectAtIndex:offset];
6377 index = [package index];
6380 if (section == nil || [section index] != index) {
6381 _profile(PackageTable$reloadData$Section$Allocate)
6382 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6385 [index_ addObject:[section name]];
6386 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6388 _profile(PackageTable$reloadData$Section$Add)
6389 [sections_ addObject:section];
6393 [section addToCount];
6398 _profile(PackageTable$reloadData$List)
6403 - (void) resetCursor {
6404 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
6409 /* Filtered Package List Controller {{{ */
6410 @interface FilteredPackageListController : PackageListController {
6416 - (void) setObject:(id)object;
6417 - (void) setObject:(id)object forFilter:(SEL)filter;
6419 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6423 @implementation FilteredPackageListController
6431 - (void) setFilter:(SEL)filter {
6434 /* XXX: this is an unsafe optimization of doomy hell */
6435 Method method(class_getInstanceMethod([Package class], filter));
6436 _assert(method != NULL);
6437 imp_ = method_getImplementation(method);
6438 _assert(imp_ != NULL);
6441 - (void) setObject:(id)object {
6447 object_ = [object retain];
6450 - (void) setObject:(id)object forFilter:(SEL)filter {
6451 [self setFilter:filter];
6452 [self setObject:object];
6455 - (bool) hasPackage:(Package *)package {
6456 _profile(FilteredPackageTable$hasPackage)
6457 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
6461 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6462 if ((self = [super initWithDatabase:database title:title]) != nil) {
6463 [self setFilter:filter];
6464 [self setObject:object];
6471 /* Home Controller {{{ */
6472 @interface HomeController : CydiaWebViewController {
6477 @implementation HomeController
6480 if ((self = [super init]) != nil) {
6481 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6486 - (NSURL *) navigationURL {
6487 return [NSURL URLWithString:@"cydia://home"];
6490 - (void) aboutButtonClicked {
6491 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6493 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6494 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6495 [alert setCancelButtonIndex:0];
6498 @"Copyright (C) 2008-2011\n"
6499 "Jay Freeman (saurik)\n"
6500 "saurik@saurik.com\n"
6501 "http://www.saurik.com/"
6507 - (void) viewDidLoad {
6508 [super viewDidLoad];
6510 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6511 initWithTitle:UCLocalize("ABOUT")
6512 style:UIBarButtonItemStylePlain
6514 action:@selector(aboutButtonClicked)
6518 - (void) unloadData {
6525 /* Manage Controller {{{ */
6526 @interface ManageController : CydiaWebViewController {
6529 - (void) queueStatusDidChange;
6533 @implementation ManageController
6536 if ((self = [super init]) != nil) {
6537 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/manage/", UI_]]];
6541 - (NSURL *) navigationURL {
6542 return [NSURL URLWithString:@"cydia://manage"];
6545 - (void) viewDidLoad {
6546 [super viewDidLoad];
6548 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6549 initWithTitle:UCLocalize("SETTINGS")
6550 style:UIBarButtonItemStylePlain
6552 action:@selector(settingsButtonClicked)
6555 [self queueStatusDidChange];
6558 - (void) settingsButtonClicked {
6559 [delegate_ showSettings];
6563 - (void) queueButtonClicked {
6567 - (void) applyLoadingTitle {
6568 // Disable "Loading" title.
6571 - (void) applyRightButton {
6572 // Disable right button.
6576 - (void) queueStatusDidChange {
6578 if (!IsWildcat_ && Queuing_) {
6579 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6580 initWithTitle:UCLocalize("QUEUE")
6581 style:UIBarButtonItemStyleDone
6583 action:@selector(queueButtonClicked)
6586 [[self navigationItem] setRightBarButtonItem:nil];
6591 - (bool) isLoading {
6592 // Never show as loading.
6599 /* Refresh Bar {{{ */
6600 @interface RefreshBar : UINavigationBar {
6601 UIProgressIndicator *indicator_;
6602 UITextLabel *prompt_;
6603 UIProgressBar *progress_;
6604 UINavigationButton *cancel_;
6609 @implementation RefreshBar
6612 [indicator_ release];
6614 [progress_ release];
6619 - (void) positionViews {
6620 CGRect frame = [cancel_ frame];
6621 frame.size = [cancel_ sizeThatFits:frame.size];
6622 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6623 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6624 [cancel_ setFrame:frame];
6626 CGSize prgsize = {75, 100};
6628 [self frame].size.width - prgsize.width - 10,
6629 ([self frame].size.height - prgsize.height) / 2
6631 [progress_ setFrame:prgrect];
6633 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6634 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6635 CGRect indrect = {{indoffset, indoffset}, indsize};
6636 [indicator_ setFrame:indrect];
6638 CGSize prmsize = {215, indsize.height + 4};
6640 indoffset * 2 + indsize.width,
6641 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6643 [prompt_ setFrame:prmrect];
6646 - (void) setFrame:(CGRect)frame {
6647 [super setFrame:frame];
6648 [self positionViews];
6651 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6652 if ((self = [super initWithFrame:frame]) != nil) {
6653 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6655 [self setBarStyle:UIBarStyleBlack];
6657 UIBarStyle barstyle([self _barStyle:NO]);
6658 bool ugly(barstyle == UIBarStyleDefault);
6660 UIProgressIndicatorStyle style = ugly ?
6661 UIProgressIndicatorStyleMediumBrown :
6662 UIProgressIndicatorStyleMediumWhite;
6664 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6665 [indicator_ setStyle:style];
6666 [indicator_ startAnimation];
6667 [self addSubview:indicator_];
6669 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6670 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6671 [prompt_ setBackgroundColor:[UIColor clearColor]];
6672 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6673 [self addSubview:prompt_];
6675 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6676 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6677 [progress_ setStyle:0];
6678 [self addSubview:progress_];
6680 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6681 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6682 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6683 [cancel_ setBarStyle:barstyle];
6685 [self positionViews];
6689 - (void) setCancellable:(bool)cancellable {
6691 [self addSubview:cancel_];
6693 [cancel_ removeFromSuperview];
6697 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6698 [progress_ setProgress:0];
6702 [self setCancellable:NO];
6705 - (void) setPrompt:(NSString *)prompt {
6706 [prompt_ setText:prompt];
6709 - (void) setProgress:(float)progress {
6710 [progress_ setProgress:progress];
6716 /* Cydia Navigation Controller Interface {{{ */
6717 @interface UINavigationController (Cydia)
6719 - (NSArray *) navigationURLCollection;
6720 - (void) unloadData;
6725 /* Cydia Tab Bar Controller {{{ */
6726 @interface CYTabBarController : UITabBarController <
6727 UITabBarControllerDelegate,
6730 _transient Database *database_;
6731 RefreshBar *refreshbar_;
6735 // XXX: ok, "updatedelegate_"?...
6736 _transient NSObject<CydiaDelegate> *updatedelegate_;
6739 UIViewController *remembered_;
6740 _transient UIViewController *transient_;
6743 - (NSArray *) navigationURLCollection;
6744 - (void) dropBar:(BOOL)animated;
6745 - (void) beginUpdate;
6746 - (void) raiseBar:(BOOL)animated;
6748 - (void) unloadData;
6752 @implementation CYTabBarController
6754 - (void) setUnselectedViewController:(UIViewController *)transient {
6755 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6756 if (transient != nil) {
6757 if (transient_ == nil)
6758 remembered_ = [[controllers objectAtIndex:0] retain];
6759 transient_ = transient;
6760 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6761 [controllers replaceObjectAtIndex:0 withObject:transient_];
6762 [self setSelectedIndex:0];
6763 [self setViewControllers:controllers];
6764 [self concealTabBarSelection];
6765 } else if (remembered_ != nil) {
6766 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6767 transient_ = transient;
6768 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6769 [remembered_ release];
6771 [self setViewControllers:controllers];
6772 [self revealTabBarSelection];
6776 - (UIViewController *) unselectedViewController {
6780 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6781 if ([self unselectedViewController])
6782 [self setUnselectedViewController:nil];
6785 - (NSArray *) navigationURLCollection {
6786 NSMutableArray *items([NSMutableArray array]);
6788 // XXX: Should this deal with transient view controllers?
6789 for (id navigation in [self viewControllers]) {
6790 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6792 [items addObject:stack];
6798 - (void) unloadData {
6799 UIViewController *selected([self selectedViewController]);
6800 for (UINavigationController *controller in [self viewControllers])
6801 [controller unloadData];
6803 [selected reloadData];
6805 if (UIViewController *unselected = [self unselectedViewController])
6806 [unselected reloadData];
6812 [refreshbar_ release];
6813 [[NSNotificationCenter defaultCenter] removeObserver:self];
6818 - (id) initWithDatabase:(Database *)database {
6819 if ((self = [super init]) != nil) {
6820 database_ = database;
6821 [self setDelegate:self];
6823 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6824 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6826 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
6830 - (void) setUpdate:(NSDate *)date {
6834 - (void) beginUpdate {
6835 [refreshbar_ start];
6838 [updatedelegate_ retainNetworkActivityIndicator];
6842 detachNewThreadSelector:@selector(performUpdate)
6848 - (void) performUpdate { _pooled
6850 status.setDelegate(self);
6851 [database_ updateWithStatus:status];
6854 performSelectorOnMainThread:@selector(completeUpdate)
6860 - (void) stopUpdateWithSelector:(SEL)selector {
6862 [updatedelegate_ releaseNetworkActivityIndicator];
6864 [self raiseBar:YES];
6867 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6870 - (void) completeUpdate {
6873 [self stopUpdateWithSelector:@selector(reloadData)];
6876 - (void) cancelUpdate {
6877 [self stopUpdateWithSelector:@selector(updateData)];
6880 - (void) cancelPressed {
6881 [self cancelUpdate];
6888 - (void) addProgressEvent:(CydiaProgressEvent *)event {
6889 [refreshbar_ setPrompt:[event compoundMessage]];
6892 - (bool) isProgressCancelled {
6896 - (void) setProgressCancellable:(NSNumber *)cancellable {
6897 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
6900 - (void) setProgressPercent:(NSNumber *)percent {
6901 [refreshbar_ setProgress:[percent floatValue]];
6904 - (void) setProgressStatus:(NSDictionary *)status {
6906 [self setProgressPercent:[status objectForKey:@"Percent"]];
6909 - (void) setUpdateDelegate:(id)delegate {
6910 updatedelegate_ = delegate;
6913 - (CGFloat) statusBarHeight {
6914 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
6915 return [[UIApplication sharedApplication] statusBarFrame].size.height;
6917 return [[UIApplication sharedApplication] statusBarFrame].size.width;
6921 - (UIView *) transitionView {
6922 if ([self respondsToSelector:@selector(_transitionView)])
6923 return [self _transitionView];
6925 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6928 - (void) dropBar:(BOOL)animated {
6933 UIView *transition([self transitionView]);
6934 [[self view] addSubview:refreshbar_];
6936 CGRect barframe([refreshbar_ frame]);
6938 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6939 barframe.origin.y = [self statusBarHeight];
6941 barframe.origin.y = 0;
6943 [refreshbar_ setFrame:barframe];
6946 [UIView beginAnimations:nil context:NULL];
6948 CGRect viewframe = [transition frame];
6949 viewframe.origin.y += barframe.size.height;
6950 viewframe.size.height -= barframe.size.height;
6951 [transition setFrame:viewframe];
6954 [UIView commitAnimations];
6956 // Ensure bar has the proper width for our view, it might have changed
6957 barframe.size.width = viewframe.size.width;
6958 [refreshbar_ setFrame:barframe];
6960 // XXX: fix Apple's layout bug
6961 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6964 - (void) raiseBar:(BOOL)animated {
6969 UIView *transition([self transitionView]);
6970 [refreshbar_ removeFromSuperview];
6972 CGRect barframe([refreshbar_ frame]);
6975 [UIView beginAnimations:nil context:NULL];
6977 CGRect viewframe = [transition frame];
6978 viewframe.origin.y -= barframe.size.height;
6979 viewframe.size.height += barframe.size.height;
6980 [transition setFrame:viewframe];
6983 [UIView commitAnimations];
6985 // XXX: fix Apple's layout bug
6986 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6990 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
6991 // XXX: fix Apple's layout bug
6992 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6996 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6997 bool dropped(dropped_);
7002 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
7007 // XXX: fix Apple's layout bug
7008 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
7011 - (void) statusBarFrameChanged:(NSNotification *)notification {
7021 /* Cydia Navigation Controller Implementation {{{ */
7022 @implementation UINavigationController (Cydia)
7024 - (NSArray *) navigationURLCollection {
7025 NSMutableArray *stack([NSMutableArray array]);
7027 for (CYViewController *controller in [self viewControllers]) {
7028 NSString *url = [[controller navigationURL] absoluteString];
7030 [stack addObject:url];
7036 - (void) reloadData {
7039 if (UIViewController *visible = [self visibleViewController])
7040 [visible reloadData];
7043 - (void) unloadData {
7044 for (CYViewController *page in [self viewControllers])
7053 /* Cydia:// Protocol {{{ */
7054 @interface CydiaURLProtocol : NSURLProtocol {
7059 @implementation CydiaURLProtocol
7061 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7062 NSURL *url([request URL]);
7066 NSString *scheme([[url scheme] lowercaseString]);
7067 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7069 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7075 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7079 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7080 id<NSURLProtocolClient> client([self client]);
7082 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7084 NSData *data(UIImagePNGRepresentation(icon));
7086 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7087 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7088 [client URLProtocol:self didLoadData:data];
7089 [client URLProtocolDidFinishLoading:self];
7093 - (void) startLoading {
7094 id<NSURLProtocolClient> client([self client]);
7095 NSURLRequest *request([self request]);
7097 NSURL *url([request URL]);
7098 NSString *href([url absoluteString]);
7099 NSString *scheme([[url scheme] lowercaseString]);
7103 if ([scheme isEqualToString:@"cydia"])
7104 path = [href substringFromIndex:8];
7105 else if ([scheme isEqualToString:@"about"])
7106 path = [href substringFromIndex:12];
7107 else _assert(false);
7109 NSRange slash([path rangeOfString:@"/"]);
7112 if (slash.location == NSNotFound) {
7116 command = [path substringToIndex:slash.location];
7117 path = [path substringFromIndex:(slash.location + 1)];
7120 Database *database([Database sharedInstance]);
7122 if ([command isEqualToString:@"package-icon"]) {
7125 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7126 Package *package([database packageWithName:path]);
7129 UIImage *icon([package icon]);
7130 [self _returnPNGWithImage:icon forRequest:request];
7131 } else if ([command isEqualToString:@"source-icon"]) {
7134 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7135 NSString *source(Simplify(path));
7136 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
7138 icon = [UIImage applicationImageNamed:@"unknown.png"];
7139 [self _returnPNGWithImage:icon forRequest:request];
7140 } else if ([command isEqualToString:@"uikit-image"]) {
7143 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7144 UIImage *icon(_UIImageWithName(path));
7145 [self _returnPNGWithImage:icon forRequest:request];
7146 } else if ([command isEqualToString:@"section-icon"]) {
7149 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7150 NSString *section(Simplify(path));
7151 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
7153 icon = [UIImage applicationImageNamed:@"unknown.png"];
7154 [self _returnPNGWithImage:icon forRequest:request];
7156 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7160 - (void) stopLoading {
7166 /* Section Controller {{{ */
7167 @interface SectionController : FilteredPackageListController {
7168 _H<NSString> section_;
7171 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
7175 @implementation SectionController
7177 - (NSURL *) navigationURL {
7178 NSString *name = section_;
7182 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
7185 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7188 title = UCLocalize("ALL_PACKAGES");
7189 else if (![name isEqual:@""])
7190 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7192 title = UCLocalize("NO_SECTION");
7194 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7201 /* Sections Controller {{{ */
7202 @interface SectionsController : CYViewController <
7203 UITableViewDataSource,
7206 _transient Database *database_;
7207 NSMutableArray *sections_;
7208 NSMutableArray *filtered_;
7212 - (id) initWithDatabase:(Database *)database;
7213 - (void) editButtonClicked;
7217 @implementation SectionsController
7220 [self releaseSubviews];
7221 [sections_ release];
7222 [filtered_ release];
7227 - (NSURL *) navigationURL {
7228 return [NSURL URLWithString:@"cydia://sections"];
7231 - (void) updateNavigationItem {
7232 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7233 if ([sections_ count] == 0) {
7234 [[self navigationItem] setRightBarButtonItem:nil];
7236 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7237 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7239 action:@selector(editButtonClicked)
7240 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7244 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7245 [super setEditing:editing animated:animated];
7250 [delegate_ updateData];
7252 [self updateNavigationItem];
7255 - (void) viewDidAppear:(BOOL)animated {
7256 [super viewDidAppear:animated];
7257 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7260 - (void) viewWillDisappear:(BOOL)animated {
7261 [super viewWillDisappear:animated];
7262 if ([self isEditing]) [self setEditing:NO];
7265 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7266 Section *section = nil;
7267 int index = [indexPath row];
7268 if (![self isEditing]) {
7271 section = [filtered_ objectAtIndex:index];
7273 section = [sections_ objectAtIndex:index];
7278 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7279 if ([self isEditing])
7280 return [sections_ count];
7282 return [filtered_ count] + 1;
7285 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7289 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7290 static NSString *reuseIdentifier = @"SectionCell";
7292 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7294 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7296 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7301 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7302 if ([self isEditing])
7305 Section *section = [self sectionAtIndexPath:indexPath];
7307 SectionController *controller = [[[SectionController alloc]
7308 initWithDatabase:database_
7309 section:[section name]
7311 [controller setDelegate:delegate_];
7313 [[self navigationController] pushViewController:controller animated:YES];
7317 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7319 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
7320 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7321 [list_ setRowHeight:45.0f];
7322 [list_ setDataSource:self];
7323 [list_ setDelegate:self];
7324 [[self view] addSubview:list_];
7327 - (void) viewDidLoad {
7328 [super viewDidLoad];
7330 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7333 - (void) releaseSubviews {
7338 - (id) initWithDatabase:(Database *)database {
7339 if ((self = [super init]) != nil) {
7340 database_ = database;
7342 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7343 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
7347 - (void) reloadData {
7350 NSArray *packages = [database_ packages];
7352 [sections_ removeAllObjects];
7353 [filtered_ removeAllObjects];
7355 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7358 for (Package *package in packages) {
7359 NSString *name([package section]);
7360 NSString *key(name == nil ? @"" : name);
7364 _profile(SectionsView$reloadData$Section)
7365 section = [sections objectForKey:key];
7366 if (section == nil) {
7367 _profile(SectionsView$reloadData$Section$Allocate)
7368 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7369 [sections setObject:section forKey:key];
7374 [section addToCount];
7376 _profile(SectionsView$reloadData$Filter)
7377 if (![package valid] || ![package visible])
7385 [sections_ addObjectsFromArray:[sections allValues]];
7387 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7389 for (Section *section in sections_) {
7390 size_t count([section row]);
7394 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7395 [section setCount:count];
7396 [filtered_ addObject:section];
7399 [self updateNavigationItem];
7404 - (void) editButtonClicked {
7405 [self setEditing:![self isEditing] animated:YES];
7411 /* Changes Controller {{{ */
7412 @interface ChangesController : CYViewController <
7413 UITableViewDataSource,
7416 _transient Database *database_;
7418 CFMutableArrayRef packages_;
7419 NSMutableArray *sections_;
7424 - (id) initWithDatabase:(Database *)database;
7428 @implementation ChangesController
7431 [self releaseSubviews];
7432 CFRelease(packages_);
7433 [sections_ release];
7438 - (NSURL *) navigationURL {
7439 return [NSURL URLWithString:@"cydia://changes"];
7442 - (void) viewDidAppear:(BOOL)animated {
7443 [super viewDidAppear:animated];
7444 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7447 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7448 NSInteger count([sections_ count]);
7449 return count == 0 ? 1 : count;
7452 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7453 if ([sections_ count] == 0)
7455 return [[sections_ objectAtIndex:section] name];
7458 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7459 if ([sections_ count] == 0)
7461 return [[sections_ objectAtIndex:section] count];
7464 - (Package *) packageAtIndex:(NSUInteger)index {
7465 return (Package *) CFArrayGetValueAtIndex(packages_, index);
7468 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7469 @synchronized (database_) {
7470 if ([database_ era] != era_)
7473 NSUInteger sectionIndex([path section]);
7474 if (sectionIndex >= [sections_ count])
7476 Section *section([sections_ objectAtIndex:sectionIndex]);
7477 NSInteger row([path row]);
7478 return [[[self packageAtIndex:([section row] + row)] retain] autorelease];
7481 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7482 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7484 cell = [[[PackageCell alloc] init] autorelease];
7485 [cell setPackage:[self packageAtIndexPath:path]];
7489 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7490 Package *package([self packageAtIndexPath:path]);
7491 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7492 [view setDelegate:delegate_];
7493 [[self navigationController] pushViewController:view animated:YES];
7497 - (void) refreshButtonClicked {
7498 [delegate_ beginUpdate];
7499 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7502 - (void) upgradeButtonClicked {
7503 [delegate_ distUpgrade];
7507 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7509 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7510 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7511 [list_ setRowHeight:73];
7512 [list_ setDataSource:self];
7513 [list_ setDelegate:self];
7514 [[self view] addSubview:list_];
7517 - (void) viewDidLoad {
7518 [super viewDidLoad];
7520 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7523 - (void) releaseSubviews {
7528 - (id) initWithDatabase:(Database *)database {
7529 if ((self = [super init]) != nil) {
7530 database_ = database;
7532 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7533 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7537 // this mostly works because reloadData (below) is @synchronized (database_)
7538 // XXX: that said, I've been running into problems with NSRangeExceptions :(
7539 - (void) _reloadPackages:(NSArray *)packages {
7540 CFRelease(packages_);
7541 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, [packages count], NULL);
7544 _profile(ChangesController$_reloadPackages$Filter)
7545 for (Package *package in packages)
7546 if ([package upgradableAndEssential:YES] || [package visible])
7547 CFArrayAppendValue(packages_, package);
7550 _profile(ChangesController$_reloadPackages$radixSort)
7551 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7556 - (void) _reloadData {
7557 @synchronized (database_) {
7558 era_ = [database_ era];
7559 NSArray *packages = [database_ packages];
7561 [sections_ removeAllObjects];
7564 UIProgressHUD *hud([delegate_ addProgressHUD]);
7565 [hud setText:UCLocalize("LOADING")];
7566 //NSLog(@"HUD:%@::%@", delegate_, hud);
7567 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7568 [delegate_ removeProgressHUD:hud];
7570 [self _reloadPackages:packages];
7573 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7574 Section *ignored = nil;
7575 Section *section = nil;
7579 bool unseens = false;
7581 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7583 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7584 Package *package = [self packageAtIndex:offset];
7586 BOOL uae = [package upgradableAndEssential:YES];
7590 time_t seen([package seen]);
7592 if (section == nil || last != seen) {
7596 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7599 _profile(ChangesController$reloadData$Allocate)
7600 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7601 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7602 [sections_ addObject:section];
7606 [section addToCount];
7607 } else if ([package ignored]) {
7608 if (ignored == nil) {
7609 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7611 [ignored addToCount];
7614 [upgradable addToCount];
7619 CFRelease(formatter);
7622 Section *last = [sections_ lastObject];
7623 size_t count = [last count];
7624 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7625 [sections_ removeLastObject];
7628 if ([ignored count] != 0)
7629 [sections_ insertObject:ignored atIndex:0];
7631 [sections_ insertObject:upgradable atIndex:0];
7636 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7637 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7638 style:UIBarButtonItemStylePlain
7640 action:@selector(upgradeButtonClicked)
7643 if (![delegate_ updating])
7644 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7645 initWithTitle:UCLocalize("REFRESH")
7646 style:UIBarButtonItemStylePlain
7648 action:@selector(refreshButtonClicked)
7654 - (void) reloadData {
7656 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
7661 /* Search Controller {{{ */
7662 @interface SearchController : FilteredPackageListController <
7665 _H<UISearchBar> search_;
7669 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7670 - (void) reloadData;
7674 @implementation SearchController
7677 [search_ setDelegate:nil];
7681 - (NSURL *) navigationURL {
7682 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7683 return [NSURL URLWithString:@"cydia://search"];
7685 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7688 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7689 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7690 [search_ resignFirstResponder];
7694 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7695 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7699 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7700 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:query])) {
7701 search_ = [[[UISearchBar alloc] init] autorelease];
7702 [search_ setDelegate:self];
7705 [search_ setText:query];
7709 - (void) viewDidAppear:(BOOL)animated {
7710 [super viewDidAppear:animated];
7712 if (!searchloaded_) {
7713 searchloaded_ = YES;
7714 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7715 [search_ layoutSubviews];
7716 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7718 UITextField *textField;
7719 if ([search_ respondsToSelector:@selector(searchField)])
7720 textField = [search_ searchField];
7722 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7724 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7725 [textField setEnablesReturnKeyAutomatically:NO];
7726 [[self navigationItem] setTitleView:textField];
7730 - (void) reloadData {
7731 [self setObject:[search_ text]];
7737 - (void) didSelectPackage:(Package *)package {
7738 [search_ resignFirstResponder];
7739 [super didSelectPackage:package];
7744 /* Package Settings Controller {{{ */
7745 @interface PackageSettingsController : CYViewController <
7746 UITableViewDataSource,
7749 _transient Database *database_;
7752 UITableView *table_;
7753 UISwitch *subscribedSwitch_;
7754 UISwitch *ignoredSwitch_;
7755 UITableViewCell *subscribedCell_;
7756 UITableViewCell *ignoredCell_;
7759 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7763 @implementation PackageSettingsController
7766 [self releaseSubviews];
7773 - (NSURL *) navigationURL {
7774 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", [package_ id]]];
7777 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7778 if (package_ == nil)
7781 if ([package_ installed] == nil)
7787 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7788 if (package_ == nil)
7791 // both sections contain just one item right now.
7795 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7799 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7801 return UCLocalize("SHOW_ALL_CHANGES_EX");
7803 return UCLocalize("IGNORE_UPGRADES_EX");
7806 - (void) onSubscribed:(id)control {
7807 bool value([control isOn]);
7808 if (package_ == nil)
7810 if ([package_ setSubscribed:value])
7811 [delegate_ updateData];
7814 - (void) _updateIgnored {
7815 const char *package([name_ UTF8String]);
7816 bool on([ignoredSwitch_ isOn]);
7818 pid_t pid(ExecFork());
7820 FILE *dpkg(popen("dpkg --set-selections", "w"));
7821 fwrite(package, strlen(package), 1, dpkg);
7824 fwrite(" hold\n", 6, 1, dpkg);
7826 fwrite(" install\n", 9, 1, dpkg);
7836 int result(waitpid(pid, &status, 0));
7839 _assert(result == pid);
7845 - (void) onIgnored:(id)control {
7846 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7847 [invocation setTarget:self];
7848 [invocation setSelector:@selector(_updateIgnored)];
7850 [delegate_ reloadDataWithInvocation:invocation];
7853 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7854 if (package_ == nil)
7857 switch ([indexPath section]) {
7858 case 0: return subscribedCell_;
7859 case 1: return ignoredCell_;
7868 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7870 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7871 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7872 [table_ setDataSource:self];
7873 [table_ setDelegate:self];
7874 [[self view] addSubview:table_];
7876 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7877 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7878 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7880 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7881 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7882 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7884 subscribedCell_ = [[UITableViewCell alloc] init];
7885 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7886 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7887 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7889 ignoredCell_ = [[UITableViewCell alloc] init];
7890 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7891 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7892 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7895 - (void) viewDidLoad {
7896 [super viewDidLoad];
7898 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7901 - (void) releaseSubviews {
7902 [ignoredCell_ release];
7905 [subscribedCell_ release];
7906 subscribedCell_ = nil;
7911 [ignoredSwitch_ release];
7912 ignoredSwitch_ = nil;
7914 [subscribedSwitch_ release];
7915 subscribedSwitch_ = nil;
7918 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7919 if ((self = [super init]) != nil) {
7920 database_ = database;
7921 name_ = [package retain];
7925 - (void) reloadData {
7928 if (package_ != nil)
7929 [package_ autorelease];
7930 package_ = [database_ packageWithName:name_];
7932 if (package_ != nil) {
7933 package_ = [package_ retain];
7934 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7935 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7936 } // XXX: what now, G?
7938 [table_ reloadData];
7944 /* Installed Controller {{{ */
7945 @interface InstalledController : FilteredPackageListController {
7949 - (id) initWithDatabase:(Database *)database;
7951 - (void) updateRoleButton;
7952 - (void) queueStatusDidChange;
7956 @implementation InstalledController
7962 - (NSURL *) navigationURL {
7963 return [NSURL URLWithString:@"cydia://installed"];
7966 - (id) initWithDatabase:(Database *)database {
7967 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7968 [self updateRoleButton];
7969 [self queueStatusDidChange];
7974 - (void) queueButtonClicked {
7979 - (void) queueStatusDidChange {
7983 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7984 initWithTitle:UCLocalize("QUEUE")
7985 style:UIBarButtonItemStyleDone
7987 action:@selector(queueButtonClicked)
7990 [[self navigationItem] setLeftBarButtonItem:nil];
7996 - (void) updateRoleButton {
7997 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7998 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7999 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
8000 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8002 action:@selector(roleButtonClicked)
8006 - (void) roleButtonClicked {
8007 [self setObject:[NSNumber numberWithBool:expert_]];
8011 [self updateRoleButton];
8017 /* Source Cell {{{ */
8018 @interface SourceCell : CYTableViewCell <
8026 - (void) setSource:(Source *)source;
8030 @implementation SourceCell
8032 - (void) clearSource {
8042 - (void) setSource:(Source *)source {
8046 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
8048 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
8049 icon_ = [icon_ retain];
8051 origin_ = [[source name] retain];
8052 label_ = [[source uri] retain];
8054 [content_ setNeedsDisplay];
8062 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8063 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8064 UIView *content([self contentView]);
8065 CGRect bounds([content bounds]);
8067 content_ = [[ContentView alloc] initWithFrame:bounds];
8068 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8069 [content_ setBackgroundColor:[UIColor whiteColor]];
8070 [content addSubview:content_];
8072 [content_ setDelegate:self];
8073 [content_ setOpaque:YES];
8077 - (NSString *) accessibilityLabel {
8081 - (void) drawContentRect:(CGRect)rect {
8082 bool highlighted(highlighted_);
8083 float width(rect.size.width);
8086 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
8093 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
8097 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
8102 /* Source Controller {{{ */
8103 @interface SourceController : FilteredPackageListController {
8104 _transient Source *source_;
8108 - (id) initWithDatabase:(Database *)database source:(Source *)source;
8112 @implementation SourceController
8114 - (NSURL *) navigationURL {
8115 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [source_ name]]];
8118 - (id) initWithDatabase:(Database *)database source:(Source *)source {
8119 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
8121 key_ = [[source key] retain];
8125 - (void) reloadData {
8126 source_ = [database_ sourceWithKey:key_];
8128 key_ = [[source_ key] retain];
8129 [self setObject:source_];
8131 [[self navigationItem] setTitle:[source_ label]];
8138 /* Sources Controller {{{ */
8139 @interface SourcesController : CYViewController <
8140 UITableViewDataSource,
8143 _transient Database *database_;
8145 NSMutableArray *sources_;
8149 UIProgressHUD *hud_;
8152 //NSURLConnection *installer_;
8153 NSURLConnection *trivial_;
8154 NSURLConnection *trivial_bz2_;
8155 NSURLConnection *trivial_gz_;
8156 //NSURLConnection *automatic_;
8161 - (id) initWithDatabase:(Database *)database;
8162 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
8166 @implementation SourcesController
8168 - (void) _releaseConnection:(NSURLConnection *)connection {
8169 if (connection != nil) {
8170 [connection cancel];
8171 //[connection setDelegate:nil];
8172 [connection release];
8177 [self releaseSubviews];
8183 //[self _releaseConnection:installer_];
8184 [self _releaseConnection:trivial_];
8185 [self _releaseConnection:trivial_gz_];
8186 [self _releaseConnection:trivial_bz2_];
8187 //[self _releaseConnection:automatic_];
8193 - (NSURL *) navigationURL {
8194 return [NSURL URLWithString:@"cydia://sources"];
8197 - (void) viewDidAppear:(BOOL)animated {
8198 [super viewDidAppear:animated];
8199 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8202 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8203 return offset_ == 0 ? 1 : 2;
8206 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8207 switch (section + (offset_ == 0 ? 1 : 0)) {
8208 case 0: return UCLocalize("ENTERED_BY_USER");
8209 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
8215 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8216 int count = [sources_ count];
8218 case 0: return (offset_ == 0 ? count : offset_);
8219 case 1: return count - offset_;
8225 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8227 switch (indexPath.section) {
8228 case 0: idx = indexPath.row; break;
8229 case 1: idx = indexPath.row + offset_; break;
8233 return [sources_ objectAtIndex:idx];
8236 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8237 static NSString *cellIdentifier = @"SourceCell";
8239 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8240 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8241 [cell setSource:[self sourceAtIndexPath:indexPath]];
8242 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8247 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8248 Source *source = [self sourceAtIndexPath:indexPath];
8250 SourceController *controller = [[[SourceController alloc]
8251 initWithDatabase:database_
8255 [controller setDelegate:delegate_];
8257 [[self navigationController] pushViewController:controller animated:YES];
8260 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8261 Source *source = [self sourceAtIndexPath:indexPath];
8262 return [source record] != nil;
8265 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8266 Source *source = [self sourceAtIndexPath:indexPath];
8267 [Sources_ removeObjectForKey:[source key]];
8268 [delegate_ syncData];
8272 [delegate_ addTrivialSource:href_];
8273 [delegate_ syncData];
8276 - (NSString *) getWarning {
8277 NSString *href(href_);
8278 NSRange colon([href rangeOfString:@"://"]);
8279 if (colon.location != NSNotFound)
8280 href = [href substringFromIndex:(colon.location + 3)];
8281 href = [href stringByAddingPercentEscapes];
8282 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8283 href = [href stringByCachingURLWithCurrentCDN];
8285 NSURL *url([NSURL URLWithString:href]);
8287 NSStringEncoding encoding;
8288 NSError *error(nil);
8290 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8291 return [warning length] == 0 ? nil : warning;
8295 - (void) _endConnection:(NSURLConnection *)connection {
8296 // XXX: the memory management in this method is horribly awkward
8298 NSURLConnection **field = NULL;
8299 if (connection == trivial_)
8301 else if (connection == trivial_bz2_)
8302 field = &trivial_bz2_;
8303 else if (connection == trivial_gz_)
8304 field = &trivial_gz_;
8305 _assert(field != NULL);
8306 [connection release];
8311 trivial_bz2_ == nil &&
8317 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
8320 UIAlertView *alert = [[[UIAlertView alloc]
8321 initWithTitle:UCLocalize("SOURCE_WARNING")
8324 cancelButtonTitle:UCLocalize("CANCEL")
8326 UCLocalize("ADD_ANYWAY"),
8330 [alert setContext:@"warning"];
8331 [alert setNumberOfRows:1];
8335 } else if (error_ != nil) {
8336 UIAlertView *alert = [[[UIAlertView alloc]
8337 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8338 message:[error_ localizedDescription]
8340 cancelButtonTitle:UCLocalize("OK")
8341 otherButtonTitles:nil
8344 [alert setContext:@"urlerror"];
8347 UIAlertView *alert = [[[UIAlertView alloc]
8348 initWithTitle:UCLocalize("NOT_REPOSITORY")
8349 message:UCLocalize("NOT_REPOSITORY_EX")
8351 cancelButtonTitle:UCLocalize("OK")
8352 otherButtonTitles:nil
8355 [alert setContext:@"trivial"];
8359 [delegate_ releaseNetworkActivityIndicator];
8361 [delegate_ removeProgressHUD:hud_];
8370 if (error_ != nil) {
8377 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8378 switch ([response statusCode]) {
8384 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8385 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8387 error_ = [error retain];
8388 [self _endConnection:connection];
8391 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8392 [self _endConnection:connection];
8395 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8396 NSMutableURLRequest *request = [NSMutableURLRequest
8397 requestWithURL:[NSURL URLWithString:href]
8398 cachePolicy:NSURLRequestUseProtocolCachePolicy
8399 timeoutInterval:120.0
8402 [request setHTTPMethod:method];
8404 if (Machine_ != NULL)
8405 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8406 if (UniqueID_ != nil)
8407 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8409 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8412 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8413 NSString *context([alert context]);
8415 if ([context isEqualToString:@"source"]) {
8418 NSString *href = [[alert textField] text];
8420 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8422 if (![href hasSuffix:@"/"])
8423 href_ = [href stringByAppendingString:@"/"];
8426 href_ = [href_ retain];
8428 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8429 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8430 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8431 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8435 // XXX: this is stupid
8436 hud_ = [[delegate_ addProgressHUD] retain];
8437 [hud_ setText:UCLocalize("VERIFYING_URL")];
8438 [delegate_ retainNetworkActivityIndicator];
8447 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8448 } else if ([context isEqualToString:@"trivial"])
8449 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8450 else if ([context isEqualToString:@"urlerror"])
8451 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8452 else if ([context isEqualToString:@"warning"]) {
8467 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8472 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8474 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
8475 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8476 [list_ setRowHeight:56];
8477 [list_ setDataSource:self];
8478 [list_ setDelegate:self];
8479 [[self view] addSubview:list_];
8482 - (void) viewDidLoad {
8483 [super viewDidLoad];
8485 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8486 [self updateButtonsForEditingStatus:NO animated:NO];
8489 - (void) releaseSubviews {
8494 - (id) initWithDatabase:(Database *)database {
8495 if ((self = [super init]) != nil) {
8496 database_ = database;
8497 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
8501 - (void) reloadData {
8505 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8508 [sources_ removeAllObjects];
8509 [sources_ addObjectsFromArray:[database_ sources]];
8511 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8514 int count([sources_ count]);
8516 for (int i = 0; i != count; i++) {
8517 if ([[sources_ objectAtIndex:i] record] == nil)
8522 [list_ setEditing:NO];
8523 [self updateButtonsForEditingStatus:NO animated:NO];
8527 - (void) showAddSourcePrompt {
8528 UIAlertView *alert = [[[UIAlertView alloc]
8529 initWithTitle:UCLocalize("ENTER_APT_URL")
8532 cancelButtonTitle:UCLocalize("CANCEL")
8534 UCLocalize("ADD_SOURCE"),
8538 [alert setContext:@"source"];
8539 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
8541 [alert setNumberOfRows:1];
8542 [alert addTextFieldWithValue:@"http://" label:@""];
8544 UITextInputTraits *traits = [[alert textField] textInputTraits];
8545 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8546 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8547 [traits setKeyboardType:UIKeyboardTypeURL];
8548 // XXX: UIReturnKeyDone
8549 [traits setReturnKeyType:UIReturnKeyNext];
8554 - (void) addButtonClicked {
8555 [self showAddSourcePrompt];
8558 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8559 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8560 initWithTitle:UCLocalize("ADD")
8561 style:UIBarButtonItemStylePlain
8563 action:@selector(addButtonClicked)
8564 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8566 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8567 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8568 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8570 action:@selector(editButtonClicked)
8571 ] autorelease] animated:animated];
8573 if (IsWildcat_ && !editing)
8574 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8575 initWithTitle:UCLocalize("SETTINGS")
8576 style:UIBarButtonItemStylePlain
8578 action:@selector(settingsButtonClicked)
8582 - (void) settingsButtonClicked {
8583 [delegate_ showSettings];
8586 - (void) editButtonClicked {
8587 [list_ setEditing:![list_ isEditing] animated:YES];
8589 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8595 /* Settings Controller {{{ */
8596 @interface SettingsController : CYViewController <
8597 UITableViewDataSource,
8600 _transient Database *database_;
8601 // XXX: ok, "roledelegate_"?...
8602 _transient id roledelegate_;
8603 UITableView *table_;
8604 UISegmentedControl *segment_;
8608 - (void) showDoneButton;
8609 - (void) resizeSegmentedControl;
8613 @implementation SettingsController
8616 [self releaseSubviews];
8622 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8624 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
8625 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8626 [table_ setDelegate:self];
8627 [table_ setDataSource:self];
8628 [[self view] addSubview:table_];
8630 NSArray *items = [NSArray arrayWithObjects:
8632 UCLocalize("HACKER"),
8633 UCLocalize("DEVELOPER"),
8635 segment_ = [[UISegmentedControl alloc] initWithItems:items];
8636 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
8637 [container_ addSubview:segment_];
8640 - (void) viewDidLoad {
8641 [super viewDidLoad];
8643 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8646 if ([Role_ isEqualToString:@"User"]) index = 0;
8647 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8648 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8650 [segment_ setSelectedSegmentIndex:index];
8651 [self showDoneButton];
8654 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8655 [self resizeSegmentedControl];
8658 - (void) releaseSubviews {
8665 [container_ release];
8669 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8670 if ((self = [super init]) != nil) {
8671 database_ = database;
8672 roledelegate_ = delegate;
8676 - (void) resizeSegmentedControl {
8677 CGFloat width = [[self view] frame].size.width;
8678 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8681 - (void) viewWillAppear:(BOOL)animated {
8682 [super viewWillAppear:animated];
8684 [self resizeSegmentedControl];
8687 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8688 [self resizeSegmentedControl];
8691 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8692 [self resizeSegmentedControl];
8696 NSString *role(nil);
8698 switch ([segment_ selectedSegmentIndex]) {
8699 case 0: role = @"User"; break;
8700 case 1: role = @"Hacker"; break;
8701 case 2: role = @"Developer"; break;
8706 if (![role isEqualToString:Role_]) {
8707 bool rolling(Role_ == nil);
8710 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8714 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8718 [roledelegate_ loadData];
8720 [roledelegate_ updateData];
8724 - (void) segmentChanged:(UISegmentedControl *)control {
8725 [self showDoneButton];
8728 - (void) saveAndClose {
8731 [[self navigationItem] setRightBarButtonItem:nil];
8732 [[self navigationController] dismissModalViewControllerAnimated:YES];
8735 - (void) doneButtonClicked {
8736 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8737 [spinner startAnimating];
8738 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8739 [[self navigationItem] setRightBarButtonItem:spinItem];
8741 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8744 - (void) showDoneButton {
8745 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8746 initWithTitle:UCLocalize("DONE")
8747 style:UIBarButtonItemStyleDone
8749 action:@selector(doneButtonClicked)
8750 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8753 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8754 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8758 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8762 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8763 return nil; // This method is required by the protocol.
8766 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8768 return UCLocalize("ROLE_EX");
8770 return [NSString stringWithFormat:
8771 @"%@: %@\n%@: %@\n%@: %@",
8772 UCLocalize("USER"), UCLocalize("USER_EX"),
8773 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8774 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8779 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8780 return section == 3 ? 44.0f : 0;
8783 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8784 return section == 3 ? container_ : nil;
8787 - (void) reloadData {
8790 [table_ reloadData];
8795 /* Stash Controller {{{ */
8796 @interface StashController : CYViewController {
8797 UIActivityIndicatorView *spinner_;
8804 @implementation StashController
8807 [self releaseSubviews];
8813 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8814 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8816 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8817 CGRect spinrect = [spinner_ frame];
8818 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8819 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8820 [spinner_ setFrame:spinrect];
8821 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8822 [[self view] addSubview:spinner_];
8823 [spinner_ startAnimating];
8826 captrect.size.width = [[self view] frame].size.width;
8827 captrect.size.height = 40.0f;
8828 captrect.origin.x = 0;
8829 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8830 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8831 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8832 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8833 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8834 [caption_ setTextColor:[UIColor whiteColor]];
8835 [caption_ setBackgroundColor:[UIColor clearColor]];
8836 [caption_ setShadowColor:[UIColor blackColor]];
8837 [caption_ setTextAlignment:UITextAlignmentCenter];
8838 [[self view] addSubview:caption_];
8841 statusrect.size.width = [[self view] frame].size.width;
8842 statusrect.size.height = 30.0f;
8843 statusrect.origin.x = 0;
8844 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8845 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8846 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8847 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8848 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8849 [status_ setTextColor:[UIColor whiteColor]];
8850 [status_ setBackgroundColor:[UIColor clearColor]];
8851 [status_ setShadowColor:[UIColor blackColor]];
8852 [status_ setTextAlignment:UITextAlignmentCenter];
8853 [[self view] addSubview:status_];
8856 - (void) releaseSubviews {
8870 @interface Cydia : UIApplication <
8871 ConfirmationControllerDelegate,
8874 UINavigationControllerDelegate,
8875 UITabBarControllerDelegate
8877 // XXX: evaluate all fields for _transient
8880 CYTabBarController *tabbar_;
8881 CYEmulatedLoadingController *emulated_;
8883 NSMutableArray *essential_;
8884 NSMutableArray *broken_;
8886 Database *database_;
8893 StashController *stash_;
8902 @implementation Cydia
8904 - (void) beginUpdate {
8905 [tabbar_ beginUpdate];
8909 return [tabbar_ updating];
8913 if ([broken_ count] != 0) {
8914 int count = [broken_ count];
8916 UIAlertView *alert = [[[UIAlertView alloc]
8917 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8918 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8920 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8922 UCLocalize("TEMPORARY_IGNORE"),
8926 [alert setContext:@"fixhalf"];
8927 [alert setNumberOfRows:2];
8929 } else if (!Ignored_ && [essential_ count] != 0) {
8930 int count = [essential_ count];
8932 UIAlertView *alert = [[[UIAlertView alloc]
8933 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8934 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8936 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8938 UCLocalize("UPGRADE_ESSENTIAL"),
8939 UCLocalize("COMPLETE_UPGRADE"),
8943 [alert setContext:@"upgrade"];
8948 - (void) _saveConfig {
8954 NSString *error(nil);
8956 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8958 NSError *error(nil);
8959 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8960 NSLog(@"failure to save metadata data: %@", error);
8965 NSLog(@"failure to serialize metadata: %@", error);
8970 // Navigation controller for the queuing badge.
8971 - (UINavigationController *) queueNavigationController {
8972 NSArray *controllers = [tabbar_ viewControllers];
8973 return [controllers objectAtIndex:3];
8976 - (void) unloadData {
8977 [tabbar_ unloadData];
8980 - (void) _updateData {
8985 UINavigationController *navigation = [self queueNavigationController];
8987 id queuedelegate = nil;
8988 if ([[navigation viewControllers] count] > 0)
8989 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8991 [queuedelegate queueStatusDidChange];
8992 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8995 - (void) _refreshIfPossible:(NSDate *)update {
8996 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8998 bool recently = false;
8999 if (update != nil) {
9000 NSTimeInterval interval([update timeIntervalSinceNow]);
9001 if (interval <= 0 && interval > -(15*60))
9005 // Don't automatic refresh if:
9006 // - We already refreshed recently.
9007 // - We already auto-refreshed this launch.
9008 // - Auto-refresh is disabled.
9009 if (recently || loaded_ || ManualRefresh) {
9010 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9012 // If we are cancelling, we need to make sure it knows it's already loaded.
9016 // We are going to load, so remember that.
9020 SCNetworkReachabilityFlags flags; {
9021 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
9022 SCNetworkReachabilityGetFlags(reachability, &flags);
9023 CFRelease(reachability);
9026 // XXX: this elaborate mess is what Apple is using to determine this? :(
9027 // XXX: do we care if the user has to intervene? maybe that's ok?
9029 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
9030 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
9031 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
9032 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
9033 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
9034 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
9038 // If we can reach the server, auto-refresh!
9040 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
9045 - (void) refreshIfPossible {
9046 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
9049 - (void) _reloadDataWithInvocation:(NSInvocation *)invocation {
9050 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9051 [hud setText:UCLocalize("RELOADING_DATA")];
9053 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9056 [self removeProgressHUD:hud];
9060 [essential_ removeAllObjects];
9061 [broken_ removeAllObjects];
9063 NSArray *packages([database_ packages]);
9064 for (Package *package in packages) {
9066 [broken_ addObject:package];
9067 if ([package upgradableAndEssential:NO]) {
9068 if ([package essential])
9069 [essential_ addObject:package];
9074 NSLog(@"changes:#%u", changes);
9076 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9079 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9080 [changesItem setBadgeValue:badge];
9081 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9082 [self setApplicationIconBadgeNumber:changes];
9085 [changesItem setBadgeValue:nil];
9086 [changesItem setAnimatedBadge:NO];
9087 [self setApplicationIconBadgeNumber:0];
9092 [self refreshIfPossible];
9095 - (void) updateData {
9104 @synchronized (self) {
9105 [self _reloadDataWithInvocation:nil];
9109 - (void) disemulate {
9110 if (emulated_ == nil)
9113 [window_ addSubview:[tabbar_ view]];
9114 [[emulated_ view] removeFromSuperview];
9115 [emulated_ release];
9117 [window_ setUserInteractionEnabled:YES];
9120 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9121 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9123 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9125 UIViewController *parent;
9126 if (emulated_ == nil)
9135 [parent presentModalViewController:navigation animated:YES];
9138 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9139 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9141 if (navigation != nil)
9142 [navigation pushViewController:progress animated:YES];
9144 [self presentModalViewController:progress force:YES];
9146 [progress invoke:invocation withTitle:title];
9150 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9151 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9154 - (void) repairWithInvocation:(NSInvocation *)invocation {
9156 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9160 - (void) repairWithSelector:(SEL)selector {
9161 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9167 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
9168 _assert(file != NULL);
9170 for (NSString *key in [Sources_ allKeys]) {
9171 NSDictionary *source([Sources_ objectForKey:key]);
9173 fprintf(file, "%s %s %s\n",
9174 [[source objectForKey:@"Type"] UTF8String],
9175 [[source objectForKey:@"URI"] UTF8String],
9176 [[source objectForKey:@"Distribution"] UTF8String]
9182 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9187 - (void) addTrivialSource:(NSString *)href {
9188 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
9191 @"./", @"Distribution",
9192 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href]];
9197 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9198 @synchronized (self) {
9199 [self _reloadDataWithInvocation:invocation];
9203 - (void) reloadData {
9204 [self reloadDataWithInvocation:nil];
9208 pkgProblemResolver *resolver = [database_ resolver];
9210 resolver->InstallProtect();
9211 if (!resolver->Resolve(true))
9216 // XXX: this is a really crappy way of doing this.
9217 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9218 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9219 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9220 if ([tabbar_ updating])
9221 [tabbar_ cancelUpdate];
9223 if (![database_ prepare])
9226 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9227 [page setDelegate:self];
9228 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9231 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9232 [tabbar_ presentModalViewController:confirm_ animated:YES];
9238 @synchronized (self) {
9243 - (void) clearPackage:(Package *)package {
9244 @synchronized (self) {
9251 - (void) installPackages:(NSArray *)packages {
9252 @synchronized (self) {
9253 for (Package *package in packages)
9260 - (void) installPackage:(Package *)package {
9261 @synchronized (self) {
9268 - (void) removePackage:(Package *)package {
9269 @synchronized (self) {
9276 - (void) distUpgrade {
9277 @synchronized (self) {
9278 if (![database_ upgrade])
9284 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9287 [self detachNewProgressSelector:@selector(perform) toTarget:database_ forController:navigation title:@"RUNNING"];
9292 - (void) showSettings {
9293 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
9296 - (void) retainNetworkActivityIndicator {
9297 if (activity_++ == 0)
9298 [self setNetworkActivityIndicatorVisible:YES];
9301 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9305 - (void) releaseNetworkActivityIndicator {
9306 if (--activity_ == 0)
9307 [self setNetworkActivityIndicatorVisible:NO];
9310 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9315 - (void) cancelAndClear:(bool)clear {
9316 @synchronized (self) {
9328 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9329 NSString *context([alert context]);
9331 if ([context isEqualToString:@"conffile"]) {
9332 FILE *input = [database_ input];
9333 if (button == [alert cancelButtonIndex])
9334 fprintf(input, "N\n");
9335 else if (button == [alert firstOtherButtonIndex])
9336 fprintf(input, "Y\n");
9339 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9340 } else if ([context isEqualToString:@"fixhalf"]) {
9341 if (button == [alert cancelButtonIndex]) {
9342 @synchronized (self) {
9343 for (Package *broken in broken_) {
9346 NSString *id = [broken id];
9347 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9348 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9349 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9350 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9356 } else if (button == [alert firstOtherButtonIndex]) {
9357 [broken_ removeAllObjects];
9361 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9362 } else if ([context isEqualToString:@"upgrade"]) {
9363 if (button == [alert firstOtherButtonIndex]) {
9364 @synchronized (self) {
9365 for (Package *essential in essential_)
9366 [essential install];
9371 } else if (button == [alert firstOtherButtonIndex] + 1) {
9373 } else if (button == [alert cancelButtonIndex]) {
9377 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9381 - (void) system:(NSString *)command { _pooled
9383 system([command UTF8String]);
9387 - (void) applicationWillSuspend {
9389 [super applicationWillSuspend];
9392 - (BOOL) isSafeToSuspend {
9395 NSLog(@"isSafeToSuspend: locked_ != 0");
9400 // Use external process status API internally.
9401 // This is probably a really bad idea.
9402 // XXX: what is the point of this? does this solve anything at all?
9403 uint64_t status = 0;
9405 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9406 notify_get_state(notify_token, &status);
9407 notify_cancel(notify_token);
9412 NSLog(@"isSafeToSuspend: status != 0");
9418 NSLog(@"isSafeToSuspend: -> true");
9423 - (void) applicationSuspend:(__GSEvent *)event {
9424 if ([self isSafeToSuspend])
9425 [super applicationSuspend:event];
9428 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9429 if ([self isSafeToSuspend])
9430 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9433 - (void) _setSuspended:(BOOL)value {
9434 if ([self isSafeToSuspend])
9435 [super _setSuspended:value];
9438 - (UIProgressHUD *) addProgressHUD {
9439 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
9440 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9442 [window_ setUserInteractionEnabled:NO];
9444 UIViewController *target(tabbar_);
9445 if (UIViewController *modal = [target modalViewController])
9448 UIView *view([target view]);
9449 [view addSubview:hud];
9457 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9460 [hud removeFromSuperview];
9461 [window_ setUserInteractionEnabled:YES];
9464 - (CYViewController *) pageForPackage:(NSString *)name {
9465 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9468 - (CYViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9469 NSString *scheme([[url scheme] lowercaseString]);
9470 if ([[url absoluteString] length] <= [scheme length] + 3)
9472 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9473 NSArray *components([path pathComponents]);
9475 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9476 return [self pageForPackage:[components objectAtIndex:1]];
9478 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9481 NSString *base([components objectAtIndex:0]);
9483 CYViewController *controller = nil;
9485 if ([base isEqualToString:@"url"]) {
9486 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9487 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9488 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9489 } else if (!external && [components count] == 1) {
9490 if ([base isEqualToString:@"manage"]) {
9491 controller = [[[ManageController alloc] init] autorelease];
9494 if ([base isEqualToString:@"sources"]) {
9495 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9498 if ([base isEqualToString:@"home"]) {
9499 controller = [[[HomeController alloc] init] autorelease];
9502 if ([base isEqualToString:@"sections"]) {
9503 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9506 if ([base isEqualToString:@"search"]) {
9507 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9510 if ([base isEqualToString:@"changes"]) {
9511 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9514 if ([base isEqualToString:@"installed"]) {
9515 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9517 } else if ([components count] == 2) {
9518 NSString *argument = [components objectAtIndex:1];
9520 if ([base isEqualToString:@"package"]) {
9521 controller = [self pageForPackage:argument];
9524 if (!external && [base isEqualToString:@"search"]) {
9525 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9528 if (!external && [base isEqualToString:@"sections"]) {
9529 if ([argument isEqualToString:@"all"])
9531 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9534 if (!external && [base isEqualToString:@"sources"]) {
9535 if ([argument isEqualToString:@"add"]) {
9536 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9537 [(SourcesController *)controller showAddSourcePrompt];
9539 Source *source = [database_ sourceWithKey:argument];
9540 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9544 if (!external && [base isEqualToString:@"launch"]) {
9545 [self launchApplicationWithIdentifier:argument suspended:NO];
9548 } else if (!external && [components count] == 3) {
9549 NSString *arg1 = [components objectAtIndex:1];
9550 NSString *arg2 = [components objectAtIndex:2];
9552 if ([base isEqualToString:@"package"]) {
9553 if ([arg2 isEqualToString:@"settings"]) {
9554 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9555 } else if ([arg2 isEqualToString:@"files"]) {
9556 if (Package *package = [database_ packageWithName:arg1]) {
9557 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9558 [(FileTable *)controller setPackage:package];
9564 [controller setDelegate:self];
9568 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9569 CYViewController *page([self pageForURL:url forExternal:external]);
9572 UINavigationController *nav = [[[UINavigationController alloc] init] autorelease];
9573 [nav setViewControllers:[NSArray arrayWithObject:page]];
9574 [tabbar_ setUnselectedViewController:nav];
9580 - (void) applicationOpenURL:(NSURL *)url {
9581 [super applicationOpenURL:url];
9583 if (!loaded_) starturl_ = [url retain];
9584 else [self openCydiaURL:url forExternal:YES];
9587 - (void) applicationWillResignActive:(UIApplication *)application {
9588 // Stop refreshing if you get a phone call or lock the device.
9589 if ([tabbar_ updating])
9590 [tabbar_ cancelUpdate];
9592 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9593 [super applicationWillResignActive:application];
9596 - (void) applicationWillTerminate:(UIApplication *)application {
9598 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9599 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9600 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9605 - (void) setConfigurationData:(NSString *)data {
9606 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9608 if (!conffile_r(data)) {
9609 lprintf("E:invalid conffile\n");
9613 NSString *ofile = conffile_r[1];
9614 //NSString *nfile = conffile_r[2];
9616 UIAlertView *alert = [[[UIAlertView alloc]
9617 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9618 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9620 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9622 UCLocalize("ACCEPT_NEW_COPY"),
9623 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9627 [alert setContext:@"conffile"];
9628 [alert setNumberOfRows:2];
9632 - (void) addStashController {
9634 stash_ = [[StashController alloc] init];
9635 [window_ addSubview:[stash_ view]];
9638 - (void) removeStashController {
9639 [[stash_ view] removeFromSuperview];
9645 [self setIdleTimerDisabled:YES];
9647 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9648 UpdateExternalStatus(1);
9649 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9650 UpdateExternalStatus(0);
9652 [self removeStashController];
9654 if (ExecFork() == 0) {
9655 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9656 perror("launchctl stop");
9660 - (void) setupViewControllers {
9661 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
9663 NSMutableArray *items([NSMutableArray arrayWithObjects:
9664 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9665 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9666 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9667 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9671 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9672 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9674 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9677 NSMutableArray *controllers([NSMutableArray array]);
9678 for (UITabBarItem *item in items) {
9679 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9680 [controller setTabBarItem:item];
9681 [controllers addObject:controller];
9683 [tabbar_ setViewControllers:controllers];
9685 [tabbar_ setUpdateDelegate:self];
9688 - (void) applicationDidFinishLaunching:(id)unused {
9690 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9691 [self setApplicationSupportsShakeToEdit:NO];
9693 @synchronized (HostConfig_) {
9694 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9697 [NSURLCache setSharedURLCache:[[[SDURLCache alloc]
9698 initWithMemoryCapacity:524288
9699 diskCapacity:10485760
9700 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9703 [CydiaWebViewController _initialize];
9705 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9707 Font12_ = [[UIFont systemFontOfSize:12] retain];
9708 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
9709 Font14_ = [[UIFont systemFontOfSize:14] retain];
9710 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
9711 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
9713 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
9714 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
9716 // XXX: I really need this thing... like, seriously... I'm sorry
9717 [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
9719 window_ = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
9720 [window_ orderFront:self];
9721 [window_ makeKey:self];
9722 [window_ setHidden:NO];
9725 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9726 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9727 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9728 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9729 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9730 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9731 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9732 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9733 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9736 [self addStashController];
9737 // XXX: this would be much cleaner as a yieldToSelector:
9738 // that way the removeStashController could happen right here inline
9739 // we also could no longer require the useless stash_ field anymore
9740 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9744 database_ = [Database sharedInstance];
9745 [database_ setDelegate:self];
9747 [window_ setUserInteractionEnabled:NO];
9748 [self setupViewControllers];
9750 emulated_ = [[CYEmulatedLoadingController alloc] initWithDatabase:database_];
9751 [window_ addSubview:[emulated_ view]];
9753 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9757 - (NSArray *) defaultStartPages {
9758 NSMutableArray *standard = [NSMutableArray array];
9759 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9760 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9761 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9763 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9765 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9766 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9768 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9775 [window_ setUserInteractionEnabled:YES];
9776 [self showSettings];
9779 if ([emulated_ modalViewController] != nil)
9780 [emulated_ dismissModalViewControllerAnimated:YES];
9781 [window_ setUserInteractionEnabled:NO];
9789 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9790 NSArray *saved = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9791 int standardIndex = 0;
9792 NSArray *standard = [self defaultStartPages];
9799 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9800 if (valid && closed != nil) {
9801 NSTimeInterval interval([closed timeIntervalSinceNow]);
9802 // XXX: Is 15 minutes the optimal time here?
9803 if (interval > 0 && interval <= -(15*60))
9807 if (valid && [saved count] != [standard count])
9811 for (unsigned int i = 0; i < [standard count]; i++) {
9812 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9813 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9814 // but it's good enough for now.
9815 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9822 NSArray *items = nil;
9824 [tabbar_ setSelectedIndex:savedIndex];
9827 [tabbar_ setSelectedIndex:standardIndex];
9831 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9832 NSArray *stack = [items objectAtIndex:tab];
9833 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9834 NSMutableArray *current = [NSMutableArray array];
9836 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9837 NSString *addr = [stack objectAtIndex:nav];
9838 NSURL *url = [NSURL URLWithString:addr];
9839 CYViewController *page = [self pageForURL:url forExternal:NO];
9841 [current addObject:page];
9844 [navigation setViewControllers:current];
9847 // (Try to) show the startup URL.
9848 if (starturl_ != nil) {
9849 [self openCydiaURL:starturl_ forExternal:NO];
9850 [starturl_ release];
9855 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9856 if (item != nil && IsWildcat_) {
9857 [sheet showFromBarButtonItem:item animated:YES];
9859 [sheet showInView:window_];
9863 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9864 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9865 [progress setTitle:task];
9866 [progress addProgressEvent:event];
9869 - (void) addProgressEventForTask:(NSArray *)data {
9870 CydiaProgressEvent *event([data objectAtIndex:0]);
9871 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9872 [self addProgressEvent:event forTask:task];
9875 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9876 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9882 id Alloc_(id self, SEL selector) {
9883 id object = alloc_(self, selector);
9884 lprintf("[%s]A-%p\n", self->isa->name, object);
9889 id Dealloc_(id self, SEL selector) {
9890 id object = dealloc_(self, selector);
9891 lprintf("[%s]D-%p\n", self->isa->name, object);
9895 Class $WebDefaultUIKitDelegate;
9897 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9898 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9899 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9900 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9903 static NSSet *MobilizedFiles_;
9905 static NSURL *MobilizeURL(NSURL *url) {
9906 NSString *path([url path]);
9907 if ([path hasPrefix:@"/var/root/"]) {
9908 NSString *file([path substringFromIndex:10]);
9909 if ([MobilizedFiles_ containsObject:file])
9910 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
9916 Class $CFXPreferencesPropertyListSource;
9917 @class CFXPreferencesPropertyListSource;
9919 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9920 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9921 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9922 url = MobilizeURL(url);
9923 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
9924 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
9930 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9931 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9932 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9933 url = MobilizeURL(url);
9934 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
9935 //NSLog(@"%@ %@", [url absoluteString], value);
9941 Class $NSURLConnection;
9943 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
9944 NSMutableURLRequest *copy([request mutableCopy]);
9946 NSURL *url([copy URL]);
9947 NSString *host([url host]);
9948 NSString *scheme([[url scheme] lowercaseString]);
9950 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
9952 @synchronized (HostConfig_) {
9953 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
9954 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
9955 [copy setHTTPShouldUsePipelining:YES];
9958 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
9962 int main(int argc, char *argv[]) { _pooled
9965 UpdateExternalStatus(0);
9967 if (Class $UIDevice = objc_getClass("UIDevice")) {
9968 UIDevice *device([$UIDevice currentDevice]);
9969 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
9973 UIScreen *screen([UIScreen mainScreen]);
9974 if ([screen respondsToSelector:@selector(scale)])
9975 ScreenScale_ = [screen scale];
9979 UIDevice *device([UIDevice currentDevice]);
9980 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
9983 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
9984 if (idiom == UIUserInterfaceIdiomPhone)
9986 else if (idiom == UIUserInterfaceIdiomPad)
9989 NSLog(@"unknown UIUserInterfaceIdiom!");
9992 SessionData_ = [[NSMutableDictionary alloc] initWithCapacity:4];
9994 HostConfig_ = [[NSObject alloc] init];
9995 @synchronized (HostConfig_) {
9996 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
9997 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
10000 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios~%@", Idiom_]);
10002 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10004 MobilizedFiles_ = [NSMutableSet setWithObjects:
10005 @"Library/Preferences/com.apple.Accessibility.plist",
10006 @"Library/Preferences/com.apple.preferences.sounds.plist",
10009 /* Library Hacks {{{ */
10010 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10012 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
10014 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
10015 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
10016 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10017 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10020 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
10021 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
10022 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
10023 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
10026 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
10027 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
10028 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
10029 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
10030 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
10033 $NSURLConnection = objc_getClass("NSURLConnection");
10034 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10035 if (NSURLConnection$init$ != NULL) {
10036 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10037 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10040 /* Set Locale {{{ */
10041 Locale_ = CFLocaleCopyCurrent();
10042 Languages_ = [NSLocale preferredLanguages];
10044 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10045 //NSLog(@"%@", [Languages_ description]);
10048 if (Locale_ != NULL)
10049 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10050 else if (Languages_ != nil && [Languages_ count] != 0)
10051 lang = [[Languages_ objectAtIndex:0] UTF8String];
10053 // XXX: consider just setting to C and then falling through?
10056 if (lang != NULL) {
10057 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
10058 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10061 NSLog(@"Setting Language: %s", lang);
10063 if (lang != NULL) {
10064 setenv("LANG", lang, true);
10065 std::setlocale(LC_ALL, lang);
10069 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
10071 /* Parse Arguments {{{ */
10072 bool substrate(false);
10078 for (int argi(1); argi != argc; ++argi)
10079 if (strcmp(argv[argi], "--") == 0) {
10081 argv[argi] = argv[0];
10087 for (int argi(1); argi != arge; ++argi)
10088 if (strcmp(args[argi], "--substrate") == 0)
10091 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10095 App_ = [[NSBundle mainBundle] bundlePath];
10101 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10102 alloc_ = alloc->method_imp;
10103 alloc->method_imp = (IMP) &Alloc_;*/
10105 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10106 dealloc_ = dealloc->method_imp;
10107 dealloc->method_imp = (IMP) &Dealloc_;*/
10109 /* System Information {{{ */
10113 size = sizeof(maxproc);
10114 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10115 perror("sysctlbyname(\"kern.maxproc\", ?)");
10116 else if (maxproc < 64) {
10118 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10119 perror("sysctlbyname(\"kern.maxproc\", #)");
10122 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10123 char *osversion = new char[size];
10124 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10125 perror("sysctlbyname(\"kern.osversion\", ?)");
10127 System_ = [NSString stringWithUTF8String:osversion];
10129 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10130 char *machine = new char[size];
10131 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10132 perror("sysctlbyname(\"hw.machine\", ?)");
10134 Machine_ = machine;
10136 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
10137 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
10138 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
10139 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
10143 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
10144 NSData *data((NSData *) ecid);
10145 size_t length([data length]);
10146 uint8_t bytes[length];
10147 [data getBytes:bytes];
10148 char string[length * 2 + 1];
10149 for (size_t i(0); i != length; ++i)
10150 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
10151 ChipID_ = [NSString stringWithUTF8String:string];
10155 IOObjectRelease(service);
10159 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
10161 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
10162 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10163 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
10165 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
10166 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10167 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
10169 if (mcc != NULL && mnc != NULL)
10170 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
10177 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
10178 Build_ = [system objectForKey:@"ProductBuildVersion"];
10179 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10180 Product_ = [info objectForKey:@"SafariProductVersion"];
10181 Safari_ = [info objectForKey:@"CFBundleVersion"];
10184 /* Load Database {{{ */
10186 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10188 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10190 if (Metadata_ == NULL)
10191 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10193 Settings_ = [Metadata_ objectForKey:@"Settings"];
10195 Packages_ = [Metadata_ objectForKey:@"Packages"];
10196 Sections_ = [Metadata_ objectForKey:@"Sections"];
10197 Sources_ = [Metadata_ objectForKey:@"Sources"];
10199 Token_ = [Metadata_ objectForKey:@"Token"];
10202 if (Settings_ != nil)
10203 Role_ = [Settings_ objectForKey:@"Role"];
10205 if (Sections_ == nil) {
10206 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10207 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10210 if (Sources_ == nil) {
10211 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10212 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10217 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10220 if (Packages_ != nil) {
10222 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10226 [Metadata_ removeObjectForKey:@"Packages"];
10232 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10234 #define MobileSubstrate_(name) \
10235 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10236 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10237 if (handle == NULL) \
10238 NSLog(@"%s", dlerror()); \
10241 MobileSubstrate_(Activator)
10242 MobileSubstrate_(libstatusbar)
10243 MobileSubstrate_(SimulatedKeyEvents)
10244 MobileSubstrate_(WinterBoard)
10246 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10247 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10249 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10251 if (access("/tmp/.cydia.fw", F_OK) == 0) {
10252 unlink("/tmp/.cydia.fw");
10254 } else if (access("/User", F_OK) != 0 || version < 4) {
10257 system("/usr/libexec/cydia/firmware.sh");
10261 _assert([[NSFileManager defaultManager]
10262 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10263 withIntermediateDirectories:YES
10268 if (access("/tmp/cydia.chk", F_OK) == 0) {
10269 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10270 _assert(errno == ENOENT);
10271 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10272 _assert(errno == ENOENT);
10275 /* APT Initialization {{{ */
10276 _assert(pkgInitConfig(*_config));
10277 _assert(pkgInitSystem(*_config, _system));
10280 _config->Set("APT::Acquire::Translation", lang);
10282 // XXX: this timeout might be important :(
10283 //_config->Set("Acquire::http::Timeout", 15);
10285 _config->Set("Acquire::http::MaxParallel", 3);
10287 /* Color Choices {{{ */
10288 space_ = CGColorSpaceCreateDeviceRGB();
10290 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10291 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10292 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10293 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10294 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10295 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10296 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10297 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10298 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10300 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10301 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10303 /* UIKit Configuration {{{ */
10304 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10305 if ($GSFontSetUseLegacyFontMetrics != NULL)
10306 $GSFontSetUseLegacyFontMetrics(YES);
10308 // XXX: I have a feeling this was important
10309 //UIKeyboardDisableAutomaticAppearance();
10312 Colon_ = UCLocalize("COLON_DELIMITED");
10313 Elision_ = UCLocalize("ELISION");
10314 Error_ = UCLocalize("ERROR");
10315 Warning_ = UCLocalize("WARNING");
10318 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10320 CGColorSpaceRelease(space_);
10321 CFRelease(Locale_);