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 "Menes/Menes.h"
125 #include "CyteKit/PerlCompatibleRegEx.hpp"
126 #include "CyteKit/WebScriptObject-Cyte.h"
127 #include "CyteKit/WebViewController.h"
128 #include "CyteKit/stringWithUTF8Bytes.h"
130 #include "Cydia/ProgressEvent.h"
132 #include "SDURLCache/SDURLCache.h"
134 #include <CydiaSubstrate/CydiaSubstrate.h>
141 #define _timestamp ({ \
143 gettimeofday(&tv, NULL); \
144 tv.tv_sec * 1000000 + tv.tv_usec; \
147 typedef std::vector<class ProfileTime *> TimeList;
157 ProfileTime(const char *name) :
161 times_.push_back(this);
164 void AddTime(uint64_t time) {
171 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
183 ProfileTimer(ProfileTime &time) :
190 time_.AddTime(_timestamp - start_);
195 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
197 std::cerr << "========" << std::endl;
200 #define _profile(name) { \
201 static ProfileTime name(#name); \
202 ProfileTimer _ ## name(name);
207 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
209 #define CYPoolStart() \
210 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
212 #define CYPoolEnd() \
216 #define Cydia_ CYDIA_VERSION
218 #define lprintf(args...) fprintf(stderr, args)
221 #define TraceLogging (1 && !ForRelease)
222 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
223 #define ProfileTimes (0 && !ForRelease)
224 #define ForSaurik (0 && !ForRelease)
225 #define LogBrowser (0 && !ForRelease)
226 #define TrackResize (0 && !ForRelease)
227 #define ManualRefresh (1 && !ForRelease)
228 #define ShowInternals (0 && !ForRelease)
229 #define AlwaysReload (0 && !ForRelease)
230 #define TryIndexedCollation (0 && !ForRelease)
234 #define _trace(args...)
239 #define _profile(name) {
242 #define PrintTimes() do {} while (false)
245 // Hash Functions/Structures {{{
246 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
254 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
256 static _finline NSString *CydiaURL(NSString *path) {
258 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
259 page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
260 page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
261 page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
262 page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
264 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
267 static _finline void UpdateExternalStatus(uint64_t newStatus) {
269 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
270 notify_set_state(notify_token, newStatus);
271 notify_cancel(notify_token);
273 notify_post("com.saurik.Cydia.status");
276 /* NSForcedOrderingSearch doesn't work on the iPhone */
277 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
278 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
279 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
282 typedef uint32_t (*SKRadixFunction)(id, void *);
284 @interface NSMutableArray (Radix)
285 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
293 @implementation NSMutableArray (Radix)
295 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
296 size_t count([self count]);
297 struct RadixItem_ *swap(new RadixItem_[count * 2]);
299 for (size_t i(0); i != count; ++i) {
300 RadixItem_ &item(swap[i]);
303 id object([self objectAtIndex:i]);
304 item.key = function(object, argument);
307 struct RadixItem_ *lhs(swap), *rhs(swap + count);
309 static const size_t width = 32;
310 static const size_t bits = 11;
311 static const size_t slots = 1 << bits;
312 static const size_t passes = (width + (bits - 1)) / bits;
314 size_t *hist(new size_t[slots]);
316 for (size_t pass(0); pass != passes; ++pass) {
317 memset(hist, 0, sizeof(size_t) * slots);
319 for (size_t i(0); i != count; ++i) {
320 uint32_t key(lhs[i].key);
322 key &= _not(uint32_t) >> width - bits;
327 for (size_t i(0); i != slots; ++i) {
328 size_t local(offset);
333 for (size_t i(0); i != count; ++i) {
334 uint32_t key(lhs[i].key);
336 key &= _not(uint32_t) >> width - bits;
337 rhs[hist[key]++] = lhs[i];
340 RadixItem_ *tmp(lhs);
347 const void **values(new const void *[count]);
348 for (size_t i(0); i != count; ++i)
349 values[i] = [self objectAtIndex:lhs[i].index];
350 CFArrayReplaceValues((CFMutableArrayRef) self, CFRangeMake(0, count), values, count);
358 /* Insertion Sort {{{ */
360 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
361 const char *ptr = (const char *)list;
363 CFIndex half = count / 2;
364 const char *probe = ptr + elementSize * half;
365 CFComparisonResult cr = comparator(element, probe, context);
366 if (0 == cr) return (probe - (const char *)list) / elementSize;
367 ptr = (cr < 0) ? ptr : probe + elementSize;
368 count = (cr < 0) ? half : (half + (count & 1) - 1);
370 return (ptr - (const char *)list) / elementSize;
373 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
374 const char *ptr = (const char *)list;
376 CFIndex half = count / 2;
377 const char *probe = ptr + elementSize * half;
378 CFComparisonResult cr = comparator(element, probe, context);
379 if (0 == cr) return (probe - (const char *)list) / elementSize;
380 ptr = (cr < 0) ? ptr : probe + elementSize;
381 count = (cr < 0) ? half : (half + (count & 1) - 1);
383 return (ptr - (const char *)list) / elementSize;
386 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
387 if (range.length == 0)
389 const void **values(new const void *[range.length]);
390 CFArrayGetValues(array, range, values);
392 #if HistogramInsertionSort > 0
393 uint32_t total(0), *offsets(new uint32_t[range.length]);
396 for (CFIndex index(1); index != range.length; ++index) {
397 const void *value(values[index]);
398 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
399 CFIndex correct(index);
400 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
401 #if HistogramInsertionSort > 1
402 NSLog(@"%@ < %@", value, values[correct - 1]);
407 if (correct != index) {
408 size_t offset(index - correct);
409 #if HistogramInsertionSort
413 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
415 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
416 values[correct] = value;
420 CFArrayReplaceValues(array, range, values, range.length);
423 #if HistogramInsertionSort > 0
424 for (CFIndex index(0); index != range.length; ++index)
425 if (offsets[index] != 0)
426 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
427 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
434 /* Apple Bug Fixes {{{ */
435 @implementation UIWebDocumentView (Cydia)
437 - (void) _setScrollerOffset:(CGPoint)offset {
438 UIScroller *scroller([self _scroller]);
440 CGSize size([scroller contentSize]);
441 CGSize bounds([scroller bounds].size);
444 max.x = size.width - bounds.width;
445 max.y = size.height - bounds.height;
453 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
454 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
456 [scroller setOffset:offset];
462 @interface NSInvocation (Cydia)
463 + (NSInvocation *) invocationWithSelector:(SEL)selector forTarget:(id)target;
466 @implementation NSInvocation (Cydia)
468 + (NSInvocation *) invocationWithSelector:(SEL)selector forTarget:(id)target {
469 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[target methodSignatureForSelector:selector]]);
470 [invocation setTarget:target];
471 [invocation setSelector:selector];
477 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
478 size_t length([self length] - state->state);
481 else if (length > count)
483 for (size_t i(0); i != length; ++i)
484 objects[i] = [self item:state->state++];
485 state->itemsPtr = objects;
486 state->mutationsPtr = (unsigned long *) self;
490 /* Cydia NSString Additions {{{ */
491 @interface NSString (Cydia)
492 - (NSComparisonResult) compareByPath:(NSString *)other;
493 - (NSString *) stringByCachingURLWithCurrentCDN;
494 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
497 @implementation NSString (Cydia)
499 - (NSComparisonResult) compareByPath:(NSString *)other {
500 NSString *prefix = [self commonPrefixWithString:other options:0];
501 size_t length = [prefix length];
503 NSRange lrange = NSMakeRange(length, [self length] - length);
504 NSRange rrange = NSMakeRange(length, [other length] - length);
506 lrange = [self rangeOfString:@"/" options:0 range:lrange];
507 rrange = [other rangeOfString:@"/" options:0 range:rrange];
509 NSComparisonResult value;
511 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
512 value = NSOrderedSame;
513 else if (lrange.location == NSNotFound)
514 value = NSOrderedAscending;
515 else if (rrange.location == NSNotFound)
516 value = NSOrderedDescending;
518 value = NSOrderedSame;
520 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
521 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
522 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
523 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
525 NSComparisonResult result = [lpath compare:rpath];
526 return result == NSOrderedSame ? value : result;
529 - (NSString *) stringByCachingURLWithCurrentCDN {
531 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
532 withString:@"://cache.cydia.saurik.com/"
536 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
537 return [(id)CFURLCreateStringByAddingPercentEscapes(
542 kCFStringEncodingUTF8
549 /* C++ NSString Wrapper Cache {{{ */
550 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
551 return size == 0 ? NULL :
552 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
553 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
556 static _finline CFStringRef CYStringCreate(const char *data) {
557 return CYStringCreate(data, strlen(data));
566 _finline void clear_() {
567 if (cache_ != NULL) {
574 _finline bool empty() const {
578 _finline size_t size() const {
582 _finline char *data() const {
586 _finline void clear() {
591 _finline CYString() :
598 _finline ~CYString() {
602 void operator =(const CYString &rhs) {
606 if (rhs.cache_ == nil)
609 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
612 void copy(apr_pool_t *pool) {
613 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
614 memcpy(temp, data_, size_);
619 void set(apr_pool_t *pool, const char *data, size_t size) {
625 data_ = const_cast<char *>(data);
633 _finline void set(apr_pool_t *pool, const char *data) {
634 set(pool, data, data == NULL ? 0 : strlen(data));
637 _finline void set(apr_pool_t *pool, const std::string &rhs) {
638 set(pool, rhs.data(), rhs.size());
641 bool operator ==(const CYString &rhs) const {
642 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
645 _finline operator CFStringRef() {
647 cache_ = CYStringCreate(data_, size_);
651 _finline operator id() {
652 return (NSString *) static_cast<CFStringRef>(*this);
655 _finline operator const char *() {
656 return reinterpret_cast<const char *>(data_);
660 /* C++ NSString Algorithm Adapters {{{ */
662 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
665 struct NSStringMapHash :
666 std::unary_function<NSString *, size_t>
668 _finline size_t operator ()(NSString *value) const {
669 return CFStringHashNSString((CFStringRef) value);
673 struct NSStringMapLess :
674 std::binary_function<NSString *, NSString *, bool>
676 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
677 return [lhs compare:rhs] == NSOrderedAscending;
681 struct NSStringMapEqual :
682 std::binary_function<NSString *, NSString *, bool>
684 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
685 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
686 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
687 //[lhs isEqualToString:rhs];
692 /* Mime Addresses {{{ */
693 @interface Address : NSObject {
699 - (NSString *) address;
701 - (void) setAddress:(NSString *)address;
703 + (Address *) addressWithString:(NSString *)string;
704 - (Address *) initWithString:(NSString *)string;
708 @implementation Address
717 - (NSString *) name {
721 - (NSString *) address {
725 - (void) setAddress:(NSString *)address {
727 [address_ autorelease];
731 address_ = [address retain];
734 + (Address *) addressWithString:(NSString *)string {
735 return [[[Address alloc] initWithString:string] autorelease];
738 + (NSArray *) _attributeKeys {
739 return [NSArray arrayWithObjects:
745 - (NSArray *) attributeKeys {
746 return [[self class] _attributeKeys];
749 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
750 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
753 - (Address *) initWithString:(NSString *)string {
754 if ((self = [super init]) != nil) {
755 const char *data = [string UTF8String];
756 size_t size = [string length];
758 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
760 if (address_r(data, size)) {
761 name_ = [address_r[1] retain];
762 address_ = [address_r[2] retain];
764 name_ = [string retain];
772 /* CoreGraphics Primitives {{{ */
777 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
778 CGFloat color[] = {red, green, blue, alpha};
779 return CGColorCreate(space, color);
788 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
789 color_(Create_(space, red, green, blue, alpha))
791 Set(space, red, green, blue, alpha);
796 CGColorRelease(color_);
803 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
805 color_ = Create_(space, red, green, blue, alpha);
808 operator CGColorRef() {
814 /* Random Global Variables {{{ */
815 static const int PulseInterval_ = 50000;
817 static const NSString *UI_;
820 static bool RestartSubstrate_;
821 static NSArray *Finishes_;
823 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
824 #define NotifyConfig_ "/etc/notify.conf"
826 static bool Queuing_;
828 static CYColor Blue_;
829 static CYColor Blueish_;
830 static CYColor Black_;
832 static CYColor White_;
833 static CYColor Gray_;
834 static CYColor Green_;
835 static CYColor Purple_;
836 static CYColor Purplish_;
838 static UIColor *InstallingColor_;
839 static UIColor *RemovingColor_;
841 static NSString *App_;
843 static BOOL Advanced_;
844 static BOOL Ignored_;
846 static UIFont *Font12_;
847 static UIFont *Font12Bold_;
848 static UIFont *Font14_;
849 static UIFont *Font18Bold_;
850 static UIFont *Font22Bold_;
852 static const char *Machine_ = NULL;
853 static NSString *System_ = nil;
854 static NSString *SerialNumber_ = nil;
855 static NSString *ChipID_ = nil;
856 static _H<NSString> Token_;
857 static NSString *UniqueID_ = nil;
858 static NSString *PLMN_ = nil;
859 static NSString *Build_ = nil;
860 static NSString *Product_ = nil;
861 static NSString *Safari_ = nil;
863 static CFLocaleRef Locale_;
864 static NSArray *Languages_;
865 static CGColorSpaceRef space_;
867 static NSDictionary *SectionMap_;
868 static NSMutableDictionary *Metadata_;
869 static _transient NSMutableDictionary *Settings_;
870 static _transient NSString *Role_;
871 static _transient NSMutableDictionary *Packages_;
872 static _transient NSMutableDictionary *Sections_;
873 static _transient NSMutableDictionary *Sources_;
874 static bool Changed_;
878 static CGFloat ScreenScale_;
879 static NSString *Idiom_;
881 static NSMutableDictionary *SessionData_;
882 static NSObject *HostConfig_;
883 static NSMutableSet *BridgedHosts_;
884 static NSMutableSet *PipelinedHosts_;
886 static NSString *kCydiaProgressEventTypeError = @"Error";
887 static NSString *kCydiaProgressEventTypeInformation = @"Information";
888 static NSString *kCydiaProgressEventTypeStatus = @"Status";
889 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
892 /* Display Helpers {{{ */
893 inline float Interpolate(float begin, float end, float fraction) {
894 return (end - begin) * fraction + begin;
897 static _finline const char *StripVersion_(const char *version) {
898 const char *colon(strchr(version, ':'));
899 return colon == NULL ? version : colon + 1;
902 NSString *LocalizeSection(NSString *section) {
903 static Pcre title_r("^(.*?) \\((.*)\\)$");
904 if (title_r(section)) {
905 NSString *parent(title_r[1]);
906 NSString *child(title_r[2]);
908 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
909 LocalizeSection(parent),
910 LocalizeSection(child)
914 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
917 NSString *Simplify(NSString *title) {
918 const char *data = [title UTF8String];
919 size_t size = [title length];
921 static Pcre square_r("^\\[(.*)\\]$");
922 if (square_r(data, size))
923 return Simplify(square_r[1]);
925 static Pcre paren_r("^\\((.*)\\)$");
926 if (paren_r(data, size))
927 return Simplify(paren_r[1]);
929 static Pcre title_r("^(.*?) \\((.*)\\)$");
930 if (title_r(data, size))
931 return Simplify(title_r[1]);
937 NSString *GetLastUpdate() {
938 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
941 return UCLocalize("NEVER_OR_UNKNOWN");
943 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
944 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
946 CFRelease(formatter);
948 return [(NSString *) formatted autorelease];
951 bool isSectionVisible(NSString *section) {
952 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
953 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
954 return hidden == nil || ![hidden boolValue];
959 /* Delegate Prototypes {{{ */
962 @class CydiaProgressEvent;
964 @protocol DatabaseDelegate
965 - (void) repairWithSelector:(SEL)selector;
966 - (void) setConfigurationData:(NSString *)data;
967 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
970 @class CYPackageController;
972 @protocol CydiaDelegate
973 - (void) retainNetworkActivityIndicator;
974 - (void) releaseNetworkActivityIndicator;
975 - (void) clearPackage:(Package *)package;
976 - (void) installPackage:(Package *)package;
977 - (void) installPackages:(NSArray *)packages;
978 - (void) removePackage:(Package *)package;
979 - (void) beginUpdate;
981 - (void) distUpgrade;
985 - (void) addTrivialSource:(NSString *)href;
986 - (void) showSettings;
987 - (UIProgressHUD *) addProgressHUD;
988 - (void) removeProgressHUD:(UIProgressHUD *)hud;
989 - (CyteViewController *) pageForPackage:(NSString *)name;
990 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
991 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
995 /* Status Delegation {{{ */
997 public pkgAcquireStatus
1000 _transient NSObject<ProgressDelegate> *delegate_;
1010 void setDelegate(NSObject<ProgressDelegate> *delegate) {
1011 delegate_ = delegate;
1014 NSObject<ProgressDelegate> *getDelegate() const {
1018 virtual bool MediaChange(std::string media, std::string drive) {
1022 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1025 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1026 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1027 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
1028 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1031 virtual void Done(pkgAcquire::ItemDesc &item) {
1034 virtual void Fail(pkgAcquire::ItemDesc &item) {
1036 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1037 item.Owner->Status == pkgAcquire::Item::StatDone
1041 std::string &error(item.Owner->ErrorText);
1045 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItem:item]);
1046 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1049 virtual bool Pulse(pkgAcquire *Owner) {
1050 bool value = pkgAcquireStatus::Pulse(Owner);
1053 double(CurrentBytes + CurrentItems) /
1054 double(TotalBytes + TotalItems)
1057 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
1058 [NSNumber numberWithDouble:percent], @"Percent",
1060 [NSNumber numberWithDouble:CurrentBytes], @"Current",
1061 [NSNumber numberWithDouble:TotalBytes], @"Total",
1062 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
1063 nil] waitUntilDone:YES];
1065 if (value && ![delegate_ isProgressCancelled])
1073 _finline bool WasCancelled() const {
1077 virtual void Start() {
1078 pkgAcquireStatus::Start();
1079 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
1082 virtual void Stop() {
1083 pkgAcquireStatus::Stop();
1084 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
1085 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
1089 /* Database Interface {{{ */
1090 typedef std::map< unsigned long, _H<Source> > SourceMap;
1092 @interface Database : NSObject {
1098 pkgCacheFile cache_;
1099 pkgDepCache::Policy *policy_;
1100 pkgRecords *records_;
1101 pkgProblemResolver *resolver_;
1102 pkgAcquire *fetcher_;
1104 SPtr<pkgPackageManager> manager_;
1105 pkgSourceList *list_;
1107 SourceMap sourceMap_;
1108 NSMutableArray *sourceList_;
1110 CFMutableArrayRef packages_;
1112 _transient NSObject<DatabaseDelegate> *delegate_;
1113 _transient NSObject<ProgressDelegate> *progress_;
1121 std::map<const char *, _H<NSString> > sections_;
1124 + (Database *) sharedInstance;
1127 - (void) _readCydia:(NSNumber *)fd;
1128 - (void) _readStatus:(NSNumber *)fd;
1129 - (void) _readOutput:(NSNumber *)fd;
1133 - (Package *) packageWithName:(NSString *)name;
1135 - (pkgCacheFile &) cache;
1136 - (pkgDepCache::Policy *) policy;
1137 - (pkgRecords *) records;
1138 - (pkgProblemResolver *) resolver;
1139 - (pkgAcquire &) fetcher;
1140 - (pkgSourceList &) list;
1141 - (NSArray *) packages;
1142 - (NSArray *) sources;
1143 - (Source *) sourceWithKey:(NSString *)key;
1144 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1152 - (void) updateWithStatus:(Status &)status;
1154 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1156 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1157 - (NSObject<ProgressDelegate> *) progressDelegate;
1159 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1161 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1165 /* ProgressEvent Implementation {{{ */
1166 @implementation CydiaProgressEvent
1168 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1169 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1172 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1173 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1174 [event setPackage:package];
1178 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item {
1179 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1181 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1182 NSArray *fields([description componentsSeparatedByString:@" "]);
1183 [event setItem:fields];
1185 if ([fields count] > 3) {
1186 [event setPackage:[fields objectAtIndex:2]];
1187 [event setVersion:[fields objectAtIndex:3]];
1190 [event setURL:[NSString stringWithUTF8String:item.URI.c_str()]];
1195 + (NSArray *) _attributeKeys {
1196 return [NSArray arrayWithObjects:
1206 - (NSArray *) attributeKeys {
1207 return [[self class] _attributeKeys];
1210 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1211 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1214 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1215 if ((self = [super init]) != nil) {
1221 - (NSString *) message {
1225 - (NSString *) type {
1229 - (NSArray *) item {
1230 return (id) item_ ?: [NSNull null];
1233 - (void) setItem:(NSArray *)item {
1237 - (NSString *) package {
1238 return (id) package_ ?: [NSNull null];
1241 - (void) setPackage:(NSString *)package {
1245 - (NSString *) url {
1246 return (id) url_ ?: [NSNull null];
1249 - (void) setURL:(NSString *)url {
1253 - (void) setVersion:(NSString *)version {
1257 - (NSString *) version {
1258 return (id) version_ ?: [NSNull null];
1261 - (NSString *) compound:(NSString *)value {
1263 NSString *mode(nil); {
1264 NSString *type([self type]);
1265 if ([type isEqualToString:kCydiaProgressEventTypeError])
1266 mode = UCLocalize("ERROR");
1267 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1268 mode = UCLocalize("WARNING");
1272 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1278 - (NSString *) compoundMessage {
1279 return [self compound:[self message]];
1282 - (NSString *) compoundTitle {
1285 if (package_ == nil)
1287 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1288 title = [package name];
1292 return [self compound:title];
1298 // Cytore Definitions {{{
1299 struct PackageValue :
1302 Cytore::Offset<PackageValue> next_;
1304 uint32_t index_ : 23;
1305 uint32_t subscribed_ : 1;
1322 Cytore::Offset<PackageValue> packages_[1 << 16];
1325 static Cytore::File<MetaValue> MetaFile_;
1327 // Cytore Helper Functions {{{
1328 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1329 SplitHash nhash = { hashlittle(name, length) };
1331 PackageValue *metadata;
1333 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1334 offset: if (offset->IsNull()) {
1335 *offset = MetaFile_.New<PackageValue>(length + 1);
1336 metadata = &MetaFile_.Get(*offset);
1338 if (metadata == NULL) {
1342 metadata = new PackageValue();
1343 memset(metadata, 0, sizeof(*metadata));
1346 memcpy(metadata->name_, name, length + 1);
1347 metadata->nhash_ = nhash.u16[1];
1349 metadata = &MetaFile_.Get(*offset);
1351 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1352 offset = &metadata->next_;
1360 static void PackageImport(const void *key, const void *value, void *context) {
1361 bool &fail(*reinterpret_cast<bool *>(context));
1364 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1365 NSLog(@"failed to import package %@", key);
1369 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1370 NSDictionary *package((NSDictionary *) value);
1372 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1373 if ([subscribed boolValue] && !metadata->subscribed_)
1374 metadata->subscribed_ = true;
1376 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1377 time_t time([date timeIntervalSince1970]);
1378 if (metadata->first_ > time || metadata->first_ == 0)
1379 metadata->first_ = time;
1382 NSDate *date([package objectForKey:@"LastSeen"]);
1383 NSString *version([package objectForKey:@"LastVersion"]);
1385 if (date != nil && version != nil) {
1386 time_t time([date timeIntervalSince1970]);
1387 if (metadata->last_ < time || metadata->last_ == 0)
1388 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1389 size_t length(strlen(buffer));
1390 uint16_t vhash(hashlittle(buffer, length));
1392 size_t capped(std::min<size_t>(8, length));
1393 char *latest(buffer + length - capped);
1395 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1396 metadata->vhash_ = vhash;
1398 metadata->last_ = time;
1404 /* Source Class {{{ */
1405 @interface Source : NSObject {
1406 CYString depiction_;
1407 CYString description_;
1413 CYString distribution_;
1418 _H<NSString> authority_;
1420 CYString defaultIcon_;
1422 _H<NSDictionary> record_;
1426 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1428 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1430 - (NSString *) depictionForPackage:(NSString *)package;
1431 - (NSString *) supportForPackage:(NSString *)package;
1433 - (NSDictionary *) record;
1437 - (NSString *) distribution;
1438 - (NSString *) type;
1440 - (NSString *) host;
1442 - (NSString *) name;
1443 - (NSString *) shortDescription;
1444 - (NSString *) label;
1445 - (NSString *) origin;
1446 - (NSString *) version;
1448 - (NSString *) defaultIcon;
1452 @implementation Source
1456 distribution_.clear();
1459 description_.clear();
1465 defaultIcon_.clear();
1473 // XXX: this is a very inefficient way to call these deconstructors
1478 + (NSArray *) _attributeKeys {
1479 return [NSArray arrayWithObjects:
1486 @"shortDescription",
1494 - (NSArray *) attributeKeys {
1495 return [[self class] _attributeKeys];
1498 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1499 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1502 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1505 trusted_ = index->IsTrusted();
1507 uri_.set(pool, index->GetURI());
1508 distribution_.set(pool, index->GetDist());
1509 type_.set(pool, index->GetType());
1511 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1512 if (dindex != NULL) {
1514 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1517 pkgTagFile tags(&fd);
1519 pkgTagSection section;
1526 {"default-icon", &defaultIcon_},
1527 {"depiction", &depiction_},
1528 {"description", &description_},
1530 {"origin", &origin_},
1531 {"support", &support_},
1532 {"version", &version_},
1535 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1536 const char *start, *end;
1538 if (section.Find(names[i].name_, start, end)) {
1539 CYString &value(*names[i].value_);
1540 value.set(pool, start, end - start);
1546 record_ = [Sources_ objectForKey:[self key]];
1548 NSURL *url([NSURL URLWithString:uri_]);
1552 host_ = [host_ lowercaseString];
1555 // XXX: this is due to a bug in _H<>
1556 authority_ = (id) host_;
1558 authority_ = [url path];
1561 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1562 if ((self = [super init]) != nil) {
1563 [self setMetaIndex:index inPool:pool];
1567 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1568 NSDictionary *lhr = [self record];
1569 NSDictionary *rhr = [source record];
1572 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1574 NSString *lhs = [self name];
1575 NSString *rhs = [source name];
1577 if ([lhs length] != 0 && [rhs length] != 0) {
1578 unichar lhc = [lhs characterAtIndex:0];
1579 unichar rhc = [rhs characterAtIndex:0];
1581 if (isalpha(lhc) && !isalpha(rhc))
1582 return NSOrderedAscending;
1583 else if (!isalpha(lhc) && isalpha(rhc))
1584 return NSOrderedDescending;
1587 return [lhs compare:rhs options:LaxCompareOptions_];
1590 - (NSString *) depictionForPackage:(NSString *)package {
1591 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1594 - (NSString *) supportForPackage:(NSString *)package {
1595 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1598 - (NSDictionary *) record {
1606 - (NSString *) uri {
1610 - (NSString *) distribution {
1611 return distribution_;
1614 - (NSString *) type {
1618 - (NSString *) key {
1619 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1622 - (NSString *) host {
1626 - (NSString *) name {
1627 return origin_.empty() ? (id) authority_ : origin_;
1630 - (NSString *) shortDescription {
1631 return description_;
1634 - (NSString *) label {
1635 return label_.empty() ? (id) authority_ : label_;
1638 - (NSString *) origin {
1642 - (NSString *) version {
1646 - (NSString *) defaultIcon {
1647 return defaultIcon_;
1652 /* CydiaOperation Class {{{ */
1653 @interface CydiaOperation : NSObject {
1654 NSString *operator_;
1658 - (NSString *) operator;
1659 - (NSString *) value;
1663 @implementation CydiaOperation
1666 [operator_ release];
1671 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1672 if ((self = [super init]) != nil) {
1673 operator_ = [[NSString alloc] initWithUTF8String:_operator];
1674 value_ = [[NSString alloc] initWithUTF8String:value];
1678 + (NSArray *) _attributeKeys {
1679 return [NSArray arrayWithObjects:
1685 - (NSArray *) attributeKeys {
1686 return [[self class] _attributeKeys];
1689 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1690 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1693 - (NSString *) operator {
1697 - (NSString *) value {
1703 /* CydiaClause Class {{{ */
1704 @interface CydiaClause : NSObject {
1706 CydiaOperation *version_;
1709 - (NSString *) package;
1710 - (CydiaOperation *) version;
1714 @implementation CydiaClause
1722 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1723 if ((self = [super init]) != nil) {
1724 package_ = [[NSString alloc] initWithUTF8String:dep.TargetPkg().Name()];
1726 if (const char *version = dep.TargetVer())
1727 version_ = [[CydiaOperation alloc] initWithOperator:dep.CompType() value:version];
1729 version_ = [[NSNull null] retain];
1733 + (NSArray *) _attributeKeys {
1734 return [NSArray arrayWithObjects:
1740 - (NSArray *) attributeKeys {
1741 return [[self class] _attributeKeys];
1744 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1745 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1748 - (NSString *) package {
1752 - (CydiaOperation *) version {
1758 /* CydiaRelation Class {{{ */
1759 @interface CydiaRelation : NSObject {
1760 NSString *relationship_;
1761 NSMutableArray *clauses_;
1764 - (NSString *) relationship;
1765 - (NSArray *) clauses;
1769 @implementation CydiaRelation
1772 [relationship_ release];
1777 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1778 if ((self = [super init]) != nil) {
1779 relationship_ = [[NSString alloc] initWithUTF8String:dep.DepType()];
1780 clauses_ = [[NSMutableArray alloc] initWithCapacity:8];
1782 pkgCache::DepIterator start;
1783 pkgCache::DepIterator end;
1784 dep.GlobOr(start, end); // ++dep
1787 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1789 // yes, seriously. (wtf?)
1797 + (NSArray *) _attributeKeys {
1798 return [NSArray arrayWithObjects:
1804 - (NSArray *) attributeKeys {
1805 return [[self class] _attributeKeys];
1808 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1809 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1812 - (NSString *) relationship {
1813 return relationship_;
1816 - (NSArray *) clauses {
1820 - (void) addClause:(CydiaClause *)clause {
1821 [clauses_ addObject:clause];
1826 /* Package Class {{{ */
1827 struct ParsedPackage {
1832 CYString depiction_;
1842 @interface Package : NSObject {
1845 uint32_t essential_ : 1;
1846 uint32_t obsolete_ : 1;
1847 uint32_t ignored_ : 1;
1851 _transient Database *database_;
1853 pkgCache::VerIterator version_;
1854 pkgCache::PkgIterator iterator_;
1855 pkgCache::VerFileIterator file_;
1861 CYString installed_;
1863 const char *section_;
1864 _transient NSString *section$_;
1868 PackageValue *metadata_;
1869 ParsedPackage *parsed_;
1871 NSMutableArray *tags_;
1874 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1875 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1877 - (pkgCache::PkgIterator) iterator;
1880 - (NSString *) section;
1881 - (NSString *) simpleSection;
1883 - (NSString *) longSection;
1884 - (NSString *) shortSection;
1888 - (Address *) maintainer;
1890 - (NSString *) longDescription;
1891 - (NSString *) shortDescription;
1894 - (PackageValue *) metadata;
1897 - (bool) subscribed;
1898 - (bool) setSubscribed:(bool)subscribed;
1902 - (NSString *) latest;
1903 - (NSString *) installed;
1904 - (BOOL) uninstalled;
1907 - (BOOL) upgradableAndEssential:(BOOL)essential;
1910 - (BOOL) unfiltered;
1914 - (BOOL) halfConfigured;
1915 - (BOOL) halfInstalled;
1917 - (NSString *) mode;
1920 - (NSString *) name;
1922 - (NSString *) homepage;
1923 - (NSString *) depiction;
1924 - (Address *) author;
1926 - (NSString *) support;
1928 - (NSArray *) files;
1929 - (NSArray *) warnings;
1930 - (NSArray *) applications;
1932 - (Source *) source;
1934 - (BOOL) matches:(NSString *)text;
1936 - (bool) hasSupportingRole;
1937 - (BOOL) hasTag:(NSString *)tag;
1938 - (NSString *) primaryPurpose;
1939 - (NSArray *) purposes;
1940 - (bool) isCommercial;
1942 - (void) setIndex:(size_t)index;
1944 - (CYString &) cyname;
1946 - (uint32_t) compareBySection:(NSArray *)sections;
1951 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1952 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1953 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1954 - (bool) isVisibleInSection:(NSString *)section;
1955 - (bool) isVisibleInSource:(Source *)source;
1959 uint32_t PackageChangesRadix(Package *self, void *) {
1964 uint32_t timestamp : 30;
1965 uint32_t ignored : 1;
1966 uint32_t upgradable : 1;
1970 bool upgradable([self upgradableAndEssential:YES]);
1971 value.bits.upgradable = upgradable ? 1 : 0;
1974 value.bits.timestamp = 0;
1975 value.bits.ignored = [self ignored] ? 0 : 1;
1976 value.bits.upgradable = 1;
1978 value.bits.timestamp = [self seen] >> 2;
1979 value.bits.ignored = 0;
1980 value.bits.upgradable = 0;
1983 return _not(uint32_t) - value.key;
1986 uint32_t PackagePrefixRadix(Package *self, void *context) {
1987 size_t offset(reinterpret_cast<size_t>(context));
1988 CYString &name([self cyname]);
1990 size_t size(name.size());
1993 char *text(name.data());
1996 if (!isdigit(text[0]))
2000 while (size != digits && isdigit(text[digits]))
2008 if (offset == 0 && zeros != 0) {
2009 memset(data, '0', zeros);
2010 memcpy(data + zeros, text, 4 - zeros);
2012 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2013 if (size <= offset - zeros)
2016 text += offset - zeros;
2017 size -= offset - zeros;
2020 memcpy(data, text, 4);
2022 memcpy(data, text, size);
2023 memset(data + size, 0, 4 - size);
2026 for (size_t i(0); i != 4; ++i)
2027 if (isalpha(data[i]))
2035 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2037 /* XXX: ntohl may be more honest */
2038 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2041 CYString &(*PackageName)(Package *self, SEL sel);
2043 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2044 _profile(PackageNameCompare)
2045 CYString &lhi(PackageName(lhs, @selector(cyname)));
2046 CYString &rhi(PackageName(rhs, @selector(cyname)));
2047 CFStringRef lhn(lhi), rhn(rhi);
2050 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2051 else if (rhn == NULL)
2052 return NSOrderedDescending;
2054 _profile(PackageNameCompare$NumbersLast)
2055 if (!lhi.empty() && !rhi.empty()) {
2056 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2057 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2058 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2059 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2060 return lha ? NSOrderedAscending : NSOrderedDescending;
2064 CFIndex length = CFStringGetLength(lhn);
2066 _profile(PackageNameCompare$Compare)
2067 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2072 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2073 return PackageNameCompare(*lhs, *rhs, context);
2076 struct PackageNameOrdering :
2077 std::binary_function<Package *, Package *, bool>
2079 _finline bool operator ()(Package *lhs, Package *rhs) const {
2080 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2084 @implementation Package
2086 - (NSString *) description {
2087 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2091 if (parsed_ != NULL)
2100 + (NSString *) webScriptNameForSelector:(SEL)selector {
2102 else if (selector == @selector(clear))
2104 else if (selector == @selector(getField:))
2106 else if (selector == @selector(hasTag:))
2108 else if (selector == @selector(install))
2110 else if (selector == @selector(remove))
2116 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2117 return [self webScriptNameForSelector:selector] == nil;
2120 + (NSArray *) _attributeKeys {
2121 return [NSArray arrayWithObjects:
2140 @"shortDescription",
2153 - (NSArray *) attributeKeys {
2154 return [[self class] _attributeKeys];
2157 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2158 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2161 - (NSArray *) relations {
2162 @synchronized (database_) {
2163 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2164 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2165 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2169 - (NSString *) getField:(NSString *)name {
2170 @synchronized (database_) {
2171 if ([database_ era] != era_ || file_.end())
2174 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2176 const char *start, *end;
2177 if (!parser.Find([name UTF8String], start, end))
2178 return (NSString *) [NSNull null];
2180 return [(NSString *) CYStringCreate(start, end - start) autorelease];
2184 if (parsed_ != NULL)
2186 @synchronized (database_) {
2187 if ([database_ era] != era_ || file_.end())
2190 ParsedPackage *parsed(new ParsedPackage);
2193 _profile(Package$parse)
2194 pkgRecords::Parser *parser;
2196 _profile(Package$parse$Lookup)
2197 parser = &[database_ records]->Lookup(file_);
2202 _profile(Package$parse$Find)
2207 {"icon", &parsed->icon_},
2208 {"depiction", &parsed->depiction_},
2209 {"homepage", &parsed->homepage_},
2210 {"website", &website},
2211 {"bugs", &parsed->bugs_},
2212 {"support", &parsed->support_},
2213 {"sponsor", &parsed->sponsor_},
2214 {"author", &parsed->author_},
2217 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2218 const char *start, *end;
2220 if (parser->Find(names[i].name_, start, end)) {
2221 CYString &value(*names[i].value_);
2222 _profile(Package$parse$Value)
2223 value.set(pool_, start, end - start);
2229 _profile(Package$parse$Tagline)
2230 const char *start, *end;
2231 if (parser->ShortDesc(start, end)) {
2232 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2235 while (stop != start && stop[-1] == '\r')
2237 parsed->tagline_.set(pool_, start, stop - start);
2241 _profile(Package$parse$Retain)
2242 if (parsed->homepage_.empty())
2243 parsed->homepage_ = website;
2244 if (parsed->homepage_ == parsed->depiction_)
2245 parsed->homepage_.clear();
2250 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2251 if ((self = [super init]) != nil) {
2252 _profile(Package$initWithVersion)
2255 database_ = database;
2256 era_ = [database era];
2260 pkgCache::PkgIterator iterator(version.ParentPkg());
2261 iterator_ = iterator;
2263 _profile(Package$initWithVersion$Version)
2264 if (!version_.end())
2265 file_ = version_.FileList();
2267 pkgCache &cache([database_ cache]);
2268 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2272 _profile(Package$initWithVersion$Cache)
2273 name_.set(NULL, iterator.Display());
2275 latest_.set(NULL, StripVersion_(version_.VerStr()));
2277 pkgCache::VerIterator current(iterator.CurrentVer());
2279 installed_.set(NULL, StripVersion_(current.VerStr()));
2282 _profile(Package$initWithVersion$Tags)
2283 pkgCache::TagIterator tag(iterator.TagList());
2285 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2287 const char *name(tag.Name());
2288 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2290 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2291 if (strcmp(name + 6, "enduser") == 0)
2293 else if (strcmp(name + 6, "hacker") == 0)
2295 else if (strcmp(name + 6, "developer") == 0)
2297 else if (strcmp(name + 6, "cydia") == 0)
2303 if (strncmp(name, "cydia::", 7) == 0) {
2304 if (strcmp(name + 7, "essential") == 0)
2306 else if (strcmp(name + 7, "obsolete") == 0)
2311 } while (!tag.end());
2315 _profile(Package$initWithVersion$Metadata)
2316 const char *mixed(iterator.Name());
2317 size_t size(strlen(mixed));
2318 char lower[size + 1];
2320 for (size_t i(0); i != size; ++i)
2321 lower[i] = mixed[i] | 0x20;
2324 PackageValue *metadata(PackageFind(lower, size));
2325 metadata_ = metadata;
2327 id_.set(NULL, metadata->name_, size);
2329 const char *latest(version_.VerStr());
2330 size_t length(strlen(latest));
2332 uint16_t vhash(hashlittle(latest, length));
2334 size_t capped(std::min<size_t>(8, length));
2335 latest = latest + length - capped;
2337 if (metadata->first_ == 0)
2338 metadata->first_ = now_;
2340 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2341 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2342 metadata->vhash_ = vhash;
2343 metadata->last_ = now_;
2344 } else if (metadata->last_ == 0)
2345 metadata->last_ = metadata->first_;
2348 _profile(Package$initWithVersion$Section)
2349 section_ = iterator.Section();
2352 _profile(Package$initWithVersion$Flags)
2353 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2354 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2359 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2360 pkgCache::VerIterator version;
2362 _profile(Package$packageWithIterator$GetCandidateVer)
2363 version = [database policy]->GetCandidateVer(iterator);
2371 _profile(Package$packageWithIterator$Allocate)
2372 package = [Package allocWithZone:zone];
2375 _profile(Package$packageWithIterator$Initialize)
2377 initWithVersion:version
2384 _profile(Package$packageWithIterator$Autorelease)
2385 package = [package autorelease];
2391 - (pkgCache::PkgIterator) iterator {
2395 - (NSString *) section {
2396 if (section$_ == nil) {
2397 if (section_ == NULL)
2400 _profile(Package$section$mappedSectionForPointer)
2401 section$_ = [database_ mappedSectionForPointer:section_];
2406 - (NSString *) simpleSection {
2407 if (NSString *section = [self section])
2408 return Simplify(section);
2413 - (NSString *) longSection {
2414 return LocalizeSection([self section]);
2417 - (NSString *) shortSection {
2418 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2421 - (NSString *) uri {
2424 pkgIndexFile *index;
2425 pkgCache::PkgFileIterator file(file_.File());
2426 if (![database_ list].FindIndex(file, index))
2428 return [NSString stringWithUTF8String:iterator_->Path];
2429 //return [NSString stringWithUTF8String:file.Site()];
2430 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2434 - (Address *) maintainer {
2435 @synchronized (database_) {
2436 if ([database_ era] != era_ || file_.end())
2439 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2440 const std::string &maintainer(parser->Maintainer());
2441 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2445 @synchronized (database_) {
2446 if ([database_ era] != era_ || version_.end())
2449 return version_->InstalledSize;
2452 - (NSString *) longDescription {
2453 @synchronized (database_) {
2454 if ([database_ era] != era_ || file_.end())
2457 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2458 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2460 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2461 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2462 if ([lines count] < 2)
2465 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2466 for (size_t i(1), e([lines count]); i != e; ++i) {
2467 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2468 [trimmed addObject:trim];
2471 return [trimmed componentsJoinedByString:@"\n"];
2474 - (NSString *) shortDescription {
2475 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2479 _profile(Package$index)
2480 CFStringRef name((CFStringRef) [self name]);
2481 if (CFStringGetLength(name) == 0)
2483 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2484 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2486 return toupper(character);
2490 - (PackageValue *) metadata {
2495 PackageValue *metadata([self metadata]);
2496 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2499 - (bool) subscribed {
2500 return [self metadata]->subscribed_;
2503 - (bool) setSubscribed:(bool)subscribed {
2504 PackageValue *metadata([self metadata]);
2505 if (metadata->subscribed_ == subscribed)
2507 metadata->subscribed_ = subscribed;
2515 - (NSString *) latest {
2519 - (NSString *) installed {
2523 - (BOOL) uninstalled {
2524 return installed_.empty();
2528 return !version_.end();
2531 - (BOOL) upgradableAndEssential:(BOOL)essential {
2532 _profile(Package$upgradableAndEssential)
2533 pkgCache::VerIterator current(iterator_.CurrentVer());
2535 return essential && essential_;
2537 return !version_.end() && version_ != current;
2541 - (BOOL) essential {
2546 return [database_ cache][iterator_].InstBroken();
2549 - (BOOL) unfiltered {
2550 _profile(Package$unfiltered$obsolete)
2551 if (_unlikely(obsolete_))
2555 _profile(Package$unfiltered$hasSupportingRole)
2556 if (_unlikely(![self hasSupportingRole]))
2564 if (![self unfiltered])
2569 _profile(Package$visible$section)
2570 section = [self section];
2573 _profile(Package$visible$isSectionVisible)
2574 if (!isSectionVisible(section))
2582 unsigned char current(iterator_->CurrentState);
2583 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2586 - (BOOL) halfConfigured {
2587 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2590 - (BOOL) halfInstalled {
2591 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2595 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2596 return state.Mode != pkgDepCache::ModeKeep;
2599 - (NSString *) mode {
2600 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2602 switch (state.Mode) {
2603 case pkgDepCache::ModeDelete:
2604 if ((state.iFlags & pkgDepCache::Purge) != 0)
2608 case pkgDepCache::ModeKeep:
2609 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2610 return @"REINSTALL";
2611 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2615 case pkgDepCache::ModeInstall:
2616 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2617 return @"REINSTALL";
2618 else*/ switch (state.Status) {
2620 return @"DOWNGRADE";
2626 return @"NEW_INSTALL";
2637 - (NSString *) name {
2638 return name_.empty() ? id_ : name_;
2641 - (UIImage *) icon {
2642 NSString *section = [self simpleSection];
2645 if (parsed_ != NULL)
2646 if (NSString *href = parsed_->icon_)
2647 if ([href hasPrefix:@"file:///"])
2648 // XXX: correct escaping
2649 icon = [UIImage imageAtPath:[href substringFromIndex:7]];
2650 if (icon == nil) if (section != nil)
2651 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2652 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2653 if ([dicon hasPrefix:@"file:///"])
2654 // XXX: correct escaping
2655 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2657 icon = [UIImage applicationImageNamed:@"unknown.png"];
2661 - (NSString *) homepage {
2662 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2665 - (NSString *) depiction {
2666 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2669 - (Address *) sponsor {
2670 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [Address addressWithString:parsed_->sponsor_];
2673 - (Address *) author {
2674 return parsed_ == NULL || parsed_->author_.empty() ? nil : [Address addressWithString:parsed_->author_];
2677 - (NSString *) support {
2678 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2681 - (NSArray *) files {
2682 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2683 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2686 fin.open([path UTF8String]);
2691 while (std::getline(fin, line))
2692 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2697 - (NSString *) state {
2698 @synchronized (database_) {
2699 if ([database_ era] != era_ || file_.end())
2702 switch (iterator_->CurrentState) {
2703 case pkgCache::State::NotInstalled:
2704 return @"NotInstalled";
2705 case pkgCache::State::UnPacked:
2707 case pkgCache::State::HalfConfigured:
2708 return @"HalfConfigured";
2709 case pkgCache::State::HalfInstalled:
2710 return @"HalfInstalled";
2711 case pkgCache::State::ConfigFiles:
2712 return @"ConfigFiles";
2713 case pkgCache::State::Installed:
2714 return @"Installed";
2715 case pkgCache::State::TriggersAwaited:
2716 return @"TriggersAwaited";
2717 case pkgCache::State::TriggersPending:
2718 return @"TriggersPending";
2721 return (NSString *) [NSNull null];
2724 - (NSString *) selection {
2725 @synchronized (database_) {
2726 if ([database_ era] != era_ || file_.end())
2729 switch (iterator_->SelectedState) {
2730 case pkgCache::State::Unknown:
2732 case pkgCache::State::Install:
2734 case pkgCache::State::Hold:
2736 case pkgCache::State::DeInstall:
2737 return @"DeInstall";
2738 case pkgCache::State::Purge:
2742 return (NSString *) [NSNull null];
2745 - (NSArray *) warnings {
2746 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2747 const char *name(iterator_.Name());
2749 size_t length(strlen(name));
2750 if (length < 2) invalid:
2751 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2752 else for (size_t i(0); i != length; ++i)
2754 /* XXX: technically this is not allowed */
2755 (name[i] < 'A' || name[i] > 'Z') &&
2756 (name[i] < 'a' || name[i] > 'z') &&
2757 (name[i] < '0' || name[i] > '9') &&
2758 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2761 if (strcmp(name, "cydia") != 0) {
2764 bool _private = false;
2767 bool repository = [[self section] isEqualToString:@"Repositories"];
2769 if (NSArray *files = [self files])
2770 for (NSString *file in files)
2771 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2773 else if (!user && [file isEqualToString:@"/User"])
2775 else if (!_private && [file isEqualToString:@"/private"])
2777 else if (!stash && [file isEqualToString:@"/var/stash"])
2780 /* XXX: this is not sensitive enough. only some folders are valid. */
2781 if (cydia && !repository)
2782 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2784 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2786 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2788 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2791 return [warnings count] == 0 ? nil : warnings;
2794 - (NSArray *) applications {
2795 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2797 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2799 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2800 if (NSArray *files = [self files])
2801 for (NSString *file in files)
2802 if (application_r(file)) {
2803 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2804 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2805 if ([id isEqualToString:me])
2808 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2810 display = application_r[1];
2812 NSString *bundle([file stringByDeletingLastPathComponent]);
2813 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2814 if (icon == nil || [icon length] == 0)
2816 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2818 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2819 [applications addObject:application];
2821 [application addObject:id];
2822 [application addObject:display];
2823 [application addObject:url];
2826 return [applications count] == 0 ? nil : applications;
2829 - (Source *) source {
2830 if (source_ == nil) {
2831 @synchronized (database_) {
2832 if ([database_ era] != era_ || file_.end())
2833 source_ = (Source *) [NSNull null];
2835 source_ = [([database_ getSource:file_.File()] ?: (Source *) [NSNull null]) retain];
2839 return source_ == (Source *) [NSNull null] ? nil : source_;
2842 - (BOOL) matches:(NSString *)text {
2848 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2849 if (range.location != NSNotFound)
2852 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2853 if (range.location != NSNotFound)
2858 NSString *description([self shortDescription]);
2859 NSUInteger length([description length]);
2861 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_ range:NSMakeRange(0, std::min<NSUInteger>(length, 100))];
2862 if (range.location != NSNotFound)
2868 - (bool) hasSupportingRole {
2873 if ([Role_ isEqualToString:@"User"])
2877 if ([Role_ isEqualToString:@"Hacker"])
2881 if ([Role_ isEqualToString:@"Developer"])
2886 - (NSArray *) tags {
2890 - (BOOL) hasTag:(NSString *)tag {
2891 return tags_ == nil ? NO : [tags_ containsObject:tag];
2894 - (NSString *) primaryPurpose {
2895 for (NSString *tag in tags_)
2896 if ([tag hasPrefix:@"purpose::"])
2897 return [tag substringFromIndex:9];
2901 - (NSArray *) purposes {
2902 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2903 for (NSString *tag in tags_)
2904 if ([tag hasPrefix:@"purpose::"])
2905 [purposes addObject:[tag substringFromIndex:9]];
2906 return [purposes count] == 0 ? nil : purposes;
2909 - (bool) isCommercial {
2910 return [self hasTag:@"cydia::commercial"];
2913 - (void) setIndex:(size_t)index {
2914 if (metadata_->index_ != index)
2915 metadata_->index_ = index;
2918 - (CYString &) cyname {
2919 return name_.empty() ? id_ : name_;
2922 - (uint32_t) compareBySection:(NSArray *)sections {
2923 NSString *section([self section]);
2924 for (size_t i(0), e([sections count]); i != e; ++i) {
2925 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2929 return _not(uint32_t);
2933 @synchronized (database_) {
2934 pkgProblemResolver *resolver = [database_ resolver];
2935 resolver->Clear(iterator_);
2937 pkgCacheFile &cache([database_ cache]);
2938 cache->SetReInstall(iterator_, false);
2939 cache->MarkKeep(iterator_, false);
2943 @synchronized (database_) {
2944 pkgProblemResolver *resolver = [database_ resolver];
2945 resolver->Clear(iterator_);
2946 resolver->Protect(iterator_);
2948 pkgCacheFile &cache([database_ cache]);
2949 cache->SetReInstall(iterator_, false);
2950 cache->MarkInstall(iterator_, false);
2952 pkgDepCache::StateCache &state((*cache)[iterator_]);
2953 if (!state.Install())
2954 cache->SetReInstall(iterator_, true);
2958 @synchronized (database_) {
2959 pkgProblemResolver *resolver = [database_ resolver];
2960 resolver->Clear(iterator_);
2961 resolver->Remove(iterator_);
2962 resolver->Protect(iterator_);
2964 pkgCacheFile &cache([database_ cache]);
2965 cache->SetReInstall(iterator_, false);
2966 cache->MarkDelete(iterator_, true);
2969 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2970 _profile(Package$isUnfilteredAndSearchedForBy)
2973 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2974 value &= [self unfiltered];
2977 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2978 value &= [self matches:search];
2985 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2986 if ([search length] == 0)
2989 _profile(Package$isUnfilteredAndSelectedForBy)
2992 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2993 value &= [self unfiltered];
2996 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2997 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
3004 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
3005 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
3008 - (bool) isVisibleInSection:(NSString *)name {
3009 NSString *section([self section]);
3013 section == nil && [name length] == 0 ||
3014 [name isEqualToString:section]
3015 ) && [self visible];
3018 - (bool) isVisibleInSource:(Source *)source {
3019 return [self source] == source && [self visible];
3024 /* Section Class {{{ */
3025 @interface Section : NSObject {
3030 NSString *localized_;
3033 - (NSComparisonResult) compareByLocalized:(Section *)section;
3034 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3035 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3036 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3037 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
3038 - (NSString *) name;
3045 - (void) addToCount;
3047 - (void) setCount:(size_t)count;
3048 - (NSString *) localized;
3052 @implementation Section
3056 if (localized_ != nil)
3057 [localized_ release];
3061 - (NSComparisonResult) compareByLocalized:(Section *)section {
3062 NSString *lhs(localized_);
3063 NSString *rhs([section localized]);
3065 /*if ([lhs length] != 0 && [rhs length] != 0) {
3066 unichar lhc = [lhs characterAtIndex:0];
3067 unichar rhc = [rhs characterAtIndex:0];
3069 if (isalpha(lhc) && !isalpha(rhc))
3070 return NSOrderedAscending;
3071 else if (!isalpha(lhc) && isalpha(rhc))
3072 return NSOrderedDescending;
3075 return [lhs compare:rhs options:LaxCompareOptions_];
3078 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3079 if ((self = [self initWithName:name localize:NO]) != nil) {
3080 if (localized != nil)
3081 localized_ = [localized retain];
3085 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3086 return [self initWithName:name row:0 localize:localize];
3089 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3090 if ((self = [super init]) != nil) {
3091 name_ = [name retain];
3095 localized_ = [LocalizeSection(name_) retain];
3099 /* XXX: localize the index thingees */
3100 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
3101 if ((self = [super init]) != nil) {
3102 name_ = [[NSString stringWithCharacters:&index length:1] retain];
3108 - (NSString *) name {
3128 - (void) addToCount {
3132 - (void) setCount:(size_t)count {
3136 - (NSString *) localized {
3143 static NSString *Colon_;
3144 static NSString *Elision_;
3145 static NSString *Error_;
3146 static NSString *Warning_;
3148 /* Database Implementation {{{ */
3149 @implementation Database
3151 + (Database *) sharedInstance {
3152 static Database *instance;
3153 if (instance == nil)
3154 instance = [[Database alloc] init];
3162 - (void) releasePackages {
3163 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3164 CFArrayRemoveAllValues(packages_);
3168 // XXX: actually implement this thing
3170 [sourceList_ release];
3171 [self releasePackages];
3172 apr_pool_destroy(pool_);
3173 NSRecycleZone(zone_);
3177 - (void) _readCydia:(NSNumber *)fd { _pooled
3178 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3179 std::istream is(&ib);
3182 static Pcre finish_r("^finish:([^:]*)$");
3184 while (std::getline(is, line)) {
3185 const char *data(line.c_str());
3186 size_t size = line.size();
3187 lprintf("C:%s\n", data);
3189 if (finish_r(data, size)) {
3190 NSString *finish = finish_r[1];
3191 int index = [Finishes_ indexOfObject:finish];
3192 if (index != INT_MAX && index > Finish_)
3200 - (void) _readStatus:(NSNumber *)fd { _pooled
3201 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3202 std::istream is(&ib);
3205 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3206 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3208 while (std::getline(is, line)) {
3209 const char *data(line.c_str());
3210 size_t size(line.size());
3211 lprintf("S:%s\n", data);
3213 if (conffile_r(data, size)) {
3214 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3215 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3216 } else if (strncmp(data, "status: ", 8) == 0) {
3217 // status: <package>: {unpacked,half-configured,installed}
3218 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3219 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3220 } else if (strncmp(data, "processing: ", 12) == 0) {
3221 // processing: configure: config-test
3222 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3223 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3224 } else if (pmstatus_r(data, size)) {
3225 std::string type([pmstatus_r[1] UTF8String]);
3227 NSString *package = pmstatus_r[2];
3228 if ([package isEqualToString:@"dpkg-exec"])
3231 float percent([pmstatus_r[3] floatValue]);
3232 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3234 NSString *string = pmstatus_r[4];
3236 if (type == "pmerror") {
3237 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3238 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3239 } else if (type == "pmstatus") {
3240 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3241 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3242 } else if (type == "pmconffile")
3243 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3245 lprintf("E:unknown pmstatus\n");
3247 lprintf("E:unknown status\n");
3253 - (void) _readOutput:(NSNumber *)fd { _pooled
3254 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3255 std::istream is(&ib);
3258 while (std::getline(is, line)) {
3259 lprintf("O:%s\n", line.c_str());
3261 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3262 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3272 - (Package *) packageWithName:(NSString *)name {
3273 @synchronized (self) {
3274 if (static_cast<pkgDepCache *>(cache_) == NULL)
3276 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3277 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3281 if ((self = [super init]) != nil) {
3288 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3289 apr_pool_create(&pool_, NULL);
3291 size_t capacity(MetaFile_->active_);
3297 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3298 sourceList_ = [[NSMutableArray alloc] initWithCapacity:16];
3302 _assert(pipe(fds) != -1);
3305 _config->Set("APT::Keep-Fds::", cydiafd_);
3306 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3309 detachNewThreadSelector:@selector(_readCydia:)
3311 withObject:[NSNumber numberWithInt:fds[0]]
3314 _assert(pipe(fds) != -1);
3318 detachNewThreadSelector:@selector(_readStatus:)
3320 withObject:[NSNumber numberWithInt:fds[0]]
3323 _assert(pipe(fds) != -1);
3324 _assert(dup2(fds[0], 0) != -1);
3325 _assert(close(fds[0]) != -1);
3327 input_ = fdopen(fds[1], "a");
3329 _assert(pipe(fds) != -1);
3330 _assert(dup2(fds[1], 1) != -1);
3331 _assert(close(fds[1]) != -1);
3334 detachNewThreadSelector:@selector(_readOutput:)
3336 withObject:[NSNumber numberWithInt:fds[0]]
3341 - (pkgCacheFile &) cache {
3345 - (pkgDepCache::Policy *) policy {
3349 - (pkgRecords *) records {
3353 - (pkgProblemResolver *) resolver {
3357 - (pkgAcquire &) fetcher {
3361 - (pkgSourceList &) list {
3365 - (NSArray *) packages {
3366 return (NSArray *) packages_;
3369 - (NSArray *) sources {
3373 - (Source *) sourceWithKey:(NSString *)key {
3374 for (Source *source in [self sources]) {
3375 if ([[source key] isEqualToString:key])
3380 - (bool) popErrorWithTitle:(NSString *)title {
3383 while (!_error->empty()) {
3385 bool warning(!_error->PopMessage(error));
3390 size_t size(error.size());
3391 if (size == 0 || error[size - 1] != '\n')
3393 error.resize(size - 1);
3396 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3398 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3404 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3405 return [self popErrorWithTitle:title] || !success;
3408 - (void) reloadDataWithInvocation:(NSInvocation *)invocation { CYPoolStart() {
3409 @synchronized (self) {
3412 [self releasePackages];
3415 [sourceList_ removeAllObjects];
3435 apr_pool_clear(pool_);
3437 NSRecycleZone(zone_);
3438 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3440 int chk(creat("/tmp/cydia.chk", 0644));
3444 if (invocation != nil)
3445 [invocation invoke];
3447 NSString *title(UCLocalize("DATABASE"));
3450 OpProgress progress;
3451 while (!cache_.Open(progress, true)) { pop:
3453 bool warning(!_error->PopMessage(error));
3454 lprintf("cache_.Open():[%s]\n", error.c_str());
3456 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3457 [delegate_ repairWithSelector:@selector(configure)];
3458 else if (error == "The package lists or status file could not be parsed or opened.")
3459 [delegate_ repairWithSelector:@selector(update)];
3460 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3461 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3462 // else if (error == "Malformed Status line")
3463 // else if (error == "The list of sources could not be read.")
3465 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3475 unlink("/tmp/cydia.chk");
3477 now_ = [[NSDate date] timeIntervalSince1970];
3479 policy_ = new pkgDepCache::Policy();
3480 records_ = new pkgRecords(cache_);
3481 resolver_ = new pkgProblemResolver(cache_);
3482 fetcher_ = new pkgAcquire(&status_);
3485 list_ = new pkgSourceList();
3486 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3489 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3490 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3494 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3497 if (cache_->BrokenCount() != 0) {
3498 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3501 if (cache_->BrokenCount() != 0) {
3502 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3506 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3510 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3511 Source *object([[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease]);
3512 [sourceList_ addObject:object];
3514 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3515 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3516 // XXX: this could be more intelligent
3517 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3518 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3520 sourceMap_[cached->ID] = object;
3525 /*std::vector<Package *> packages;
3526 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3527 [packages_ release];
3532 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3533 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3534 //packages.push_back(package);
3535 CFArrayAppendValue(packages_, [package retain]);
3539 /*if (packages.empty())
3540 packages_ = [[NSArray alloc] init];
3542 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3545 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3546 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3547 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3555 /*if (!packages.empty())
3556 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3557 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3559 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3561 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3563 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3567 size_t count(CFArrayGetCount(packages_));
3568 MetaFile_->active_ = count;
3570 for (size_t index(0); index != count; ++index)
3571 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3575 } } CYPoolEnd() _trace(); }
3578 @synchronized (self) {
3580 resolver_ = new pkgProblemResolver(cache_);
3582 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3583 if (!cache_[iterator].Keep())
3584 cache_->MarkKeep(iterator, false);
3585 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3586 cache_->SetReInstall(iterator, false);
3589 - (void) configure {
3590 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3592 system([dpkg UTF8String]);
3597 // XXX: I don't remember this condition
3602 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3604 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3606 if ([self popErrorWithTitle:title])
3610 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3613 public pkgArchiveCleaner
3616 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3621 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3628 fetcher_->Shutdown();
3630 pkgRecords records(cache_);
3632 lock_ = new FileFd();
3633 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3635 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3637 if ([self popErrorWithTitle:title])
3641 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3644 manager_ = (_system->CreatePM(cache_));
3645 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3652 bool substrate(RestartSubstrate_);
3653 RestartSubstrate_ = false;
3655 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3657 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3659 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3661 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3662 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3665 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3667 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3669 [self popErrorWithTitle:title];
3673 bool failed = false;
3674 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3675 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3677 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3683 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3691 RestartSubstrate_ = true;
3694 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3696 if (_error->PendingError()) {
3701 if (result == pkgPackageManager::Failed) {
3706 if (result != pkgPackageManager::Completed) {
3711 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3713 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3715 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3716 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3719 if (![before isEqualToArray:after])
3724 NSString *title(UCLocalize("UPGRADE"));
3725 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3731 [self updateWithStatus:status_];
3734 - (void) updateWithStatus:(Status &)status {
3735 NSString *title(UCLocalize("REFRESHING_DATA"));
3738 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3742 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3743 if ([self popErrorWithTitle:title])
3746 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3748 bool success(ListUpdate(status, list, PulseInterval_));
3749 if (status.WasCancelled())
3752 [self popErrorWithTitle:title forOperation:success];
3754 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3756 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3760 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
3761 delegate_ = delegate;
3764 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
3765 progress_ = delegate;
3766 status_.setDelegate(delegate);
3769 - (NSObject<ProgressDelegate> *) progressDelegate {
3773 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3774 SourceMap::const_iterator i(sourceMap_.find(file->ID));
3775 return i == sourceMap_.end() ? nil : i->second;
3778 - (NSString *) mappedSectionForPointer:(const char *)section {
3779 _H<NSString> *mapped;
3781 _profile(Database$mappedSectionForPointer$Cache)
3782 mapped = §ions_[section];
3785 if (*mapped == NULL) {
3786 size_t length(strlen(section));
3787 char spaced[length + 1];
3789 _profile(Database$mappedSectionForPointer$Replace)
3790 for (size_t index(0); index != length; ++index)
3791 spaced[index] = section[index] == '_' ? ' ' : section[index];
3792 spaced[length] = '\0';
3797 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3798 string = [NSString stringWithUTF8String:spaced];
3801 _profile(Database$mappedSectionForPointer$Map)
3802 string = [SectionMap_ objectForKey:string] ?: string;
3812 static NSMutableSet *Diversions_;
3814 @interface Diversion : NSObject {
3817 _H<NSString> format_;
3822 @implementation Diversion
3824 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
3825 if ((self = [super init]) != nil) {
3826 pattern_ = [from UTF8String];
3832 - (NSString *) divert:(NSString *)url {
3833 return !pattern_(url) ? nil : pattern_->*format_;
3836 + (NSURL *) divertURL:(NSURL *)url {
3838 NSString *href([url absoluteString]);
3840 for (Diversion *diversion in Diversions_)
3841 if (NSString *diverted = [diversion divert:href]) {
3843 NSLog(@"div: %@", diverted);
3845 url = [NSURL URLWithString:diverted];
3852 - (NSString *) key {
3856 - (NSUInteger) hash {
3860 - (BOOL) isEqual:(Diversion *)object {
3861 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
3866 @interface CydiaObject : NSObject {
3868 _transient id delegate_;
3871 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3875 @interface CydiaWebViewController : CyteWebViewController {
3876 CydiaObject *cydia_;
3879 + (void) addDiversion:(Diversion *)diversion;
3883 /* Web Scripting {{{ */
3884 @implementation CydiaObject
3887 [indirect_ release];
3891 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3892 if ((self = [super init]) != nil) {
3893 indirect_ = [indirect retain];
3897 - (void) setDelegate:(id)delegate {
3898 delegate_ = delegate;
3901 + (NSArray *) _attributeKeys {
3902 return [NSArray arrayWithObjects:
3917 - (NSArray *) attributeKeys {
3918 return [[self class] _attributeKeys];
3921 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3922 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3925 - (NSString *) version {
3929 - (NSString *) device {
3930 return [[UIDevice currentDevice] uniqueIdentifier];
3933 - (NSString *) firmware {
3934 return [[UIDevice currentDevice] systemVersion];
3937 - (NSString *) hostname {
3938 return [[UIDevice currentDevice] name];
3941 - (NSString *) idiom {
3942 return (id) Idiom_ ?: [NSNull null];
3945 - (NSString *) plmn {
3946 return (id) PLMN_ ?: [NSNull null];
3949 - (NSString *) ecid {
3950 return (id) ChipID_ ?: [NSNull null];
3953 - (NSString *) serial {
3954 return SerialNumber_;
3957 - (NSString *) role {
3958 return (id) Role_ ?: [NSNull null];
3961 - (NSString *) model {
3962 return [NSString stringWithUTF8String:Machine_];
3965 - (NSString *) token {
3966 return (id) Token_ ?: [NSNull null];
3969 + (NSString *) webScriptNameForSelector:(SEL)selector {
3971 else if (selector == @selector(addBridgedHost:))
3972 return @"addBridgedHost";
3973 else if (selector == @selector(addInternalRedirect::))
3974 return @"addInternalRedirect";
3975 else if (selector == @selector(addPipelinedHost:scheme:))
3976 return @"addPipelinedHost";
3977 else if (selector == @selector(addTrivialSource:))
3978 return @"addTrivialSource";
3979 else if (selector == @selector(close))
3981 else if (selector == @selector(du:))
3983 else if (selector == @selector(stringWithFormat:arguments:))
3985 else if (selector == @selector(getAllSources))
3986 return @"getAllSourcs";
3987 else if (selector == @selector(getKernelNumber:))
3988 return @"getKernelNumber";
3989 else if (selector == @selector(getKernelString:))
3990 return @"getKernelString";
3991 else if (selector == @selector(getInstalledPackages))
3992 return @"getInstalledPackages";
3993 else if (selector == @selector(getLocaleIdentifier))
3994 return @"getLocaleIdentifier";
3995 else if (selector == @selector(getPreferredLanguages))
3996 return @"getPreferredLanguages";
3997 else if (selector == @selector(getPackageById:))
3998 return @"getPackageById";
3999 else if (selector == @selector(getSessionValue:))
4000 return @"getSessionValue";
4001 else if (selector == @selector(installPackages:))
4002 return @"installPackages";
4003 else if (selector == @selector(localizedStringForKey:value:table:))
4005 else if (selector == @selector(popViewController:))
4006 return @"popViewController";
4007 else if (selector == @selector(refreshSources))
4008 return @"refreshSources";
4009 else if (selector == @selector(removeButton))
4010 return @"removeButton";
4011 else if (selector == @selector(setSessionValue::))
4012 return @"setSessionValue";
4013 else if (selector == @selector(substitutePackageNames:))
4014 return @"substitutePackageNames";
4015 else if (selector == @selector(scrollToBottom:))
4016 return @"scrollToBottom";
4017 else if (selector == @selector(setAllowsNavigationAction:))
4018 return @"setAllowsNavigationAction";
4019 else if (selector == @selector(setBadgeValue:))
4020 return @"setBadgeValue";
4021 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4022 return @"setButtonImage";
4023 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4024 return @"setButtonTitle";
4025 else if (selector == @selector(setHidesBackButton:))
4026 return @"setHidesBackButton";
4027 else if (selector == @selector(setHidesNavigationBar:))
4028 return @"setHidesNavigationBar";
4029 else if (selector == @selector(setNavigationBarStyle:))
4030 return @"setNavigationBarStyle";
4031 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4032 return @"setNavigationBarTintColor";
4033 else if (selector == @selector(setPasteboardString:))
4034 return @"setPasteboardString";
4035 else if (selector == @selector(setPasteboardURL:))
4036 return @"setPasteboardURL";
4037 else if (selector == @selector(setToken:))
4039 else if (selector == @selector(setViewportWidth:))
4040 return @"setViewportWidth";
4041 else if (selector == @selector(statfs:))
4043 else if (selector == @selector(supports:))
4049 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4050 return [self webScriptNameForSelector:selector] == nil;
4053 - (BOOL) supports:(NSString *)feature {
4054 return [feature isEqualToString:@"window.open"];
4057 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4058 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4061 - (NSNumber *) getKernelNumber:(NSString *)name {
4062 const char *string([name UTF8String]);
4065 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4066 return (id) [NSNull null];
4068 if (size != sizeof(int))
4069 return (id) [NSNull null];
4072 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4073 return (id) [NSNull null];
4075 return [NSNumber numberWithInt:value];
4078 - (NSString *) getKernelString:(NSString *)name {
4079 const char *string([name UTF8String]);
4082 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4083 return (id) [NSNull null];
4085 char value[size + 1];
4086 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4087 return (id) [NSNull null];
4089 // XXX: just in case you request something ludicrous
4092 return [NSString stringWithCString:value];
4095 - (id) getSessionValue:(NSString *)key {
4096 @synchronized (SessionData_) {
4097 return [SessionData_ objectForKey:key];
4100 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4101 @synchronized (SessionData_) {
4102 if (value == (id) [WebUndefined undefined])
4103 [SessionData_ removeObjectForKey:key];
4105 [SessionData_ setObject:value forKey:key];
4108 - (void) addBridgedHost:(NSString *)host {
4109 @synchronized (HostConfig_) {
4110 [BridgedHosts_ addObject:host];
4113 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4114 @synchronized (HostConfig_) {
4115 if (scheme != (id) [WebUndefined undefined])
4116 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4118 [PipelinedHosts_ addObject:host];
4121 - (void) popViewController:(NSNumber *)value {
4122 if (value == (id) [WebUndefined undefined])
4123 value = [NSNumber numberWithBool:YES];
4124 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4127 - (void) addTrivialSource:(NSString *)href {
4128 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4131 - (void) refreshSources {
4132 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4135 - (NSArray *) getAllSources {
4136 return [[Database sharedInstance] sources];
4139 - (NSArray *) getInstalledPackages {
4140 Database *database([Database sharedInstance]);
4141 @synchronized (database) {
4142 NSArray *packages([database packages]);
4143 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4144 for (Package *package in packages)
4145 if (![package uninstalled])
4146 [installed addObject:package];
4150 - (Package *) getPackageById:(NSString *)id {
4151 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4155 return (Package *) [NSNull null];
4158 - (NSString *) getLocaleIdentifier {
4159 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4162 - (NSArray *) getPreferredLanguages {
4166 - (NSArray *) statfs:(NSString *)path {
4169 if (path == nil || statfs([path UTF8String], &stat) == -1)
4172 return [NSArray arrayWithObjects:
4173 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4174 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4175 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4179 - (NSNumber *) du:(NSString *)path {
4180 NSNumber *value(nil);
4183 _assert(pipe(fds) != -1);
4185 pid_t pid(ExecFork());
4187 _assert(dup2(fds[1], 1) != -1);
4188 _assert(close(fds[0]) != -1);
4189 _assert(close(fds[1]) != -1);
4190 /* XXX: this should probably not use du */
4191 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4196 _assert(close(fds[1]) != -1);
4198 if (FILE *du = fdopen(fds[0], "r")) {
4200 while (fgets(line, sizeof(line), du) != NULL) {
4201 size_t length(strlen(line));
4202 while (length != 0 && line[length - 1] == '\n')
4203 line[--length] = '\0';
4204 if (char *tab = strchr(line, '\t')) {
4206 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4211 } else _assert(close(fds[0]));
4215 if (waitpid(pid, &status, 0) == -1)
4218 else _assert(false);
4224 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4227 - (void) installPackages:(NSArray *)packages {
4228 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4231 - (NSString *) substitutePackageNames:(NSString *)message {
4232 NSMutableArray *words([[message componentsSeparatedByString:@" "] mutableCopy]);
4233 for (size_t i(0), e([words count]); i != e; ++i) {
4234 NSString *word([words objectAtIndex:i]);
4235 if (Package *package = [[Database sharedInstance] packageWithName:word])
4236 [words replaceObjectAtIndex:i withObject:[package name]];
4239 return [words componentsJoinedByString:@" "];
4242 - (void) removeButton {
4243 [indirect_ removeButton];
4246 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4247 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4250 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4251 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4254 - (void) setBadgeValue:(id)value {
4255 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4258 - (void) setAllowsNavigationAction:(NSString *)value {
4259 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4262 - (void) setHidesBackButton:(NSString *)value {
4263 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4266 - (void) setHidesNavigationBar:(NSString *)value {
4267 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4270 - (void) setNavigationBarStyle:(NSString *)value {
4271 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4274 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4275 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4276 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4277 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4280 - (void) setPasteboardString:(NSString *)value {
4281 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4284 - (void) setPasteboardURL:(NSString *)value {
4285 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4288 - (void) _setToken:(NSString *)token {
4292 [Metadata_ removeObjectForKey:@"Token"];
4294 [Metadata_ setObject:Token_ forKey:@"Token"];
4299 - (void) setToken:(NSString *)token {
4300 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4303 - (void) scrollToBottom:(NSNumber *)animated {
4304 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4307 - (void) setViewportWidth:(float)width {
4308 [indirect_ setViewportWidthOnMainThread:width];
4311 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4312 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4313 unsigned count([arguments count]);
4315 for (unsigned i(0); i != count; ++i)
4316 values[i] = [arguments objectAtIndex:i];
4317 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4320 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4321 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4323 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4325 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4331 /* @ Loading... Indicator {{{ */
4332 @interface CYLoadingIndicator : UIView {
4333 _H<UIActivityIndicatorView> spinner_;
4335 _H<UIView> container_;
4338 @property (readonly, nonatomic) UILabel *label;
4339 @property (readonly, nonatomic) UIActivityIndicatorView *activityIndicatorView;
4343 @implementation CYLoadingIndicator
4345 - (id) initWithFrame:(CGRect)frame {
4346 if ((self = [super initWithFrame:frame]) != nil) {
4347 container_ = [[[UIView alloc] init] autorelease];
4348 [container_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
4350 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
4351 [spinner_ startAnimating];
4352 [container_ addSubview:spinner_];
4354 label_ = [[[UILabel alloc] init] autorelease];
4355 [label_ setFont:[UIFont boldSystemFontOfSize:15.0f]];
4356 [label_ setBackgroundColor:[UIColor clearColor]];
4357 [label_ setTextColor:[UIColor blackColor]];
4358 [label_ setShadowColor:[UIColor whiteColor]];
4359 [label_ setShadowOffset:CGSizeMake(0, 1)];
4360 [label_ setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
4361 [container_ addSubview:label_];
4363 CGSize viewsize = frame.size;
4364 CGSize spinnersize = [spinner_ bounds].size;
4365 CGSize textsize = [[label_ text] sizeWithFont:[label_ font]];
4366 float bothwidth = spinnersize.width + textsize.width + 5.0f;
4368 CGRect containrect = {
4369 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
4370 CGSizeMake(bothwidth, spinnersize.height)
4373 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
4381 [container_ setFrame:containrect];
4382 [spinner_ setFrame:spinrect];
4383 [label_ setFrame:textrect];
4384 [self addSubview:container_];
4388 - (UILabel *) label {
4392 - (UIActivityIndicatorView *) activityIndicatorView {
4398 /* Emulated Loading Controller {{{ */
4399 @interface CYEmulatedLoadingController : CyteViewController {
4400 _transient Database *database_;
4401 _H<CYLoadingIndicator> indicator_;
4402 _H<UITabBar> tabbar_;
4403 _H<UINavigationBar> navbar_;
4408 @implementation CYEmulatedLoadingController
4410 - (id) initWithDatabase:(Database *)database {
4411 if ((self = [super init]) != nil) {
4412 database_ = database;
4417 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
4419 UITableView *table([[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease]);
4420 [table setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4421 [[self view] addSubview:table];
4423 indicator_ = [[[CYLoadingIndicator alloc] initWithFrame:[[self view] bounds]] autorelease];
4424 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4425 [[self view] addSubview:indicator_];
4427 tabbar_ = [[[UITabBar alloc] initWithFrame:CGRectMake(0, 0, 0, 49.0f)] autorelease];
4428 [tabbar_ setFrame:CGRectMake(0.0f, [[self view] bounds].size.height - [tabbar_ bounds].size.height, [[self view] bounds].size.width, [tabbar_ bounds].size.height)];
4429 [tabbar_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth];
4430 [[self view] addSubview:tabbar_];
4432 navbar_ = [[[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 0, 44.0f)] autorelease];
4433 [navbar_ setFrame:CGRectMake(0.0f, 0.0f, [[self view] bounds].size.width, [navbar_ bounds].size.height)];
4434 [navbar_ setAutoresizingMask:UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth];
4435 [[self view] addSubview:navbar_];
4438 - (void) releaseSubviews {
4447 /* Cydia Browser Controller {{{ */
4448 @implementation CydiaWebViewController
4455 - (NSURL *) navigationURL {
4456 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4459 + (void) initialize {
4460 Diversions_ = [[NSMutableSet alloc] initWithCapacity:0];
4463 + (void) addDiversion:(Diversion *)diversion {
4464 [Diversions_ addObject:diversion];
4467 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4468 [super webView:view didClearWindowObject:window forFrame:frame];
4470 WebDataSource *source([frame dataSource]);
4471 NSURLResponse *response([source response]);
4472 NSURL *url([response URL]);
4473 NSString *scheme([[url scheme] lowercaseString]);
4475 bool bridged(false);
4477 @synchronized (HostConfig_) {
4478 if ([scheme isEqualToString:@"file"])
4480 else if ([scheme isEqualToString:@"https"])
4481 if ([BridgedHosts_ containsObject:[url host]])
4486 [window setValue:cydia_ forKey:@"cydia"];
4489 - (NSURL *) URLWithURL:(NSURL *)url {
4490 return [Diversion divertURL:url];
4493 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4494 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4496 if (System_ != NULL)
4497 [copy setValue:System_ forHTTPHeaderField:@"X-System"];
4498 if (Machine_ != NULL)
4499 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4501 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4506 - (void) setDelegate:(id)delegate {
4507 [super setDelegate:delegate];
4508 [cydia_ setDelegate:delegate];
4512 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4513 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
4515 WebView *webview([[webview_ _documentView] webView]);
4517 NSString *application([NSString stringWithFormat:@"Cydia/%@", @ Cydia_]);
4520 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4522 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4523 if (Product_ != nil)
4524 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4526 [webview setApplicationNameForUserAgent:application];
4534 @interface NSObject (CydiaScript)
4535 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4538 @implementation NSObject (CydiaScript)
4540 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4546 @implementation NSArray (CydiaScript)
4548 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4549 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4550 for (size_t i(0), e([self count]); i != e; ++i)
4551 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4557 @implementation NSDictionary (CydiaScript)
4559 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4560 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4562 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4569 /* Confirmation Controller {{{ */
4570 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4571 if (!iterator.end())
4572 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4573 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4575 pkgCache::PkgIterator package(dep.TargetPkg());
4578 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4585 @protocol ConfirmationControllerDelegate
4586 - (void) cancelAndClear:(bool)clear;
4587 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4591 @interface ConfirmationController : CydiaWebViewController {
4592 _transient Database *database_;
4594 UIAlertView *essential_;
4596 NSDictionary *changes_;
4597 NSMutableArray *issues_;
4598 NSDictionary *sizes_;
4603 - (id) initWithDatabase:(Database *)database;
4607 @implementation ConfirmationController
4614 if (essential_ != nil)
4615 [essential_ release];
4622 RestartSubstrate_ = true;
4623 [delegate_ confirmWithNavigationController:[self navigationController]];
4626 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4627 NSString *context([alert context]);
4629 if ([context isEqualToString:@"remove"]) {
4630 if (button == [alert cancelButtonIndex])
4631 [self dismissModalViewControllerAnimated:YES];
4632 else if (button == [alert firstOtherButtonIndex]) {
4636 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4637 } else if ([context isEqualToString:@"unable"]) {
4638 [self dismissModalViewControllerAnimated:YES];
4639 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4641 [super alertView:alert clickedButtonAtIndex:button];
4645 - (void) _doContinue {
4646 [self dismissModalViewControllerAnimated:YES];
4647 [delegate_ cancelAndClear:NO];
4650 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4651 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4655 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4656 [super webView:view didClearWindowObject:window forFrame:frame];
4658 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
4659 changes_, @"changes",
4663 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
4666 - (id) initWithDatabase:(Database *)database {
4667 if ((self = [super init]) != nil) {
4668 database_ = database;
4670 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
4671 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
4672 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
4673 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
4674 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
4678 pkgCacheFile &cache([database_ cache]);
4679 NSArray *packages([database_ packages]);
4680 pkgDepCache::Policy *policy([database_ policy]);
4682 issues_ = [[NSMutableArray arrayWithCapacity:4] retain];
4684 for (Package *package in packages) {
4685 pkgCache::PkgIterator iterator([package iterator]);
4686 NSString *name([package id]);
4688 if ([package broken]) {
4689 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
4691 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4693 reasons, @"reasons",
4696 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
4700 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
4701 pkgCache::DepIterator start;
4702 pkgCache::DepIterator end;
4703 dep.GlobOr(start, end); // ++dep
4705 if (!cache->IsImportantDep(end))
4707 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
4710 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
4712 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4713 [NSString stringWithUTF8String:start.DepType()], @"relationship",
4714 clauses, @"clauses",
4718 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
4720 pkgCache::PkgIterator target(start.TargetPkg());
4721 if (target->ProvidesList != 0)
4722 reason = @"missing";
4724 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
4726 reason = @"installed";
4727 installed = [NSString stringWithUTF8String:ver.VerStr()];
4728 } else if (!cache[target].CandidateVerIter(cache).end())
4729 reason = @"uninstalled";
4730 else if (target->ProvidesList == 0)
4731 reason = @"uninstallable";
4733 reason = @"virtual";
4736 NSDictionary *version(start.TargetVer() == 0 ? [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
4737 [NSString stringWithUTF8String:start.CompType()], @"operator",
4738 [NSString stringWithUTF8String:start.TargetVer()], @"value",
4741 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4742 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
4743 version, @"version",
4745 installed, @"installed",
4748 // yes, seriously. (wtf?)
4756 pkgDepCache::StateCache &state(cache[iterator]);
4758 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
4760 if (state.NewInstall())
4761 [installs addObject:name];
4762 // XXX: else if (state.Install())
4763 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4764 [reinstalls addObject:name];
4765 // XXX: move before previous if
4766 else if (state.Upgrade())
4767 [upgrades addObject:name];
4768 else if (state.Downgrade())
4769 [downgrades addObject:name];
4770 else if (!state.Delete())
4771 // XXX: _assert(state.Keep());
4773 else if (special_r(name))
4774 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
4775 [NSNull null], @"package",
4776 [NSArray arrayWithObjects:
4777 [NSDictionary dictionaryWithObjectsAndKeys:
4778 @"Conflicts", @"relationship",
4779 [NSArray arrayWithObjects:
4780 [NSDictionary dictionaryWithObjectsAndKeys:
4782 [NSNull null], @"version",
4783 @"installed", @"reason",
4790 if ([package essential])
4792 [removes addObject:name];
4795 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4796 substrate_ |= DepSubstrate(iterator.CurrentVer());
4801 else if (Advanced_) {
4802 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4804 essential_ = [[UIAlertView alloc]
4805 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4806 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4808 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4810 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
4814 [essential_ setContext:@"remove"];
4816 essential_ = [[UIAlertView alloc]
4817 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4818 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4820 cancelButtonTitle:UCLocalize("OKAY")
4821 otherButtonTitles:nil
4824 [essential_ setContext:@"unable"];
4827 changes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
4828 installs, @"installs",
4829 reinstalls, @"reinstalls",
4830 upgrades, @"upgrades",
4831 downgrades, @"downgrades",
4832 removes, @"removes",
4835 sizes_ = [[NSDictionary alloc] initWithObjectsAndKeys:
4836 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
4837 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
4840 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
4842 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
4843 initWithTitle:UCLocalize("CANCEL")
4844 style:UIBarButtonItemStylePlain
4846 action:@selector(cancelButtonClicked)
4852 - (void) applyRightButton {
4853 if ([issues_ count] == 0 && ![self isLoading])
4854 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4855 initWithTitle:UCLocalize("CONFIRM")
4856 style:UIBarButtonItemStyleDone
4858 action:@selector(confirmButtonClicked)
4861 [[self navigationItem] setRightBarButtonItem:nil];
4865 - (void) cancelButtonClicked {
4866 [self dismissModalViewControllerAnimated:YES];
4867 [delegate_ cancelAndClear:YES];
4871 - (void) confirmButtonClicked {
4872 if (essential_ != nil)
4882 /* Progress Data {{{ */
4883 @interface CydiaProgressData : NSObject {
4884 _transient id delegate_;
4893 _H<NSMutableArray> events_;
4894 _H<NSString> title_;
4896 _H<NSString> status_;
4897 _H<NSString> finish_;
4902 @implementation CydiaProgressData
4904 + (NSArray *) _attributeKeys {
4905 return [NSArray arrayWithObjects:
4917 - (NSArray *) attributeKeys {
4918 return [[self class] _attributeKeys];
4921 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4922 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4926 if ((self = [super init]) != nil) {
4927 events_ = [NSMutableArray arrayWithCapacity:32];
4931 - (void) setDelegate:(id)delegate {
4932 delegate_ = delegate;
4935 - (void) setPercent:(float)value {
4939 - (NSNumber *) percent {
4940 return [NSNumber numberWithFloat:percent_];
4943 - (void) setCurrent:(float)value {
4947 - (NSNumber *) current {
4948 return [NSNumber numberWithFloat:current_];
4951 - (void) setTotal:(float)value {
4955 - (NSNumber *) total {
4956 return [NSNumber numberWithFloat:total_];
4959 - (void) setSpeed:(float)value {
4963 - (NSNumber *) speed {
4964 return [NSNumber numberWithFloat:speed_];
4967 - (NSArray *) events {
4971 - (void) removeAllEvents {
4972 [events_ removeAllObjects];
4975 - (void) addEvent:(CydiaProgressEvent *)event {
4976 [events_ addObject:event];
4979 - (void) setTitle:(NSString *)text {
4983 - (NSString *) title {
4987 - (void) setFinish:(NSString *)text {
4991 - (NSString *) finish {
4992 return (id) finish_ ?: [NSNull null];
4995 - (void) setRunning:(bool)running {
4999 - (NSNumber *) running {
5000 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5005 /* Progress Controller {{{ */
5006 @interface ProgressController : CydiaWebViewController <
5009 _transient Database *database_;
5010 _H<CydiaProgressData> progress_;
5014 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5016 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5018 - (void) setTitle:(NSString *)title;
5019 - (void) setCancellable:(bool)cancellable;
5023 @implementation ProgressController
5026 [database_ setProgressDelegate:nil];
5027 [progress_ setDelegate:nil];
5031 - (void) updateCancel {
5032 [[self navigationItem] setLeftBarButtonItem:(cancel_ == 1 ? [[[UIBarButtonItem alloc]
5033 initWithTitle:UCLocalize("CANCEL")
5034 style:UIBarButtonItemStylePlain
5036 action:@selector(cancel)
5037 ] autorelease] : nil)];
5040 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5041 if ((self = [super init]) != nil) {
5042 database_ = database;
5043 delegate_ = delegate;
5045 [database_ setProgressDelegate:self];
5047 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5048 [progress_ setDelegate:self];
5050 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5052 [scroller_ setBackgroundColor:[UIColor blackColor]];
5054 [[self navigationItem] setHidesBackButton:YES];
5056 [self updateCancel];
5060 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5061 [super webView:view didClearWindowObject:window forFrame:frame];
5062 [window setValue:progress_ forKey:@"cydiaProgress"];
5065 - (void) updateProgress {
5066 [self dispatchEvent:@"CydiaProgressUpdate"];
5069 - (void) viewWillAppear:(BOOL)animated {
5070 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5071 [super viewWillAppear:animated];
5075 UpdateExternalStatus(0);
5082 [delegate_ terminateWithSuccess];
5083 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5084 [delegate_ suspendWithAnimation:YES];
5086 [delegate_ suspend];*/
5098 system("/usr/bin/sbreload");
5104 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5105 SBReboot(SBSSpringBoardServerPort());
5107 reboot2(RB_AUTOBOOT);
5114 - (void) setTitle:(NSString *)title {
5115 [progress_ setTitle:title];
5116 [self updateProgress];
5119 - (UIBarButtonItem *) rightButton {
5120 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5121 initWithTitle:UCLocalize("CLOSE")
5122 style:UIBarButtonItemStylePlain
5124 action:@selector(close)
5128 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5129 UpdateExternalStatus(1);
5131 [progress_ setRunning:true];
5132 [self setTitle:title];
5133 // implicit updateProgress
5135 SHA1SumValue notifyconf; {
5137 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5140 MMap mmap(file, MMap::ReadOnly);
5142 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5143 notifyconf = sha1.Result();
5147 SHA1SumValue springlist; {
5149 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5152 MMap mmap(file, MMap::ReadOnly);
5154 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5155 springlist = sha1.Result();
5159 if (invocation != nil) {
5160 [invocation yieldToSelector:@selector(invoke)];
5161 [self setTitle:@"COMPLETE"];
5166 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5169 MMap mmap(file, MMap::ReadOnly);
5171 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5172 if (!(notifyconf == sha1.Result()))
5179 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5182 MMap mmap(file, MMap::ReadOnly);
5184 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5185 if (!(springlist == sha1.Result()))
5191 if (RestartSubstrate_)
5195 RestartSubstrate_ = false;
5198 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5199 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5200 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5201 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5202 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5206 system("su -c /usr/bin/uicache mobile");
5209 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5211 [progress_ setRunning:false];
5212 [self updateProgress];
5214 [self applyRightButton];
5217 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5218 [progress_ addEvent:event];
5219 [self updateProgress];
5222 - (bool) isProgressCancelled {
5223 return cancel_ == 2;
5228 [self updateCancel];
5231 - (void) setCancellable:(bool)cancellable {
5232 unsigned cancel(cancel_);
5236 else if (cancel_ == 0)
5239 if (cancel != cancel_)
5240 [self updateCancel];
5243 - (void) setProgressCancellable:(NSNumber *)cancellable {
5244 [self setCancellable:[cancellable boolValue]];
5247 - (void) setProgressPercent:(NSNumber *)percent {
5248 [progress_ setPercent:[percent floatValue]];
5249 [self updateProgress];
5252 - (void) setProgressStatus:(NSDictionary *)status {
5253 if (status == nil) {
5254 [progress_ setCurrent:0];
5255 [progress_ setTotal:0];
5256 [progress_ setSpeed:0];
5258 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5260 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5261 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5262 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5265 [self updateProgress];
5271 /* Cell Content View {{{ */
5272 @protocol ContentDelegate
5273 - (void) drawContentRect:(CGRect)rect;
5276 @interface ContentView : UIView {
5277 _transient id<ContentDelegate> delegate_;
5282 @implementation ContentView
5284 - (id) initWithFrame:(CGRect)frame {
5285 if ((self = [super initWithFrame:frame]) != nil) {
5286 [self setNeedsDisplayOnBoundsChange:YES];
5290 - (void) setDelegate:(id<ContentDelegate>)delegate {
5291 delegate_ = delegate;
5294 - (void) drawRect:(CGRect)rect {
5295 [super drawRect:rect];
5296 [delegate_ drawContentRect:rect];
5301 /* Cydia TableView Cell {{{ */
5302 @interface CYTableViewCell : UITableViewCell {
5303 ContentView *content_;
5309 @implementation CYTableViewCell
5316 - (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
5317 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
5319 if (view == content_) {
5320 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
5321 highlighted_ = highlighted;
5324 [super _updateHighlightColorsForView:view highlighted:highlighted];
5327 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
5328 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
5329 highlighted_ = selected;
5331 [super setSelected:selected animated:animated];
5332 [content_ setNeedsDisplay];
5338 /* Package Cell {{{ */
5339 @interface PackageCell : CYTableViewCell <
5344 NSString *description_;
5352 - (PackageCell *) init;
5353 - (void) setPackage:(Package *)package;
5355 - (void) drawContentRect:(CGRect)rect;
5359 @implementation PackageCell
5361 - (void) clearPackage {
5372 if (description_ != nil) {
5373 [description_ release];
5377 if (source_ != nil) {
5382 if (badge_ != nil) {
5387 if (placard_ != nil) {
5397 [self clearPackage];
5401 - (PackageCell *) init {
5402 CGRect frame(CGRectMake(0, 0, 320, 74));
5403 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5404 UIView *content([self contentView]);
5405 CGRect bounds([content bounds]);
5407 content_ = [[ContentView alloc] initWithFrame:bounds];
5408 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5409 [content addSubview:content_];
5411 [content_ setDelegate:self];
5412 [content_ setOpaque:YES];
5416 - (NSString *) accessibilityLabel {
5417 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), name_, description_];
5420 - (void) setPackage:(Package *)package {
5421 [self clearPackage];
5424 Source *source = [package source];
5426 icon_ = [[package icon] retain];
5427 name_ = [[package name] retain];
5430 description_ = [package longDescription];
5431 if (description_ == nil)
5432 description_ = [package shortDescription];
5433 if (description_ != nil)
5434 description_ = [description_ retain];
5436 commercial_ = [package isCommercial];
5438 package_ = [package retain];
5440 NSString *label = nil;
5441 bool trusted = false;
5443 if (source != nil) {
5444 label = [source label];
5445 trusted = [source trusted];
5446 } else if ([[package id] isEqualToString:@"firmware"])
5447 label = UCLocalize("APPLE");
5449 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5451 NSString *from(label);
5453 NSString *section = [package simpleSection];
5454 if (section != nil && ![section isEqualToString:label]) {
5455 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5456 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5459 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
5460 source_ = [from retain];
5462 if (NSString *purpose = [package primaryPurpose])
5463 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
5464 badge_ = [badge_ retain];
5469 if (NSString *mode = [package_ mode]) {
5470 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5471 color = RemovingColor_;
5472 //placard = @"removing";
5474 color = InstallingColor_;
5475 //placard = @"installing";
5478 // XXX: the removing/installing placards are not @2x
5481 color = [UIColor whiteColor];
5483 if ([package installed] != nil)
5484 placard = @"installed";
5489 [content_ setBackgroundColor:color];
5492 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]]) != nil)
5493 placard_ = [placard_ retain];
5495 [self setNeedsDisplay];
5496 [content_ setNeedsDisplay];
5499 - (void) drawContentRect:(CGRect)rect {
5500 bool highlighted(highlighted_);
5501 float width([self bounds].size.width);
5504 CGContextRef context(UIGraphicsGetCurrentContext());
5505 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
5506 CGContextFillRect(context, rect);
5511 rect.size = [icon_ size];
5513 rect.size.width /= 2;
5514 rect.size.height /= 2;
5516 rect.origin.x = 25 - rect.size.width / 2;
5517 rect.origin.y = 25 - rect.size.height / 2;
5519 [icon_ drawInRect:rect];
5522 if (badge_ != nil) {
5524 rect.size = [badge_ size];
5526 rect.size.width /= 2;
5527 rect.size.height /= 2;
5529 rect.origin.x = 36 - rect.size.width / 2;
5530 rect.origin.y = 36 - rect.size.height / 2;
5532 [badge_ drawInRect:rect];
5539 UISetColor(commercial_ ? Purple_ : Black_);
5540 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5541 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5544 UISetColor(commercial_ ? Purplish_ : Gray_);
5545 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5547 if (placard_ != nil)
5548 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5553 /* Section Cell {{{ */
5554 @interface SectionCell : CYTableViewCell <
5566 - (void) setSection:(Section *)section editing:(BOOL)editing;
5570 @implementation SectionCell
5572 - (void) clearSection {
5573 if (basic_ != nil) {
5578 if (section_ != nil) {
5588 if (count_ != nil) {
5595 [self clearSection];
5601 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5602 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5603 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
5604 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
5605 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5607 UIView *content([self contentView]);
5608 CGRect bounds([content bounds]);
5610 content_ = [[ContentView alloc] initWithFrame:bounds];
5611 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5612 [content addSubview:content_];
5613 [content_ setBackgroundColor:[UIColor whiteColor]];
5615 [content_ setDelegate:self];
5619 - (void) onSwitch:(id)sender {
5620 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5621 if (metadata == nil) {
5622 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5623 [Sections_ setObject:metadata forKey:basic_];
5626 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5630 - (void) setSection:(Section *)section editing:(BOOL)editing {
5631 if (editing != editing_) {
5633 [switch_ removeFromSuperview];
5635 [self addSubview:switch_];
5639 [self clearSection];
5641 if (section == nil) {
5642 name_ = [UCLocalize("ALL_PACKAGES") retain];
5645 basic_ = [section name];
5647 basic_ = [basic_ retain];
5649 section_ = [section localized];
5650 if (section_ != nil)
5651 section_ = [section_ retain];
5653 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
5654 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
5657 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5660 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5661 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5663 [content_ setNeedsDisplay];
5666 - (void) setFrame:(CGRect)frame {
5667 [super setFrame:frame];
5669 CGRect rect([switch_ frame]);
5670 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5673 - (NSString *) accessibilityLabel {
5677 - (void) drawContentRect:(CGRect)rect {
5678 bool highlighted(highlighted_ && !editing_);
5680 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5685 float width(rect.size.width);
5691 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5693 CGSize size = [count_ sizeWithFont:Font14_];
5697 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5703 /* File Table {{{ */
5704 @interface FileTable : CyteViewController <
5705 UITableViewDataSource,
5708 _transient Database *database_;
5711 NSMutableArray *files_;
5715 - (id) initWithDatabase:(Database *)database;
5716 - (void) setPackage:(Package *)package;
5720 @implementation FileTable
5723 [self releaseSubviews];
5732 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5733 return files_ == nil ? 0 : [files_ count];
5736 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5740 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5741 static NSString *reuseIdentifier = @"Cell";
5743 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5745 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5746 [cell setFont:[UIFont systemFontOfSize:16]];
5748 [cell setText:[files_ objectAtIndex:indexPath.row]];
5749 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5754 - (NSURL *) navigationURL {
5755 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
5759 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
5761 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5762 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5763 [list_ setRowHeight:24.0f];
5764 [list_ setDataSource:self];
5765 [list_ setDelegate:self];
5766 [[self view] addSubview:list_];
5769 - (void) viewDidLoad {
5770 [super viewDidLoad];
5772 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5775 - (void) releaseSubviews {
5780 - (id) initWithDatabase:(Database *)database {
5781 if ((self = [super init]) != nil) {
5782 database_ = database;
5784 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5788 - (void) setPackage:(Package *)package {
5789 if (package_ != nil) {
5790 [package_ autorelease];
5799 [files_ removeAllObjects];
5801 if (package != nil) {
5802 package_ = [package retain];
5803 name_ = [[package id] retain];
5805 if (NSArray *files = [package files])
5806 [files_ addObjectsFromArray:files];
5808 if ([files_ count] != 0) {
5809 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5810 [files_ removeObjectAtIndex:0];
5811 [files_ sortUsingSelector:@selector(compareByPath:)];
5813 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5814 [stack addObject:@"/"];
5816 for (int i(0), e([files_ count]); i != e; ++i) {
5817 NSString *file = [files_ objectAtIndex:i];
5818 while (![file hasPrefix:[stack lastObject]])
5819 [stack removeLastObject];
5820 NSString *directory = [stack lastObject];
5821 [stack addObject:[file stringByAppendingString:@"/"]];
5822 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5823 ([stack count] - 2) * 3, "",
5824 [file substringFromIndex:[directory length]]
5833 - (void) reloadData {
5836 [self setPackage:[database_ packageWithName:name_]];
5841 /* Package Controller {{{ */
5842 @interface CYPackageController : CydiaWebViewController <
5843 UIActionSheetDelegate
5845 _transient Database *database_;
5846 _H<Package> package_;
5849 _H<NSMutableArray> buttons_;
5850 _H<UIBarButtonItem> button_;
5853 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name;
5857 @implementation CYPackageController
5859 - (NSURL *) navigationURL {
5860 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
5863 /* XXX: this is not safe at all... localization of /fail/ */
5864 - (void) _clickButtonWithName:(NSString *)name {
5865 if ([name isEqualToString:UCLocalize("CLEAR")])
5866 [delegate_ clearPackage:package_];
5867 else if ([name isEqualToString:UCLocalize("INSTALL")])
5868 [delegate_ installPackage:package_];
5869 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5870 [delegate_ installPackage:package_];
5871 else if ([name isEqualToString:UCLocalize("REMOVE")])
5872 [delegate_ removePackage:package_];
5873 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5874 [delegate_ installPackage:package_];
5875 else _assert(false);
5878 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5879 NSString *context([sheet context]);
5881 if ([context isEqualToString:@"modify"]) {
5882 if (button != [sheet cancelButtonIndex]) {
5883 NSString *buttonName = [buttons_ objectAtIndex:button];
5884 [self _clickButtonWithName:buttonName];
5887 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5891 - (bool) _allowJavaScriptPanel {
5896 - (void) _customButtonClicked {
5897 int count([buttons_ count]);
5902 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5904 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5905 [buttons addObjectsFromArray:buttons_];
5907 UIActionSheet *sheet = [[[UIActionSheet alloc]
5910 cancelButtonTitle:nil
5911 destructiveButtonTitle:nil
5912 otherButtonTitles:nil
5915 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5917 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5918 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5920 [sheet setContext:@"modify"];
5922 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5926 // We don't want to allow non-commercial packages to do custom things to the install button,
5927 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5928 - (void) customButtonClicked {
5930 [super customButtonClicked];
5932 [self _customButtonClicked];
5935 - (void) reloadButtonClicked {
5936 // Don't reload a commerical package by tapping the loading button,
5937 // but if it's not an Install button, we should forward it on.
5938 if (![package_ uninstalled])
5939 [self _customButtonClicked];
5942 - (void) applyLoadingTitle {
5943 // Don't show "Loading" as the title. Ever.
5946 - (UIBarButtonItem *) rightButton {
5951 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name {
5952 if ((self = [super init]) != nil) {
5953 database_ = database;
5954 buttons_ = [NSMutableArray arrayWithCapacity:4];
5955 name_ = [NSString stringWithString:name];
5956 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]]];
5960 - (void) reloadData {
5963 package_ = [database_ packageWithName:name_];
5965 [buttons_ removeAllObjects];
5967 if (package_ != nil) {
5968 [(Package *) package_ parse];
5970 commercial_ = [package_ isCommercial];
5972 if ([package_ mode] != nil)
5973 [buttons_ addObject:UCLocalize("CLEAR")];
5974 if ([package_ source] == nil);
5975 else if ([package_ upgradableAndEssential:NO])
5976 [buttons_ addObject:UCLocalize("UPGRADE")];
5977 else if ([package_ uninstalled])
5978 [buttons_ addObject:UCLocalize("INSTALL")];
5980 [buttons_ addObject:UCLocalize("REINSTALL")];
5981 if (![package_ uninstalled])
5982 [buttons_ addObject:UCLocalize("REMOVE")];
5986 switch ([buttons_ count]) {
5987 case 0: title = nil; break;
5988 case 1: title = [buttons_ objectAtIndex:0]; break;
5989 default: title = UCLocalize("MODIFY"); break;
5992 button_ = [[[UIBarButtonItem alloc]
5994 style:UIBarButtonItemStylePlain
5996 action:@selector(customButtonClicked)
6000 - (bool) isLoading {
6001 return commercial_ ? [super isLoading] : false;
6007 /* Package List Controller {{{ */
6008 @interface PackageListController : CyteViewController <
6009 UITableViewDataSource,
6012 _transient Database *database_;
6014 NSMutableArray *packages_;
6015 NSMutableArray *sections_;
6017 NSMutableArray *index_;
6018 NSMutableDictionary *indices_;
6022 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6023 - (void) setDelegate:(id)delegate;
6024 - (void) resetCursor;
6028 @implementation PackageListController
6031 [packages_ release];
6032 [sections_ release];
6041 - (void) deselectWithAnimation:(BOOL)animated {
6042 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6045 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6046 CGRect base = [[self view] bounds];
6047 base.size.height -= bounds.size.height;
6048 base.origin = [list_ frame].origin;
6050 [UIView beginAnimations:nil context:NULL];
6051 [UIView setAnimationBeginsFromCurrentState:YES];
6052 [UIView setAnimationCurve:curve];
6053 [UIView setAnimationDuration:duration];
6054 [list_ setFrame:base];
6055 [UIView commitAnimations];
6058 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6059 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6062 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6063 [self resizeForKeyboardBounds:bounds duration:0];
6066 - (void) keyboardWillShow:(NSNotification *)notification {
6069 NSTimeInterval duration;
6070 UIViewAnimationCurve curve;
6071 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6072 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6073 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
6074 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
6076 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);
6077 UIViewController *base = self;
6078 while ([base parentViewController] != nil)
6079 base = [base parentViewController];
6080 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6081 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6083 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6086 - (void) keyboardWillHide:(NSNotification *)notification {
6087 NSTimeInterval duration;
6088 UIViewAnimationCurve curve;
6089 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:&curve];
6090 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:&duration];
6092 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6095 - (void) viewWillAppear:(BOOL)animated {
6096 [super viewWillAppear:animated];
6098 [self resizeForKeyboardBounds:CGRectZero];
6099 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6100 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6103 - (void) viewWillDisappear:(BOOL)animated {
6104 [super viewWillDisappear:animated];
6106 [self resizeForKeyboardBounds:CGRectZero];
6107 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6108 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6111 - (void) viewDidAppear:(BOOL)animated {
6112 [super viewDidAppear:animated];
6113 [self deselectWithAnimation:animated];
6116 - (void) didSelectPackage:(Package *)package {
6117 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
6118 [view setDelegate:delegate_];
6119 [[self navigationController] pushViewController:view animated:YES];
6122 #if TryIndexedCollation
6123 + (BOOL) hasIndexedCollation {
6124 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
6128 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6129 NSInteger count([sections_ count]);
6130 return count == 0 ? 1 : count;
6133 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6134 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6136 return [[sections_ objectAtIndex:section] name];
6139 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6140 if ([sections_ count] == 0)
6142 return [[sections_ objectAtIndex:section] count];
6145 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6146 @synchronized (database_) {
6147 if ([database_ era] != era_)
6150 Section *section([sections_ objectAtIndex:[path section]]);
6151 NSInteger row([path row]);
6152 Package *package([packages_ objectAtIndex:([section row] + row)]);
6153 return [[package retain] autorelease];
6156 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6157 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6159 cell = [[[PackageCell alloc] init] autorelease];
6160 [cell setPackage:[self packageAtIndexPath:path]];
6164 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6165 Package *package([self packageAtIndexPath:path]);
6166 package = [database_ packageWithName:[package id]];
6167 [self didSelectPackage:package];
6170 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6171 // XXX: is 20 the most optimal number here?
6172 return [packages_ count] > 20 ? index_ : nil;
6175 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6176 #if TryIndexedCollation
6177 if ([[self class] hasIndexedCollation]) {
6178 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
6185 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6186 if ((self = [super init]) != nil) {
6187 database_ = database;
6188 title_ = [title copy];
6189 [[self navigationItem] setTitle:title_];
6191 #if TryIndexedCollation
6192 if ([[self class] hasIndexedCollation])
6193 index_ = [[[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles] retain]
6196 index_ = [[NSMutableArray alloc] initWithCapacity:32];
6198 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
6200 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
6201 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6203 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6204 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6205 [list_ setRowHeight:73];
6206 [[self view] addSubview:list_];
6208 [list_ setDataSource:self];
6209 [list_ setDelegate:self];
6213 - (void) setDelegate:(id)delegate {
6214 delegate_ = delegate;
6217 - (bool) hasPackage:(Package *)package {
6221 - (void) reloadData {
6224 era_ = [database_ era];
6225 NSArray *packages = [database_ packages];
6227 [packages_ removeAllObjects];
6228 [sections_ removeAllObjects];
6230 _profile(PackageTable$reloadData$Filter)
6231 for (Package *package in packages)
6232 if ([self hasPackage:package])
6233 [packages_ addObject:package];
6236 [indices_ removeAllObjects];
6238 Section *section = nil;
6240 #if TryIndexedCollation
6241 if ([[self class] hasIndexedCollation]) {
6242 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
6243 NSArray *titles = [collation sectionIndexTitles];
6246 _profile(PackageTable$reloadData$Section)
6247 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6251 _profile(PackageTable$reloadData$Section$Package)
6252 package = [packages_ objectAtIndex:offset];
6253 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
6256 while (secidx < index) {
6259 _profile(PackageTable$reloadData$Section$Allocate)
6260 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
6263 _profile(PackageTable$reloadData$Section$Add)
6264 [sections_ addObject:section];
6268 [section addToCount];
6274 [index_ removeAllObjects];
6276 _profile(PackageTable$reloadData$Section)
6277 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
6281 _profile(PackageTable$reloadData$Section$Package)
6282 package = [packages_ objectAtIndex:offset];
6283 index = [package index];
6286 if (section == nil || [section index] != index) {
6287 _profile(PackageTable$reloadData$Section$Allocate)
6288 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
6291 [index_ addObject:[section name]];
6292 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
6294 _profile(PackageTable$reloadData$Section$Add)
6295 [sections_ addObject:section];
6299 [section addToCount];
6304 _profile(PackageTable$reloadData$List)
6309 - (void) resetCursor {
6310 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
6315 /* Filtered Package List Controller {{{ */
6316 @interface FilteredPackageListController : PackageListController {
6322 - (void) setObject:(id)object;
6323 - (void) setObject:(id)object forFilter:(SEL)filter;
6325 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
6329 @implementation FilteredPackageListController
6337 - (void) setFilter:(SEL)filter {
6340 /* XXX: this is an unsafe optimization of doomy hell */
6341 Method method(class_getInstanceMethod([Package class], filter));
6342 _assert(method != NULL);
6343 imp_ = method_getImplementation(method);
6344 _assert(imp_ != NULL);
6347 - (void) setObject:(id)object {
6353 object_ = [object retain];
6356 - (void) setObject:(id)object forFilter:(SEL)filter {
6357 [self setFilter:filter];
6358 [self setObject:object];
6361 - (bool) hasPackage:(Package *)package {
6362 _profile(FilteredPackageTable$hasPackage)
6363 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
6367 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
6368 if ((self = [super initWithDatabase:database title:title]) != nil) {
6369 [self setFilter:filter];
6370 [self setObject:object];
6377 /* Home Controller {{{ */
6378 @interface HomeController : CydiaWebViewController {
6383 @implementation HomeController
6386 if ((self = [super init]) != nil) {
6387 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6392 - (NSURL *) navigationURL {
6393 return [NSURL URLWithString:@"cydia://home"];
6396 - (void) aboutButtonClicked {
6397 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6399 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6400 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6401 [alert setCancelButtonIndex:0];
6404 @"Copyright \u00a9 2008-2011\n"
6407 "Jay Freeman (saurik)\n"
6408 "saurik@saurik.com\n"
6409 "http://www.saurik.com/"
6415 - (void) viewDidLoad {
6416 [super viewDidLoad];
6418 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6419 initWithTitle:UCLocalize("ABOUT")
6420 style:UIBarButtonItemStylePlain
6422 action:@selector(aboutButtonClicked)
6426 - (void) unloadData {
6433 /* Manage Controller {{{ */
6434 @interface ManageController : CydiaWebViewController {
6437 - (void) queueStatusDidChange;
6441 @implementation ManageController
6444 if ((self = [super init]) != nil) {
6445 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/manage/", UI_]]];
6449 - (NSURL *) navigationURL {
6450 return [NSURL URLWithString:@"cydia://manage"];
6453 - (void) viewDidLoad {
6454 [super viewDidLoad];
6456 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6457 initWithTitle:UCLocalize("SETTINGS")
6458 style:UIBarButtonItemStylePlain
6460 action:@selector(settingsButtonClicked)
6464 - (void) settingsButtonClicked {
6465 [delegate_ showSettings];
6468 - (void) queueButtonClicked {
6472 - (UIBarButtonItem *) customButton {
6473 return Queuing_ ? [[[UIBarButtonItem alloc]
6474 initWithTitle:UCLocalize("QUEUE")
6475 style:UIBarButtonItemStyleDone
6477 action:@selector(queueButtonClicked)
6478 ] autorelease] : [super customButton];
6481 - (void) queueStatusDidChange {
6482 [self applyRightButton];
6485 - (bool) isLoading {
6486 return !Queuing_ && [super isLoading];
6492 /* Refresh Bar {{{ */
6493 @interface RefreshBar : UINavigationBar {
6494 UIProgressIndicator *indicator_;
6495 UITextLabel *prompt_;
6496 UIProgressBar *progress_;
6497 UINavigationButton *cancel_;
6502 @implementation RefreshBar
6505 [indicator_ release];
6507 [progress_ release];
6512 - (void) positionViews {
6513 CGRect frame = [cancel_ frame];
6514 frame.size = [cancel_ sizeThatFits:frame.size];
6515 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6516 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6517 [cancel_ setFrame:frame];
6519 CGSize prgsize = {75, 100};
6521 [self frame].size.width - prgsize.width - 10,
6522 ([self frame].size.height - prgsize.height) / 2
6524 [progress_ setFrame:prgrect];
6526 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6527 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6528 CGRect indrect = {{indoffset, indoffset}, indsize};
6529 [indicator_ setFrame:indrect];
6531 CGSize prmsize = {215, indsize.height + 4};
6533 indoffset * 2 + indsize.width,
6534 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6536 [prompt_ setFrame:prmrect];
6539 - (void) setFrame:(CGRect)frame {
6540 [super setFrame:frame];
6541 [self positionViews];
6544 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6545 if ((self = [super initWithFrame:frame]) != nil) {
6546 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6548 [self setBarStyle:UIBarStyleBlack];
6550 UIBarStyle barstyle([self _barStyle:NO]);
6551 bool ugly(barstyle == UIBarStyleDefault);
6553 UIProgressIndicatorStyle style = ugly ?
6554 UIProgressIndicatorStyleMediumBrown :
6555 UIProgressIndicatorStyleMediumWhite;
6557 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6558 [indicator_ setStyle:style];
6559 [indicator_ startAnimation];
6560 [self addSubview:indicator_];
6562 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6563 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6564 [prompt_ setBackgroundColor:[UIColor clearColor]];
6565 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6566 [self addSubview:prompt_];
6568 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6569 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6570 [progress_ setStyle:0];
6571 [self addSubview:progress_];
6573 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6574 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6575 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6576 [cancel_ setBarStyle:barstyle];
6578 [self positionViews];
6582 - (void) setCancellable:(bool)cancellable {
6584 [self addSubview:cancel_];
6586 [cancel_ removeFromSuperview];
6590 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6591 [progress_ setProgress:0];
6595 [self setCancellable:NO];
6598 - (void) setPrompt:(NSString *)prompt {
6599 [prompt_ setText:prompt];
6602 - (void) setProgress:(float)progress {
6603 [progress_ setProgress:progress];
6609 /* Cydia Navigation Controller Interface {{{ */
6610 @interface UINavigationController (Cydia)
6612 - (NSArray *) navigationURLCollection;
6613 - (void) unloadData;
6618 /* Cydia Tab Bar Controller {{{ */
6619 @interface CYTabBarController : UITabBarController <
6620 UITabBarControllerDelegate,
6623 _transient Database *database_;
6624 RefreshBar *refreshbar_;
6628 // XXX: ok, "updatedelegate_"?...
6629 _transient NSObject<CydiaDelegate> *updatedelegate_;
6632 UIViewController *remembered_;
6633 _transient UIViewController *transient_;
6636 - (NSArray *) navigationURLCollection;
6637 - (void) dropBar:(BOOL)animated;
6638 - (void) beginUpdate;
6639 - (void) raiseBar:(BOOL)animated;
6641 - (void) unloadData;
6645 @implementation CYTabBarController
6647 - (void) setUnselectedViewController:(UIViewController *)transient {
6648 NSMutableArray *controllers = [[self viewControllers] mutableCopy];
6649 if (transient != nil) {
6650 if (transient_ == nil)
6651 remembered_ = [[controllers objectAtIndex:0] retain];
6652 transient_ = transient;
6653 [transient_ setTabBarItem:[remembered_ tabBarItem]];
6654 [controllers replaceObjectAtIndex:0 withObject:transient_];
6655 [self setSelectedIndex:0];
6656 [self setViewControllers:controllers];
6657 [self concealTabBarSelection];
6658 } else if (remembered_ != nil) {
6659 [remembered_ setTabBarItem:[transient_ tabBarItem]];
6660 transient_ = transient;
6661 [controllers replaceObjectAtIndex:0 withObject:remembered_];
6662 [remembered_ release];
6664 [self setViewControllers:controllers];
6665 [self revealTabBarSelection];
6669 - (UIViewController *) unselectedViewController {
6673 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
6674 if ([self unselectedViewController])
6675 [self setUnselectedViewController:nil];
6678 - (NSArray *) navigationURLCollection {
6679 NSMutableArray *items([NSMutableArray array]);
6681 // XXX: Should this deal with transient view controllers?
6682 for (id navigation in [self viewControllers]) {
6683 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6685 [items addObject:stack];
6691 - (void) unloadData {
6692 UIViewController *selected([self selectedViewController]);
6693 for (UINavigationController *controller in [self viewControllers])
6694 [controller unloadData];
6696 [selected reloadData];
6698 if (UIViewController *unselected = [self unselectedViewController])
6699 [unselected reloadData];
6705 [refreshbar_ release];
6706 [[NSNotificationCenter defaultCenter] removeObserver:self];
6711 - (id) initWithDatabase:(Database *)database {
6712 if ((self = [super init]) != nil) {
6713 database_ = database;
6714 [self setDelegate:self];
6716 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6717 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6719 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
6723 - (void) setUpdate:(NSDate *)date {
6727 - (void) beginUpdate {
6728 [refreshbar_ start];
6731 [updatedelegate_ retainNetworkActivityIndicator];
6735 detachNewThreadSelector:@selector(performUpdate)
6741 - (void) performUpdate { _pooled
6743 status.setDelegate(self);
6744 [database_ updateWithStatus:status];
6747 performSelectorOnMainThread:@selector(completeUpdate)
6753 - (void) stopUpdateWithSelector:(SEL)selector {
6755 [updatedelegate_ releaseNetworkActivityIndicator];
6757 [self raiseBar:YES];
6760 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6763 - (void) completeUpdate {
6766 [self stopUpdateWithSelector:@selector(reloadData)];
6769 - (void) cancelUpdate {
6770 [self stopUpdateWithSelector:@selector(updateData)];
6773 - (void) cancelPressed {
6774 [self cancelUpdate];
6781 - (void) addProgressEvent:(CydiaProgressEvent *)event {
6782 [refreshbar_ setPrompt:[event compoundMessage]];
6785 - (bool) isProgressCancelled {
6789 - (void) setProgressCancellable:(NSNumber *)cancellable {
6790 [refreshbar_ setCancellable:(updating_ && [cancellable boolValue])];
6793 - (void) setProgressPercent:(NSNumber *)percent {
6794 [refreshbar_ setProgress:[percent floatValue]];
6797 - (void) setProgressStatus:(NSDictionary *)status {
6799 [self setProgressPercent:[status objectForKey:@"Percent"]];
6802 - (void) setUpdateDelegate:(id)delegate {
6803 updatedelegate_ = delegate;
6806 - (CGFloat) statusBarHeight {
6807 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
6808 return [[UIApplication sharedApplication] statusBarFrame].size.height;
6810 return [[UIApplication sharedApplication] statusBarFrame].size.width;
6814 - (UIView *) transitionView {
6815 if ([self respondsToSelector:@selector(_transitionView)])
6816 return [self _transitionView];
6818 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6821 - (void) dropBar:(BOOL)animated {
6826 UIView *transition([self transitionView]);
6827 [[self view] addSubview:refreshbar_];
6829 CGRect barframe([refreshbar_ frame]);
6831 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6832 barframe.origin.y = [self statusBarHeight];
6834 barframe.origin.y = 0;
6836 [refreshbar_ setFrame:barframe];
6839 [UIView beginAnimations:nil context:NULL];
6841 CGRect viewframe = [transition frame];
6842 viewframe.origin.y += barframe.size.height;
6843 viewframe.size.height -= barframe.size.height;
6844 [transition setFrame:viewframe];
6847 [UIView commitAnimations];
6849 // Ensure bar has the proper width for our view, it might have changed
6850 barframe.size.width = viewframe.size.width;
6851 [refreshbar_ setFrame:barframe];
6853 // XXX: fix Apple's layout bug
6854 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6857 - (void) raiseBar:(BOOL)animated {
6862 UIView *transition([self transitionView]);
6863 [refreshbar_ removeFromSuperview];
6865 CGRect barframe([refreshbar_ frame]);
6868 [UIView beginAnimations:nil context:NULL];
6870 CGRect viewframe = [transition frame];
6871 viewframe.origin.y -= barframe.size.height;
6872 viewframe.size.height += barframe.size.height;
6873 [transition setFrame:viewframe];
6876 [UIView commitAnimations];
6878 // XXX: fix Apple's layout bug
6879 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6883 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
6884 // XXX: fix Apple's layout bug
6885 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6889 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6890 bool dropped(dropped_);
6895 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6900 // XXX: fix Apple's layout bug
6901 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6904 - (void) statusBarFrameChanged:(NSNotification *)notification {
6914 /* Cydia Navigation Controller Implementation {{{ */
6915 @implementation UINavigationController (Cydia)
6917 - (NSArray *) navigationURLCollection {
6918 NSMutableArray *stack([NSMutableArray array]);
6920 for (CyteViewController *controller in [self viewControllers]) {
6921 NSString *url = [[controller navigationURL] absoluteString];
6923 [stack addObject:url];
6929 - (void) reloadData {
6932 if (UIViewController *visible = [self visibleViewController])
6933 [visible reloadData];
6936 - (void) unloadData {
6937 for (CyteViewController *page in [self viewControllers])
6946 /* Cydia:// Protocol {{{ */
6947 @interface CydiaURLProtocol : NSURLProtocol {
6952 @implementation CydiaURLProtocol
6954 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6955 NSURL *url([request URL]);
6959 NSString *scheme([[url scheme] lowercaseString]);
6960 if (scheme != nil && [scheme isEqualToString:@"cydia"])
6962 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
6968 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6972 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6973 id<NSURLProtocolClient> client([self client]);
6975 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6977 NSData *data(UIImagePNGRepresentation(icon));
6979 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6980 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6981 [client URLProtocol:self didLoadData:data];
6982 [client URLProtocolDidFinishLoading:self];
6986 - (void) startLoading {
6987 id<NSURLProtocolClient> client([self client]);
6988 NSURLRequest *request([self request]);
6990 NSURL *url([request URL]);
6991 NSString *href([url absoluteString]);
6992 NSString *scheme([[url scheme] lowercaseString]);
6996 if ([scheme isEqualToString:@"cydia"])
6997 path = [href substringFromIndex:8];
6998 else if ([scheme isEqualToString:@"about"])
6999 path = [href substringFromIndex:12];
7000 else _assert(false);
7002 NSRange slash([path rangeOfString:@"/"]);
7005 if (slash.location == NSNotFound) {
7009 command = [path substringToIndex:slash.location];
7010 path = [path substringFromIndex:(slash.location + 1)];
7013 Database *database([Database sharedInstance]);
7015 if ([command isEqualToString:@"package-icon"]) {
7018 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7019 Package *package([database packageWithName:path]);
7022 UIImage *icon([package icon]);
7023 [self _returnPNGWithImage:icon forRequest:request];
7024 } else if ([command isEqualToString:@"source-icon"]) {
7027 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7028 NSString *source(Simplify(path));
7029 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
7031 icon = [UIImage applicationImageNamed:@"unknown.png"];
7032 [self _returnPNGWithImage:icon forRequest:request];
7033 } else if ([command isEqualToString:@"uikit-image"]) {
7036 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7037 UIImage *icon(_UIImageWithName(path));
7038 [self _returnPNGWithImage:icon forRequest:request];
7039 } else if ([command isEqualToString:@"section-icon"]) {
7042 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7043 NSString *section(Simplify(path));
7044 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
7046 icon = [UIImage applicationImageNamed:@"unknown.png"];
7047 [self _returnPNGWithImage:icon forRequest:request];
7049 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7053 - (void) stopLoading {
7059 /* Section Controller {{{ */
7060 @interface SectionController : FilteredPackageListController {
7061 _H<NSString> section_;
7064 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
7068 @implementation SectionController
7070 - (NSURL *) navigationURL {
7071 NSString *name = section_;
7075 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@", name]];
7078 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
7081 title = UCLocalize("ALL_PACKAGES");
7082 else if (![name isEqual:@""])
7083 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
7085 title = UCLocalize("NO_SECTION");
7087 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
7094 /* Sections Controller {{{ */
7095 @interface SectionsController : CyteViewController <
7096 UITableViewDataSource,
7099 _transient Database *database_;
7100 NSMutableArray *sections_;
7101 NSMutableArray *filtered_;
7105 - (id) initWithDatabase:(Database *)database;
7106 - (void) editButtonClicked;
7110 @implementation SectionsController
7113 [self releaseSubviews];
7114 [sections_ release];
7115 [filtered_ release];
7120 - (NSURL *) navigationURL {
7121 return [NSURL URLWithString:@"cydia://sections"];
7124 - (void) updateNavigationItem {
7125 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7126 if ([sections_ count] == 0) {
7127 [[self navigationItem] setRightBarButtonItem:nil];
7129 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7130 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7132 action:@selector(editButtonClicked)
7133 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7137 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7138 [super setEditing:editing animated:animated];
7143 [delegate_ updateData];
7145 [self updateNavigationItem];
7148 - (void) viewDidAppear:(BOOL)animated {
7149 [super viewDidAppear:animated];
7150 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7153 - (void) viewWillDisappear:(BOOL)animated {
7154 [super viewWillDisappear:animated];
7155 if ([self isEditing]) [self setEditing:NO];
7158 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7159 Section *section = nil;
7160 int index = [indexPath row];
7161 if (![self isEditing]) {
7164 section = [filtered_ objectAtIndex:index];
7166 section = [sections_ objectAtIndex:index];
7171 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7172 if ([self isEditing])
7173 return [sections_ count];
7175 return [filtered_ count] + 1;
7178 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7182 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7183 static NSString *reuseIdentifier = @"SectionCell";
7185 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7187 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7189 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7194 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7195 if ([self isEditing])
7198 Section *section = [self sectionAtIndexPath:indexPath];
7200 SectionController *controller = [[[SectionController alloc]
7201 initWithDatabase:database_
7202 section:[section name]
7204 [controller setDelegate:delegate_];
7206 [[self navigationController] pushViewController:controller animated:YES];
7210 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7212 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
7213 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7214 [list_ setRowHeight:45.0f];
7215 [list_ setDataSource:self];
7216 [list_ setDelegate:self];
7217 [[self view] addSubview:list_];
7220 - (void) viewDidLoad {
7221 [super viewDidLoad];
7223 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7226 - (void) releaseSubviews {
7231 - (id) initWithDatabase:(Database *)database {
7232 if ((self = [super init]) != nil) {
7233 database_ = database;
7235 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7236 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
7240 - (void) reloadData {
7243 NSArray *packages = [database_ packages];
7245 [sections_ removeAllObjects];
7246 [filtered_ removeAllObjects];
7248 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7251 for (Package *package in packages) {
7252 NSString *name([package section]);
7253 NSString *key(name == nil ? @"" : name);
7257 _profile(SectionsView$reloadData$Section)
7258 section = [sections objectForKey:key];
7259 if (section == nil) {
7260 _profile(SectionsView$reloadData$Section$Allocate)
7261 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7262 [sections setObject:section forKey:key];
7267 [section addToCount];
7269 _profile(SectionsView$reloadData$Filter)
7270 if (![package valid] || ![package visible])
7278 [sections_ addObjectsFromArray:[sections allValues]];
7280 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7282 for (Section *section in sections_) {
7283 size_t count([section row]);
7287 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7288 [section setCount:count];
7289 [filtered_ addObject:section];
7292 [self updateNavigationItem];
7297 - (void) editButtonClicked {
7298 [self setEditing:![self isEditing] animated:YES];
7304 /* Changes Controller {{{ */
7305 @interface ChangesController : CyteViewController <
7306 UITableViewDataSource,
7309 _transient Database *database_;
7311 CFMutableArrayRef packages_;
7312 NSMutableArray *sections_;
7317 - (id) initWithDatabase:(Database *)database;
7321 @implementation ChangesController
7324 [self releaseSubviews];
7325 CFRelease(packages_);
7326 [sections_ release];
7331 - (NSURL *) navigationURL {
7332 return [NSURL URLWithString:@"cydia://changes"];
7335 - (void) viewDidAppear:(BOOL)animated {
7336 [super viewDidAppear:animated];
7337 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7340 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
7341 NSInteger count([sections_ count]);
7342 return count == 0 ? 1 : count;
7345 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
7346 if ([sections_ count] == 0)
7348 return [[sections_ objectAtIndex:section] name];
7351 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
7352 if ([sections_ count] == 0)
7354 return [[sections_ objectAtIndex:section] count];
7357 - (Package *) packageAtIndex:(NSUInteger)index {
7358 return (Package *) CFArrayGetValueAtIndex(packages_, index);
7361 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7362 @synchronized (database_) {
7363 if ([database_ era] != era_)
7366 NSUInteger sectionIndex([path section]);
7367 if (sectionIndex >= [sections_ count])
7369 Section *section([sections_ objectAtIndex:sectionIndex]);
7370 NSInteger row([path row]);
7371 return [[[self packageAtIndex:([section row] + row)] retain] autorelease];
7374 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
7375 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
7377 cell = [[[PackageCell alloc] init] autorelease];
7378 [cell setPackage:[self packageAtIndexPath:path]];
7382 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
7383 Package *package([self packageAtIndexPath:path]);
7384 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id]] autorelease]);
7385 [view setDelegate:delegate_];
7386 [[self navigationController] pushViewController:view animated:YES];
7390 - (void) refreshButtonClicked {
7391 [delegate_ beginUpdate];
7392 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
7395 - (void) upgradeButtonClicked {
7396 [delegate_ distUpgrade];
7400 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7402 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7403 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7404 [list_ setRowHeight:73];
7405 [list_ setDataSource:self];
7406 [list_ setDelegate:self];
7407 [[self view] addSubview:list_];
7410 - (void) viewDidLoad {
7411 [super viewDidLoad];
7413 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
7416 - (void) releaseSubviews {
7421 - (id) initWithDatabase:(Database *)database {
7422 if ((self = [super init]) != nil) {
7423 database_ = database;
7425 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
7426 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
7430 // this mostly works because reloadData (below) is @synchronized (database_)
7431 // XXX: that said, I've been running into problems with NSRangeExceptions :(
7432 - (void) _reloadPackages:(NSArray *)packages {
7433 CFRelease(packages_);
7434 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, [packages count], NULL);
7437 _profile(ChangesController$_reloadPackages$Filter)
7438 for (Package *package in packages)
7439 if ([package upgradableAndEssential:YES] || [package visible])
7440 CFArrayAppendValue(packages_, package);
7443 _profile(ChangesController$_reloadPackages$radixSort)
7444 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
7449 - (void) _reloadData {
7450 @synchronized (database_) {
7451 era_ = [database_ era];
7452 NSArray *packages = [database_ packages];
7454 [sections_ removeAllObjects];
7457 UIProgressHUD *hud([delegate_ addProgressHUD]);
7458 [hud setText:UCLocalize("LOADING")];
7459 //NSLog(@"HUD:%@::%@", delegate_, hud);
7460 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
7461 [delegate_ removeProgressHUD:hud];
7463 [self _reloadPackages:packages];
7466 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7467 Section *ignored = nil;
7468 Section *section = nil;
7472 bool unseens = false;
7474 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7476 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7477 Package *package = [self packageAtIndex:offset];
7479 BOOL uae = [package upgradableAndEssential:YES];
7483 time_t seen([package seen]);
7485 if (section == nil || last != seen) {
7489 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7492 _profile(ChangesController$reloadData$Allocate)
7493 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7494 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7495 [sections_ addObject:section];
7499 [section addToCount];
7500 } else if ([package ignored]) {
7501 if (ignored == nil) {
7502 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7504 [ignored addToCount];
7507 [upgradable addToCount];
7512 CFRelease(formatter);
7515 Section *last = [sections_ lastObject];
7516 size_t count = [last count];
7517 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7518 [sections_ removeLastObject];
7521 if ([ignored count] != 0)
7522 [sections_ insertObject:ignored atIndex:0];
7524 [sections_ insertObject:upgradable atIndex:0];
7529 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7530 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7531 style:UIBarButtonItemStylePlain
7533 action:@selector(upgradeButtonClicked)
7536 if (![delegate_ updating])
7537 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7538 initWithTitle:UCLocalize("REFRESH")
7539 style:UIBarButtonItemStylePlain
7541 action:@selector(refreshButtonClicked)
7547 - (void) reloadData {
7549 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
7554 /* Search Controller {{{ */
7555 @interface SearchController : FilteredPackageListController <
7558 _H<UISearchBar> search_;
7562 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7563 - (void) reloadData;
7567 @implementation SearchController
7570 [search_ setDelegate:nil];
7574 - (NSURL *) navigationURL {
7575 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7576 return [NSURL URLWithString:@"cydia://search"];
7578 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [search_ text]]];
7581 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7582 [self setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7583 [search_ resignFirstResponder];
7587 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7588 [self setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7592 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7593 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:query])) {
7594 search_ = [[[UISearchBar alloc] init] autorelease];
7595 [search_ setDelegate:self];
7598 [search_ setText:query];
7602 - (void) viewDidAppear:(BOOL)animated {
7603 [super viewDidAppear:animated];
7605 if (!searchloaded_) {
7606 searchloaded_ = YES;
7607 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7608 [search_ layoutSubviews];
7609 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7611 UITextField *textField;
7612 if ([search_ respondsToSelector:@selector(searchField)])
7613 textField = [search_ searchField];
7615 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7617 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7618 [textField setEnablesReturnKeyAutomatically:NO];
7619 [[self navigationItem] setTitleView:textField];
7623 - (void) reloadData {
7624 [self setObject:[search_ text]];
7630 - (void) didSelectPackage:(Package *)package {
7631 [search_ resignFirstResponder];
7632 [super didSelectPackage:package];
7637 /* Package Settings Controller {{{ */
7638 @interface PackageSettingsController : CyteViewController <
7639 UITableViewDataSource,
7642 _transient Database *database_;
7645 UITableView *table_;
7646 UISwitch *subscribedSwitch_;
7647 UISwitch *ignoredSwitch_;
7648 UITableViewCell *subscribedCell_;
7649 UITableViewCell *ignoredCell_;
7652 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7656 @implementation PackageSettingsController
7659 [self releaseSubviews];
7666 - (NSURL *) navigationURL {
7667 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", [package_ id]]];
7670 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7671 if (package_ == nil)
7674 if ([package_ installed] == nil)
7680 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7681 if (package_ == nil)
7684 // both sections contain just one item right now.
7688 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7692 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7694 return UCLocalize("SHOW_ALL_CHANGES_EX");
7696 return UCLocalize("IGNORE_UPGRADES_EX");
7699 - (void) onSubscribed:(id)control {
7700 bool value([control isOn]);
7701 if (package_ == nil)
7703 if ([package_ setSubscribed:value])
7704 [delegate_ updateData];
7707 - (void) _updateIgnored {
7708 const char *package([name_ UTF8String]);
7709 bool on([ignoredSwitch_ isOn]);
7711 pid_t pid(ExecFork());
7713 FILE *dpkg(popen("dpkg --set-selections", "w"));
7714 fwrite(package, strlen(package), 1, dpkg);
7717 fwrite(" hold\n", 6, 1, dpkg);
7719 fwrite(" install\n", 9, 1, dpkg);
7729 int result(waitpid(pid, &status, 0));
7732 _assert(result == pid);
7738 - (void) onIgnored:(id)control {
7739 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7740 [invocation setTarget:self];
7741 [invocation setSelector:@selector(_updateIgnored)];
7743 [delegate_ reloadDataWithInvocation:invocation];
7746 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7747 if (package_ == nil)
7750 switch ([indexPath section]) {
7751 case 0: return subscribedCell_;
7752 case 1: return ignoredCell_;
7761 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
7763 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7764 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7765 [table_ setDataSource:self];
7766 [table_ setDelegate:self];
7767 [[self view] addSubview:table_];
7769 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7770 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7771 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7773 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7774 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7775 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7777 subscribedCell_ = [[UITableViewCell alloc] init];
7778 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7779 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7780 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7782 ignoredCell_ = [[UITableViewCell alloc] init];
7783 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7784 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7785 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7788 - (void) viewDidLoad {
7789 [super viewDidLoad];
7791 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7794 - (void) releaseSubviews {
7795 [ignoredCell_ release];
7798 [subscribedCell_ release];
7799 subscribedCell_ = nil;
7804 [ignoredSwitch_ release];
7805 ignoredSwitch_ = nil;
7807 [subscribedSwitch_ release];
7808 subscribedSwitch_ = nil;
7811 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7812 if ((self = [super init]) != nil) {
7813 database_ = database;
7814 name_ = [package retain];
7818 - (void) reloadData {
7821 if (package_ != nil)
7822 [package_ autorelease];
7823 package_ = [database_ packageWithName:name_];
7825 if (package_ != nil) {
7826 package_ = [package_ retain];
7827 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7828 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7829 } // XXX: what now, G?
7831 [table_ reloadData];
7837 /* Installed Controller {{{ */
7838 @interface InstalledController : FilteredPackageListController {
7842 - (id) initWithDatabase:(Database *)database;
7844 - (void) updateRoleButton;
7845 - (void) queueStatusDidChange;
7849 @implementation InstalledController
7855 - (NSURL *) navigationURL {
7856 return [NSURL URLWithString:@"cydia://installed"];
7859 - (id) initWithDatabase:(Database *)database {
7860 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7861 [self updateRoleButton];
7862 [self queueStatusDidChange];
7867 - (void) queueButtonClicked {
7872 - (void) queueStatusDidChange {
7876 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7877 initWithTitle:UCLocalize("QUEUE")
7878 style:UIBarButtonItemStyleDone
7880 action:@selector(queueButtonClicked)
7883 [[self navigationItem] setLeftBarButtonItem:nil];
7889 - (void) updateRoleButton {
7890 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7891 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7892 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7893 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7895 action:@selector(roleButtonClicked)
7899 - (void) roleButtonClicked {
7900 [self setObject:[NSNumber numberWithBool:expert_]];
7904 [self updateRoleButton];
7910 /* Source Cell {{{ */
7911 @interface SourceCell : CYTableViewCell <
7919 - (void) setSource:(Source *)source;
7923 @implementation SourceCell
7925 - (void) clearSource {
7935 - (void) setSource:(Source *)source {
7939 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
7941 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
7942 icon_ = [icon_ retain];
7944 origin_ = [[source name] retain];
7945 label_ = [[source uri] retain];
7947 [content_ setNeedsDisplay];
7955 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
7956 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
7957 UIView *content([self contentView]);
7958 CGRect bounds([content bounds]);
7960 content_ = [[ContentView alloc] initWithFrame:bounds];
7961 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7962 [content_ setBackgroundColor:[UIColor whiteColor]];
7963 [content addSubview:content_];
7965 [content_ setDelegate:self];
7966 [content_ setOpaque:YES];
7970 - (NSString *) accessibilityLabel {
7974 - (void) drawContentRect:(CGRect)rect {
7975 bool highlighted(highlighted_);
7976 float width(rect.size.width);
7979 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
7986 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
7990 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
7995 /* Source Controller {{{ */
7996 @interface SourceController : FilteredPackageListController {
7997 _transient Source *source_;
8001 - (id) initWithDatabase:(Database *)database source:(Source *)source;
8005 @implementation SourceController
8007 - (NSURL *) navigationURL {
8008 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [source_ name]]];
8011 - (id) initWithDatabase:(Database *)database source:(Source *)source {
8012 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
8014 key_ = [[source key] retain];
8018 - (void) reloadData {
8019 source_ = [database_ sourceWithKey:key_];
8021 key_ = [[source_ key] retain];
8022 [self setObject:source_];
8024 [[self navigationItem] setTitle:[source_ label]];
8031 /* Sources Controller {{{ */
8032 @interface SourcesController : CyteViewController <
8033 UITableViewDataSource,
8036 _transient Database *database_;
8038 NSMutableArray *sources_;
8042 UIProgressHUD *hud_;
8045 //NSURLConnection *installer_;
8046 NSURLConnection *trivial_;
8047 NSURLConnection *trivial_bz2_;
8048 NSURLConnection *trivial_gz_;
8049 //NSURLConnection *automatic_;
8054 - (id) initWithDatabase:(Database *)database;
8055 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
8059 @implementation SourcesController
8061 - (void) _releaseConnection:(NSURLConnection *)connection {
8062 if (connection != nil) {
8063 [connection cancel];
8064 //[connection setDelegate:nil];
8065 [connection release];
8070 [self releaseSubviews];
8076 //[self _releaseConnection:installer_];
8077 [self _releaseConnection:trivial_];
8078 [self _releaseConnection:trivial_gz_];
8079 [self _releaseConnection:trivial_bz2_];
8080 //[self _releaseConnection:automatic_];
8086 - (NSURL *) navigationURL {
8087 return [NSURL URLWithString:@"cydia://sources"];
8090 - (void) viewDidAppear:(BOOL)animated {
8091 [super viewDidAppear:animated];
8092 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8095 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8096 return offset_ == 0 ? 1 : 2;
8099 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8100 switch (section + (offset_ == 0 ? 1 : 0)) {
8101 case 0: return UCLocalize("ENTERED_BY_USER");
8102 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
8108 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8109 int count = [sources_ count];
8111 case 0: return (offset_ == 0 ? count : offset_);
8112 case 1: return count - offset_;
8118 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8120 switch (indexPath.section) {
8121 case 0: idx = indexPath.row; break;
8122 case 1: idx = indexPath.row + offset_; break;
8126 return [sources_ objectAtIndex:idx];
8129 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8130 static NSString *cellIdentifier = @"SourceCell";
8132 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8133 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8134 [cell setSource:[self sourceAtIndexPath:indexPath]];
8135 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8140 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8141 Source *source = [self sourceAtIndexPath:indexPath];
8143 SourceController *controller = [[[SourceController alloc]
8144 initWithDatabase:database_
8148 [controller setDelegate:delegate_];
8150 [[self navigationController] pushViewController:controller animated:YES];
8153 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8154 Source *source = [self sourceAtIndexPath:indexPath];
8155 return [source record] != nil;
8158 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8159 Source *source = [self sourceAtIndexPath:indexPath];
8160 [Sources_ removeObjectForKey:[source key]];
8161 [delegate_ syncData];
8165 [delegate_ addTrivialSource:href_];
8166 [delegate_ syncData];
8169 - (NSString *) getWarning {
8170 NSString *href(href_);
8171 NSRange colon([href rangeOfString:@"://"]);
8172 if (colon.location != NSNotFound)
8173 href = [href substringFromIndex:(colon.location + 3)];
8174 href = [href stringByAddingPercentEscapes];
8175 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8176 href = [href stringByCachingURLWithCurrentCDN];
8178 NSURL *url([NSURL URLWithString:href]);
8180 NSStringEncoding encoding;
8181 NSError *error(nil);
8183 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8184 return [warning length] == 0 ? nil : warning;
8188 - (void) _endConnection:(NSURLConnection *)connection {
8189 // XXX: the memory management in this method is horribly awkward
8191 NSURLConnection **field = NULL;
8192 if (connection == trivial_)
8194 else if (connection == trivial_bz2_)
8195 field = &trivial_bz2_;
8196 else if (connection == trivial_gz_)
8197 field = &trivial_gz_;
8198 _assert(field != NULL);
8199 [connection release];
8204 trivial_bz2_ == nil &&
8210 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
8213 UIAlertView *alert = [[[UIAlertView alloc]
8214 initWithTitle:UCLocalize("SOURCE_WARNING")
8217 cancelButtonTitle:UCLocalize("CANCEL")
8219 UCLocalize("ADD_ANYWAY"),
8223 [alert setContext:@"warning"];
8224 [alert setNumberOfRows:1];
8228 } else if (error_ != nil) {
8229 UIAlertView *alert = [[[UIAlertView alloc]
8230 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8231 message:[error_ localizedDescription]
8233 cancelButtonTitle:UCLocalize("OK")
8234 otherButtonTitles:nil
8237 [alert setContext:@"urlerror"];
8240 UIAlertView *alert = [[[UIAlertView alloc]
8241 initWithTitle:UCLocalize("NOT_REPOSITORY")
8242 message:UCLocalize("NOT_REPOSITORY_EX")
8244 cancelButtonTitle:UCLocalize("OK")
8245 otherButtonTitles:nil
8248 [alert setContext:@"trivial"];
8252 [delegate_ releaseNetworkActivityIndicator];
8254 [delegate_ removeProgressHUD:hud_];
8263 if (error_ != nil) {
8270 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8271 switch ([response statusCode]) {
8277 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8278 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8280 error_ = [error retain];
8281 [self _endConnection:connection];
8284 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8285 [self _endConnection:connection];
8288 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8289 NSMutableURLRequest *request = [NSMutableURLRequest
8290 requestWithURL:[NSURL URLWithString:href]
8291 cachePolicy:NSURLRequestUseProtocolCachePolicy
8292 timeoutInterval:120.0
8295 [request setHTTPMethod:method];
8297 if (Machine_ != NULL)
8298 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8299 if (UniqueID_ != nil)
8300 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8302 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8305 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8306 NSString *context([alert context]);
8308 if ([context isEqualToString:@"source"]) {
8311 NSString *href = [[alert textField] text];
8313 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
8315 if (![href hasSuffix:@"/"])
8316 href_ = [href stringByAppendingString:@"/"];
8319 href_ = [href_ retain];
8321 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
8322 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8323 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8324 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
8328 // XXX: this is stupid
8329 hud_ = [[delegate_ addProgressHUD] retain];
8330 [hud_ setText:UCLocalize("VERIFYING_URL")];
8331 [delegate_ retainNetworkActivityIndicator];
8340 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8341 } else if ([context isEqualToString:@"trivial"])
8342 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8343 else if ([context isEqualToString:@"urlerror"])
8344 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8345 else if ([context isEqualToString:@"warning"]) {
8360 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8365 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8367 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
8368 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8369 [list_ setRowHeight:56];
8370 [list_ setDataSource:self];
8371 [list_ setDelegate:self];
8372 [[self view] addSubview:list_];
8375 - (void) viewDidLoad {
8376 [super viewDidLoad];
8378 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8379 [self updateButtonsForEditingStatus:NO animated:NO];
8382 - (void) releaseSubviews {
8387 - (id) initWithDatabase:(Database *)database {
8388 if ((self = [super init]) != nil) {
8389 database_ = database;
8390 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
8394 - (void) reloadData {
8398 if ([database_ popErrorWithTitle:UCLocalize("SOURCES") forOperation:list.ReadMainList()])
8401 [sources_ removeAllObjects];
8402 [sources_ addObjectsFromArray:[database_ sources]];
8404 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
8407 int count([sources_ count]);
8409 for (int i = 0; i != count; i++) {
8410 if ([[sources_ objectAtIndex:i] record] == nil)
8415 [list_ setEditing:NO];
8416 [self updateButtonsForEditingStatus:NO animated:NO];
8420 - (void) showAddSourcePrompt {
8421 UIAlertView *alert = [[[UIAlertView alloc]
8422 initWithTitle:UCLocalize("ENTER_APT_URL")
8425 cancelButtonTitle:UCLocalize("CANCEL")
8427 UCLocalize("ADD_SOURCE"),
8431 [alert setContext:@"source"];
8432 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
8434 [alert setNumberOfRows:1];
8435 [alert addTextFieldWithValue:@"http://" label:@""];
8437 UITextInputTraits *traits = [[alert textField] textInputTraits];
8438 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8439 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8440 [traits setKeyboardType:UIKeyboardTypeURL];
8441 // XXX: UIReturnKeyDone
8442 [traits setReturnKeyType:UIReturnKeyNext];
8447 - (void) addButtonClicked {
8448 [self showAddSourcePrompt];
8451 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
8452 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
8453 initWithTitle:UCLocalize("ADD")
8454 style:UIBarButtonItemStylePlain
8456 action:@selector(addButtonClicked)
8457 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
8459 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8460 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8461 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8463 action:@selector(editButtonClicked)
8464 ] autorelease] animated:animated];
8466 if (IsWildcat_ && !editing)
8467 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8468 initWithTitle:UCLocalize("SETTINGS")
8469 style:UIBarButtonItemStylePlain
8471 action:@selector(settingsButtonClicked)
8475 - (void) settingsButtonClicked {
8476 [delegate_ showSettings];
8479 - (void) editButtonClicked {
8480 [list_ setEditing:![list_ isEditing] animated:YES];
8482 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
8488 /* Settings Controller {{{ */
8489 @interface SettingsController : CyteViewController <
8490 UITableViewDataSource,
8493 _transient Database *database_;
8494 // XXX: ok, "roledelegate_"?...
8495 _transient id roledelegate_;
8496 UITableView *table_;
8497 UISegmentedControl *segment_;
8501 - (void) showDoneButton;
8502 - (void) resizeSegmentedControl;
8506 @implementation SettingsController
8509 [self releaseSubviews];
8515 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8517 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
8518 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8519 [table_ setDelegate:self];
8520 [table_ setDataSource:self];
8521 [[self view] addSubview:table_];
8523 NSArray *items = [NSArray arrayWithObjects:
8525 UCLocalize("HACKER"),
8526 UCLocalize("DEVELOPER"),
8528 segment_ = [[UISegmentedControl alloc] initWithItems:items];
8529 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
8530 [container_ addSubview:segment_];
8533 - (void) viewDidLoad {
8534 [super viewDidLoad];
8536 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
8539 if ([Role_ isEqualToString:@"User"]) index = 0;
8540 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8541 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8543 [segment_ setSelectedSegmentIndex:index];
8544 [self showDoneButton];
8547 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8548 [self resizeSegmentedControl];
8551 - (void) releaseSubviews {
8558 [container_ release];
8562 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
8563 if ((self = [super init]) != nil) {
8564 database_ = database;
8565 roledelegate_ = delegate;
8569 - (void) resizeSegmentedControl {
8570 CGFloat width = [[self view] frame].size.width;
8571 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8574 - (void) viewWillAppear:(BOOL)animated {
8575 [super viewWillAppear:animated];
8577 [self resizeSegmentedControl];
8580 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8581 [self resizeSegmentedControl];
8584 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8585 [self resizeSegmentedControl];
8589 NSString *role(nil);
8591 switch ([segment_ selectedSegmentIndex]) {
8592 case 0: role = @"User"; break;
8593 case 1: role = @"Hacker"; break;
8594 case 2: role = @"Developer"; break;
8599 if (![role isEqualToString:Role_]) {
8600 bool rolling(Role_ == nil);
8603 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8607 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8611 [roledelegate_ loadData];
8613 [roledelegate_ updateData];
8617 - (void) segmentChanged:(UISegmentedControl *)control {
8618 [self showDoneButton];
8621 - (void) saveAndClose {
8624 [[self navigationItem] setRightBarButtonItem:nil];
8625 [[self navigationController] dismissModalViewControllerAnimated:YES];
8628 - (void) doneButtonClicked {
8629 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8630 [spinner startAnimating];
8631 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8632 [[self navigationItem] setRightBarButtonItem:spinItem];
8634 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8637 - (void) showDoneButton {
8638 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8639 initWithTitle:UCLocalize("DONE")
8640 style:UIBarButtonItemStyleDone
8642 action:@selector(doneButtonClicked)
8643 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8646 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8647 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8651 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8655 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8656 return nil; // This method is required by the protocol.
8659 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8661 return UCLocalize("ROLE_EX");
8663 return [NSString stringWithFormat:
8664 @"%@: %@\n%@: %@\n%@: %@",
8665 UCLocalize("USER"), UCLocalize("USER_EX"),
8666 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8667 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8672 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8673 return section == 3 ? 44.0f : 0;
8676 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8677 return section == 3 ? container_ : nil;
8680 - (void) reloadData {
8683 [table_ reloadData];
8688 /* Stash Controller {{{ */
8689 @interface StashController : CyteViewController {
8690 UIActivityIndicatorView *spinner_;
8697 @implementation StashController
8700 [self releaseSubviews];
8706 [self setView:[[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]];
8707 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8709 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8710 CGRect spinrect = [spinner_ frame];
8711 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8712 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8713 [spinner_ setFrame:spinrect];
8714 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8715 [[self view] addSubview:spinner_];
8716 [spinner_ startAnimating];
8719 captrect.size.width = [[self view] frame].size.width;
8720 captrect.size.height = 40.0f;
8721 captrect.origin.x = 0;
8722 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8723 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8724 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8725 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8726 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8727 [caption_ setTextColor:[UIColor whiteColor]];
8728 [caption_ setBackgroundColor:[UIColor clearColor]];
8729 [caption_ setShadowColor:[UIColor blackColor]];
8730 [caption_ setTextAlignment:UITextAlignmentCenter];
8731 [[self view] addSubview:caption_];
8734 statusrect.size.width = [[self view] frame].size.width;
8735 statusrect.size.height = 30.0f;
8736 statusrect.origin.x = 0;
8737 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8738 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8739 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8740 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8741 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8742 [status_ setTextColor:[UIColor whiteColor]];
8743 [status_ setBackgroundColor:[UIColor clearColor]];
8744 [status_ setShadowColor:[UIColor blackColor]];
8745 [status_ setTextAlignment:UITextAlignmentCenter];
8746 [[self view] addSubview:status_];
8749 - (void) releaseSubviews {
8763 @interface Cydia : UIApplication <
8764 ConfirmationControllerDelegate,
8767 UINavigationControllerDelegate,
8768 UITabBarControllerDelegate
8770 // XXX: evaluate all fields for _transient
8773 CYTabBarController *tabbar_;
8774 CYEmulatedLoadingController *emulated_;
8776 NSMutableArray *essential_;
8777 NSMutableArray *broken_;
8779 Database *database_;
8786 StashController *stash_;
8795 @implementation Cydia
8797 - (void) beginUpdate {
8798 [tabbar_ beginUpdate];
8802 return [tabbar_ updating];
8806 if ([broken_ count] != 0) {
8807 int count = [broken_ count];
8809 UIAlertView *alert = [[[UIAlertView alloc]
8810 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8811 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8813 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8815 UCLocalize("TEMPORARY_IGNORE"),
8819 [alert setContext:@"fixhalf"];
8820 [alert setNumberOfRows:2];
8822 } else if (!Ignored_ && [essential_ count] != 0) {
8823 int count = [essential_ count];
8825 UIAlertView *alert = [[[UIAlertView alloc]
8826 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8827 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8829 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8831 UCLocalize("UPGRADE_ESSENTIAL"),
8832 UCLocalize("COMPLETE_UPGRADE"),
8836 [alert setContext:@"upgrade"];
8841 - (void) _saveConfig {
8847 NSString *error(nil);
8849 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8851 NSError *error(nil);
8852 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8853 NSLog(@"failure to save metadata data: %@", error);
8858 NSLog(@"failure to serialize metadata: %@", error);
8863 // Navigation controller for the queuing badge.
8864 - (UINavigationController *) queueNavigationController {
8865 NSArray *controllers = [tabbar_ viewControllers];
8866 return [controllers objectAtIndex:3];
8869 - (void) unloadData {
8870 [tabbar_ unloadData];
8873 - (void) _updateData {
8878 UINavigationController *navigation = [self queueNavigationController];
8880 id queuedelegate = nil;
8881 if ([[navigation viewControllers] count] > 0)
8882 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8884 [queuedelegate queueStatusDidChange];
8885 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8888 - (void) _refreshIfPossible:(NSDate *)update {
8889 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8891 bool recently = false;
8892 if (update != nil) {
8893 NSTimeInterval interval([update timeIntervalSinceNow]);
8894 if (interval <= 0 && interval > -(15*60))
8898 // Don't automatic refresh if:
8899 // - We already refreshed recently.
8900 // - We already auto-refreshed this launch.
8901 // - Auto-refresh is disabled.
8902 if (recently || loaded_ || ManualRefresh) {
8903 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8905 // If we are cancelling, we need to make sure it knows it's already loaded.
8909 // We are going to load, so remember that.
8913 SCNetworkReachabilityFlags flags; {
8914 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8915 SCNetworkReachabilityGetFlags(reachability, &flags);
8916 CFRelease(reachability);
8919 // XXX: this elaborate mess is what Apple is using to determine this? :(
8920 // XXX: do we care if the user has to intervene? maybe that's ok?
8922 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8923 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8924 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8925 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8926 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8927 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8931 // If we can reach the server, auto-refresh!
8933 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8938 - (void) refreshIfPossible {
8939 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
8942 - (void) _reloadDataWithInvocation:(NSInvocation *)invocation {
8943 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8944 [hud setText:UCLocalize("RELOADING_DATA")];
8946 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
8949 [self removeProgressHUD:hud];
8953 [essential_ removeAllObjects];
8954 [broken_ removeAllObjects];
8956 NSArray *packages([database_ packages]);
8957 for (Package *package in packages) {
8959 [broken_ addObject:package];
8960 if ([package upgradableAndEssential:NO]) {
8961 if ([package essential])
8962 [essential_ addObject:package];
8967 NSLog(@"changes:#%u", changes);
8969 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
8972 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8973 [changesItem setBadgeValue:badge];
8974 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8975 [self setApplicationIconBadgeNumber:changes];
8978 [changesItem setBadgeValue:nil];
8979 [changesItem setAnimatedBadge:NO];
8980 [self setApplicationIconBadgeNumber:0];
8985 [self refreshIfPossible];
8988 - (void) updateData {
8997 @synchronized (self) {
8998 [self _reloadDataWithInvocation:nil];
9002 - (void) disemulate {
9003 if (emulated_ == nil)
9006 [window_ addSubview:[tabbar_ view]];
9007 [[emulated_ view] removeFromSuperview];
9008 [emulated_ release];
9010 [window_ setUserInteractionEnabled:YES];
9013 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9014 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9016 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9018 UIViewController *parent;
9019 if (emulated_ == nil)
9028 [parent presentModalViewController:navigation animated:YES];
9031 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9032 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9034 if (navigation != nil)
9035 [navigation pushViewController:progress animated:YES];
9037 [self presentModalViewController:progress force:YES];
9039 [progress invoke:invocation withTitle:title];
9043 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9044 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9047 - (void) repairWithInvocation:(NSInvocation *)invocation {
9049 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9053 - (void) repairWithSelector:(SEL)selector {
9054 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9060 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
9061 _assert(file != NULL);
9063 for (NSString *key in [Sources_ allKeys]) {
9064 NSDictionary *source([Sources_ objectForKey:key]);
9066 fprintf(file, "%s %s %s\n",
9067 [[source objectForKey:@"Type"] UTF8String],
9068 [[source objectForKey:@"URI"] UTF8String],
9069 [[source objectForKey:@"Distribution"] UTF8String]
9075 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9080 - (void) addTrivialSource:(NSString *)href {
9081 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
9084 @"./", @"Distribution",
9085 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href]];
9090 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9091 @synchronized (self) {
9092 [self _reloadDataWithInvocation:invocation];
9096 - (void) reloadData {
9097 [self reloadDataWithInvocation:nil];
9101 pkgProblemResolver *resolver = [database_ resolver];
9103 resolver->InstallProtect();
9104 if (!resolver->Resolve(true))
9109 // XXX: this is a really crappy way of doing this.
9110 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9111 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9112 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9113 if ([tabbar_ updating])
9114 [tabbar_ cancelUpdate];
9116 if (![database_ prepare])
9119 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9120 [page setDelegate:self];
9121 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9124 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9125 [tabbar_ presentModalViewController:confirm_ animated:YES];
9131 @synchronized (self) {
9136 - (void) clearPackage:(Package *)package {
9137 @synchronized (self) {
9144 - (void) installPackages:(NSArray *)packages {
9145 @synchronized (self) {
9146 for (Package *package in packages)
9153 - (void) installPackage:(Package *)package {
9154 @synchronized (self) {
9161 - (void) removePackage:(Package *)package {
9162 @synchronized (self) {
9169 - (void) distUpgrade {
9170 @synchronized (self) {
9171 if (![database_ upgrade])
9177 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9180 [self detachNewProgressSelector:@selector(perform) toTarget:database_ forController:navigation title:@"RUNNING"];
9185 - (void) showSettings {
9186 [self presentModalViewController:[[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease] force:NO];
9189 - (void) retainNetworkActivityIndicator {
9190 if (activity_++ == 0)
9191 [self setNetworkActivityIndicatorVisible:YES];
9194 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9198 - (void) releaseNetworkActivityIndicator {
9199 if (--activity_ == 0)
9200 [self setNetworkActivityIndicatorVisible:NO];
9203 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9208 - (void) cancelAndClear:(bool)clear {
9209 @synchronized (self) {
9221 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9222 NSString *context([alert context]);
9224 if ([context isEqualToString:@"conffile"]) {
9225 FILE *input = [database_ input];
9226 if (button == [alert cancelButtonIndex])
9227 fprintf(input, "N\n");
9228 else if (button == [alert firstOtherButtonIndex])
9229 fprintf(input, "Y\n");
9232 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9233 } else if ([context isEqualToString:@"fixhalf"]) {
9234 if (button == [alert cancelButtonIndex]) {
9235 @synchronized (self) {
9236 for (Package *broken in broken_) {
9239 NSString *id = [broken id];
9240 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9241 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9242 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9243 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9249 } else if (button == [alert firstOtherButtonIndex]) {
9250 [broken_ removeAllObjects];
9254 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9255 } else if ([context isEqualToString:@"upgrade"]) {
9256 if (button == [alert firstOtherButtonIndex]) {
9257 @synchronized (self) {
9258 for (Package *essential in essential_)
9259 [essential install];
9264 } else if (button == [alert firstOtherButtonIndex] + 1) {
9266 } else if (button == [alert cancelButtonIndex]) {
9270 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9274 - (void) system:(NSString *)command { _pooled
9276 system([command UTF8String]);
9280 - (void) applicationWillSuspend {
9282 [super applicationWillSuspend];
9285 - (BOOL) isSafeToSuspend {
9288 NSLog(@"isSafeToSuspend: locked_ != 0");
9293 // Use external process status API internally.
9294 // This is probably a really bad idea.
9295 // XXX: what is the point of this? does this solve anything at all?
9296 uint64_t status = 0;
9298 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9299 notify_get_state(notify_token, &status);
9300 notify_cancel(notify_token);
9305 NSLog(@"isSafeToSuspend: status != 0");
9311 NSLog(@"isSafeToSuspend: -> true");
9316 - (void) applicationSuspend:(__GSEvent *)event {
9317 if ([self isSafeToSuspend])
9318 [super applicationSuspend:event];
9321 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9322 if ([self isSafeToSuspend])
9323 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9326 - (void) _setSuspended:(BOOL)value {
9327 if ([self isSafeToSuspend])
9328 [super _setSuspended:value];
9331 - (UIProgressHUD *) addProgressHUD {
9332 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
9333 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9335 [window_ setUserInteractionEnabled:NO];
9337 UIViewController *target(tabbar_);
9338 if (UIViewController *modal = [target modalViewController])
9341 UIView *view([target view]);
9342 [view addSubview:hud];
9350 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9353 [hud removeFromSuperview];
9354 [window_ setUserInteractionEnabled:YES];
9357 - (CyteViewController *) pageForPackage:(NSString *)name {
9358 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name] autorelease];
9361 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external {
9362 NSString *scheme([[url scheme] lowercaseString]);
9363 if ([[url absoluteString] length] <= [scheme length] + 3)
9365 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9366 NSArray *components([path pathComponents]);
9368 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
9369 return [self pageForPackage:[components objectAtIndex:1]];
9371 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9374 NSString *base([components objectAtIndex:0]);
9376 CyteViewController *controller = nil;
9378 if ([base isEqualToString:@"url"]) {
9379 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9380 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9381 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9382 } else if (!external && [components count] == 1) {
9383 if ([base isEqualToString:@"manage"]) {
9384 controller = [[[ManageController alloc] init] autorelease];
9387 if ([base isEqualToString:@"sources"]) {
9388 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9391 if ([base isEqualToString:@"home"]) {
9392 controller = [[[HomeController alloc] init] autorelease];
9395 if ([base isEqualToString:@"sections"]) {
9396 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
9399 if ([base isEqualToString:@"search"]) {
9400 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9403 if ([base isEqualToString:@"changes"]) {
9404 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9407 if ([base isEqualToString:@"installed"]) {
9408 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9410 } else if ([components count] == 2) {
9411 NSString *argument = [components objectAtIndex:1];
9413 if ([base isEqualToString:@"package"]) {
9414 controller = [self pageForPackage:argument];
9417 if (!external && [base isEqualToString:@"search"]) {
9418 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9421 if (!external && [base isEqualToString:@"sections"]) {
9422 if ([argument isEqualToString:@"all"])
9424 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
9427 if (!external && [base isEqualToString:@"sources"]) {
9428 if ([argument isEqualToString:@"add"]) {
9429 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9430 [(SourcesController *)controller showAddSourcePrompt];
9432 Source *source = [database_ sourceWithKey:argument];
9433 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
9437 if (!external && [base isEqualToString:@"launch"]) {
9438 [self launchApplicationWithIdentifier:argument suspended:NO];
9441 } else if (!external && [components count] == 3) {
9442 NSString *arg1 = [components objectAtIndex:1];
9443 NSString *arg2 = [components objectAtIndex:2];
9445 if ([base isEqualToString:@"package"]) {
9446 if ([arg2 isEqualToString:@"settings"]) {
9447 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9448 } else if ([arg2 isEqualToString:@"files"]) {
9449 if (Package *package = [database_ packageWithName:arg1]) {
9450 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9451 [(FileTable *)controller setPackage:package];
9457 [controller setDelegate:self];
9461 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9462 CyteViewController *page([self pageForURL:url forExternal:external]);
9465 UINavigationController *nav = [[[UINavigationController alloc] init] autorelease];
9466 [nav setViewControllers:[NSArray arrayWithObject:page]];
9467 [tabbar_ setUnselectedViewController:nav];
9473 - (void) applicationOpenURL:(NSURL *)url {
9474 [super applicationOpenURL:url];
9476 if (!loaded_) starturl_ = [url retain];
9477 else [self openCydiaURL:url forExternal:YES];
9480 - (void) applicationWillResignActive:(UIApplication *)application {
9481 // Stop refreshing if you get a phone call or lock the device.
9482 if ([tabbar_ updating])
9483 [tabbar_ cancelUpdate];
9485 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9486 [super applicationWillResignActive:application];
9489 - (void) applicationWillTerminate:(UIApplication *)application {
9491 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9492 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9493 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9498 - (void) setConfigurationData:(NSString *)data {
9499 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9501 if (!conffile_r(data)) {
9502 lprintf("E:invalid conffile\n");
9506 NSString *ofile = conffile_r[1];
9507 //NSString *nfile = conffile_r[2];
9509 UIAlertView *alert = [[[UIAlertView alloc]
9510 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9511 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9513 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9515 UCLocalize("ACCEPT_NEW_COPY"),
9516 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9520 [alert setContext:@"conffile"];
9521 [alert setNumberOfRows:2];
9525 - (void) addStashController {
9527 stash_ = [[StashController alloc] init];
9528 [window_ addSubview:[stash_ view]];
9531 - (void) removeStashController {
9532 [[stash_ view] removeFromSuperview];
9538 [self setIdleTimerDisabled:YES];
9540 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9541 UpdateExternalStatus(1);
9542 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9543 UpdateExternalStatus(0);
9545 [self removeStashController];
9547 if (ExecFork() == 0) {
9548 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9549 perror("launchctl stop");
9553 - (void) setupViewControllers {
9554 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
9556 NSMutableArray *items([NSMutableArray arrayWithObjects:
9557 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9558 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9559 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9560 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9564 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
9565 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9567 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
9570 NSMutableArray *controllers([NSMutableArray array]);
9571 for (UITabBarItem *item in items) {
9572 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9573 [controller setTabBarItem:item];
9574 [controllers addObject:controller];
9576 [tabbar_ setViewControllers:controllers];
9578 [tabbar_ setUpdateDelegate:self];
9581 - (void) applicationDidFinishLaunching:(id)unused {
9583 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9584 [self setApplicationSupportsShakeToEdit:NO];
9586 @synchronized (HostConfig_) {
9587 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9590 [NSURLCache setSharedURLCache:[[[SDURLCache alloc]
9591 initWithMemoryCapacity:524288
9592 diskCapacity:10485760
9593 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
9596 [CydiaWebViewController _initialize];
9598 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9600 Font12_ = [[UIFont systemFontOfSize:12] retain];
9601 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
9602 Font14_ = [[UIFont systemFontOfSize:14] retain];
9603 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
9604 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
9606 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
9607 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
9609 // XXX: I really need this thing... like, seriously... I'm sorry
9610 [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
9612 window_ = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
9613 [window_ orderFront:self];
9614 [window_ makeKey:self];
9615 [window_ setHidden:NO];
9618 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
9619 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
9620 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
9621 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
9622 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
9623 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
9624 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
9625 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
9626 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
9629 [self addStashController];
9630 // XXX: this would be much cleaner as a yieldToSelector:
9631 // that way the removeStashController could happen right here inline
9632 // we also could no longer require the useless stash_ field anymore
9633 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9637 database_ = [Database sharedInstance];
9638 [database_ setDelegate:self];
9640 [window_ setUserInteractionEnabled:NO];
9641 [self setupViewControllers];
9643 emulated_ = [[CYEmulatedLoadingController alloc] initWithDatabase:database_];
9644 [window_ addSubview:[emulated_ view]];
9646 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9650 - (NSArray *) defaultStartPages {
9651 NSMutableArray *standard = [NSMutableArray array];
9652 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9653 [standard addObject:[NSArray arrayWithObject:@"cydia://sections"]];
9654 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9656 [standard addObject:[NSArray arrayWithObject:@"cydia://manage"]];
9658 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9659 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9661 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9668 [window_ setUserInteractionEnabled:YES];
9669 [self showSettings];
9672 if ([emulated_ modalViewController] != nil)
9673 [emulated_ dismissModalViewControllerAnimated:YES];
9674 [window_ setUserInteractionEnabled:NO];
9682 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9683 NSArray *saved = [[Metadata_ objectForKey:@"InterfaceState"] mutableCopy];
9684 int standardIndex = 0;
9685 NSArray *standard = [self defaultStartPages];
9692 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9693 if (valid && closed != nil) {
9694 NSTimeInterval interval([closed timeIntervalSinceNow]);
9695 // XXX: Is 15 minutes the optimal time here?
9696 if (interval > 0 && interval <= -(15*60))
9700 if (valid && [saved count] != [standard count])
9704 for (unsigned int i = 0; i < [standard count]; i++) {
9705 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9706 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9707 // but it's good enough for now.
9708 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9715 NSArray *items = nil;
9717 [tabbar_ setSelectedIndex:savedIndex];
9720 [tabbar_ setSelectedIndex:standardIndex];
9724 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9725 NSArray *stack = [items objectAtIndex:tab];
9726 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9727 NSMutableArray *current = [NSMutableArray array];
9729 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9730 NSString *addr = [stack objectAtIndex:nav];
9731 NSURL *url = [NSURL URLWithString:addr];
9732 CyteViewController *page = [self pageForURL:url forExternal:NO];
9734 [current addObject:page];
9737 [navigation setViewControllers:current];
9740 // (Try to) show the startup URL.
9741 if (starturl_ != nil) {
9742 [self openCydiaURL:starturl_ forExternal:NO];
9743 [starturl_ release];
9748 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9749 if (item != nil && IsWildcat_) {
9750 [sheet showFromBarButtonItem:item animated:YES];
9752 [sheet showInView:window_];
9756 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9757 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9758 [progress setTitle:task];
9759 [progress addProgressEvent:event];
9762 - (void) addProgressEventForTask:(NSArray *)data {
9763 CydiaProgressEvent *event([data objectAtIndex:0]);
9764 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9765 [self addProgressEvent:event forTask:task];
9768 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9769 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9775 id Alloc_(id self, SEL selector) {
9776 id object = alloc_(self, selector);
9777 lprintf("[%s]A-%p\n", self->isa->name, object);
9782 id Dealloc_(id self, SEL selector) {
9783 id object = dealloc_(self, selector);
9784 lprintf("[%s]D-%p\n", self->isa->name, object);
9788 Class $WebDefaultUIKitDelegate;
9790 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9791 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9792 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9793 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9796 static NSSet *MobilizedFiles_;
9798 static NSURL *MobilizeURL(NSURL *url) {
9799 NSString *path([url path]);
9800 if ([path hasPrefix:@"/var/root/"]) {
9801 NSString *file([path substringFromIndex:10]);
9802 if ([MobilizedFiles_ containsObject:file])
9803 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
9809 Class $CFXPreferencesPropertyListSource;
9810 @class CFXPreferencesPropertyListSource;
9812 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9813 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9814 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9815 url = MobilizeURL(url);
9816 BOOL value(_CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd));
9817 //NSLog(@"%@ %s", [url absoluteString], value ? "YES" : "NO");
9823 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9824 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9825 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9826 url = MobilizeURL(url);
9827 void *value(_CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd));
9828 //NSLog(@"%@ %@", [url absoluteString], value);
9834 Class $NSURLConnection;
9836 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
9837 NSMutableURLRequest *copy([request mutableCopy]);
9839 NSURL *url([copy URL]);
9840 NSString *host([url host]);
9841 NSString *scheme([[url scheme] lowercaseString]);
9843 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
9845 @synchronized (HostConfig_) {
9846 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
9847 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
9848 [copy setHTTPShouldUsePipelining:YES];
9851 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
9855 int main(int argc, char *argv[]) { _pooled
9858 UpdateExternalStatus(0);
9860 if (Class $UIDevice = objc_getClass("UIDevice")) {
9861 UIDevice *device([$UIDevice currentDevice]);
9862 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
9866 UIScreen *screen([UIScreen mainScreen]);
9867 if ([screen respondsToSelector:@selector(scale)])
9868 ScreenScale_ = [screen scale];
9872 UIDevice *device([UIDevice currentDevice]);
9873 if (![device respondsToSelector:@selector(userInterfaceIdiom)])
9876 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
9877 if (idiom == UIUserInterfaceIdiomPhone)
9879 else if (idiom == UIUserInterfaceIdiomPad)
9882 NSLog(@"unknown UIUserInterfaceIdiom!");
9885 SessionData_ = [[NSMutableDictionary alloc] initWithCapacity:4];
9887 HostConfig_ = [[NSObject alloc] init];
9888 @synchronized (HostConfig_) {
9889 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
9890 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
9893 UI_ = CydiaURL([NSString stringWithFormat:@"ui/ios~%@", Idiom_]);
9895 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9897 MobilizedFiles_ = [NSMutableSet setWithObjects:
9898 @"Library/Preferences/com.apple.Accessibility.plist",
9899 @"Library/Preferences/com.apple.preferences.sounds.plist",
9902 /* Library Hacks {{{ */
9903 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
9905 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
9907 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
9908 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
9909 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
9910 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
9913 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
9914 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
9915 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
9916 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
9919 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
9920 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
9921 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
9922 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
9923 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
9926 $NSURLConnection = objc_getClass("NSURLConnection");
9927 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
9928 if (NSURLConnection$init$ != NULL) {
9929 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
9930 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
9933 /* Set Locale {{{ */
9934 Locale_ = CFLocaleCopyCurrent();
9935 Languages_ = [NSLocale preferredLanguages];
9937 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
9938 //NSLog(@"%@", [Languages_ description]);
9941 if (Locale_ != NULL)
9942 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
9943 else if (Languages_ != nil && [Languages_ count] != 0)
9944 lang = [[Languages_ objectAtIndex:0] UTF8String];
9946 // XXX: consider just setting to C and then falling through?
9950 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
9951 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
9954 NSLog(@"Setting Language: %s", lang);
9957 setenv("LANG", lang, true);
9958 std::setlocale(LC_ALL, lang);
9962 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
9964 /* Parse Arguments {{{ */
9965 bool substrate(false);
9971 for (int argi(1); argi != argc; ++argi)
9972 if (strcmp(argv[argi], "--") == 0) {
9974 argv[argi] = argv[0];
9980 for (int argi(1); argi != arge; ++argi)
9981 if (strcmp(args[argi], "--substrate") == 0)
9984 fprintf(stderr, "unknown argument: %s\n", args[argi]);
9988 App_ = [[NSBundle mainBundle] bundlePath];
9994 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
9995 alloc_ = alloc->method_imp;
9996 alloc->method_imp = (IMP) &Alloc_;*/
9998 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
9999 dealloc_ = dealloc->method_imp;
10000 dealloc->method_imp = (IMP) &Dealloc_;*/
10002 /* System Information {{{ */
10006 size = sizeof(maxproc);
10007 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10008 perror("sysctlbyname(\"kern.maxproc\", ?)");
10009 else if (maxproc < 64) {
10011 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10012 perror("sysctlbyname(\"kern.maxproc\", #)");
10015 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10016 char *osversion = new char[size];
10017 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10018 perror("sysctlbyname(\"kern.osversion\", ?)");
10020 System_ = [NSString stringWithUTF8String:osversion];
10022 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10023 char *machine = new char[size];
10024 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10025 perror("sysctlbyname(\"hw.machine\", ?)");
10027 Machine_ = machine;
10029 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
10030 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
10031 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
10032 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
10036 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
10037 NSData *data((NSData *) ecid);
10038 size_t length([data length]);
10039 uint8_t bytes[length];
10040 [data getBytes:bytes];
10041 char string[length * 2 + 1];
10042 for (size_t i(0); i != length; ++i)
10043 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
10044 ChipID_ = [NSString stringWithUTF8String:string];
10048 IOObjectRelease(service);
10052 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
10054 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
10055 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10056 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
10058 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
10059 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
10060 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
10062 if (mcc != NULL && mnc != NULL)
10063 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
10070 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
10071 Build_ = [system objectForKey:@"ProductBuildVersion"];
10072 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10073 Product_ = [info objectForKey:@"SafariProductVersion"];
10074 Safari_ = [info objectForKey:@"CFBundleVersion"];
10077 /* Load Database {{{ */
10079 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10081 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10083 if (Metadata_ == NULL)
10084 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10086 Settings_ = [Metadata_ objectForKey:@"Settings"];
10088 Packages_ = [Metadata_ objectForKey:@"Packages"];
10089 Sections_ = [Metadata_ objectForKey:@"Sections"];
10090 Sources_ = [Metadata_ objectForKey:@"Sources"];
10092 Token_ = [Metadata_ objectForKey:@"Token"];
10095 if (Settings_ != nil)
10096 Role_ = [Settings_ objectForKey:@"Role"];
10098 if (Sections_ == nil) {
10099 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10100 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10103 if (Sources_ == nil) {
10104 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10105 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10110 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10113 if (Packages_ != nil) {
10115 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10119 [Metadata_ removeObjectForKey:@"Packages"];
10125 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10127 #define MobileSubstrate_(name) \
10128 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10129 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10130 if (handle == NULL) \
10131 NSLog(@"%s", dlerror()); \
10134 MobileSubstrate_(Activator)
10135 MobileSubstrate_(libstatusbar)
10136 MobileSubstrate_(SimulatedKeyEvents)
10137 MobileSubstrate_(WinterBoard)
10139 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10140 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10142 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10144 if (access("/tmp/.cydia.fw", F_OK) == 0) {
10145 unlink("/tmp/.cydia.fw");
10147 } else if (access("/User", F_OK) != 0 || version < 4) {
10150 system("/usr/libexec/cydia/firmware.sh");
10154 _assert([[NSFileManager defaultManager]
10155 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10156 withIntermediateDirectories:YES
10161 if (access("/tmp/cydia.chk", F_OK) == 0) {
10162 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10163 _assert(errno == ENOENT);
10164 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10165 _assert(errno == ENOENT);
10168 /* APT Initialization {{{ */
10169 _assert(pkgInitConfig(*_config));
10170 _assert(pkgInitSystem(*_config, _system));
10173 _config->Set("APT::Acquire::Translation", lang);
10175 // XXX: this timeout might be important :(
10176 //_config->Set("Acquire::http::Timeout", 15);
10178 _config->Set("Acquire::http::MaxParallel", 3);
10180 /* Color Choices {{{ */
10181 space_ = CGColorSpaceCreateDeviceRGB();
10183 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10184 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10185 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10186 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10187 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10188 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10189 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10190 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10191 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10193 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10194 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10196 /* UIKit Configuration {{{ */
10197 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
10198 if ($GSFontSetUseLegacyFontMetrics != NULL)
10199 $GSFontSetUseLegacyFontMetrics(YES);
10201 // XXX: I have a feeling this was important
10202 //UIKeyboardDisableAutomaticAppearance();
10205 Colon_ = UCLocalize("COLON_DELIMITED");
10206 Elision_ = UCLocalize("ELISION");
10207 Error_ = UCLocalize("ERROR");
10208 Warning_ = UCLocalize("WARNING");
10211 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10213 CGColorSpaceRelease(space_);
10214 CFRelease(Locale_);