1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2015 Jay Freeman (saurik)
5 /* GNU General Public License, Version 3 {{{ */
7 * Cydia is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published
9 * by the Free Software Foundation, either version 3 of the License,
10 * or (at your option) any later version.
12 * Cydia is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Cydia. If not, see <http://www.gnu.org/licenses/>.
22 // XXX: wtf/FastMalloc.h... wtf?
23 #define USE_SYSTEM_MALLOC 1
25 /* #include Directives {{{ */
26 #include "CyteKit/UCPlatform.h"
27 #include "CyteKit/Localize.h"
29 #include <unicode/ustring.h>
30 #include <unicode/utrans.h>
32 #include <objc/objc.h>
33 #include <objc/runtime.h>
35 #include <CoreGraphics/CoreGraphics.h>
36 #include <Foundation/Foundation.h>
39 #define DEPLOYMENT_TARGET_MACOSX 1
40 #define CF_BUILDING_CF 1
41 #include <CoreFoundation/CFInternal.h>
44 #include <CoreFoundation/CFUniChar.h>
46 #include <SystemConfiguration/SystemConfiguration.h>
48 #include <UIKit/UIKit.h>
49 #include "iPhonePrivate.h"
51 #include <IOKit/IOKitLib.h>
53 #include <QuartzCore/CALayer.h>
55 #include <WebCore/WebCoreThread.h>
56 #include <WebKit/DOMHTMLIFrameElement.h>
64 #include <ext/stdio_filebuf.h>
68 #include <apt-pkg/acquire.h>
69 #include <apt-pkg/acquire-item.h>
70 #include <apt-pkg/algorithms.h>
71 #include <apt-pkg/cachefile.h>
72 #include <apt-pkg/clean.h>
73 #include <apt-pkg/configuration.h>
74 #include <apt-pkg/debindexfile.h>
75 #include <apt-pkg/debmetaindex.h>
76 #include <apt-pkg/error.h>
77 #include <apt-pkg/init.h>
78 #include <apt-pkg/mmap.h>
79 #include <apt-pkg/pkgrecords.h>
80 #include <apt-pkg/sha1.h>
81 #include <apt-pkg/sourcelist.h>
82 #include <apt-pkg/sptr.h>
83 #include <apt-pkg/strutl.h>
84 #include <apt-pkg/tagfile.h>
86 #include <sys/types.h>
88 #include <sys/sysctl.h>
89 #include <sys/param.h>
90 #include <sys/mount.h>
91 #include <sys/reboot.h>
98 #include <mach-o/nlist.h>
107 #include <Cytore.hpp>
110 #include "Substrate.hpp"
111 #include "Menes/Menes.h"
113 #include "CyteKit/IndirectDelegate.h"
114 #include "CyteKit/RegEx.hpp"
115 #include "CyteKit/TableViewCell.h"
116 #include "CyteKit/TabBarController.h"
117 #include "CyteKit/WebScriptObject-Cyte.h"
118 #include "CyteKit/WebViewController.h"
119 #include "CyteKit/WebViewTableViewCell.h"
120 #include "CyteKit/stringWithUTF8Bytes.h"
122 #include "Cydia/MIMEAddress.h"
123 #include "Cydia/LoadingViewController.h"
124 #include "Cydia/ProgressEvent.h"
126 #include "SDURLCache/SDURLCache.h"
133 #define _timestamp ({ \
135 gettimeofday(&tv, NULL); \
136 tv.tv_sec * 1000000 + tv.tv_usec; \
139 typedef std::vector<class ProfileTime *> TimeList;
149 ProfileTime(const char *name) :
153 times_.push_back(this);
156 void AddTime(uint64_t time) {
163 std::cerr << std::setw(7) << count_ << ", " << std::setw(8) << total_ << " : " << name_ << std::endl;
175 ProfileTimer(ProfileTime &time) :
182 time_.AddTime(_timestamp - start_);
187 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
189 std::cerr << "========" << std::endl;
192 #define _profile(name) { \
193 static ProfileTime name(#name); \
194 ProfileTimer _ ## name(name);
199 // XXX: I hate clang. Apple: please get over your petty hatred of GPL and fix your gcc fork
200 #define synchronized(lock) \
201 synchronized(static_cast<NSObject *>(lock))
203 extern NSString *Cydia_;
205 #define lprintf(args...) fprintf(stderr, args)
208 #define TraceLogging (1 && !ForRelease)
209 #define HistogramInsertionSort (0 && !ForRelease)
210 #define ProfileTimes (0 && !ForRelease)
211 #define ForSaurik (0 && !ForRelease)
212 #define LogBrowser (0 && !ForRelease)
213 #define TrackResize (0 && !ForRelease)
214 #define ManualRefresh (1 && !ForRelease)
215 #define ShowInternals (0 && !ForRelease)
216 #define AlwaysReload (0 && !ForRelease)
220 #define _trace(args...)
225 #define _profile(name) {
228 #define PrintTimes() do {} while (false)
231 // Hash Functions/Structures {{{
232 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
240 static NSString *Colon_;
242 static NSString *Error_;
243 static NSString *Warning_;
245 static NSString *Cache_;
246 #define Cache(file) \
247 [NSString stringWithFormat:@"%@/%s", Cache_, file]
249 static void (*$SBSSetInterceptsMenuButtonForever)(bool);
251 static CFStringRef (*$MGCopyAnswer)(CFStringRef);
253 static NSString *UniqueIdentifier(UIDevice *device = nil) {
254 if (kCFCoreFoundationVersionNumber < 800) // iOS 7.x
255 return [device ?: [UIDevice currentDevice] uniqueIdentifier];
257 return [(id)$MGCopyAnswer(CFSTR("UniqueDeviceID")) autorelease];
260 static bool IsReachable(const char *name) {
261 SCNetworkReachabilityFlags flags; {
262 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, name));
263 SCNetworkReachabilityGetFlags(reachability, &flags);
264 CFRelease(reachability);
267 // XXX: this elaborate mess is what Apple is using to determine this? :(
268 // XXX: do we care if the user has to intervene? maybe that's ok?
270 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
271 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
272 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
273 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
274 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
275 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
280 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
282 static _finline NSString *CydiaURL(NSString *path) {
284 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
285 page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
286 page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
287 page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
288 page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
290 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
293 static NSString *ShellEscape(NSString *value) {
294 return [NSString stringWithFormat:@"'%@'", [value stringByReplacingOccurrencesOfString:@"'" withString:@"'\\''"]];
297 static _finline void UpdateExternalStatus(uint64_t newStatus) {
299 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
300 notify_set_state(notify_token, newStatus);
301 notify_cancel(notify_token);
303 notify_post("com.saurik.Cydia.status");
306 static CGFloat CYStatusBarHeight() {
307 CGSize size([[UIApplication sharedApplication] statusBarFrame].size);
308 return UIInterfaceOrientationIsPortrait([[UIApplication sharedApplication] statusBarOrientation]) ? size.height : size.width;
311 /* NSForcedOrderingSearch doesn't work on the iPhone */
312 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
313 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
314 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
316 /* Insertion Sort {{{ */
318 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
319 const char *ptr = (const char *)list;
321 CFIndex half = count / 2;
322 const char *probe = ptr + elementSize * half;
323 CFComparisonResult cr = comparator(element, probe, context);
324 if (0 == cr) return (probe - (const char *)list) / elementSize;
325 ptr = (cr < 0) ? ptr : probe + elementSize;
326 count = (cr < 0) ? half : (half + (count & 1) - 1);
328 return (ptr - (const char *)list) / elementSize;
331 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
332 const char *ptr = (const char *)list;
334 CFIndex half = count / 2;
335 const char *probe = ptr + elementSize * half;
336 CFComparisonResult cr = comparator(element, probe, context);
337 if (0 == cr) return (probe - (const char *)list) / elementSize;
338 ptr = (cr < 0) ? ptr : probe + elementSize;
339 count = (cr < 0) ? half : (half + (count & 1) - 1);
341 return (ptr - (const char *)list) / elementSize;
344 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
345 if (range.length == 0)
347 const void **values(new const void *[range.length]);
348 CFArrayGetValues(array, range, values);
350 #if HistogramInsertionSort > 0
351 uint32_t total(0), *offsets(new uint32_t[range.length]);
354 for (CFIndex index(1); index != range.length; ++index) {
355 const void *value(values[index]);
356 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
357 CFIndex correct(index);
358 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
359 #if HistogramInsertionSort > 1
360 NSLog(@"%@ < %@", value, values[correct - 1]);
365 if (correct != index) {
366 size_t offset(index - correct);
367 #if HistogramInsertionSort
371 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
373 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
374 values[correct] = value;
378 CFArrayReplaceValues(array, range, values, range.length);
381 #if HistogramInsertionSort > 0
382 for (CFIndex index(0); index != range.length; ++index)
383 if (offsets[index] != 0)
384 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
385 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
392 /* Apple Bug Fixes {{{ */
393 @implementation UIWebDocumentView (Cydia)
395 - (void) _setScrollerOffset:(CGPoint)offset {
396 UIScroller *scroller([self _scroller]);
398 CGSize size([scroller contentSize]);
399 CGSize bounds([scroller bounds].size);
402 max.x = size.width - bounds.width;
403 max.y = size.height - bounds.height;
411 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
412 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
414 [scroller setOffset:offset];
420 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
421 size_t length([self length] - state->state);
424 else if (length > count)
426 for (size_t i(0); i != length; ++i)
427 objects[i] = [self item:state->state++];
428 state->itemsPtr = objects;
429 state->mutationsPtr = (unsigned long *) self;
433 /* Cydia NSString Additions {{{ */
434 @interface NSString (Cydia)
435 - (NSComparisonResult) compareByPath:(NSString *)other;
436 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
439 @implementation NSString (Cydia)
441 - (NSComparisonResult) compareByPath:(NSString *)other {
442 NSString *prefix = [self commonPrefixWithString:other options:0];
443 size_t length = [prefix length];
445 NSRange lrange = NSMakeRange(length, [self length] - length);
446 NSRange rrange = NSMakeRange(length, [other length] - length);
448 lrange = [self rangeOfString:@"/" options:0 range:lrange];
449 rrange = [other rangeOfString:@"/" options:0 range:rrange];
451 NSComparisonResult value;
453 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
454 value = NSOrderedSame;
455 else if (lrange.location == NSNotFound)
456 value = NSOrderedAscending;
457 else if (rrange.location == NSNotFound)
458 value = NSOrderedDescending;
460 value = NSOrderedSame;
462 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
463 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
464 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
465 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
467 NSComparisonResult result = [lpath compare:rpath];
468 return result == NSOrderedSame ? value : result;
471 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
472 return [(id)CFURLCreateStringByAddingPercentEscapes(
477 kCFStringEncodingUTF8
484 /* C++ NSString Wrapper Cache {{{ */
485 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
486 return size == 0 ? NULL :
487 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
488 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
491 static _finline CFStringRef CYStringCreate(const char *data) {
492 return CYStringCreate(data, strlen(data));
501 _finline void clear_() {
502 if (cache_ != NULL) {
509 _finline bool empty() const {
513 _finline size_t size() const {
517 _finline char *data() const {
521 _finline void clear() {
526 _finline CYString() :
533 _finline ~CYString() {
537 void operator =(const CYString &rhs) {
541 if (rhs.cache_ == nil)
544 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
547 void copy(CYPool *pool) {
548 char *temp(pool->malloc<char>(size_ + 1));
549 memcpy(temp, data_, size_);
554 void set(CYPool *pool, const char *data, size_t size) {
560 data_ = const_cast<char *>(data);
568 _finline void set(CYPool *pool, const char *data) {
569 set(pool, data, data == NULL ? 0 : strlen(data));
572 _finline void set(CYPool *pool, const std::string &rhs) {
573 set(pool, rhs.data(), rhs.size());
576 bool operator ==(const CYString &rhs) const {
577 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
580 _finline operator CFStringRef() {
582 cache_ = CYStringCreate(data_, size_);
586 _finline operator id() {
587 return (NSString *) static_cast<CFStringRef>(*this);
590 _finline operator const char *() {
591 return reinterpret_cast<const char *>(data_);
595 /* C++ NSString Algorithm Adapters {{{ */
597 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
600 struct NSStringMapHash :
601 std::unary_function<NSString *, size_t>
603 _finline size_t operator ()(NSString *value) const {
604 return CFStringHashNSString((CFStringRef) value);
608 struct NSStringMapLess :
609 std::binary_function<NSString *, NSString *, bool>
611 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
612 return [lhs compare:rhs] == NSOrderedAscending;
616 struct NSStringMapEqual :
617 std::binary_function<NSString *, NSString *, bool>
619 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
620 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
621 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
622 //[lhs isEqualToString:rhs];
627 /* CoreGraphics Primitives {{{ */
632 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
633 CGFloat color[] = {red, green, blue, alpha};
634 return CGColorCreate(space, color);
643 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
644 color_(Create_(space, red, green, blue, alpha))
646 Set(space, red, green, blue, alpha);
651 CGColorRelease(color_);
658 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
660 color_ = Create_(space, red, green, blue, alpha);
663 operator CGColorRef() {
669 /* Random Global Variables {{{ */
670 static int PulseInterval_ = 500000;
672 static const NSString *UI_;
675 static bool RestartSubstrate_;
676 static NSArray *Finishes_;
678 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
679 #define NotifyConfig_ "/etc/notify.conf"
681 static bool Queuing_;
683 static CYColor Blue_;
684 static CYColor Blueish_;
685 static CYColor Black_;
686 static CYColor Folder_;
688 static CYColor White_;
689 static CYColor Gray_;
690 static CYColor Green_;
691 static CYColor Purple_;
692 static CYColor Purplish_;
694 static UIColor *InstallingColor_;
695 static UIColor *RemovingColor_;
697 static NSString *App_;
699 static BOOL Advanced_;
700 static BOOL Ignored_;
702 static _H<UIFont> Font12_;
703 static _H<UIFont> Font12Bold_;
704 static _H<UIFont> Font14_;
705 static _H<UIFont> Font18_;
706 static _H<UIFont> Font18Bold_;
707 static _H<UIFont> Font22Bold_;
709 static const char *Machine_ = NULL;
710 static _H<NSString> System_;
711 static NSString *SerialNumber_ = nil;
712 static NSString *ChipID_ = nil;
713 static NSString *BBSNum_ = nil;
714 static _H<NSString> UniqueID_;
715 static _H<NSString> UserAgent_;
716 static _H<NSString> Product_;
717 static _H<NSString> Safari_;
719 static _H<NSLocale> CollationLocale_;
720 static _H<NSArray> CollationThumbs_;
721 static std::vector<NSInteger> CollationOffset_;
722 static _H<NSArray> CollationTitles_;
723 static _H<NSArray> CollationStarts_;
724 static UTransliterator *CollationTransl_;
725 //static Function<NSString *, NSString *> CollationModify_;
727 typedef std::basic_string<UChar> ustring;
728 static ustring CollationString_;
730 #define CUC const ustring &str(*reinterpret_cast<const ustring *>(rep))
731 #define UC ustring &str(*reinterpret_cast<ustring *>(rep))
732 static struct UReplaceableCallbacks CollationUCalls_ = {
733 .length = [](const UReplaceable *rep) -> int32_t { CUC;
737 .charAt = [](const UReplaceable *rep, int32_t offset) -> UChar { CUC;
738 //fprintf(stderr, "charAt(%d) : %d\n", offset, str.size());
739 if (offset >= str.size())
744 .char32At = [](const UReplaceable *rep, int32_t offset) -> UChar32 { CUC;
745 //fprintf(stderr, "char32At(%d) : %d\n", offset, str.size());
746 if (offset >= str.size())
749 U16_GET(str.data(), 0, offset, str.size(), c);
753 .replace = [](UReplaceable *rep, int32_t start, int32_t limit, const UChar *text, int32_t length) -> void { UC;
754 //fprintf(stderr, "replace(%d, %d, %d) : %d\n", start, limit, length, str.size());
755 str.replace(start, limit - start, text, length);
758 .extract = [](UReplaceable *rep, int32_t start, int32_t limit, UChar *dst) -> void { UC;
759 //fprintf(stderr, "extract(%d, %d) : %d\n", start, limit, str.size());
760 str.copy(dst, limit - start, start);
763 .copy = [](UReplaceable *rep, int32_t start, int32_t limit, int32_t dest) -> void { UC;
764 //fprintf(stderr, "copy(%d, %d, %d) : %d\n", start, limit, dest, str.size());
765 str.replace(dest, 0, str, start, limit - start);
769 static CFLocaleRef Locale_;
770 static NSArray *Languages_;
771 static CGColorSpaceRef space_;
773 #define CacheState_ "/var/mobile/Library/Caches/com.saurik.Cydia/CacheState.plist"
774 #define SavedState_ "/var/mobile/Library/Caches/com.saurik.Cydia/SavedState.plist"
776 static NSDictionary *SectionMap_;
777 static _H<NSDate> Backgrounded_;
778 static _transient NSMutableDictionary *Values_;
779 static _transient NSMutableDictionary *Sections_;
780 _H<NSMutableDictionary> Sources_;
781 static _transient NSNumber *Version_;
785 CGFloat ScreenScale_;
786 static NSString *Idiom_;
787 static _H<NSString> Firmware_;
788 static NSString *Major_;
790 static _H<NSMutableDictionary> SessionData_;
791 static _H<NSObject> HostConfig_;
792 static _H<NSMutableSet> BridgedHosts_;
793 static _H<NSMutableSet> InsecureHosts_;
794 static _H<NSMutableSet> PipelinedHosts_;
795 static _H<NSMutableSet> CachedURLs_;
797 static NSString *kCydiaProgressEventTypeError = @"Error";
798 static NSString *kCydiaProgressEventTypeInformation = @"Information";
799 static NSString *kCydiaProgressEventTypeStatus = @"Status";
800 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
803 /* Display Helpers {{{ */
804 inline float Interpolate(float begin, float end, float fraction) {
805 return (end - begin) * fraction + begin;
808 static inline double Retina(double value) {
809 value *= ScreenScale_;
810 value = round(value);
811 value /= ScreenScale_;
815 static inline CGRect Retina(CGRect value) {
816 value.origin.x *= ScreenScale_;
817 value.origin.y *= ScreenScale_;
818 value.size.width *= ScreenScale_;
819 value.size.height *= ScreenScale_;
820 value = CGRectIntegral(value);
821 value.origin.x /= ScreenScale_;
822 value.origin.y /= ScreenScale_;
823 value.size.width /= ScreenScale_;
824 value.size.height /= ScreenScale_;
828 static _finline const char *StripVersion_(const char *version) {
829 const char *colon(strchr(version, ':'));
830 return colon == NULL ? version : colon + 1;
833 NSString *LocalizeSection(NSString *section) {
834 static RegEx title_r("(.*?) \\((.*)\\)");
835 if (title_r(section)) {
836 NSString *parent(title_r[1]);
837 NSString *child(title_r[2]);
839 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
840 LocalizeSection(parent),
841 LocalizeSection(child)
845 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
848 NSString *Simplify(NSString *title) {
849 const char *data = [title UTF8String];
850 size_t size = [title lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
852 static RegEx square_r("\\[(.*)\\]");
853 if (square_r(data, size))
854 return Simplify(square_r[1]);
856 static RegEx paren_r("\\((.*)\\)");
857 if (paren_r(data, size))
858 return Simplify(paren_r[1]);
860 static RegEx title_r("(.*?) \\((.*)\\)");
861 if (title_r(data, size))
862 return Simplify(title_r[1]);
868 bool isSectionVisible(NSString *section) {
869 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
870 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
871 return hidden == nil || ![hidden boolValue];
874 static NSObject *CYIOGetValue(const char *path, NSString *property) {
875 io_registry_entry_t entry(IORegistryEntryFromPath(kIOMasterPortDefault, path));
876 if (entry == MACH_PORT_NULL)
879 CFTypeRef value(IORegistryEntryCreateCFProperty(entry, (CFStringRef) property, kCFAllocatorDefault, 0));
880 IOObjectRelease(entry);
884 return [(id) value autorelease];
887 static NSString *CYHex(NSData *data, bool reverse = false) {
891 size_t length([data length]);
892 uint8_t bytes[length];
893 [data getBytes:bytes];
895 char string[length * 2 + 1];
896 for (size_t i(0); i != length; ++i)
897 sprintf(string + i * 2, "%.2x", bytes[reverse ? length - i - 1 : i]);
899 return [NSString stringWithUTF8String:string];
902 static NSString *VerifySource(NSString *href) {
903 static RegEx href_r("(http(s?)://|file:///)[^# ]*");
905 [[[[UIAlertView alloc]
906 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("INVALID_URL")]
907 message:UCLocalize("INVALID_URL_EX")
909 cancelButtonTitle:UCLocalize("OK")
910 otherButtonTitles:nil
911 ] autorelease] show];
916 if (![href hasSuffix:@"/"])
917 href = [href stringByAppendingString:@"/"];
923 /* Delegate Prototypes {{{ */
926 @class CydiaProgressEvent;
928 @protocol DatabaseDelegate
929 - (void) repairWithSelector:(SEL)selector;
930 - (void) setConfigurationData:(NSString *)data;
931 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
934 @class CYPackageController;
936 @protocol SourceDelegate
937 - (void) setFetch:(NSNumber *)fetch;
940 @protocol FetchDelegate
941 - (bool) isSourceCancelled;
942 - (void) startSourceFetch:(NSString *)uri;
943 - (void) stopSourceFetch:(NSString *)uri;
946 @protocol CydiaDelegate
947 - (void) returnToCydia;
949 - (void) retainNetworkActivityIndicator;
950 - (void) releaseNetworkActivityIndicator;
951 - (void) clearPackage:(Package *)package;
952 - (void) installPackage:(Package *)package;
953 - (void) installPackages:(NSArray *)packages;
954 - (void) removePackage:(Package *)package;
955 - (void) beginUpdate;
957 - (bool) requestUpdate;
958 - (void) distUpgrade;
961 - (void) _saveConfig;
963 - (void) addSource:(NSDictionary *)source;
964 - (BOOL) addTrivialSource:(NSString *)href;
965 - (UIProgressHUD *) addProgressHUD;
966 - (void) removeProgressHUD:(UIProgressHUD *)hud;
967 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
968 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
972 /* CancelStatus {{{ */
974 public pkgAcquireStatus
985 virtual bool MediaChange(std::string media, std::string drive) {
989 virtual void IMSHit(pkgAcquire::ItemDesc &desc) {
993 virtual bool Pulse_(pkgAcquire *Owner) = 0;
995 virtual bool Pulse(pkgAcquire *Owner) {
996 if (pkgAcquireStatus::Pulse(Owner) && Pulse_(Owner))
1004 _finline bool WasCancelled() const {
1009 /* DelegateStatus {{{ */
1014 _transient NSObject<ProgressDelegate> *delegate_;
1022 void setDelegate(NSObject<ProgressDelegate> *delegate) {
1023 delegate_ = delegate;
1026 virtual void Fetch(pkgAcquire::ItemDesc &desc) {
1027 NSString *name([NSString stringWithUTF8String:desc.ShortDesc.c_str()]);
1028 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItemDesc:desc]);
1029 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1032 virtual void Done(pkgAcquire::ItemDesc &desc) {
1033 NSString *name([NSString stringWithUTF8String:desc.ShortDesc.c_str()]);
1034 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:Colon_, UCLocalize("DONE"), name] ofType:kCydiaProgressEventTypeStatus forItemDesc:desc]);
1035 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1038 virtual void Fail(pkgAcquire::ItemDesc &desc) {
1040 desc.Owner->Status == pkgAcquire::Item::StatIdle ||
1041 desc.Owner->Status == pkgAcquire::Item::StatDone
1045 std::string &error(desc.Owner->ErrorText);
1049 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItemDesc:desc]);
1050 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1053 virtual bool Pulse_(pkgAcquire *Owner) {
1055 double(CurrentBytes + CurrentItems) /
1056 double(TotalBytes + TotalItems)
1059 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
1060 [NSNumber numberWithDouble:percent], @"Percent",
1062 [NSNumber numberWithDouble:CurrentBytes], @"Current",
1063 [NSNumber numberWithDouble:TotalBytes], @"Total",
1064 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
1065 nil] waitUntilDone:YES];
1067 return ![delegate_ isProgressCancelled];
1070 virtual void Start() {
1071 pkgAcquireStatus::Start();
1072 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
1075 virtual void Stop() {
1076 pkgAcquireStatus::Stop();
1077 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
1078 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
1082 /* Database Interface {{{ */
1083 typedef std::map< unsigned long, _H<Source> > SourceMap;
1085 @interface Database : NSObject {
1092 pkgCacheFile cache_;
1093 pkgDepCache::Policy *policy_;
1094 pkgRecords *records_;
1095 pkgProblemResolver *resolver_;
1096 pkgAcquire *fetcher_;
1098 SPtr<pkgPackageManager> manager_;
1099 pkgSourceList *list_;
1101 SourceMap sourceMap_;
1102 _H<NSMutableArray> sourceList_;
1104 CFMutableArrayRef packages_;
1106 _transient NSObject<DatabaseDelegate> *delegate_;
1107 _transient NSObject<ProgressDelegate> *progress_;
1109 CydiaStatus status_;
1115 std::map<const char *, _H<NSString> > sections_;
1118 + (Database *) sharedInstance;
1121 - (void) _readCydia:(NSNumber *)fd;
1122 - (void) _readStatus:(NSNumber *)fd;
1123 - (void) _readOutput:(NSNumber *)fd;
1127 - (Package *) packageWithName:(NSString *)name;
1129 - (pkgCacheFile &) cache;
1130 - (pkgDepCache::Policy *) policy;
1131 - (pkgRecords *) records;
1132 - (pkgProblemResolver *) resolver;
1133 - (pkgAcquire &) fetcher;
1134 - (pkgSourceList &) list;
1135 - (NSArray *) packages;
1136 - (NSArray *) sources;
1137 - (Source *) sourceWithKey:(NSString *)key;
1138 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1146 - (void) updateWithStatus:(CancelStatus &)status;
1148 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1150 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1151 - (NSObject<ProgressDelegate> *) progressDelegate;
1153 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1154 - (void) setFetch:(bool)fetch forURI:(const char *)uri;
1155 - (void) resetFetch;
1157 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1161 /* SourceStatus {{{ */
1162 class SourceStatus :
1166 _transient NSObject<FetchDelegate> *delegate_;
1167 _transient Database *database_;
1168 std::set<std::string> fetches_;
1171 SourceStatus(NSObject<FetchDelegate> *delegate, Database *database) :
1172 delegate_(delegate),
1177 void Set(bool fetch, const std::string &uri) {
1179 if (!fetches_.insert(uri).second)
1182 if (fetches_.erase(uri) == 0)
1186 //printf("Set(%s, %s)\n", fetch ? "true" : "false", uri.c_str());
1187 [database_ setFetch:fetch forURI:uri.c_str()];
1190 _finline void Set(bool fetch, pkgAcquire::Item *item) {
1191 /*unsigned long ID(fetch ? 1 : 0);
1195 Set(fetch, item->DescURI());
1198 void Log(const char *tag, pkgAcquire::Item *item) {
1199 //printf("%s(%s) S:%u Q:%u\n", tag, item->DescURI().c_str(), item->Status, item->QueueCounter);
1202 virtual void Fetch(pkgAcquire::ItemDesc &desc) {
1203 Log("Fetch", desc.Owner);
1204 Set(true, desc.Owner);
1207 virtual void Done(pkgAcquire::ItemDesc &desc) {
1208 Log("Done", desc.Owner);
1209 Set(false, desc.Owner);
1212 virtual void Fail(pkgAcquire::ItemDesc &desc) {
1213 Log("Fail", desc.Owner);
1214 Set(false, desc.Owner);
1217 virtual bool Pulse_(pkgAcquire *Owner) {
1218 std::set<std::string> fetches;
1219 for (pkgAcquire::ItemCIterator item(Owner->ItemsBegin()); item != Owner->ItemsEnd(); ++item) {
1221 if ((*item)->QueueCounter == 0)
1223 else switch ((*item)->Status) {
1224 case pkgAcquire::Item::StatFetching:
1225 fetches.insert((*item)->DescURI());
1234 Log(fetch ? "Pulse<true>" : "Pulse<false>", *item);
1238 std::vector<std::string> stops;
1239 std::set_difference(fetches_.begin(), fetches_.end(), fetches.begin(), fetches.end(), std::back_insert_iterator<std::vector<std::string>>(stops));
1240 for (std::vector<std::string>::const_iterator stop(stops.begin()); stop != stops.end(); ++stop) {
1241 //printf("Stop(%s)\n", stop->c_str());
1245 return ![delegate_ isSourceCancelled];
1248 virtual void Stop() {
1249 pkgAcquireStatus::Stop();
1250 [database_ resetFetch];
1254 /* ProgressEvent Implementation {{{ */
1255 @implementation CydiaProgressEvent
1257 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1258 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1261 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1262 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1263 [event setPackage:package];
1267 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItemDesc:(pkgAcquire::ItemDesc &)desc {
1268 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1270 NSString *description([NSString stringWithUTF8String:desc.Description.c_str()]);
1271 NSArray *fields([description componentsSeparatedByString:@" "]);
1272 [event setItem:fields];
1274 if ([fields count] > 3) {
1275 [event setPackage:[fields objectAtIndex:2]];
1276 [event setVersion:[fields objectAtIndex:3]];
1279 [event setURL:[NSString stringWithUTF8String:desc.URI.c_str()]];
1284 + (NSArray *) _attributeKeys {
1285 return [NSArray arrayWithObjects:
1295 - (NSArray *) attributeKeys {
1296 return [[self class] _attributeKeys];
1299 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1300 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1303 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1304 if ((self = [super init]) != nil) {
1310 - (NSString *) message {
1314 - (NSString *) type {
1318 - (NSArray *) item {
1319 return (id) item_ ?: [NSNull null];
1322 - (void) setItem:(NSArray *)item {
1326 - (NSString *) package {
1327 return (id) package_ ?: [NSNull null];
1330 - (void) setPackage:(NSString *)package {
1334 - (NSString *) url {
1335 return (id) url_ ?: [NSNull null];
1338 - (void) setURL:(NSString *)url {
1342 - (void) setVersion:(NSString *)version {
1346 - (NSString *) version {
1347 return (id) version_ ?: [NSNull null];
1350 - (NSString *) compound:(NSString *)value {
1352 NSString *mode(nil); {
1353 NSString *type([self type]);
1354 if ([type isEqualToString:kCydiaProgressEventTypeError])
1355 mode = UCLocalize("ERROR");
1356 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1357 mode = UCLocalize("WARNING");
1361 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1367 - (NSString *) compoundMessage {
1368 return [self compound:[self message]];
1371 - (NSString *) compoundTitle {
1374 if (package_ == nil)
1376 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1377 title = [package name];
1381 return [self compound:title];
1387 // Cytore Definitions {{{
1388 struct PackageValue :
1391 Cytore::Offset<PackageValue> next_;
1393 uint32_t index_ : 23;
1394 uint32_t subscribed_ : 1;
1411 Cytore::Offset<PackageValue> packages_[1 << 16];
1414 static Cytore::File<MetaValue> MetaFile_;
1416 // Cytore Helper Functions {{{
1417 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1418 SplitHash nhash = { hashlittle(name, length) };
1420 PackageValue *metadata;
1422 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1423 for (;; offset = &metadata->next_) { if (offset->IsNull()) {
1424 *offset = MetaFile_.New<PackageValue>(length + 1);
1425 metadata = &MetaFile_.Get(*offset);
1427 if (metadata == NULL) {
1431 metadata = new PackageValue();
1432 memset(metadata, 0, sizeof(*metadata));
1435 memcpy(metadata->name_, name, length);
1436 metadata->name_[length] = '\0';
1437 metadata->nhash_ = nhash.u16[1];
1439 metadata = &MetaFile_.Get(*offset);
1440 if (metadata->nhash_ != nhash.u16[1])
1442 if (strncmp(metadata->name_, name, length) != 0)
1444 if (metadata->name_[length] != '\0')
1451 static void PackageImport(const void *key, const void *value, void *context) {
1452 bool &fail(*reinterpret_cast<bool *>(context));
1455 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1456 NSLog(@"failed to import package %@", key);
1460 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1461 NSDictionary *package((NSDictionary *) value);
1463 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1464 if ([subscribed boolValue] && !metadata->subscribed_)
1465 metadata->subscribed_ = true;
1467 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1468 time_t time([date timeIntervalSince1970]);
1469 if (metadata->first_ > time || metadata->first_ == 0)
1470 metadata->first_ = time;
1473 NSDate *date([package objectForKey:@"LastSeen"]);
1474 NSString *version([package objectForKey:@"LastVersion"]);
1476 if (date != nil && version != nil) {
1477 time_t time([date timeIntervalSince1970]);
1478 if (metadata->last_ < time || metadata->last_ == 0)
1479 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1480 size_t length(strlen(buffer));
1481 uint16_t vhash(hashlittle(buffer, length));
1483 size_t capped(std::min<size_t>(8, length));
1484 char *latest(buffer + length - capped);
1486 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1487 metadata->vhash_ = vhash;
1489 metadata->last_ = time;
1495 static NSDate *GetStatusDate() {
1496 return [[[NSFileManager defaultManager] attributesOfItemAtPath:@"/var/lib/dpkg/status" error:NULL] fileModificationDate];
1499 static void SaveConfig(NSObject *lock) {
1500 @synchronized (lock) {
1506 CFPreferencesSetMultiple((CFDictionaryRef) [NSDictionary dictionaryWithObjectsAndKeys:
1507 Values_, @"CydiaValues",
1508 Sections_, @"CydiaSections",
1509 (id) Sources_, @"CydiaSources",
1510 Version_, @"CydiaVersion",
1511 nil], NULL, CFSTR("com.saurik.Cydia"), kCFPreferencesCurrentUser, kCFPreferencesCurrentHost);
1513 if (!CFPreferencesAppSynchronize(CFSTR("com.saurik.Cydia")))
1514 NSLog(@"CFPreferencesAppSynchronize(com.saurik.Cydia) == false");
1516 CydiaWriteSources();
1519 /* Source Class {{{ */
1520 @interface Source : NSObject {
1522 Database *database_;
1525 CYString depiction_;
1526 CYString description_;
1532 CYString distribution_;
1538 _H<NSString> authority_;
1540 CYString defaultIcon_;
1542 _H<NSMutableDictionary> record_;
1545 std::set<std::string> fetches_;
1546 std::set<std::string> files_;
1547 _transient NSObject<SourceDelegate> *delegate_;
1550 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(CYPool *)pool;
1552 - (NSComparisonResult) compareByName:(Source *)source;
1554 - (NSString *) depictionForPackage:(NSString *)package;
1555 - (NSString *) supportForPackage:(NSString *)package;
1557 - (metaIndex *) metaIndex;
1558 - (NSDictionary *) record;
1561 - (NSString *) rooturi;
1562 - (NSString *) distribution;
1563 - (NSString *) type;
1566 - (NSString *) host;
1568 - (NSString *) name;
1569 - (NSString *) shortDescription;
1570 - (NSString *) label;
1571 - (NSString *) origin;
1572 - (NSString *) version;
1574 - (NSString *) defaultIcon;
1575 - (NSURL *) iconURL;
1577 - (void) setFetch:(bool)fetch forURI:(const char *)uri;
1578 - (void) resetFetch;
1582 @implementation Source
1584 + (NSString *) webScriptNameForSelector:(SEL)selector {
1586 else if (selector == @selector(addSection:))
1587 return @"addSection";
1588 else if (selector == @selector(getField:))
1590 else if (selector == @selector(removeSection:))
1591 return @"removeSection";
1592 else if (selector == @selector(remove))
1598 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1599 return [self webScriptNameForSelector:selector] == nil;
1602 + (NSArray *) _attributeKeys {
1603 return [NSArray arrayWithObjects:
1614 @"shortDescription",
1621 - (NSArray *) attributeKeys {
1622 return [[self class] _attributeKeys];
1625 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1626 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1629 - (metaIndex *) metaIndex {
1633 - (void) setMetaIndex:(metaIndex *)index inPool:(CYPool *)pool {
1634 trusted_ = index->IsTrusted();
1636 uri_.set(pool, index->GetURI());
1637 distribution_.set(pool, index->GetDist());
1638 type_.set(pool, index->GetType());
1640 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1641 if (dindex != NULL) {
1642 std::string file(dindex->MetaIndexURI(""));
1643 base_.set(pool, file);
1646 _profile(Source$setMetaIndex$GetIndexes)
1647 dindex->GetIndexes(&acquire, true);
1649 _profile(Source$setMetaIndex$DescURI)
1650 for (pkgAcquire::ItemIterator item(acquire.ItemsBegin()); item != acquire.ItemsEnd(); item++) {
1651 std::string file((*item)->DescURI());
1652 files_.insert(file);
1653 if (file.length() < sizeof("Packages.bz2") || file.substr(file.length() - sizeof("Packages.bz2")) != "/Packages.bz2")
1655 file = file.substr(0, file.length() - 4);
1656 files_.insert(file);
1657 files_.insert(file + ".gz");
1658 files_.insert(file + "Index");
1663 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1666 pkgTagFile tags(&fd);
1668 pkgTagSection section;
1675 {"default-icon", &defaultIcon_},
1676 {"depiction", &depiction_},
1677 {"description", &description_},
1679 {"origin", &origin_},
1680 {"support", &support_},
1681 {"version", &version_},
1684 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1685 const char *start, *end;
1687 if (section.Find(names[i].name_, start, end)) {
1688 CYString &value(*names[i].value_);
1689 value.set(pool, start, end - start);
1695 record_ = [Sources_ objectForKey:[self key]];
1697 NSURL *url([NSURL URLWithString:uri_]);
1701 host_ = [host_ lowercaseString];
1706 authority_ = [url path];
1709 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(CYPool *)pool {
1710 if ((self = [super init]) != nil) {
1711 era_ = [database era];
1712 database_ = database;
1715 _profile(Source$initWithMetaIndex$setMetaIndex)
1716 [self setMetaIndex:index inPool:pool];
1721 - (NSString *) getField:(NSString *)name {
1722 @synchronized (database_) {
1723 if ([database_ era] != era_ || index_ == NULL)
1726 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index_));
1731 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly)) {
1736 pkgTagFile tags(&fd);
1738 pkgTagSection section;
1741 const char *start, *end;
1742 if (!section.Find([name UTF8String], start, end))
1743 return (NSString *) [NSNull null];
1745 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
1748 - (NSComparisonResult) compareByName:(Source *)source {
1749 NSString *lhs = [self name];
1750 NSString *rhs = [source name];
1752 if ([lhs length] != 0 && [rhs length] != 0) {
1753 unichar lhc = [lhs characterAtIndex:0];
1754 unichar rhc = [rhs characterAtIndex:0];
1756 if (isalpha(lhc) && !isalpha(rhc))
1757 return NSOrderedAscending;
1758 else if (!isalpha(lhc) && isalpha(rhc))
1759 return NSOrderedDescending;
1762 return [lhs compare:rhs options:LaxCompareOptions_];
1765 - (NSString *) depictionForPackage:(NSString *)package {
1766 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1769 - (NSString *) supportForPackage:(NSString *)package {
1770 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1773 - (NSArray *) sections {
1774 return record_ == nil ? (id) [NSNull null] : [record_ objectForKey:@"Sections"] ?: [NSArray array];
1777 - (void) _addSection:(NSString *)section {
1780 else if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) {
1781 if (![sections containsObject:section])
1782 [sections addObject:section];
1784 [record_ setObject:[NSMutableArray arrayWithObject:section] forKey:@"Sections"];
1787 - (bool) addSection:(NSString *)section {
1791 [self performSelectorOnMainThread:@selector(_addSection:) withObject:section waitUntilDone:NO];
1795 - (void) _removeSection:(NSString *)section {
1799 if (NSMutableArray *sections = [record_ objectForKey:@"Sections"])
1800 if ([sections containsObject:section])
1801 [sections removeObject:section];
1804 - (bool) removeSection:(NSString *)section {
1808 [self performSelectorOnMainThread:@selector(_removeSection:) withObject:section waitUntilDone:NO];
1813 [Sources_ removeObjectForKey:[self key]];
1817 bool value(record_ != nil);
1818 [self performSelectorOnMainThread:@selector(_remove) withObject:nil waitUntilDone:NO];
1822 - (NSDictionary *) record {
1830 - (NSString *) rooturi {
1834 - (NSString *) distribution {
1835 return distribution_;
1838 - (NSString *) type {
1842 - (NSString *) baseuri {
1843 return base_.empty() ? nil : (id) base_;
1846 - (NSString *) iconuri {
1847 if (NSString *base = [self baseuri])
1848 return [base stringByAppendingString:@"CydiaIcon.png"];
1853 - (NSURL *) iconURL {
1854 if (NSString *uri = [self iconuri])
1855 return [NSURL URLWithString:uri];
1859 - (NSString *) key {
1860 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1863 - (NSString *) host {
1867 - (NSString *) name {
1868 return origin_.empty() ? (id) authority_ : origin_;
1871 - (NSString *) shortDescription {
1872 return description_;
1875 - (NSString *) label {
1876 return label_.empty() ? (id) authority_ : label_;
1879 - (NSString *) origin {
1883 - (NSString *) version {
1887 - (NSString *) defaultIcon {
1888 return defaultIcon_;
1891 - (void) setDelegate:(NSObject<SourceDelegate> *)delegate {
1892 delegate_ = delegate;
1896 return !fetches_.empty();
1899 - (void) setFetch:(bool)fetch forURI:(const char *)uri {
1901 if (fetches_.erase(uri) == 0)
1903 } else if (files_.find(uri) == files_.end())
1905 else if (!fetches_.insert(uri).second)
1908 [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:[self fetch]] waitUntilDone:NO];
1911 - (void) resetFetch {
1913 [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:NO];
1918 /* CydiaOperation Class {{{ */
1919 @interface CydiaOperation : NSObject {
1920 _H<NSString> operator_;
1921 _H<NSString> value_;
1924 - (NSString *) operator;
1925 - (NSString *) value;
1929 @implementation CydiaOperation
1931 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1932 if ((self = [super init]) != nil) {
1933 operator_ = [NSString stringWithUTF8String:_operator];
1934 value_ = [NSString stringWithUTF8String:value];
1938 + (NSArray *) _attributeKeys {
1939 return [NSArray arrayWithObjects:
1945 - (NSArray *) attributeKeys {
1946 return [[self class] _attributeKeys];
1949 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1950 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1953 - (NSString *) operator {
1957 - (NSString *) value {
1963 /* CydiaClause Class {{{ */
1964 @interface CydiaClause : NSObject {
1965 _H<NSString> package_;
1966 _H<CydiaOperation> version_;
1969 - (NSString *) package;
1970 - (CydiaOperation *) version;
1974 @implementation CydiaClause
1976 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1977 if ((self = [super init]) != nil) {
1978 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1980 if (const char *version = dep.TargetVer())
1981 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1983 version_ = (id) [NSNull null];
1987 + (NSArray *) _attributeKeys {
1988 return [NSArray arrayWithObjects:
1994 - (NSArray *) attributeKeys {
1995 return [[self class] _attributeKeys];
1998 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1999 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2002 - (NSString *) package {
2006 - (CydiaOperation *) version {
2012 /* CydiaRelation Class {{{ */
2013 @interface CydiaRelation : NSObject {
2014 _H<NSString> relationship_;
2015 _H<NSMutableArray> clauses_;
2018 - (NSString *) relationship;
2019 - (NSArray *) clauses;
2023 @implementation CydiaRelation
2025 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
2026 if ((self = [super init]) != nil) {
2027 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
2028 clauses_ = [NSMutableArray arrayWithCapacity:8];
2030 pkgCache::DepIterator start;
2031 pkgCache::DepIterator end;
2032 dep.GlobOr(start, end); // ++dep
2035 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
2037 // yes, seriously. (wtf?)
2045 + (NSArray *) _attributeKeys {
2046 return [NSArray arrayWithObjects:
2052 - (NSArray *) attributeKeys {
2053 return [[self class] _attributeKeys];
2056 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2057 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2060 - (NSString *) relationship {
2061 return relationship_;
2064 - (NSArray *) clauses {
2068 - (void) addClause:(CydiaClause *)clause {
2069 [clauses_ addObject:clause];
2074 /* Package Class {{{ */
2075 struct ParsedPackage {
2079 CYString architecture_;
2082 CYString depiction_;
2089 @interface Package : NSObject {
2091 @public uint32_t role_ : 3;
2092 uint32_t essential_ : 1;
2093 uint32_t obsolete_ : 1;
2094 uint32_t ignored_ : 1;
2095 uint32_t pooled_ : 1;
2101 _transient Database *database_;
2103 pkgCache::VerIterator version_;
2104 pkgCache::PkgIterator iterator_;
2105 pkgCache::VerFileIterator file_;
2109 CYString transform_;
2112 CYString installed_;
2115 const char *section_;
2116 _transient NSString *section$_;
2120 PackageValue *metadata_;
2121 ParsedPackage *parsed_;
2123 _H<NSMutableArray> tags_;
2126 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database;
2127 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database;
2129 - (pkgCache::PkgIterator) iterator;
2132 - (NSString *) section;
2133 - (NSString *) simpleSection;
2135 - (NSString *) longSection;
2136 - (NSString *) shortSection;
2140 - (MIMEAddress *) maintainer;
2142 - (NSString *) longDescription;
2143 - (NSString *) shortDescription;
2146 - (PackageValue *) metadata;
2149 - (bool) subscribed;
2150 - (bool) setSubscribed:(bool)subscribed;
2154 - (NSString *) latest;
2155 - (NSString *) installed;
2156 - (BOOL) uninstalled;
2159 - (BOOL) upgradableAndEssential:(BOOL)essential;
2162 - (BOOL) unfiltered;
2166 - (BOOL) halfConfigured;
2167 - (BOOL) halfInstalled;
2169 - (NSString *) mode;
2172 - (NSString *) name;
2174 - (NSString *) homepage;
2175 - (NSString *) depiction;
2176 - (MIMEAddress *) author;
2178 - (NSString *) support;
2180 - (NSArray *) files;
2181 - (NSArray *) warnings;
2182 - (NSArray *) applications;
2184 - (Source *) source;
2187 - (BOOL) matches:(NSArray *)query;
2189 - (BOOL) hasTag:(NSString *)tag;
2190 - (NSString *) primaryPurpose;
2191 - (NSArray *) purposes;
2192 - (bool) isCommercial;
2194 - (void) setIndex:(size_t)index;
2196 - (CYString &) cyname;
2198 - (uint32_t) compareBySection:(NSArray *)sections;
2205 uint32_t PackageChangesRadix(Package *self, void *) {
2210 uint32_t timestamp : 30;
2211 uint32_t ignored : 1;
2212 uint32_t upgradable : 1;
2216 bool upgradable([self upgradableAndEssential:YES]);
2217 value.bits.upgradable = upgradable ? 1 : 0;
2220 value.bits.timestamp = 0;
2221 value.bits.ignored = [self ignored] ? 0 : 1;
2222 value.bits.upgradable = 1;
2224 value.bits.timestamp = [self seen] >> 2;
2225 value.bits.ignored = 0;
2226 value.bits.upgradable = 0;
2229 return _not(uint32_t) - value.key;
2232 CYString &(*PackageName)(Package *self, SEL sel);
2234 uint32_t PackagePrefixRadix(Package *self, void *context) {
2235 size_t offset(reinterpret_cast<size_t>(context));
2236 CYString &name(PackageName(self, @selector(cyname)));
2238 size_t size(name.size());
2241 char *text(name.data());
2244 if (!isdigit(text[0]))
2248 while (size != digits && isdigit(text[digits]))
2256 if (offset == 0 && zeros != 0) {
2257 memset(data, '0', zeros);
2258 memcpy(data + zeros, text, 4 - zeros);
2260 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2261 if (size <= offset - zeros)
2264 text += offset - zeros;
2265 size -= offset - zeros;
2268 memcpy(data, text, 4);
2270 memcpy(data, text, size);
2271 memset(data + size, 0, 4 - size);
2274 for (size_t i(0); i != 4; ++i)
2275 if (isalpha(data[i]))
2283 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2285 /* XXX: ntohl may be more honest */
2286 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2289 CFComparisonResult StringNameCompare(CFStringRef lhn, CFStringRef rhn, size_t length) {
2290 _profile(PackageNameCompare)
2292 return rhn == NULL ? kCFCompareEqualTo : kCFCompareLessThan;
2293 else if (rhn == NULL)
2294 return kCFCompareGreaterThan;
2296 CFIndex length(CFStringGetLength(lhn));
2298 _profile(PackageNameCompare$NumbersLast)
2299 if (length != 0 && CFStringGetLength(rhn) != 0) {
2300 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2301 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2302 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2303 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2304 return lha ? kCFCompareLessThan : kCFCompareGreaterThan;
2308 _profile(PackageNameCompare$Compare)
2309 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, (CFLocaleRef) (id) CollationLocale_);
2314 _finline CFComparisonResult StringNameCompare(NSString *lhn, NSString*rhn, size_t length) {
2315 return StringNameCompare((CFStringRef) lhn, (CFStringRef) rhn, length);
2318 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2319 CYString &lhn(PackageName(lhs, @selector(cyname)));
2320 NSString *rhn(PackageName(rhs, @selector(cyname)));
2321 return StringNameCompare(lhn, rhn, lhn.size());
2324 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *arg) {
2325 return PackageNameCompare(*lhs, *rhs, arg);
2328 struct PackageNameOrdering :
2329 std::binary_function<Package *, Package *, bool>
2331 _finline bool operator ()(Package *lhs, Package *rhs) const {
2332 return PackageNameCompare(lhs, rhs, NULL) == kCFCompareLessThan;
2336 @implementation Package
2338 - (NSString *) description {
2339 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2345 if (parsed_ != NULL)
2350 + (NSString *) webScriptNameForSelector:(SEL)selector {
2352 else if (selector == @selector(clear))
2354 else if (selector == @selector(getField:))
2356 else if (selector == @selector(getRecord))
2357 return @"getRecord";
2358 else if (selector == @selector(hasTag:))
2360 else if (selector == @selector(install))
2362 else if (selector == @selector(remove))
2368 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2369 return [self webScriptNameForSelector:selector] == nil;
2372 + (NSArray *) _attributeKeys {
2373 return [NSArray arrayWithObjects:
2394 @"shortDescription",
2407 - (NSArray *) attributeKeys {
2408 return [[self class] _attributeKeys];
2411 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2412 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2415 - (NSArray *) relations {
2416 @synchronized (database_) {
2417 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2418 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2419 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2423 - (NSString *) architecture {
2425 @synchronized (database_) {
2426 return parsed_->architecture_.empty() ? [NSNull null] : (id) parsed_->architecture_;
2429 - (NSString *) getField:(NSString *)name {
2430 @synchronized (database_) {
2431 if ([database_ era] != era_ || file_.end())
2434 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2436 const char *start, *end;
2437 if (!parser.Find([name UTF8String], start, end))
2438 return (NSString *) [NSNull null];
2440 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2443 - (NSString *) getRecord {
2444 @synchronized (database_) {
2445 if ([database_ era] != era_ || file_.end())
2448 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2450 const char *start, *end;
2451 parser.GetRec(start, end);
2453 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2457 if (parsed_ != NULL)
2459 @synchronized (database_) {
2460 if ([database_ era] != era_ || file_.end())
2463 ParsedPackage *parsed(new ParsedPackage);
2466 _profile(Package$parse)
2467 pkgRecords::Parser *parser;
2469 _profile(Package$parse$Lookup)
2470 parser = &[database_ records]->Lookup(file_);
2476 _profile(Package$parse$Find)
2481 {"architecture", &parsed->architecture_},
2482 {"icon", &parsed->icon_},
2483 {"depiction", &parsed->depiction_},
2484 {"homepage", &parsed->homepage_},
2485 {"website", &website},
2487 {"support", &parsed->support_},
2488 {"author", &parsed->author_},
2489 {"md5sum", &parsed->md5sum_},
2492 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2493 const char *start, *end;
2495 if (parser->Find(names[i].name_, start, end)) {
2496 CYString &value(*names[i].value_);
2497 _profile(Package$parse$Value)
2498 value.set(pool_, start, end - start);
2504 _profile(Package$parse$Tagline)
2505 const char *start, *end;
2506 if (parser->ShortDesc(start, end)) {
2507 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2510 while (stop != start && stop[-1] == '\r')
2512 parsed->tagline_.set(pool_, start, stop - start);
2516 _profile(Package$parse$Retain)
2517 if (parsed->homepage_.empty())
2518 parsed->homepage_ = website;
2519 if (parsed->homepage_ == parsed->depiction_)
2520 parsed->homepage_.clear();
2521 if (parsed->support_.empty())
2522 parsed->support_ = bugs;
2527 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database {
2528 if ((self = [super init]) != nil) {
2529 _profile(Package$initWithVersion)
2531 pool_ = new CYPool();
2537 database_ = database;
2538 era_ = [database era];
2542 pkgCache::PkgIterator iterator(version.ParentPkg());
2543 iterator_ = iterator;
2545 _profile(Package$initWithVersion$Version)
2546 if (!version_.end())
2547 file_ = version_.FileList();
2549 pkgCache &cache([database_ cache]);
2550 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2554 _profile(Package$initWithVersion$Cache)
2555 name_.set(NULL, iterator.Display());
2557 latest_.set(NULL, StripVersion_(version_.VerStr()));
2559 pkgCache::VerIterator current(iterator.CurrentVer());
2561 installed_.set(NULL, StripVersion_(current.VerStr()));
2564 _profile(Package$initWithVersion$Transliterate) do {
2565 if (CollationTransl_ == NULL)
2570 _profile(Package$initWithVersion$Transliterate$utf8)
2571 const uint8_t *data(reinterpret_cast<const uint8_t *>(name_.data()));
2572 for (size_t i(0), e(name_.size()); i != e; ++i)
2573 if (data[i] >= 0x80)
2578 UErrorCode code(U_ZERO_ERROR);
2581 _profile(Package$initWithVersion$Transliterate$u_strFromUTF8WithSub)
2582 CollationString_.resize(name_.size());
2583 u_strFromUTF8WithSub(&CollationString_[0], CollationString_.size(), &length, name_.data(), name_.size(), 0xfffd, NULL, &code);
2584 if (!U_SUCCESS(code))
2586 CollationString_.resize(length);
2589 _profile(Package$initWithVersion$Transliterate$utrans_trans)
2590 length = CollationString_.size();
2591 utrans_trans(CollationTransl_, reinterpret_cast<UReplaceable *>(&CollationString_), &CollationUCalls_, 0, &length, &code);
2592 if (!U_SUCCESS(code))
2594 _assert(CollationString_.size() == length);
2597 _profile(Package$initWithVersion$Transliterate$u_strToUTF8WithSub$preflight)
2598 u_strToUTF8WithSub(NULL, 0, &length, CollationString_.data(), CollationString_.size(), 0xfffd, NULL, &code);
2599 if (code == U_BUFFER_OVERFLOW_ERROR)
2600 code = U_ZERO_ERROR;
2601 else if (!U_SUCCESS(code))
2606 _profile(Package$initWithVersion$Transliterate$apr_palloc)
2607 transform = pool_->malloc<char>(length);
2609 _profile(Package$initWithVersion$Transliterate$u_strToUTF8WithSub$transform)
2610 u_strToUTF8WithSub(transform, length, NULL, CollationString_.data(), CollationString_.size(), 0xfffd, NULL, &code);
2611 if (!U_SUCCESS(code))
2615 transform_.set(NULL, transform, length);
2616 } while (false); _end
2618 _profile(Package$initWithVersion$Tags)
2619 pkgCache::TagIterator tag(iterator.TagList());
2621 tags_ = [NSMutableArray arrayWithCapacity:8];
2623 goto tag; for (; !tag.end(); ++tag) tag: {
2624 const char *name(tag.Name());
2625 NSString *string((NSString *) CYStringCreate(name));
2629 [tags_ addObject:[string autorelease]];
2631 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2632 if (strcmp(name + 6, "enduser") == 0)
2634 else if (strcmp(name + 6, "hacker") == 0)
2636 else if (strcmp(name + 6, "developer") == 0)
2638 else if (strcmp(name + 6, "cydia") == 0)
2644 if (strncmp(name, "cydia::", 7) == 0) {
2645 if (strcmp(name + 7, "essential") == 0)
2647 else if (strcmp(name + 7, "obsolete") == 0)
2654 _profile(Package$initWithVersion$Metadata)
2655 const char *mixed(iterator.Name());
2656 size_t size(strlen(mixed));
2657 static const size_t prefix(sizeof("/var/lib/dpkg/info/") - 1);
2658 char lower[prefix + size + 5 + 1];
2660 for (size_t i(0); i != size; ++i)
2661 lower[prefix + i] = mixed[i] | 0x20;
2663 if (!installed_.empty()) {
2664 memcpy(lower, "/var/lib/dpkg/info/", prefix);
2665 memcpy(lower + prefix + size, ".list", 6);
2667 if (stat(lower, &info) != -1)
2668 upgraded_ = info.st_birthtime;
2671 PackageValue *metadata(PackageFind(lower + prefix, size));
2672 metadata_ = metadata;
2674 id_.set(NULL, metadata->name_, size);
2676 const char *latest(version_.VerStr());
2677 size_t length(strlen(latest));
2679 uint16_t vhash(hashlittle(latest, length));
2681 size_t capped(std::min<size_t>(8, length));
2682 latest = latest + length - capped;
2684 if (metadata->first_ == 0)
2685 metadata->first_ = now_;
2687 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2688 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2689 metadata->vhash_ = vhash;
2690 metadata->last_ = now_;
2691 } else if (metadata->last_ == 0)
2692 metadata->last_ = metadata->first_;
2695 _profile(Package$initWithVersion$Section)
2696 section_ = version_.Section();
2699 _profile(Package$initWithVersion$Flags)
2700 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2701 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2706 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database {
2707 pkgCache::VerIterator version;
2709 _profile(Package$packageWithIterator$GetCandidateVer)
2710 version = [database policy]->GetCandidateVer(iterator);
2718 _profile(Package$packageWithIterator$Allocate)
2719 package = [Package allocWithZone:zone];
2722 _profile(Package$packageWithIterator$Initialize)
2724 initWithVersion:version
2731 _profile(Package$packageWithIterator$Autorelease)
2732 package = [package autorelease];
2738 - (pkgCache::PkgIterator) iterator {
2742 - (NSString *) section {
2743 if (section$_ == nil) {
2744 if (section_ == NULL)
2747 _profile(Package$section$mappedSectionForPointer)
2748 section$_ = [database_ mappedSectionForPointer:section_];
2753 - (NSString *) simpleSection {
2754 if (NSString *section = [self section])
2755 return Simplify(section);
2760 - (NSString *) longSection {
2761 return LocalizeSection([self section]);
2764 - (NSString *) shortSection {
2765 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2768 - (NSString *) uri {
2771 pkgIndexFile *index;
2772 pkgCache::PkgFileIterator file(file_.File());
2773 if (![database_ list].FindIndex(file, index))
2775 return [NSString stringWithUTF8String:iterator_->Path];
2776 //return [NSString stringWithUTF8String:file.Site()];
2777 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2781 - (MIMEAddress *) maintainer {
2782 @synchronized (database_) {
2783 if ([database_ era] != era_ || file_.end())
2786 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2787 const std::string &maintainer(parser->Maintainer());
2788 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2791 - (NSString *) md5sum {
2792 return parsed_ == NULL ? nil : (id) parsed_->md5sum_;
2796 @synchronized (database_) {
2797 if ([database_ era] != era_ || version_.end())
2800 return version_->InstalledSize;
2803 - (NSString *) longDescription {
2804 @synchronized (database_) {
2805 if ([database_ era] != era_ || file_.end())
2808 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2809 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2811 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2812 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2813 if ([lines count] < 2)
2816 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2817 for (size_t i(1), e([lines count]); i != e; ++i) {
2818 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2819 [trimmed addObject:trim];
2822 return [trimmed componentsJoinedByString:@"\n"];
2825 - (NSString *) shortDescription {
2826 if (parsed_ != NULL)
2827 return static_cast<NSString *>(parsed_->tagline_);
2829 @synchronized (database_) {
2830 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2832 const char *start, *end;
2833 if (!parser.ShortDesc(start, end))
2836 if (end - start > 200)
2840 if (const char *stop = reinterpret_cast<const char *>(memchr(start, '\n', end - start)))
2843 while (end != start && end[-1] == '\r')
2847 return [(id) CYStringCreate(start, end - start) autorelease];
2851 _profile(Package$index)
2852 CFStringRef name((CFStringRef) [self name]);
2853 if (CFStringGetLength(name) == 0)
2855 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2856 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2858 return toupper(character);
2862 - (PackageValue *) metadata {
2867 PackageValue *metadata([self metadata]);
2868 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2871 - (bool) subscribed {
2872 return [self metadata]->subscribed_;
2875 - (bool) setSubscribed:(bool)subscribed {
2876 PackageValue *metadata([self metadata]);
2877 if (metadata->subscribed_ == subscribed)
2879 metadata->subscribed_ = subscribed;
2887 - (NSString *) latest {
2891 - (NSString *) installed {
2895 - (BOOL) uninstalled {
2896 return installed_.empty();
2900 return !version_.end();
2903 - (BOOL) upgradableAndEssential:(BOOL)essential {
2904 _profile(Package$upgradableAndEssential)
2905 pkgCache::VerIterator current(iterator_.CurrentVer());
2907 return essential && essential_;
2909 return !version_.end() && version_ != current;
2913 - (BOOL) essential {
2918 return [database_ cache][iterator_].InstBroken();
2921 - (BOOL) unfiltered {
2922 _profile(Package$unfiltered$obsolete)
2923 if (_unlikely(obsolete_))
2927 _profile(Package$unfiltered$role)
2928 if (_unlikely(role_ > 3))
2936 if (![self unfiltered])
2941 _profile(Package$visible$section)
2942 section = [self section];
2945 _profile(Package$visible$isSectionVisible)
2946 if (!isSectionVisible(section))
2954 unsigned char current(iterator_->CurrentState);
2955 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2958 - (BOOL) halfConfigured {
2959 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2962 - (BOOL) halfInstalled {
2963 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2967 @synchronized (database_) {
2968 if ([database_ era] != era_ || iterator_.end())
2971 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2972 return state.Mode != pkgDepCache::ModeKeep;
2975 - (NSString *) mode {
2976 @synchronized (database_) {
2977 if ([database_ era] != era_ || iterator_.end())
2980 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2982 switch (state.Mode) {
2983 case pkgDepCache::ModeDelete:
2984 if ((state.iFlags & pkgDepCache::Purge) != 0)
2988 case pkgDepCache::ModeKeep:
2989 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2990 return @"REINSTALL";
2991 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2995 case pkgDepCache::ModeInstall:
2996 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2997 return @"REINSTALL";
2998 else*/ switch (state.Status) {
3000 return @"DOWNGRADE";
3006 return @"NEW_INSTALL";
3017 - (NSString *) name {
3018 return name_.empty() ? id_ : name_;
3021 - (UIImage *) icon {
3022 NSString *section = [self simpleSection];
3025 if (parsed_ != NULL)
3026 if (NSString *href = parsed_->icon_)
3027 if ([href hasPrefix:@"file:///"])
3028 icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
3029 if (icon == nil) if (section != nil)
3030 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]];
3031 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
3032 if ([dicon hasPrefix:@"file:///"])
3033 icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
3035 icon = [UIImage imageNamed:@"unknown.png"];
3039 - (NSString *) homepage {
3040 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
3043 - (NSString *) depiction {
3044 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
3047 - (MIMEAddress *) author {
3048 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
3051 - (NSString *) support {
3052 return parsed_ != NULL && !parsed_->support_.empty() ? parsed_->support_ : [[self source] supportForPackage:id_];
3055 - (NSArray *) files {
3056 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
3057 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
3060 fin.open([path UTF8String]);
3065 while (std::getline(fin, line))
3066 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
3071 - (NSString *) state {
3072 @synchronized (database_) {
3073 if ([database_ era] != era_ || file_.end())
3076 switch (iterator_->CurrentState) {
3077 case pkgCache::State::NotInstalled:
3078 return @"NotInstalled";
3079 case pkgCache::State::UnPacked:
3081 case pkgCache::State::HalfConfigured:
3082 return @"HalfConfigured";
3083 case pkgCache::State::HalfInstalled:
3084 return @"HalfInstalled";
3085 case pkgCache::State::ConfigFiles:
3086 return @"ConfigFiles";
3087 case pkgCache::State::Installed:
3088 return @"Installed";
3089 case pkgCache::State::TriggersAwaited:
3090 return @"TriggersAwaited";
3091 case pkgCache::State::TriggersPending:
3092 return @"TriggersPending";
3095 return (NSString *) [NSNull null];
3098 - (NSString *) selection {
3099 @synchronized (database_) {
3100 if ([database_ era] != era_ || file_.end())
3103 switch (iterator_->SelectedState) {
3104 case pkgCache::State::Unknown:
3106 case pkgCache::State::Install:
3108 case pkgCache::State::Hold:
3110 case pkgCache::State::DeInstall:
3111 return @"DeInstall";
3112 case pkgCache::State::Purge:
3116 return (NSString *) [NSNull null];
3119 - (NSArray *) warnings {
3120 @synchronized (database_) {
3121 if ([database_ era] != era_ || file_.end())
3124 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
3125 const char *name(iterator_.Name());
3127 size_t length(strlen(name));
3128 if (length < 2) invalid:
3129 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
3130 else for (size_t i(0); i != length; ++i)
3132 /* XXX: technically this is not allowed */
3133 (name[i] < 'A' || name[i] > 'Z') &&
3134 (name[i] < 'a' || name[i] > 'z') &&
3135 (name[i] < '0' || name[i] > '9') &&
3136 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
3139 if (strcmp(name, "cydia") != 0) {
3142 bool _private = false;
3144 bool dbstash = false;
3145 bool dsstore = false;
3147 bool repository = [[self section] isEqualToString:@"Repositories"];
3149 if (NSArray *files = [self files])
3150 for (NSString *file in files)
3151 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
3153 else if (!user && [file isEqualToString:@"/User"])
3155 else if (!_private && [file isEqualToString:@"/private"])
3157 else if (!stash && [file isEqualToString:@"/var/stash"])
3159 else if (!dbstash && [file isEqualToString:@"/var/db/stash"])
3161 else if (!dsstore && [file hasSuffix:@"/.DS_Store"])
3164 /* XXX: this is not sensitive enough. only some folders are valid. */
3165 if (cydia && !repository)
3166 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
3168 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
3170 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
3172 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
3174 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/db/stash"]];
3176 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @".DS_Store"]];
3179 return [warnings count] == 0 ? nil : warnings;
3182 - (NSArray *) applications {
3183 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
3185 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
3187 static RegEx application_r("/Applications/(.*)\\.app/Info.plist");
3188 if (NSArray *files = [self files])
3189 for (NSString *file in files)
3190 if (application_r(file)) {
3191 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
3194 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
3195 if (id == nil || [id isEqualToString:me])
3198 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
3200 display = application_r[1];
3202 NSString *bundle([file stringByDeletingLastPathComponent]);
3203 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
3204 // XXX: maybe this should check if this is really a string, not just for length
3205 if (icon == nil || ![icon respondsToSelector:@selector(length)] || [icon length] == 0)
3207 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
3209 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
3210 [applications addObject:application];
3212 [application addObject:id];
3213 [application addObject:display];
3214 [application addObject:url];
3217 return [applications count] == 0 ? nil : applications;
3220 - (Source *) source {
3221 if (source_ == nil) {
3222 @synchronized (database_) {
3223 if ([database_ era] != era_ || file_.end())
3224 source_ = (Source *) [NSNull null];
3226 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
3230 return source_ == (Source *) [NSNull null] ? nil : source_;
3233 - (time_t) upgraded {
3237 - (uint32_t) recent {
3238 return std::numeric_limits<uint32_t>::max() - upgraded_;
3245 - (BOOL) matches:(NSArray *)query {
3246 if (query == nil || [query count] == 0)
3255 string = [self name];
3256 length = [string length];
3259 for (NSString *term in query) {
3260 range = [string rangeOfString:term options:MatchCompareOptions_];
3261 if (range.location != NSNotFound)
3262 rank_ -= 6 * 1000000 / length;
3267 length = [string length];
3270 for (NSString *term in query) {
3271 range = [string rangeOfString:term options:MatchCompareOptions_];
3272 if (range.location != NSNotFound)
3273 rank_ -= 6 * 1000000 / length;
3277 string = [self shortDescription];
3278 length = [string length];
3279 NSUInteger stop(std::min<NSUInteger>(length, 200));
3282 for (NSString *term in query) {
3283 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
3284 if (range.location != NSNotFound)
3285 rank_ -= 2 * 100000;
3291 - (NSArray *) tags {
3295 - (BOOL) hasTag:(NSString *)tag {
3296 return tags_ == nil ? NO : [tags_ containsObject:tag];
3299 - (NSString *) primaryPurpose {
3300 for (NSString *tag in (NSArray *) tags_)
3301 if ([tag hasPrefix:@"purpose::"])
3302 return [tag substringFromIndex:9];
3306 - (NSArray *) purposes {
3307 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
3308 for (NSString *tag in (NSArray *) tags_)
3309 if ([tag hasPrefix:@"purpose::"])
3310 [purposes addObject:[tag substringFromIndex:9]];
3311 return [purposes count] == 0 ? nil : purposes;
3314 - (bool) isCommercial {
3315 return [self hasTag:@"cydia::commercial"];
3318 - (void) setIndex:(size_t)index {
3319 if (metadata_->index_ != index)
3320 metadata_->index_ = index;
3323 - (CYString &) cyname {
3324 return !transform_.empty() ? transform_ : !name_.empty() ? name_ : id_;
3327 - (uint32_t) compareBySection:(NSArray *)sections {
3328 NSString *section([self section]);
3329 for (size_t i(0), e([sections count]); i != e; ++i) {
3330 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3334 return _not(uint32_t);
3338 @synchronized (database_) {
3339 pkgProblemResolver *resolver = [database_ resolver];
3340 resolver->Clear(iterator_);
3342 pkgCacheFile &cache([database_ cache]);
3343 cache->SetReInstall(iterator_, false);
3344 cache->MarkKeep(iterator_, false);
3348 @synchronized (database_) {
3349 pkgProblemResolver *resolver = [database_ resolver];
3350 resolver->Clear(iterator_);
3351 resolver->Protect(iterator_);
3353 pkgCacheFile &cache([database_ cache]);
3354 cache->SetReInstall(iterator_, false);
3355 cache->MarkInstall(iterator_, false);
3357 pkgDepCache::StateCache &state((*cache)[iterator_]);
3358 if (!state.Install())
3359 cache->SetReInstall(iterator_, true);
3363 @synchronized (database_) {
3364 pkgProblemResolver *resolver = [database_ resolver];
3365 resolver->Clear(iterator_);
3366 resolver->Remove(iterator_);
3367 resolver->Protect(iterator_);
3369 pkgCacheFile &cache([database_ cache]);
3370 cache->SetReInstall(iterator_, false);
3371 cache->MarkDelete(iterator_, true);
3376 /* Section Class {{{ */
3377 @interface Section : NSObject {
3381 _H<NSString> localized_;
3384 - (NSComparisonResult) compareByLocalized:(Section *)section;
3385 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3386 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3387 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3389 - (NSString *) name;
3390 - (void) setName:(NSString *)name;
3396 - (void) addToCount;
3398 - (void) setCount:(size_t)count;
3399 - (NSString *) localized;
3403 @implementation Section
3405 - (NSComparisonResult) compareByLocalized:(Section *)section {
3406 NSString *lhs(localized_);
3407 NSString *rhs([section localized]);
3409 /*if ([lhs length] != 0 && [rhs length] != 0) {
3410 unichar lhc = [lhs characterAtIndex:0];
3411 unichar rhc = [rhs characterAtIndex:0];
3413 if (isalpha(lhc) && !isalpha(rhc))
3414 return NSOrderedAscending;
3415 else if (!isalpha(lhc) && isalpha(rhc))
3416 return NSOrderedDescending;
3419 return [lhs compare:rhs options:LaxCompareOptions_];
3422 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3423 if ((self = [self initWithName:name localize:NO]) != nil) {
3424 if (localized != nil)
3425 localized_ = localized;
3429 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3430 return [self initWithName:name row:0 localize:localize];
3433 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3434 if ((self = [super init]) != nil) {
3438 localized_ = LocalizeSection(name_);
3442 - (NSString *) name {
3446 - (void) setName:(NSString *)name {
3462 - (void) addToCount {
3466 - (void) setCount:(size_t)count {
3470 - (NSString *) localized {
3477 class CydiaLogCleaner :
3478 public pkgArchiveCleaner
3481 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3486 /* Database Implementation {{{ */
3487 @implementation Database
3489 + (Database *) sharedInstance {
3490 static _H<Database> instance;
3491 if (instance == nil)
3492 instance = [[[Database alloc] init] autorelease];
3500 - (void) releasePackages {
3501 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3502 CFArrayRemoveAllValues(packages_);
3506 // XXX: actually implement this thing
3508 [self releasePackages];
3509 NSRecycleZone(zone_);
3513 - (void) _readCydia:(NSNumber *)fd {
3514 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3515 std::istream is(&ib);
3518 static RegEx finish_r("finish:([^:]*)");
3520 while (std::getline(is, line)) {
3521 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3523 const char *data(line.c_str());
3524 size_t size = line.size();
3525 lprintf("C:%s\n", data);
3527 if (finish_r(data, size)) {
3528 NSString *finish = finish_r[1];
3529 int index = [Finishes_ indexOfObject:finish];
3530 if (index != INT_MAX && index > Finish_)
3540 - (void) _readStatus:(NSNumber *)fd {
3541 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3542 std::istream is(&ib);
3545 static RegEx conffile_r("status: [^ ]* : conffile-prompt : (.*?) *");
3546 static RegEx pmstatus_r("([^:]*):([^:]*):([^:]*):(.*)");
3548 while (std::getline(is, line)) {
3549 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3551 const char *data(line.c_str());
3552 size_t size(line.size());
3553 lprintf("S:%s\n", data);
3555 if (conffile_r(data, size)) {
3556 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3557 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3558 } else if (strncmp(data, "status: ", 8) == 0) {
3559 // status: <package>: {unpacked,half-configured,installed}
3560 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3561 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3562 } else if (strncmp(data, "processing: ", 12) == 0) {
3563 // processing: configure: config-test
3564 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3565 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3566 } else if (pmstatus_r(data, size)) {
3567 std::string type([pmstatus_r[1] UTF8String]);
3569 NSString *package = pmstatus_r[2];
3570 if ([package isEqualToString:@"dpkg-exec"])
3573 float percent([pmstatus_r[3] floatValue]);
3574 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3576 NSString *string = pmstatus_r[4];
3578 if (type == "pmerror") {
3579 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3580 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3581 } else if (type == "pmstatus") {
3582 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3583 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3584 } else if (type == "pmconffile")
3585 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3587 lprintf("E:unknown pmstatus\n");
3589 lprintf("E:unknown status\n");
3597 - (void) _readOutput:(NSNumber *)fd {
3598 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3599 std::istream is(&ib);
3602 while (std::getline(is, line)) {
3603 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3605 lprintf("O:%s\n", line.c_str());
3607 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3608 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3620 - (Package *) packageWithName:(NSString *)name {
3623 @synchronized (self) {
3624 if (static_cast<pkgDepCache *>(cache_) == NULL)
3626 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3627 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:NULL database:self];
3631 if ((self = [super init]) != nil) {
3638 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3640 size_t capacity(MetaFile_->active_);
3646 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3647 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3651 _assert(pipe(fds) != -1);
3654 _config->Set("APT::Keep-Fds::", cydiafd_);
3655 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3658 detachNewThreadSelector:@selector(_readCydia:)
3660 withObject:[NSNumber numberWithInt:fds[0]]
3663 _assert(pipe(fds) != -1);
3667 detachNewThreadSelector:@selector(_readStatus:)
3669 withObject:[NSNumber numberWithInt:fds[0]]
3672 _assert(pipe(fds) != -1);
3673 _assert(dup2(fds[0], 0) != -1);
3674 _assert(close(fds[0]) != -1);
3676 input_ = fdopen(fds[1], "a");
3678 _assert(pipe(fds) != -1);
3679 _assert(dup2(fds[1], 1) != -1);
3680 _assert(close(fds[1]) != -1);
3683 detachNewThreadSelector:@selector(_readOutput:)
3685 withObject:[NSNumber numberWithInt:fds[0]]
3690 - (pkgCacheFile &) cache {
3694 - (pkgDepCache::Policy *) policy {
3698 - (pkgRecords *) records {
3702 - (pkgProblemResolver *) resolver {
3706 - (pkgAcquire &) fetcher {
3710 - (pkgSourceList &) list {
3714 - (NSArray *) packages {
3715 return (NSArray *) packages_;
3718 - (NSArray *) sources {
3722 - (Source *) sourceWithKey:(NSString *)key {
3723 for (Source *source in [self sources]) {
3724 if ([[source key] isEqualToString:key])
3729 - (bool) popErrorWithTitle:(NSString *)title {
3732 while (!_error->empty()) {
3734 bool warning(!_error->PopMessage(error));
3739 size_t size(error.size());
3740 if (size == 0 || error[size - 1] != '\n')
3742 error.resize(size - 1);
3745 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3747 static RegEx no_pubkey("GPG error:.* NO_PUBKEY .*");
3748 if (warning && no_pubkey(error.c_str()))
3751 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3757 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3758 return [self popErrorWithTitle:title] || !success;
3761 - (bool) _isEtceteraAptSourcesListDirectoryCydiaListSymbolicallyLinkedToMobileCachesCydiaSourceList {
3763 ssize_t length(readlink("/etc/apt/sources.list.d/cydia.list", target, sizeof(target) - 1));
3766 if (length >= sizeof(target))
3768 target[length] = '\0';
3769 return strcmp(target, "/var/mobile/Library/Caches/com.saurik.Cydia/sources.list") == 0;
3772 - (bool) popErrorWithTitle:(NSString *)title forReadList:(pkgSourceList &)list {
3773 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3775 if (![self _isEtceteraAptSourcesListDirectoryCydiaListSymbolicallyLinkedToMobileCachesCydiaSourceList])
3776 if ([self popErrorWithTitle:title forOperation:list.Read(SOURCES_LIST)])
3781 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3782 @synchronized (self) {
3785 [self releasePackages];
3788 [sourceList_ removeAllObjects];
3809 new (&pool_) CYPool();
3811 NSRecycleZone(zone_);
3812 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3814 int chk(creat("/tmp/cydia.chk", 0644));
3818 if (invocation != nil)
3819 [invocation invoke];
3821 NSString *title(UCLocalize("DATABASE"));
3823 list_ = new pkgSourceList();
3824 _profile(reloadDataWithInvocation$ReadMainList)
3825 if ([self popErrorWithTitle:title forReadList:*list_])
3829 _profile(reloadDataWithInvocation$Source$initWithMetaIndex)
3830 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3831 Source *object([[[Source alloc] initWithMetaIndex:*source forDatabase:self inPool:&pool_] autorelease]);
3832 [sourceList_ addObject:object];
3837 OpProgress progress;
3840 delock_ = GetStatusDate();
3841 _profile(reloadDataWithInvocation$pkgCacheFile)
3842 opened = cache_.Open(progress, false);
3845 // XXX: what if there are errors, but Open() == true? this should be merged with popError:
3846 while (!_error->empty()) {
3848 bool warning(!_error->PopMessage(error));
3850 lprintf("cache_.Open():[%s]\n", error.c_str());
3852 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3856 else if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3857 repair = @selector(configure);
3858 //else if (error == "The package lists or status file could not be parsed or opened.")
3859 // repair = @selector(update);
3860 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3861 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3862 // else if (error == "Malformed Status line")
3863 // else if (error == "The list of sources could not be read.")
3865 if (repair != NULL) {
3867 [delegate_ repairWithSelector:repair];
3876 unlink("/tmp/cydia.chk");
3878 now_ = [[NSDate date] timeIntervalSince1970];
3880 policy_ = new pkgDepCache::Policy();
3881 records_ = new pkgRecords(cache_);
3882 resolver_ = new pkgProblemResolver(cache_);
3883 fetcher_ = new pkgAcquire(&status_);
3886 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3887 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3891 _profile(reloadDataWithInvocation$pkgApplyStatus)
3892 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3896 if (cache_->BrokenCount() != 0) {
3897 _profile(pkgApplyStatus$pkgFixBroken)
3898 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3902 if (cache_->BrokenCount() != 0) {
3903 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3907 _profile(pkgApplyStatus$pkgMinimizeUpgrade)
3908 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3913 for (Source *object in (id) sourceList_) {
3914 metaIndex *source([object metaIndex]);
3915 std::vector<pkgIndexFile *> *indices = source->GetIndexFiles();
3916 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3917 // XXX: this could be more intelligent
3918 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3919 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3921 sourceMap_[cached->ID] = object;
3926 /*std::vector<Package *> packages;
3927 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3930 _profile(reloadDataWithInvocation$packageWithIterator)
3931 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3932 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:&pool_ database:self])
3933 //packages.push_back(package);
3934 CFArrayAppendValue(packages_, CFRetain(package));
3938 /*if (packages.empty())
3939 packages_ = [[NSArray alloc] init];
3941 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3944 _profile(reloadDataWithInvocation$radix$8)
3945 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(8)];
3948 _profile(reloadDataWithInvocation$radix$4)
3949 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3952 _profile(reloadDataWithInvocation$radix$0)
3953 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3956 _profile(reloadDataWithInvocation$insertion)
3957 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3960 /*_profile(reloadDataWithInvocation$CFQSortArray)
3961 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);
3964 /*_profile(reloadDataWithInvocation$stdsort)
3965 std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3968 /*_profile(reloadDataWithInvocation$CFArraySortValues)
3969 CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3972 /*_profile(reloadDataWithInvocation$sortUsingFunction)
3973 [packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3977 size_t count(CFArrayGetCount(packages_));
3978 MetaFile_->active_ = count;
3979 for (size_t index(0); index != count; ++index)
3980 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3985 @synchronized (self) {
3987 resolver_ = new pkgProblemResolver(cache_);
3989 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3990 if (!cache_[iterator].Keep())
3991 cache_->MarkKeep(iterator, false);
3992 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3993 cache_->SetReInstall(iterator, false);
3996 - (void) configure {
3997 NSString *dpkg = [NSString stringWithFormat:@"/usr/libexec/cydo --configure -a --status-fd %u", statusfd_];
3999 system([dpkg UTF8String]);
4004 @synchronized (self) {
4005 // XXX: I don't remember this condition
4010 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
4012 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
4014 if ([self popErrorWithTitle:title])
4018 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
4020 CydiaLogCleaner cleaner;
4021 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
4028 fetcher_->Shutdown();
4030 pkgRecords records(cache_);
4032 lock_ = new FileFd();
4033 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
4035 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
4037 if ([self popErrorWithTitle:title])
4041 if ([self popErrorWithTitle:title forReadList:list])
4044 manager_ = (_system->CreatePM(cache_));
4045 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
4052 bool substrate(RestartSubstrate_);
4053 RestartSubstrate_ = false;
4055 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
4057 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
4059 if ([self popErrorWithTitle:title forReadList:list])
4061 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
4062 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
4065 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4067 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
4069 [self popErrorWithTitle:title];
4073 bool failed = false;
4074 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
4075 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
4077 if ((*item)->Status == pkgAcquire::Item::StatIdle)
4080 std::string uri = (*item)->DescURI();
4081 std::string error = (*item)->ErrorText;
4083 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
4086 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError]);
4087 [delegate_ addProgressEventOnMainThread:event forTask:title];
4090 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4098 RestartSubstrate_ = true;
4100 if (![delock_ isEqual:GetStatusDate()]) {
4101 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("DPKG_LOCKED") ofType:kCydiaProgressEventTypeError] forTask:title];
4107 pkgPackageManager::OrderResult result(manager_->DoInstall(statusfd_));
4109 NSString *oextended(@"/var/lib/apt/extended_states");
4110 NSString *nextended(Cache("extended_states"));
4113 if (stat([nextended UTF8String], &info) != -1 && (info.st_mode & S_IFMT) == S_IFREG) {
4114 system([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /bin/mv -f %@ %@", ShellEscape(nextended), ShellEscape(oextended)] UTF8String]);
4115 system([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /bin/chown 0:0 %@", ShellEscape(oextended)] UTF8String]);
4118 unlink([nextended UTF8String]);
4119 symlink([oextended UTF8String], [nextended UTF8String]);
4121 if ([self popErrorWithTitle:title])
4124 if (result == pkgPackageManager::Failed) {
4129 if (result != pkgPackageManager::Completed) {
4134 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
4136 if ([self popErrorWithTitle:title forReadList:list])
4138 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
4139 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
4142 if (![before isEqualToArray:after])
4147 return ![delock_ isEqual:GetStatusDate()];
4151 NSString *title(UCLocalize("UPGRADE"));
4152 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
4158 [self updateWithStatus:status_];
4161 - (void) updateWithStatus:(CancelStatus &)status {
4162 NSString *title(UCLocalize("REFRESHING_DATA"));
4165 if ([self popErrorWithTitle:title forReadList:list])
4169 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
4170 if ([self popErrorWithTitle:title])
4173 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4175 bool success(ListUpdate(status, list, PulseInterval_));
4176 if (status.WasCancelled())
4179 [self popErrorWithTitle:title forOperation:success];
4181 [[NSDictionary dictionaryWithObjectsAndKeys:
4182 [NSDate date], @"LastUpdate",
4183 nil] writeToFile:@ CacheState_ atomically:YES];
4186 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4189 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
4190 delegate_ = delegate;
4193 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
4194 progress_ = delegate;
4195 status_.setDelegate(delegate);
4198 - (NSObject<ProgressDelegate> *) progressDelegate {
4202 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
4203 SourceMap::const_iterator i(sourceMap_.find(file->ID));
4204 return i == sourceMap_.end() ? nil : i->second;
4207 - (void) setFetch:(bool)fetch forURI:(const char *)uri {
4208 for (Source *source in (id) sourceList_)
4209 [source setFetch:fetch forURI:uri];
4212 - (void) resetFetch {
4213 for (Source *source in (id) sourceList_)
4214 [source resetFetch];
4217 - (NSString *) mappedSectionForPointer:(const char *)section {
4218 _H<NSString> *mapped;
4220 _profile(Database$mappedSectionForPointer$Cache)
4221 mapped = §ions_[section];
4224 if (*mapped == NULL) {
4225 size_t length(strlen(section));
4226 char spaced[length + 1];
4228 _profile(Database$mappedSectionForPointer$Replace)
4229 for (size_t index(0); index != length; ++index)
4230 spaced[index] = section[index] == '_' ? ' ' : section[index];
4231 spaced[length] = '\0';
4236 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
4237 string = [NSString stringWithUTF8String:spaced];
4240 _profile(Database$mappedSectionForPointer$Map)
4241 string = [SectionMap_ objectForKey:string] ?: string;
4251 static _H<NSMutableSet> Diversions_;
4253 @interface Diversion : NSObject {
4256 _H<NSString> format_;
4261 @implementation Diversion
4263 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
4264 if ((self = [super init]) != nil) {
4265 pattern_ = [from UTF8String];
4271 - (NSString *) divert:(NSString *)url {
4272 return !pattern_(url) ? nil : pattern_->*format_;
4275 + (NSURL *) divertURL:(NSURL *)url {
4277 NSString *href([url absoluteString]);
4279 for (Diversion *diversion in (id) Diversions_)
4280 if (NSString *diverted = [diversion divert:href]) {
4282 NSLog(@"div: %@", diverted);
4284 url = [NSURL URLWithString:diverted];
4291 - (NSString *) key {
4295 - (NSUInteger) hash {
4299 - (BOOL) isEqual:(Diversion *)object {
4300 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
4305 @interface CydiaObject : NSObject {
4306 _H<CyteWebViewController> indirect_;
4307 _transient id delegate_;
4310 - (id) initWithDelegate:(IndirectDelegate *)indirect;
4316 @interface CydiaWebViewController : CyteWebViewController {
4317 _H<CydiaObject> cydia_;
4320 + (void) addDiversion:(Diversion *)diversion;
4321 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request;
4322 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia;
4323 - (void) setDelegate:(id)delegate;
4327 /* Web Scripting {{{ */
4328 @implementation CydiaObject
4330 - (id) initWithDelegate:(IndirectDelegate *)indirect {
4331 if ((self = [super init]) != nil) {
4332 indirect_ = (CyteWebViewController *) indirect;
4336 - (void) setDelegate:(id)delegate {
4337 delegate_ = delegate;
4340 + (NSArray *) _attributeKeys {
4341 return [NSArray arrayWithObjects:
4344 @"coreFoundationVersionNumber",
4360 - (NSArray *) attributeKeys {
4361 return [[self class] _attributeKeys];
4364 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4365 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4368 - (NSString *) version {
4372 - (NSString *) build {
4376 - (NSString *) coreFoundationVersionNumber {
4377 return [NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber];
4380 - (NSString *) device {
4381 return UniqueIdentifier();
4384 - (NSString *) firmware {
4385 return [[UIDevice currentDevice] systemVersion];
4388 - (NSString *) hostname {
4389 return [[UIDevice currentDevice] name];
4392 - (NSString *) idiom {
4393 return (id) Idiom_ ?: [NSNull null];
4396 - (NSString *) mcc {
4397 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode")))
4398 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault) autorelease];
4402 - (NSString *) mnc {
4403 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberNetworkCode")))
4404 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault) autorelease];
4408 - (NSString *) operator {
4409 if (CFStringRef (*$CTRegistrationCopyOperatorName)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTRegistrationCopyOperatorName")))
4410 return [(NSString *) (*$CTRegistrationCopyOperatorName)(kCFAllocatorDefault) autorelease];
4414 - (NSString *) bbsnum {
4415 return (id) BBSNum_ ?: [NSNull null];
4418 - (NSString *) ecid {
4419 return (id) ChipID_ ?: [NSNull null];
4422 - (NSString *) serial {
4423 return SerialNumber_;
4426 - (NSString *) role {
4427 return (id) [NSNull null];
4430 - (NSString *) model {
4431 return [NSString stringWithUTF8String:Machine_];
4434 + (NSString *) webScriptNameForSelector:(SEL)selector {
4436 else if (selector == @selector(addBridgedHost:))
4437 return @"addBridgedHost";
4438 else if (selector == @selector(addInsecureHost:))
4439 return @"addInsecureHost";
4440 else if (selector == @selector(addInternalRedirect::))
4441 return @"addInternalRedirect";
4442 else if (selector == @selector(addPipelinedHost:scheme:))
4443 return @"addPipelinedHost";
4444 else if (selector == @selector(addSource:::))
4445 return @"addSource";
4446 else if (selector == @selector(addTrivialSource:))
4447 return @"addTrivialSource";
4448 else if (selector == @selector(close))
4450 else if (selector == @selector(du:))
4452 else if (selector == @selector(stringWithFormat:arguments:))
4454 else if (selector == @selector(getAllSources))
4455 return @"getAllSources";
4456 else if (selector == @selector(getApplicationInfo:value:))
4457 return @"getApplicationInfoValue";
4458 else if (selector == @selector(getKernelNumber:))
4459 return @"getKernelNumber";
4460 else if (selector == @selector(getKernelString:))
4461 return @"getKernelString";
4462 else if (selector == @selector(getInstalledPackages))
4463 return @"getInstalledPackages";
4464 else if (selector == @selector(getIORegistryEntry::))
4465 return @"getIORegistryEntry";
4466 else if (selector == @selector(getLocaleIdentifier))
4467 return @"getLocaleIdentifier";
4468 else if (selector == @selector(getPreferredLanguages))
4469 return @"getPreferredLanguages";
4470 else if (selector == @selector(getPackageById:))
4471 return @"getPackageById";
4472 else if (selector == @selector(getMetadataKeys))
4473 return @"getMetadataKeys";
4474 else if (selector == @selector(getMetadataValue:))
4475 return @"getMetadataValue";
4476 else if (selector == @selector(getSessionValue:))
4477 return @"getSessionValue";
4478 else if (selector == @selector(installPackages:))
4479 return @"installPackages";
4480 else if (selector == @selector(isReachable:))
4481 return @"isReachable";
4482 else if (selector == @selector(localizedStringForKey:value:table:))
4484 else if (selector == @selector(popViewController:))
4485 return @"popViewController";
4486 else if (selector == @selector(refreshSources))
4487 return @"refreshSources";
4488 else if (selector == @selector(registerFrame:))
4489 return @"registerFrame";
4490 else if (selector == @selector(removeButton))
4491 return @"removeButton";
4492 else if (selector == @selector(saveConfig))
4493 return @"saveConfig";
4494 else if (selector == @selector(setMetadataValue::))
4495 return @"setMetadataValue";
4496 else if (selector == @selector(setSessionValue::))
4497 return @"setSessionValue";
4498 else if (selector == @selector(substitutePackageNames:))
4499 return @"substitutePackageNames";
4500 else if (selector == @selector(scrollToBottom:))
4501 return @"scrollToBottom";
4502 else if (selector == @selector(setAllowsNavigationAction:))
4503 return @"setAllowsNavigationAction";
4504 else if (selector == @selector(setBadgeValue:))
4505 return @"setBadgeValue";
4506 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4507 return @"setButtonImage";
4508 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4509 return @"setButtonTitle";
4510 else if (selector == @selector(setHidesBackButton:))
4511 return @"setHidesBackButton";
4512 else if (selector == @selector(setHidesNavigationBar:))
4513 return @"setHidesNavigationBar";
4514 else if (selector == @selector(setNavigationBarStyle:))
4515 return @"setNavigationBarStyle";
4516 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4517 return @"setNavigationBarTintColor";
4518 else if (selector == @selector(setPasteboardString:))
4519 return @"setPasteboardString";
4520 else if (selector == @selector(setPasteboardURL:))
4521 return @"setPasteboardURL";
4522 else if (selector == @selector(setScrollAlwaysBounceVertical:))
4523 return @"setScrollAlwaysBounceVertical";
4524 else if (selector == @selector(setScrollIndicatorStyle:))
4525 return @"setScrollIndicatorStyle";
4526 else if (selector == @selector(setToken:))
4528 else if (selector == @selector(setViewportWidth:))
4529 return @"setViewportWidth";
4530 else if (selector == @selector(statfs:))
4532 else if (selector == @selector(supports:))
4534 else if (selector == @selector(unload))
4540 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4541 return [self webScriptNameForSelector:selector] == nil;
4544 - (BOOL) supports:(NSString *)feature {
4545 return [feature isEqualToString:@"window.open"];
4549 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4552 - (void) setScrollAlwaysBounceVertical:(NSNumber *)value {
4553 [indirect_ performSelectorOnMainThread:@selector(setScrollAlwaysBounceVerticalNumber:) withObject:value waitUntilDone:NO];
4556 - (void) setScrollIndicatorStyle:(NSString *)style {
4557 [indirect_ performSelectorOnMainThread:@selector(setScrollIndicatorStyleWithName:) withObject:style waitUntilDone:NO];
4560 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4561 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4564 - (NSDictionary *) getApplicationInfo:(NSString *)display value:(NSString *)key {
4566 if (SBBundlePathForDisplayIdentifier(SBSSpringBoardServerPort(), [display UTF8String], path) != 0)
4567 return (id) [NSNull null];
4568 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:[[NSString stringWithUTF8String:path] stringByAppendingString:@"/Info.plist"]]);
4570 return (id) [NSNull null];
4571 return [info objectForKey:key];
4574 - (NSNumber *) getKernelNumber:(NSString *)name {
4575 const char *string([name UTF8String]);
4578 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4579 return (id) [NSNull null];
4581 if (size != sizeof(int))
4582 return (id) [NSNull null];
4585 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4586 return (id) [NSNull null];
4588 return [NSNumber numberWithInt:value];
4591 - (NSString *) getKernelString:(NSString *)name {
4592 const char *string([name UTF8String]);
4595 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4596 return (id) [NSNull null];
4598 char value[size + 1];
4599 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4600 return (id) [NSNull null];
4602 // XXX: just in case you request something ludicrous
4605 return [NSString stringWithCString:value];
4608 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4609 NSObject *value(CYIOGetValue([path UTF8String], entry));
4612 if ([value isKindOfClass:[NSData class]])
4613 value = CYHex((NSData *) value);
4618 - (NSArray *) getMetadataKeys {
4619 @synchronized (Values_) {
4620 return [Values_ allKeys];
4623 - (void) registerFrame:(DOMHTMLIFrameElement *)iframe {
4624 WebFrame *frame([iframe contentFrame]);
4625 [indirect_ registerFrame:frame];
4628 - (id) getMetadataValue:(NSString *)key {
4629 @synchronized (Values_) {
4630 return [Values_ objectForKey:key];
4633 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4634 @synchronized (Values_) {
4635 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4636 [Values_ removeObjectForKey:key];
4638 [Values_ setObject:value forKey:key];
4641 - (id) getSessionValue:(NSString *)key {
4642 @synchronized (SessionData_) {
4643 return [SessionData_ objectForKey:key];
4646 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4647 @synchronized (SessionData_) {
4648 if (value == (id) [WebUndefined undefined])
4649 [SessionData_ removeObjectForKey:key];
4651 [SessionData_ setObject:value forKey:key];
4654 - (void) addBridgedHost:(NSString *)host {
4655 @synchronized (HostConfig_) {
4656 [BridgedHosts_ addObject:host];
4659 - (void) addInsecureHost:(NSString *)host {
4660 @synchronized (HostConfig_) {
4661 [InsecureHosts_ addObject:host];
4664 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4665 @synchronized (HostConfig_) {
4666 if (scheme != (id) [WebUndefined undefined])
4667 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4669 [PipelinedHosts_ addObject:host];
4672 - (void) popViewController:(NSNumber *)value {
4673 if (value == (id) [WebUndefined undefined])
4674 value = [NSNumber numberWithBool:YES];
4675 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4678 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4679 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4681 for (NSString *section in sections)
4682 [array addObject:section];
4684 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4687 distribution, @"Distribution",
4689 nil] waitUntilDone:NO];
4692 - (BOOL) addTrivialSource:(NSString *)href {
4693 href = VerifySource(href);
4696 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4700 - (void) refreshSources {
4701 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4704 - (void) saveConfig {
4705 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4708 - (NSArray *) getAllSources {
4709 return [[Database sharedInstance] sources];
4712 - (NSArray *) getInstalledPackages {
4713 Database *database([Database sharedInstance]);
4714 @synchronized (database) {
4715 NSArray *packages([database packages]);
4716 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4717 for (Package *package in packages)
4718 if (![package uninstalled])
4719 [installed addObject:package];
4723 - (Package *) getPackageById:(NSString *)id {
4724 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4728 return (Package *) [NSNull null];
4731 - (NSString *) getLocaleIdentifier {
4732 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4735 - (NSArray *) getPreferredLanguages {
4739 - (NSArray *) statfs:(NSString *)path {
4742 if (path == nil || statfs([path UTF8String], &stat) == -1)
4745 return [NSArray arrayWithObjects:
4746 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4747 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4748 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4752 - (NSNumber *) du:(NSString *)path {
4753 NSNumber *value(nil);
4755 FILE *du(popen([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /usr/libexec/cydia/du -ks %@", ShellEscape(path)] UTF8String], "r"));
4758 while (fgets(line, sizeof(line), du) != NULL) {
4759 size_t length(strlen(line));
4760 while (length != 0 && line[length - 1] == '\n')
4761 line[--length] = '\0';
4762 if (char *tab = strchr(line, '\t')) {
4764 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4774 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4777 - (NSNumber *) isReachable:(NSString *)name {
4778 return [NSNumber numberWithBool:IsReachable([name UTF8String])];
4781 - (void) installPackages:(NSArray *)packages {
4782 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4785 - (NSString *) substitutePackageNames:(NSString *)message {
4786 NSMutableArray *words([[[message componentsSeparatedByString:@" "] mutableCopy] autorelease]);
4787 for (size_t i(0), e([words count]); i != e; ++i) {
4788 NSString *word([words objectAtIndex:i]);
4789 if (Package *package = [[Database sharedInstance] packageWithName:word])
4790 [words replaceObjectAtIndex:i withObject:[package name]];
4793 return [words componentsJoinedByString:@" "];
4796 - (void) removeButton {
4797 [indirect_ removeButton];
4800 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4801 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4804 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4805 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4808 - (void) setBadgeValue:(id)value {
4809 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4812 - (void) setAllowsNavigationAction:(NSString *)value {
4813 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4816 - (void) setHidesBackButton:(NSString *)value {
4817 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4820 - (void) setHidesNavigationBar:(NSString *)value {
4821 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4824 - (void) setNavigationBarStyle:(NSString *)value {
4825 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4828 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4829 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4830 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4831 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4834 - (void) setPasteboardString:(NSString *)value {
4835 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4838 - (void) setPasteboardURL:(NSString *)value {
4839 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4842 - (void) setToken:(NSString *)token {
4843 // XXX: the website expects this :/
4846 - (void) scrollToBottom:(NSNumber *)animated {
4847 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4850 - (void) setViewportWidth:(float)width {
4851 [indirect_ setViewportWidthOnMainThread:width];
4854 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4855 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4856 unsigned count([arguments count]);
4858 for (unsigned i(0); i != count; ++i)
4859 values[i] = [arguments objectAtIndex:i];
4860 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4863 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4864 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4866 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4868 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4874 @interface NSURL (CydiaSecure)
4877 @implementation NSURL (CydiaSecure)
4879 - (bool) isCydiaSecure {
4880 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4883 @synchronized (HostConfig_) {
4884 if ([InsecureHosts_ containsObject:[self host]])
4893 /* Cydia Browser Controller {{{ */
4894 @implementation CydiaWebViewController
4896 - (NSURL *) navigationURL {
4897 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4900 + (void) _initialize {
4901 [super _initialize];
4903 Diversions_ = [NSMutableSet setWithCapacity:0];
4906 + (void) addDiversion:(Diversion *)diversion {
4907 [Diversions_ addObject:diversion];
4910 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4911 [super webView:view didClearWindowObject:window forFrame:frame];
4912 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
4915 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia {
4916 WebDataSource *source([frame dataSource]);
4917 NSURLResponse *response([source response]);
4918 NSURL *url([response URL]);
4919 NSString *scheme([[url scheme] lowercaseString]);
4921 bool bridged(false);
4923 @synchronized (HostConfig_) {
4924 if ([scheme isEqualToString:@"file"])
4926 else if ([scheme isEqualToString:@"https"])
4927 if ([BridgedHosts_ containsObject:[url host]])
4932 [window setValue:cydia forKey:@"cydia"];
4935 - (void) _setupMail:(MFMailComposeViewController *)controller {
4936 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4938 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4939 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4942 - (NSURL *) URLWithURL:(NSURL *)url {
4943 return [Diversion divertURL:url];
4946 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4947 return [CydiaWebViewController requestWithHeaders:[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
4950 - (NSURLRequest *) webThreadWebView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4951 return [CydiaWebViewController requestWithHeaders:[super webThreadWebView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
4954 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request {
4955 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
4957 NSURL *url([copy URL]);
4958 NSString *href([url absoluteString]);
4959 NSString *host([url host]);
4961 if ([href hasPrefix:@"https://cydia.saurik.com/TSS/"]) {
4962 if (NSString *agent = [copy valueForHTTPHeaderField:@"X-User-Agent"]) {
4963 [copy setValue:agent forHTTPHeaderField:@"User-Agent"];
4964 [copy setValue:nil forHTTPHeaderField:@"X-User-Agent"];
4967 [copy setValue:nil forHTTPHeaderField:@"Referer"];
4968 [copy setValue:nil forHTTPHeaderField:@"Origin"];
4970 [copy setURL:[NSURL URLWithString:[@"http://gs.apple.com/TSS/" stringByAppendingString:[href substringFromIndex:29]]]];
4974 if ([copy valueForHTTPHeaderField:@"X-Cydia-Cf"] == nil)
4975 [copy setValue:[NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber] forHTTPHeaderField:@"X-Cydia-Cf"];
4976 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4977 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4979 bool bridged; @synchronized (HostConfig_) {
4980 bridged = [BridgedHosts_ containsObject:host];
4983 if ([url isCydiaSecure] && bridged && UniqueID_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Id"] == nil)
4984 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
4989 - (void) setDelegate:(id)delegate {
4990 [super setDelegate:delegate];
4991 [cydia_ setDelegate:delegate];
4994 - (NSString *) applicationNameForUserAgent {
4999 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
5000 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
5006 @interface AppCacheController : CydiaWebViewController {
5011 @implementation AppCacheController
5013 - (void) didReceiveMemoryWarning {
5014 // XXX: this doesn't work
5017 - (bool) retainsNetworkActivityIndicator {
5025 @interface NSObject (CydiaScript)
5026 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
5029 @implementation NSObject (CydiaScript)
5031 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5037 @implementation NSArray (CydiaScript)
5039 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5040 WebScriptObject *object([context evaluateWebScript:@"[]"]);
5041 for (size_t i(0), e([self count]); i != e; ++i)
5042 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
5048 @implementation NSDictionary (CydiaScript)
5050 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5051 WebScriptObject *object([context evaluateWebScript:@"({})"]);
5053 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
5060 /* Confirmation Controller {{{ */
5061 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
5062 if (!iterator.end())
5063 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
5064 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
5066 pkgCache::PkgIterator package(dep.TargetPkg());
5069 if (strcmp(package.Name(), "mobilesubstrate") == 0)
5076 @protocol ConfirmationControllerDelegate
5077 - (void) cancelAndClear:(bool)clear;
5078 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
5082 @interface ConfirmationController : CydiaWebViewController {
5083 _transient Database *database_;
5085 _H<UIAlertView> essential_;
5087 _H<NSDictionary> changes_;
5088 _H<NSMutableArray> issues_;
5089 _H<NSDictionary> sizes_;
5094 - (id) initWithDatabase:(Database *)database;
5098 @implementation ConfirmationController
5102 RestartSubstrate_ = true;
5103 [delegate_ confirmWithNavigationController:[self navigationController]];
5106 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
5107 NSString *context([alert context]);
5109 if ([context isEqualToString:@"remove"]) {
5110 if (button == [alert cancelButtonIndex])
5112 else if (button == [alert firstOtherButtonIndex]) {
5113 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
5116 [alert dismissWithClickedButtonIndex:-1 animated:YES];
5117 } else if ([context isEqualToString:@"unable"]) {
5118 [self dismissModalViewControllerAnimated:YES];
5119 [alert dismissWithClickedButtonIndex:-1 animated:YES];
5121 [super alertView:alert clickedButtonAtIndex:button];
5125 - (void) _doContinue {
5126 [delegate_ cancelAndClear:NO];
5127 [self dismissModalViewControllerAnimated:YES];
5130 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
5131 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
5135 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5136 [super webView:view didClearWindowObject:window forFrame:frame];
5138 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
5139 (id) changes_, @"changes",
5140 (id) issues_, @"issues",
5141 (id) sizes_, @"sizes",
5143 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
5146 - (id) initWithDatabase:(Database *)database {
5147 if ((self = [super init]) != nil) {
5148 database_ = database;
5150 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
5151 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
5152 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
5153 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
5154 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
5158 pkgCacheFile &cache([database_ cache]);
5159 NSArray *packages([database_ packages]);
5160 pkgDepCache::Policy *policy([database_ policy]);
5162 issues_ = [NSMutableArray arrayWithCapacity:4];
5164 for (Package *package in packages) {
5165 pkgCache::PkgIterator iterator([package iterator]);
5166 NSString *name([package id]);
5168 if ([package broken]) {
5169 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
5171 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5173 reasons, @"reasons",
5176 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
5180 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
5181 pkgCache::DepIterator start;
5182 pkgCache::DepIterator end;
5183 dep.GlobOr(start, end); // ++dep
5185 if (!cache->IsImportantDep(end))
5187 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
5190 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
5192 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5193 [NSString stringWithUTF8String:start.DepType()], @"relationship",
5194 clauses, @"clauses",
5198 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
5200 pkgCache::PkgIterator target(start.TargetPkg());
5201 if (target->ProvidesList != 0)
5202 reason = @"missing";
5204 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
5206 reason = @"installed";
5207 installed = [NSString stringWithUTF8String:ver.VerStr()];
5208 } else if (!cache[target].CandidateVerIter(cache).end())
5209 reason = @"uninstalled";
5210 else if (target->ProvidesList == 0)
5211 reason = @"uninstallable";
5213 reason = @"virtual";
5216 NSDictionary *version(start.TargetVer() == 0 ? (NSDictionary *) [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
5217 [NSString stringWithUTF8String:start.CompType()], @"operator",
5218 [NSString stringWithUTF8String:start.TargetVer()], @"value",
5221 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5222 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
5223 version, @"version",
5225 installed, @"installed",
5228 // yes, seriously. (wtf?)
5236 pkgDepCache::StateCache &state(cache[iterator]);
5238 static RegEx special_r("(firmware|gsc\\..*|cy\\+.*)");
5240 if (state.NewInstall())
5241 [installs addObject:name];
5242 // XXX: else if (state.Install())
5243 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
5244 [reinstalls addObject:name];
5245 // XXX: move before previous if
5246 else if (state.Upgrade())
5247 [upgrades addObject:name];
5248 else if (state.Downgrade())
5249 [downgrades addObject:name];
5250 else if (!state.Delete())
5251 // XXX: _assert(state.Keep());
5253 else if (special_r(name))
5254 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5255 [NSNull null], @"package",
5256 [NSArray arrayWithObjects:
5257 [NSDictionary dictionaryWithObjectsAndKeys:
5258 @"Conflicts", @"relationship",
5259 [NSArray arrayWithObjects:
5260 [NSDictionary dictionaryWithObjectsAndKeys:
5262 [NSNull null], @"version",
5263 @"installed", @"reason",
5270 if ([package essential])
5272 [removes addObject:name];
5275 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
5276 substrate_ |= DepSubstrate(iterator.CurrentVer());
5281 else if (Advanced_) {
5282 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
5284 essential_ = [[[UIAlertView alloc]
5285 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
5286 message:UCLocalize("REMOVING_ESSENTIALS_EX")
5288 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
5290 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
5294 [essential_ setContext:@"remove"];
5295 [essential_ setNumberOfRows:2];
5297 essential_ = [[[UIAlertView alloc]
5298 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
5299 message:UCLocalize("UNABLE_TO_COMPLY_EX")
5301 cancelButtonTitle:UCLocalize("OKAY")
5302 otherButtonTitles:nil
5305 [essential_ setContext:@"unable"];
5308 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5309 installs, @"installs",
5310 reinstalls, @"reinstalls",
5311 upgrades, @"upgrades",
5312 downgrades, @"downgrades",
5313 removes, @"removes",
5316 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5317 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
5318 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
5321 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
5325 - (UIBarButtonItem *) leftButton {
5326 return [[[UIBarButtonItem alloc]
5327 initWithTitle:UCLocalize("CANCEL")
5328 style:UIBarButtonItemStylePlain
5330 action:@selector(cancelButtonClicked)
5335 - (void) applyRightButton {
5336 if ([issues_ count] == 0 && ![self isLoading])
5337 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
5338 initWithTitle:UCLocalize("CONFIRM")
5339 style:UIBarButtonItemStyleDone
5341 action:@selector(confirmButtonClicked)
5344 [[self navigationItem] setRightBarButtonItem:nil];
5348 - (void) cancelButtonClicked {
5349 [delegate_ cancelAndClear:YES];
5350 [self dismissModalViewControllerAnimated:YES];
5354 - (void) confirmButtonClicked {
5355 if (essential_ != nil)
5365 /* Progress Data {{{ */
5366 @interface CydiaProgressData : NSObject {
5367 _transient id delegate_;
5376 _H<NSMutableArray> events_;
5377 _H<NSString> title_;
5379 _H<NSString> status_;
5380 _H<NSString> finish_;
5385 @implementation CydiaProgressData
5387 + (NSArray *) _attributeKeys {
5388 return [NSArray arrayWithObjects:
5400 - (NSArray *) attributeKeys {
5401 return [[self class] _attributeKeys];
5404 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5405 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5409 if ((self = [super init]) != nil) {
5410 events_ = [NSMutableArray arrayWithCapacity:32];
5418 - (void) setDelegate:(id)delegate {
5419 delegate_ = delegate;
5422 - (void) setPercent:(float)value {
5426 - (NSNumber *) percent {
5427 return [NSNumber numberWithFloat:percent_];
5430 - (void) setCurrent:(float)value {
5434 - (NSNumber *) current {
5435 return [NSNumber numberWithFloat:current_];
5438 - (void) setTotal:(float)value {
5442 - (NSNumber *) total {
5443 return [NSNumber numberWithFloat:total_];
5446 - (void) setSpeed:(float)value {
5450 - (NSNumber *) speed {
5451 return [NSNumber numberWithFloat:speed_];
5454 - (NSArray *) events {
5458 - (void) removeAllEvents {
5459 [events_ removeAllObjects];
5462 - (void) addEvent:(CydiaProgressEvent *)event {
5463 [events_ addObject:event];
5466 - (void) setTitle:(NSString *)text {
5470 - (NSString *) title {
5474 - (void) setFinish:(NSString *)text {
5478 - (NSString *) finish {
5479 return (id) finish_ ?: [NSNull null];
5482 - (void) setRunning:(bool)running {
5486 - (NSNumber *) running {
5487 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5492 /* Progress Controller {{{ */
5493 @interface ProgressController : CydiaWebViewController <
5496 _transient Database *database_;
5497 _H<CydiaProgressData, 1> progress_;
5501 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5503 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5505 - (void) setTitle:(NSString *)title;
5506 - (void) setCancellable:(bool)cancellable;
5510 @implementation ProgressController
5513 [database_ setProgressDelegate:nil];
5517 - (UIBarButtonItem *) leftButton {
5518 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5519 initWithTitle:UCLocalize("CANCEL")
5520 style:UIBarButtonItemStylePlain
5522 action:@selector(cancel)
5523 ] autorelease] : nil;
5526 - (void) updateCancel {
5527 [super applyLeftButton];
5530 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5531 if ((self = [super init]) != nil) {
5532 database_ = database;
5533 delegate_ = delegate;
5535 [database_ setProgressDelegate:self];
5537 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5538 [progress_ setDelegate:self];
5540 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5542 [scroller_ setBackgroundColor:[UIColor blackColor]];
5544 [[self navigationItem] setHidesBackButton:YES];
5546 [self updateCancel];
5550 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5551 [super webView:view didClearWindowObject:window forFrame:frame];
5552 [window setValue:progress_ forKey:@"cydiaProgress"];
5555 - (void) updateProgress {
5556 [self dispatchEvent:@"CydiaProgressUpdate"];
5559 - (void) viewWillAppear:(BOOL)animated {
5560 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5561 [super viewWillAppear:animated];
5565 UpdateExternalStatus(0);
5568 [delegate_ saveState];
5572 [delegate_ returnToCydia];
5576 [delegate_ terminateWithSuccess];
5577 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5578 [delegate_ suspendWithAnimation:YES];
5580 [delegate_ suspend];*/
5592 UIProgressHUD *hud([delegate_ addProgressHUD]);
5593 [hud setText:UCLocalize("LOADING")];
5594 [delegate_ performSelector:@selector(reloadSpringBoard) withObject:nil afterDelay:0.5];
5600 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5601 SBReboot(SBSSpringBoardServerPort());
5603 reboot2(RB_AUTOBOOT);
5610 - (void) setTitle:(NSString *)title {
5611 [progress_ setTitle:title];
5612 [self updateProgress];
5615 - (UIBarButtonItem *) rightButton {
5616 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5617 initWithTitle:UCLocalize("CLOSE")
5618 style:UIBarButtonItemStylePlain
5620 action:@selector(close)
5624 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5625 UpdateExternalStatus(1);
5627 [progress_ setRunning:true];
5628 [self setTitle:title];
5629 // implicit updateProgress
5631 SHA1SumValue notifyconf; {
5633 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5636 MMap mmap(file, MMap::ReadOnly);
5638 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5639 notifyconf = sha1.Result();
5643 SHA1SumValue springlist; {
5645 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5648 MMap mmap(file, MMap::ReadOnly);
5650 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5651 springlist = sha1.Result();
5655 if (invocation != nil) {
5656 [invocation yieldToSelector:@selector(invoke)];
5657 [self setTitle:@"COMPLETE"];
5662 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5665 MMap mmap(file, MMap::ReadOnly);
5667 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5668 if (!(notifyconf == sha1.Result()))
5675 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5678 MMap mmap(file, MMap::ReadOnly);
5680 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5681 if (!(springlist == sha1.Result()))
5687 if (RestartSubstrate_)
5691 RestartSubstrate_ = false;
5694 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5695 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5696 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5697 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5698 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5701 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5703 [progress_ setRunning:false];
5704 [self updateProgress];
5706 [self applyRightButton];
5709 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5710 [progress_ addEvent:event];
5711 [self updateProgress];
5714 - (bool) isProgressCancelled {
5715 return cancel_ == 2;
5720 [self updateCancel];
5723 - (void) setCancellable:(bool)cancellable {
5724 unsigned cancel(cancel_);
5728 else if (cancel_ == 0)
5731 if (cancel != cancel_)
5732 [self updateCancel];
5735 - (void) setProgressCancellable:(NSNumber *)cancellable {
5736 [self setCancellable:[cancellable boolValue]];
5739 - (void) setProgressPercent:(NSNumber *)percent {
5740 [progress_ setPercent:[percent floatValue]];
5741 [self updateProgress];
5744 - (void) setProgressStatus:(NSDictionary *)status {
5745 if (status == nil) {
5746 [progress_ setCurrent:0];
5747 [progress_ setTotal:0];
5748 [progress_ setSpeed:0];
5750 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5752 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5753 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5754 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5757 [self updateProgress];
5763 /* Package Cell {{{ */
5764 @interface PackageCell : CyteTableViewCell <
5765 CyteTableViewCellDelegate
5769 _H<NSString> description_;
5771 _H<NSString> source_;
5773 _H<UIImage> placard_;
5777 - (PackageCell *) init;
5778 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5780 - (void) drawContentRect:(CGRect)rect;
5784 @implementation PackageCell
5786 - (PackageCell *) init {
5787 CGRect frame(CGRectMake(0, 0, 320, 74));
5788 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5789 UIView *content([self contentView]);
5790 CGRect bounds([content bounds]);
5792 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5793 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5794 [content addSubview:content_];
5796 [content_ setDelegate:self];
5797 [content_ setOpaque:YES];
5801 - (NSString *) accessibilityLabel {
5805 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5806 summarized_ = summary;
5816 [content_ setBackgroundColor:[UIColor whiteColor]];
5820 Source *source = [package source];
5822 icon_ = [package icon];
5824 if (NSString *name = [package name])
5825 name_ = [NSString stringWithString:name];
5827 if (NSString *description = [package shortDescription])
5828 description_ = [NSString stringWithString:description];
5830 commercial_ = [package isCommercial];
5832 NSString *label = nil;
5833 bool trusted = false;
5835 if (source != nil) {
5836 label = [source label];
5837 trusted = [source trusted];
5838 } else if ([[package id] isEqualToString:@"firmware"])
5839 label = UCLocalize("APPLE");
5841 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5843 NSString *from(label);
5845 NSString *section = [package simpleSection];
5846 if (section != nil && ![section isEqualToString:label]) {
5847 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5848 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5851 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5853 if (NSString *purpose = [package primaryPurpose])
5854 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5859 if (NSString *mode = [package mode]) {
5860 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5861 color = RemovingColor_;
5862 placard = @"removing";
5864 color = InstallingColor_;
5865 placard = @"installing";
5868 color = [UIColor whiteColor];
5870 if ([package installed] != nil)
5871 placard = @"installed";
5876 [content_ setBackgroundColor:color];
5879 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5882 [self setNeedsDisplay];
5883 [content_ setNeedsDisplay];
5886 - (void) drawSummaryContentRect:(CGRect)rect {
5887 bool highlighted(highlighted_);
5888 float width([self bounds].size.width);
5892 rect.size = [(UIImage *) icon_ size];
5894 while (rect.size.width > 16 || rect.size.height > 16) {
5895 rect.size.width /= 2;
5896 rect.size.height /= 2;
5899 rect.origin.x = 19 - rect.size.width / 2;
5900 rect.origin.y = 19 - rect.size.height / 2;
5902 [icon_ drawInRect:Retina(rect)];
5905 if (badge_ != nil) {
5907 rect.size = [(UIImage *) badge_ size];
5909 rect.size.width /= 4;
5910 rect.size.height /= 4;
5912 rect.origin.x = 25 - rect.size.width / 2;
5913 rect.origin.y = 25 - rect.size.height / 2;
5915 [badge_ drawInRect:Retina(rect)];
5918 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5922 UISetColor(commercial_ ? Purple_ : Black_);
5923 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
5925 if (placard_ != nil)
5926 [placard_ drawAtPoint:CGPointMake(width - 52, 11)];
5929 - (void) drawNormalContentRect:(CGRect)rect {
5930 bool highlighted(highlighted_);
5931 float width([self bounds].size.width);
5935 rect.size = [(UIImage *) icon_ size];
5937 while (rect.size.width > 32 || rect.size.height > 32) {
5938 rect.size.width /= 2;
5939 rect.size.height /= 2;
5942 rect.origin.x = 25 - rect.size.width / 2;
5943 rect.origin.y = 25 - rect.size.height / 2;
5945 [icon_ drawInRect:Retina(rect)];
5948 if (badge_ != nil) {
5950 rect.size = [(UIImage *) badge_ size];
5952 rect.size.width /= 2;
5953 rect.size.height /= 2;
5955 rect.origin.x = 36 - rect.size.width / 2;
5956 rect.origin.y = 36 - rect.size.height / 2;
5958 [badge_ drawInRect:Retina(rect)];
5961 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5965 UISetColor(commercial_ ? Purple_ : Black_);
5966 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
5967 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
5970 UISetColor(commercial_ ? Purplish_ : Gray_);
5971 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:NSLineBreakByTruncatingTail];
5973 if (placard_ != nil)
5974 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5977 - (void) drawContentRect:(CGRect)rect {
5979 [self drawSummaryContentRect:rect];
5981 [self drawNormalContentRect:rect];
5986 /* Section Cell {{{ */
5987 @interface SectionCell : CyteTableViewCell <
5988 CyteTableViewCellDelegate
5990 _H<NSString> basic_;
5991 _H<NSString> section_;
5993 _H<NSString> count_;
5995 _H<UISwitch> switch_;
5999 - (void) setSection:(Section *)section editing:(BOOL)editing;
6003 @implementation SectionCell
6005 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
6006 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
6007 icon_ = [UIImage imageNamed:@"folder.png"];
6008 // XXX: this initial frame is wrong, but is fixed later
6009 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
6010 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
6012 UIView *content([self contentView]);
6013 CGRect bounds([content bounds]);
6015 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
6016 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6017 [content addSubview:content_];
6018 [content_ setBackgroundColor:[UIColor whiteColor]];
6020 [content_ setDelegate:self];
6024 - (void) onSwitch:(id)sender {
6025 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
6026 if (metadata == nil) {
6027 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
6028 [Sections_ setObject:metadata forKey:basic_];
6031 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
6034 - (void) setSection:(Section *)section editing:(BOOL)editing {
6035 if (editing != editing_) {
6037 [switch_ removeFromSuperview];
6039 [self addSubview:switch_];
6048 if (section == nil) {
6049 name_ = UCLocalize("ALL_PACKAGES");
6052 basic_ = [section name];
6053 section_ = [section localized];
6055 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
6056 count_ = [NSString stringWithFormat:@"%zd", [section count]];
6059 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
6062 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
6063 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
6065 [content_ setNeedsDisplay];
6068 - (void) setFrame:(CGRect)frame {
6069 [super setFrame:frame];
6071 CGRect rect([switch_ frame]);
6072 [switch_ setFrame:CGRectMake(frame.size.width - rect.size.width - 9, 9, rect.size.width, rect.size.height)];
6075 - (NSString *) accessibilityLabel {
6079 - (void) drawContentRect:(CGRect)rect {
6080 bool highlighted(highlighted_ && !editing_);
6082 [icon_ drawInRect:CGRectMake(7, 7, 32, 32)];
6084 if (highlighted && kCFCoreFoundationVersionNumber < 800)
6087 float width(rect.size.width);
6089 width -= 9 + [switch_ frame].size.width;
6093 [name_ drawAtPoint:CGPointMake(48, 12) forWidth:(width - 58) withFont:Font18_ lineBreakMode:NSLineBreakByTruncatingTail];
6095 CGSize size = [count_ sizeWithFont:Font14_];
6097 UISetColor(Folder_);
6099 [count_ drawAtPoint:CGPointMake(Retina(10 + (30 - size.width) / 2), 18) withFont:Font12Bold_];
6105 /* File Table {{{ */
6106 @interface FileTable : CyteViewController <
6107 UITableViewDataSource,
6110 _transient Database *database_;
6111 _H<Package> package_;
6113 _H<NSMutableArray> files_;
6114 _H<UITableView, 2> list_;
6117 - (id) initWithDatabase:(Database *)database;
6118 - (void) setPackage:(Package *)package;
6122 @implementation FileTable
6124 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6125 return files_ == nil ? 0 : [files_ count];
6128 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6132 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6133 static NSString *reuseIdentifier = @"Cell";
6135 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6137 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6138 [cell setFont:[UIFont systemFontOfSize:16]];
6140 [cell setText:[files_ objectAtIndex:indexPath.row]];
6141 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
6146 - (NSURL *) navigationURL {
6147 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
6151 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
6152 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6153 [list_ setRowHeight:24.0f];
6154 [(UITableView *) list_ setDataSource:self];
6155 [list_ setDelegate:self];
6156 [self setView:list_];
6159 - (void) viewDidLoad {
6160 [super viewDidLoad];
6162 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
6165 - (void) releaseSubviews {
6171 [super releaseSubviews];
6174 - (id) initWithDatabase:(Database *)database {
6175 if ((self = [super init]) != nil) {
6176 database_ = database;
6180 - (void) setPackage:(Package *)package {
6184 files_ = [NSMutableArray arrayWithCapacity:32];
6186 if (package != nil) {
6188 name_ = [package id];
6190 if (NSArray *files = [package files])
6191 [files_ addObjectsFromArray:files];
6193 if ([files_ count] != 0) {
6194 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
6195 [files_ removeObjectAtIndex:0];
6196 [files_ sortUsingSelector:@selector(compareByPath:)];
6198 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
6199 [stack addObject:@"/"];
6201 for (int i(0), e([files_ count]); i != e; ++i) {
6202 NSString *file = [files_ objectAtIndex:i];
6203 while (![file hasPrefix:[stack lastObject]])
6204 [stack removeLastObject];
6205 NSString *directory = [stack lastObject];
6206 [stack addObject:[file stringByAppendingString:@"/"]];
6207 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
6208 ([stack count] - 2) * 3, "",
6209 [file substringFromIndex:[directory length]]
6218 - (void) reloadData {
6221 [self setPackage:[database_ packageWithName:name_]];
6226 /* Package Controller {{{ */
6227 @interface CYPackageController : CydiaWebViewController <
6228 UIActionSheetDelegate
6230 _transient Database *database_;
6231 _H<Package> package_;
6234 std::vector<std::pair<_H<NSString>, _H<NSString>>> buttons_;
6235 _H<UIBarButtonItem> button_;
6238 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer;
6242 @implementation CYPackageController
6244 - (NSURL *) navigationURL {
6245 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
6248 - (void) _clickButtonWithName:(NSString *)name {
6249 if ([name isEqualToString:@"CLEAR"])
6250 [delegate_ clearPackage:package_];
6251 else if ([name isEqualToString:@"INSTALL"])
6252 [delegate_ installPackage:package_];
6253 else if ([name isEqualToString:@"REINSTALL"])
6254 [delegate_ installPackage:package_];
6255 else if ([name isEqualToString:@"REMOVE"])
6256 [delegate_ removePackage:package_];
6257 else if ([name isEqualToString:@"UPGRADE"])
6258 [delegate_ installPackage:package_];
6259 else _assert(false);
6262 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
6263 NSString *context([sheet context]);
6265 if ([context isEqualToString:@"modify"]) {
6266 if (button != [sheet cancelButtonIndex]) {
6268 [self performSelector:@selector(_clickButtonWithName:) withObject:buttons_[button].first afterDelay:0];
6270 [self _clickButtonWithName:buttons_[button].first];
6273 [sheet dismissWithClickedButtonIndex:button animated:YES];
6277 - (bool) _allowJavaScriptPanel {
6282 - (void) _customButtonClicked {
6283 size_t count(buttons_.size());
6288 [self _clickButtonWithName:buttons_[0].first];
6290 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
6291 for (const auto &button : buttons_)
6292 [buttons addObject:button.second];
6294 UIActionSheet *sheet = [[[UIActionSheet alloc]
6297 cancelButtonTitle:nil
6298 destructiveButtonTitle:nil
6299 otherButtonTitles:nil
6302 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
6304 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
6305 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
6307 [sheet setContext:@"modify"];
6309 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
6313 - (void) reloadButtonClicked {
6314 if (commercial_ && function_ == nil && [package_ uninstalled])
6316 [self customButtonClicked];
6319 - (void) applyLoadingTitle {
6320 // Don't show "Loading" as the title. Ever.
6323 - (UIBarButtonItem *) rightButton {
6328 - (void) setPageColor:(UIColor *)color {
6329 return [super setPageColor:nil];
6332 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer {
6333 if ((self = [super init]) != nil) {
6334 database_ = database;
6335 name_ = name == nil ? @"" : [NSString stringWithString:name];
6336 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]] withReferrer:referrer];
6340 - (void) reloadData {
6343 package_ = [database_ packageWithName:name_];
6347 if (package_ != nil) {
6348 [(Package *) package_ parse];
6350 commercial_ = [package_ isCommercial];
6352 if ([package_ mode] != nil)
6353 buttons_.push_back(std::make_pair(@"CLEAR", UCLocalize("CLEAR")));
6354 if ([package_ source] == nil);
6355 else if ([package_ upgradableAndEssential:NO])
6356 buttons_.push_back(std::make_pair(@"UPGRADE", UCLocalize("UPGRADE")));
6357 else if ([package_ uninstalled])
6358 buttons_.push_back(std::make_pair(@"INSTALL", UCLocalize("INSTALL")));
6360 buttons_.push_back(std::make_pair(@"REINSTALL", UCLocalize("REINSTALL")));
6361 if (![package_ uninstalled])
6362 buttons_.push_back(std::make_pair(@"REMOVE", UCLocalize("REMOVE")));
6366 switch (buttons_.size()) {
6367 case 0: title = nil; break;
6368 case 1: title = buttons_[0].second; break;
6369 default: title = UCLocalize("MODIFY"); break;
6372 button_ = [[[UIBarButtonItem alloc]
6374 style:UIBarButtonItemStylePlain
6376 action:@selector(customButtonClicked)
6380 - (bool) isLoading {
6381 return commercial_ ? [super isLoading] : false;
6387 /* Package List Controller {{{ */
6388 @interface PackageListController : CyteViewController <
6389 UITableViewDataSource,
6392 _transient Database *database_;
6394 _H<NSArray> packages_;
6395 _H<NSArray> sections_;
6396 _H<UITableView, 2> list_;
6398 _H<NSArray> thumbs_;
6399 std::vector<NSInteger> offset_;
6401 _H<NSString> title_;
6402 unsigned reloading_;
6405 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6406 - (void) setDelegate:(id)delegate;
6407 - (void) resetCursor;
6410 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages;
6414 @implementation PackageListController
6416 - (NSURL *) referrerURL {
6417 return [self navigationURL];
6420 - (bool) isSummarized {
6424 - (bool) showsSections {
6428 - (void) deselectWithAnimation:(BOOL)animated {
6429 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6432 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6433 CGRect base = [[self view] bounds];
6434 base.size.height -= bounds.size.height;
6435 base.origin = [list_ frame].origin;
6437 [UIView beginAnimations:nil context:NULL];
6438 [UIView setAnimationBeginsFromCurrentState:YES];
6439 [UIView setAnimationCurve:curve];
6440 [UIView setAnimationDuration:duration];
6441 [list_ setFrame:base];
6442 [UIView commitAnimations];
6445 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6446 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6449 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6450 [self resizeForKeyboardBounds:bounds duration:0];
6453 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6454 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6455 *curve = UIViewAnimationCurveEaseInOut;
6457 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6459 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6462 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6465 - (void) keyboardWillShow:(NSNotification *)notification {
6468 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6469 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6471 NSTimeInterval duration;
6472 UIViewAnimationCurve curve;
6473 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6475 CGRect kbframe = CGRectMake(Retina(center.x - bounds.size.width / 2), Retina(center.y - bounds.size.height / 2), bounds.size.width, bounds.size.height);
6476 UIViewController *base = self;
6477 while ([base parentOrPresentingViewController] != nil)
6478 base = [base parentOrPresentingViewController];
6479 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6480 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6482 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6483 intersection.size.height += CYStatusBarHeight();
6485 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6488 - (void) keyboardWillHide:(NSNotification *)notification {
6489 NSTimeInterval duration;
6490 UIViewAnimationCurve curve;
6491 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6493 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6496 - (void) viewWillAppear:(BOOL)animated {
6497 [super viewWillAppear:animated];
6499 [self resizeForKeyboardBounds:CGRectZero];
6500 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6501 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6504 - (void) viewWillDisappear:(BOOL)animated {
6505 [super viewWillDisappear:animated];
6507 [self resizeForKeyboardBounds:CGRectZero];
6508 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6509 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6512 - (void) viewDidAppear:(BOOL)animated {
6513 [super viewDidAppear:animated];
6514 [self deselectWithAnimation:animated];
6517 - (void) didSelectPackage:(Package *)package {
6518 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[[self referrerURL] absoluteString]] autorelease]);
6519 [view setDelegate:delegate_];
6520 [[self navigationController] pushViewController:view animated:YES];
6523 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6524 NSInteger count([sections_ count]);
6525 return count == 0 ? 1 : count;
6528 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6529 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6531 return [[sections_ objectAtIndex:section] name];
6534 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6535 if ([sections_ count] == 0)
6537 return [[sections_ objectAtIndex:section] count];
6540 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6541 @synchronized (database_) {
6542 if ([database_ era] != era_)
6545 Section *section([sections_ objectAtIndex:[path section]]);
6546 NSInteger row([path row]);
6547 Package *package([packages_ objectAtIndex:([section row] + row)]);
6548 return [[package retain] autorelease];
6551 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6552 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6554 cell = [[[PackageCell alloc] init] autorelease];
6556 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6557 [cell setPackage:package asSummary:[self isSummarized]];
6561 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6562 Package *package([self packageAtIndexPath:path]);
6563 package = [database_ packageWithName:[package id]];
6564 [self didSelectPackage:package];
6567 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6571 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6572 return offset_[index];
6575 - (void) updateHeight {
6576 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6579 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6580 if ((self = [super init]) != nil) {
6581 database_ = database;
6582 title_ = [title copy];
6583 [[self navigationItem] setTitle:title_];
6588 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
6589 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
6590 [self setView:view];
6592 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6593 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6594 [view addSubview:list_];
6596 // XXX: is 20 the most optimal number here?
6597 [list_ setSectionIndexMinimumDisplayRowCount:20];
6599 [(UITableView *) list_ setDataSource:self];
6600 [list_ setDelegate:self];
6602 [self updateHeight];
6605 - (void) releaseSubviews {
6614 [super releaseSubviews];
6617 - (void) setDelegate:(id)delegate {
6618 delegate_ = delegate;
6621 - (bool) shouldYield {
6625 - (bool) shouldBlock {
6629 - (NSMutableArray *) _reloadPackages {
6630 @synchronized (database_) {
6631 era_ = [database_ era];
6632 NSArray *packages([database_ packages]);
6634 return [NSMutableArray arrayWithArray:packages];
6637 - (void) _reloadData {
6638 if (reloading_ != 0) {
6643 NSMutableArray *packages;
6646 if ([self shouldYield]) {
6650 if (![self shouldBlock])
6653 hud = [delegate_ addProgressHUD];
6654 [hud setText:UCLocalize("LOADING")];
6658 packages = [self yieldToSelector:@selector(_reloadPackages)];
6661 [delegate_ removeProgressHUD:hud];
6662 } while (reloading_ == 2);
6664 packages = [self _reloadPackages];
6667 @synchronized (database_) {
6668 if (era_ != [database_ era])
6675 packages_ = packages;
6677 if ([self showsSections])
6678 sections_ = [self sectionsForPackages:packages];
6680 Section *section([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6681 [section setCount:[packages_ count]];
6682 sections_ = [NSArray arrayWithObject:section];
6685 [self updateHeight];
6687 _profile(PackageTable$reloadData$List)
6688 [(UITableView *) list_ setDataSource:self];
6696 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
6697 Section *prefix([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6698 size_t end([packages count]);
6700 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
6701 Section *section(prefix);
6703 thumbs_ = CollationThumbs_;
6704 offset_ = CollationOffset_;
6707 size_t offsets([CollationStarts_ count]);
6709 NSString *start([CollationStarts_ objectAtIndex:offset]);
6710 size_t length([start length]);
6712 for (size_t index(0); index != end; ++index) {
6714 Package *package([packages objectAtIndex:index]);
6715 NSString *name(PackageName(package, @selector(cyname)));
6717 //while ([start compare:name options:NSNumericSearch range:NSMakeRange(0, length) locale:CollationLocale_] != NSOrderedDescending) {
6718 while (StringNameCompare(start, name, length) != kCFCompareGreaterThan) {
6719 NSString *title([CollationTitles_ objectAtIndex:offset]);
6720 section = [[[Section alloc] initWithName:title row:index localize:NO] autorelease];
6721 [sections addObject:section];
6723 start = ++offset == offsets ? nil : [CollationStarts_ objectAtIndex:offset];
6726 length = [start length];
6730 [section addToCount];
6733 for (; offset != offsets; ++offset) {
6734 NSString *title([CollationTitles_ objectAtIndex:offset]);
6735 Section *section([[[Section alloc] initWithName:title row:end localize:NO] autorelease]);
6736 [sections addObject:section];
6739 if ([prefix count] != 0) {
6740 Section *suffix([sections lastObject]);
6741 [prefix setName:[suffix name]];
6742 [suffix setName:nil];
6743 [sections insertObject:prefix atIndex:(offsets - 1)];
6749 - (void) reloadData {
6752 if ([self shouldYield])
6753 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6758 - (void) resetCursor {
6759 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6762 - (void) clearData {
6763 [self updateHeight];
6765 [list_ setDataSource:nil];
6773 /* Filtered Package List Controller {{{ */
6774 typedef Function<bool, Package *> PackageFilter;
6775 typedef Function<void, NSMutableArray *> PackageSorter;
6776 @interface FilteredPackageListController : PackageListController {
6777 PackageFilter filter_;
6778 PackageSorter sorter_;
6781 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter;
6783 - (void) setFilter:(PackageFilter)filter;
6784 - (void) setSorter:(PackageSorter)sorter;
6788 @implementation FilteredPackageListController
6790 - (void) setFilter:(PackageFilter)filter {
6791 @synchronized (self) {
6795 - (void) setSorter:(PackageSorter)sorter {
6796 @synchronized (self) {
6800 - (NSMutableArray *) _reloadPackages {
6801 @synchronized (database_) {
6802 era_ = [database_ era];
6804 NSArray *packages([database_ packages]);
6805 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6807 PackageFilter filter;
6808 PackageSorter sorter;
6810 @synchronized (self) {
6815 _profile(PackageTable$reloadData$Filter)
6816 for (Package *package in packages)
6817 if ([package valid] && filter(package))
6818 [filtered addObject:package];
6826 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter {
6827 if ((self = [super initWithDatabase:database title:title]) != nil) {
6828 [self setFilter:filter];
6835 /* Home Controller {{{ */
6836 @interface HomeController : CydiaWebViewController {
6837 CFRunLoopRef runloop_;
6838 SCNetworkReachabilityRef reachability_;
6843 @implementation HomeController
6845 static void HomeControllerReachabilityCallback(SCNetworkReachabilityRef reachability, SCNetworkReachabilityFlags flags, void *info) {
6846 [(HomeController *) info dispatchEvent:@"CydiaReachabilityCallback"];
6850 if ((self = [super init]) != nil) {
6851 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6854 reachability_ = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "cydia.saurik.com");
6855 if (reachability_ != NULL) {
6856 SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
6857 SCNetworkReachabilitySetCallback(reachability_, HomeControllerReachabilityCallback, &context);
6859 CFRunLoopRef runloop(CFRunLoopGetCurrent());
6860 if (SCNetworkReachabilityScheduleWithRunLoop(reachability_, runloop, kCFRunLoopDefaultMode))
6867 if (reachability_ != NULL && runloop_ != NULL)
6868 SCNetworkReachabilityUnscheduleFromRunLoop(reachability_, runloop_, kCFRunLoopDefaultMode);
6872 - (NSURL *) navigationURL {
6873 return [NSURL URLWithString:@"cydia://home"];
6876 - (void) aboutButtonClicked {
6877 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6879 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6880 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6881 [alert setCancelButtonIndex:0];
6884 @"Copyright \u00a9 2008-2015\n"
6887 "Jay Freeman (saurik)\n"
6888 "saurik@saurik.com\n"
6889 "http://www.saurik.com/"
6895 - (UIBarButtonItem *) leftButton {
6896 return [[[UIBarButtonItem alloc]
6897 initWithTitle:UCLocalize("ABOUT")
6898 style:UIBarButtonItemStylePlain
6900 action:@selector(aboutButtonClicked)
6907 /* Cydia Navigation Controller Interface {{{ */
6908 @interface UINavigationController (Cydia)
6910 - (NSArray *) navigationURLCollection;
6911 - (void) unloadData;
6916 /* Cydia Tab Bar Controller {{{ */
6917 @interface CydiaTabBarController : CyteTabBarController <
6918 UITabBarControllerDelegate,
6921 _transient Database *database_;
6923 _H<UIActivityIndicatorView> indicator_;
6926 // XXX: ok, "updatedelegate_"?...
6927 _transient NSObject<CydiaDelegate> *updatedelegate_;
6930 - (NSArray *) navigationURLCollection;
6931 - (void) beginUpdate;
6936 @implementation CydiaTabBarController
6938 - (NSArray *) navigationURLCollection {
6939 NSMutableArray *items([NSMutableArray array]);
6941 // XXX: Should this deal with transient view controllers?
6942 for (id navigation in [self viewControllers]) {
6943 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6945 [items addObject:stack];
6951 - (id) initWithDatabase:(Database *)database {
6952 if ((self = [super init]) != nil) {
6953 database_ = database;
6954 [self setDelegate:self];
6956 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteTiny] autorelease];
6957 [indicator_ setOrigin:CGPointMake(kCFCoreFoundationVersionNumber >= 800 ? 2 : 4, 2)];
6959 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6963 - (void) beginUpdate {
6967 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
6968 UITabBarItem *item([controller tabBarItem]);
6970 [item setBadgeValue:@""];
6971 UIView *badge(MSHookIvar<UIView *>([item view], "_badge"));
6973 [indicator_ startAnimating];
6974 [badge addSubview:indicator_];
6976 [updatedelegate_ retainNetworkActivityIndicator];
6980 detachNewThreadSelector:@selector(performUpdate)
6986 - (void) performUpdate {
6987 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
6989 SourceStatus status(self, database_);
6990 [database_ updateWithStatus:status];
6993 performSelectorOnMainThread:@selector(completeUpdate)
7001 - (void) stopUpdateWithSelector:(SEL)selector {
7003 [updatedelegate_ releaseNetworkActivityIndicator];
7005 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
7006 [[controller tabBarItem] setBadgeValue:nil];
7008 [indicator_ removeFromSuperview];
7009 [indicator_ stopAnimating];
7011 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
7014 - (void) completeUpdate {
7017 [self stopUpdateWithSelector:@selector(reloadData)];
7020 - (void) cancelUpdate {
7021 [self stopUpdateWithSelector:@selector(updateDataAndLoad)];
7024 - (void) cancelPressed {
7025 [self cancelUpdate];
7032 - (bool) isSourceCancelled {
7036 - (void) startSourceFetch:(NSString *)uri {
7039 - (void) stopSourceFetch:(NSString *)uri {
7042 - (void) setUpdateDelegate:(id)delegate {
7043 updatedelegate_ = delegate;
7049 /* Cydia Navigation Controller Implementation {{{ */
7050 @implementation UINavigationController (Cydia)
7052 - (NSArray *) navigationURLCollection {
7053 NSMutableArray *stack([NSMutableArray array]);
7055 for (CyteViewController *controller in [self viewControllers]) {
7056 NSString *url = [[controller navigationURL] absoluteString];
7058 [stack addObject:url];
7064 - (void) reloadData {
7067 UIViewController *visible([self visibleViewController]);
7069 [visible reloadData];
7071 // on the iPad, this view controller is ALSO visible. :(
7073 if (UIViewController *modal = [self modalViewController])
7074 if ([modal modalPresentationStyle] == UIModalPresentationFormSheet)
7075 if (UIViewController *top = [self topViewController])
7080 - (void) unloadData {
7081 for (CyteViewController *page in [self viewControllers])
7090 /* Cydia:// Protocol {{{ */
7091 @interface CydiaURLProtocol : NSURLProtocol {
7096 @implementation CydiaURLProtocol
7098 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7099 NSURL *url([request URL]);
7103 NSString *scheme([[url scheme] lowercaseString]);
7104 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7106 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7112 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7116 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7117 id<NSURLProtocolClient> client([self client]);
7119 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7121 NSData *data(UIImagePNGRepresentation(icon));
7123 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7124 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7125 [client URLProtocol:self didLoadData:data];
7126 [client URLProtocolDidFinishLoading:self];
7130 - (void) startLoading {
7131 id<NSURLProtocolClient> client([self client]);
7132 NSURLRequest *request([self request]);
7134 NSURL *url([request URL]);
7135 NSString *href([url absoluteString]);
7136 NSString *scheme([[url scheme] lowercaseString]);
7140 if ([scheme isEqualToString:@"cydia"])
7141 path = [href substringFromIndex:8];
7142 else if ([scheme isEqualToString:@"about"])
7143 path = [href substringFromIndex:12];
7144 else _assert(false);
7146 NSRange slash([path rangeOfString:@"/"]);
7149 if (slash.location == NSNotFound) {
7153 command = [path substringToIndex:slash.location];
7154 path = [path substringFromIndex:(slash.location + 1)];
7157 Database *database([Database sharedInstance]);
7159 if ([command isEqualToString:@"package-icon"]) {
7162 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7163 Package *package([database packageWithName:path]);
7167 UIImage *icon([package icon]);
7168 [self _returnPNGWithImage:icon forRequest:request];
7169 } else if ([command isEqualToString:@"uikit-image"]) {
7172 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7173 UIImage *icon(_UIImageWithName(path));
7174 [self _returnPNGWithImage:icon forRequest:request];
7175 } else if ([command isEqualToString:@"section-icon"]) {
7178 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7179 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7181 icon = [UIImage imageNamed:@"unknown.png"];
7182 [self _returnPNGWithImage:icon forRequest:request];
7184 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7188 - (void) stopLoading {
7194 /* Section Controller {{{ */
7195 @interface SectionController : FilteredPackageListController {
7197 _H<NSString> section_;
7200 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section;
7204 @implementation SectionController
7206 - (NSURL *) referrerURL {
7207 NSString *name(section_);
7208 name = name ?: @"*";
7209 NSString *key(key_);
7211 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sections/%@/%@", UI_, [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7214 - (NSURL *) navigationURL {
7215 NSString *name(section_);
7216 name = name ?: @"*";
7217 NSString *key(key_);
7219 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@/%@", [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7222 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section {
7225 title = UCLocalize("ALL_PACKAGES");
7226 else if (![section isEqual:@""])
7227 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(section) value:nil table:@"Sections"];
7229 title = UCLocalize("NO_SECTION");
7231 if ((self = [super initWithDatabase:database title:title]) != nil) {
7232 key_ = [source key];
7237 - (void) reloadData {
7238 Source *source([database_ sourceWithKey:key_]);
7239 _H<NSString> name(section_);
7241 [self setFilter:[=](Package *package) {
7242 NSString *section([package section]);
7246 section == nil && [name length] == 0 ||
7247 [name isEqualToString:section]
7250 [package source] == source
7251 ) && [package visible];
7259 /* Sections Controller {{{ */
7260 @interface SectionsController : CyteViewController <
7261 UITableViewDataSource,
7264 _transient Database *database_;
7266 _H<NSMutableArray> sections_;
7267 _H<NSMutableArray> filtered_;
7268 _H<UITableView, 2> list_;
7271 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7272 - (void) editButtonClicked;
7276 @implementation SectionsController
7278 - (NSURL *) navigationURL {
7279 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
7282 - (Source *) source {
7285 return [database_ sourceWithKey:key_];
7288 - (void) updateNavigationItem {
7289 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7290 if ([sections_ count] == 0) {
7291 [[self navigationItem] setRightBarButtonItem:nil];
7293 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7294 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7296 action:@selector(editButtonClicked)
7297 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7301 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7302 [super setEditing:editing animated:animated];
7307 [delegate_ updateData];
7309 [self updateNavigationItem];
7312 - (void) viewDidAppear:(BOOL)animated {
7313 [super viewDidAppear:animated];
7314 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7317 - (void) viewWillDisappear:(BOOL)animated {
7318 [super viewWillDisappear:animated];
7319 [self setEditing:NO];
7322 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7323 Section *section = nil;
7324 int index = [indexPath row];
7325 if (![self isEditing]) {
7328 section = [filtered_ objectAtIndex:index];
7330 section = [sections_ objectAtIndex:index];
7335 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7336 if ([self isEditing])
7337 return [sections_ count];
7339 return [filtered_ count] + 1;
7342 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7346 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7347 static NSString *reuseIdentifier = @"SectionCell";
7349 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7351 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7353 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7358 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7359 if ([self isEditing])
7362 Section *section = [self sectionAtIndexPath:indexPath];
7364 SectionController *controller = [[[SectionController alloc]
7365 initWithDatabase:database_
7366 source:[self source]
7367 section:[section name]
7369 [controller setDelegate:delegate_];
7371 [[self navigationController] pushViewController:controller animated:YES];
7375 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
7376 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7377 [list_ setRowHeight:46];
7378 [(UITableView *) list_ setDataSource:self];
7379 [list_ setDelegate:self];
7380 [self setView:list_];
7383 - (void) viewDidLoad {
7384 [super viewDidLoad];
7386 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7389 - (void) releaseSubviews {
7395 [super releaseSubviews];
7398 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7399 if ((self = [super init]) != nil) {
7400 database_ = database;
7401 key_ = [source key];
7405 - (void) reloadData {
7408 NSArray *packages = [database_ packages];
7410 sections_ = [NSMutableArray arrayWithCapacity:16];
7411 filtered_ = [NSMutableArray arrayWithCapacity:16];
7413 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7415 Source *source([self source]);
7418 for (Package *package in packages) {
7419 if (source != nil && [package source] != source)
7422 NSString *name([package section]);
7423 NSString *key(name == nil ? @"" : name);
7427 _profile(SectionsView$reloadData$Section)
7428 section = [sections objectForKey:key];
7429 if (section == nil) {
7430 _profile(SectionsView$reloadData$Section$Allocate)
7431 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7432 [sections setObject:section forKey:key];
7437 [section addToCount];
7439 _profile(SectionsView$reloadData$Filter)
7440 if (![package valid] || ![package visible])
7448 [sections_ addObjectsFromArray:[sections allValues]];
7450 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7452 for (Section *section in (id) sections_) {
7453 size_t count([section row]);
7457 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7458 [section setCount:count];
7459 [filtered_ addObject:section];
7462 [self updateNavigationItem];
7467 - (void) editButtonClicked {
7468 [self setEditing:![self isEditing] animated:YES];
7474 /* Changes Controller {{{ */
7475 @interface ChangesController : FilteredPackageListController {
7479 - (id) initWithDatabase:(Database *)database;
7483 @implementation ChangesController
7485 - (NSURL *) referrerURL {
7486 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/changes/", UI_]];
7489 - (NSURL *) navigationURL {
7490 return [NSURL URLWithString:@"cydia://changes"];
7493 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7494 @synchronized (database_) {
7495 if ([database_ era] != era_)
7498 NSUInteger sectionIndex([path section]);
7499 if (sectionIndex >= [sections_ count])
7501 Section *section([sections_ objectAtIndex:sectionIndex]);
7502 NSInteger row([path row]);
7503 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7506 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7507 NSString *context([alert context]);
7509 if ([context isEqualToString:@"norefresh"])
7510 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7513 - (void) setLeftBarButtonItem {
7514 if ([delegate_ updating])
7515 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7516 initWithTitle:UCLocalize("CANCEL")
7517 style:UIBarButtonItemStyleDone
7519 action:@selector(cancelButtonClicked)
7520 ] autorelease] animated:YES];
7522 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7523 initWithTitle:UCLocalize("REFRESH")
7524 style:UIBarButtonItemStylePlain
7526 action:@selector(refreshButtonClicked)
7527 ] autorelease] animated:YES];
7530 - (void) refreshButtonClicked {
7531 if ([delegate_ requestUpdate])
7532 [self setLeftBarButtonItem];
7535 - (void) cancelButtonClicked {
7536 [delegate_ cancelUpdate];
7539 - (void) upgradeButtonClicked {
7540 [delegate_ distUpgrade];
7541 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7544 - (bool) shouldYield {
7548 - (bool) shouldBlock {
7552 - (void) useFilter {
7553 @synchronized (self) {
7554 [self setFilter:[](Package *package) {
7555 return [package upgradableAndEssential:YES] || [package visible];
7558 [self setSorter:[](NSMutableArray *packages) {
7559 [packages radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7563 - (id) initWithDatabase:(Database *)database {
7564 if ((self = [super initWithDatabase:database title:UCLocalize("CHANGES")]) != nil) {
7569 - (void) viewDidLoad {
7570 [super viewDidLoad];
7571 [self setLeftBarButtonItem];
7574 - (void) viewWillAppear:(BOOL)animated {
7575 [super viewWillAppear:animated];
7576 [self setLeftBarButtonItem];
7579 - (void) reloadData {
7580 [self setLeftBarButtonItem];
7584 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
7585 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
7587 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7588 Section *ignored = nil;
7589 Section *section = nil;
7593 bool unseens = false;
7595 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7597 for (size_t offset = 0, count = [packages count]; offset != count; ++offset) {
7598 Package *package = [packages objectAtIndex:offset];
7600 BOOL uae = [package upgradableAndEssential:YES];
7604 time_t seen([package seen]);
7606 if (section == nil || last != seen) {
7610 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7613 _profile(ChangesController$reloadData$Allocate)
7614 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7615 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7616 [sections addObject:section];
7620 [section addToCount];
7621 } else if ([package ignored]) {
7622 if (ignored == nil) {
7623 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7625 [ignored addToCount];
7628 [upgradable addToCount];
7633 CFRelease(formatter);
7636 Section *last = [sections lastObject];
7637 size_t count = [last count];
7638 [packages removeObjectsInRange:NSMakeRange([packages count] - count, count)];
7639 [sections removeLastObject];
7642 if ([ignored count] != 0)
7643 [sections insertObject:ignored atIndex:0];
7645 [sections insertObject:upgradable atIndex:0];
7649 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7650 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7651 style:UIBarButtonItemStylePlain
7653 action:@selector(upgradeButtonClicked)
7654 ] autorelease]) animated:YES];
7661 /* Search Controller {{{ */
7662 @interface SearchController : FilteredPackageListController <
7665 _H<UISearchBar, 1> search_;
7670 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7671 - (void) reloadData;
7675 @implementation SearchController
7677 - (NSURL *) referrerURL {
7678 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/search?q=%@", UI_, [([search_ text] ?: @"") stringByAddingPercentEscapesIncludingReserved]]];
7681 - (NSURL *) navigationURL {
7682 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7683 return [NSURL URLWithString:@"cydia://search"];
7685 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [[search_ text] stringByAddingPercentEscapesIncludingReserved]]];
7688 - (NSArray *) termsForQuery:(NSString *)query {
7689 NSMutableArray *terms([NSMutableArray arrayWithCapacity:2]);
7690 for (NSString *component in [query componentsSeparatedByString:@" "])
7691 if ([component length] != 0)
7692 [terms addObject:component];
7697 - (void) useSearch {
7698 _H<NSArray> query([self termsForQuery:[search_ text]]);
7701 @synchronized (self) {
7702 [self setFilter:[=](Package *package) {
7703 if (![package unfiltered])
7705 if (![package matches:query])
7710 [self setSorter:[](NSMutableArray *packages) {
7711 [packages radixSortUsingSelector:@selector(rank)];
7719 - (void) usePrefix:(NSString *)prefix {
7720 _H<NSString> query(prefix);
7723 @synchronized (self) {
7724 [self setFilter:[=](Package *package) {
7725 if ([query length] == 0)
7727 if (![package unfiltered])
7729 if ([[package name] compare:query options:MatchCompareOptions_ range:NSMakeRange(0, [query length])] != NSOrderedSame)
7734 [self setSorter:nullptr];
7740 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7742 [self usePrefix:[search_ text]];
7745 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7746 [search_ resignFirstResponder];
7750 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7751 [search_ setText:@""];
7752 [self searchBarButtonClicked:searchBar];
7755 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7756 [self searchBarButtonClicked:searchBar];
7759 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7760 [self usePrefix:text];
7763 - (bool) shouldYield {
7767 - (bool) shouldBlock {
7771 - (bool) isSummarized {
7775 - (bool) showsSections {
7779 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7780 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH")])) {
7781 search_ = [[[UISearchBar alloc] init] autorelease];
7782 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7783 [search_ setDelegate:self];
7785 UITextField *textField;
7786 if ([search_ respondsToSelector:@selector(searchField)])
7787 textField = [search_ searchField];
7789 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7791 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7792 [textField setEnablesReturnKeyAutomatically:NO];
7793 [[self navigationItem] setTitleView:textField];
7796 [search_ setText:query];
7801 - (void) viewDidAppear:(BOOL)animated {
7802 [super viewDidAppear:animated];
7804 if (!searchloaded_) {
7805 searchloaded_ = YES;
7806 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7807 [search_ layoutSubviews];
7810 if ([self isSummarized])
7811 [search_ becomeFirstResponder];
7814 - (void) reloadData {
7819 - (void) didSelectPackage:(Package *)package {
7820 [search_ resignFirstResponder];
7821 [super didSelectPackage:package];
7826 /* Package Settings Controller {{{ */
7827 @interface PackageSettingsController : CyteViewController <
7828 UITableViewDataSource,
7831 _transient Database *database_;
7833 _H<Package> package_;
7834 _H<UITableView, 2> table_;
7835 _H<UISwitch> subscribedSwitch_;
7836 _H<UISwitch> ignoredSwitch_;
7837 _H<UITableViewCell> subscribedCell_;
7838 _H<UITableViewCell> ignoredCell_;
7841 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7845 @implementation PackageSettingsController
7847 - (NSURL *) navigationURL {
7848 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
7851 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7852 if (package_ == nil)
7855 if ([package_ installed] == nil)
7861 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7862 if (package_ == nil)
7865 // both sections contain just one item right now.
7869 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7873 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7875 return UCLocalize("SHOW_ALL_CHANGES_EX");
7877 return UCLocalize("IGNORE_UPGRADES_EX");
7880 - (void) onSubscribed:(id)control {
7881 bool value([control isOn]);
7882 if (package_ == nil)
7884 if ([package_ setSubscribed:value])
7885 [delegate_ updateData];
7888 - (void) _updateIgnored {
7889 const char *package([name_ UTF8String]);
7890 bool on([ignoredSwitch_ isOn]);
7892 FILE *dpkg(popen("/usr/libexec/cydia/cydo --set-selections", "w"));
7893 fwrite(package, strlen(package), 1, dpkg);
7896 fwrite(" hold\n", 6, 1, dpkg);
7898 fwrite(" install\n", 9, 1, dpkg);
7903 - (void) onIgnored:(id)control {
7904 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7905 [invocation setTarget:self];
7906 [invocation setSelector:@selector(_updateIgnored)];
7908 [delegate_ reloadDataWithInvocation:invocation];
7911 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7912 if (package_ == nil)
7915 switch ([indexPath section]) {
7916 case 0: return subscribedCell_;
7917 case 1: return ignoredCell_;
7926 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
7927 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
7928 [self setView:view];
7930 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7931 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7932 [(UITableView *) table_ setDataSource:self];
7933 [table_ setDelegate:self];
7934 [view addSubview:table_];
7936 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7937 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7938 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7940 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7941 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7942 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7944 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7945 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7946 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7947 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7949 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7950 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7951 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7952 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7955 - (void) viewDidLoad {
7956 [super viewDidLoad];
7958 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7961 - (void) releaseSubviews {
7963 subscribedCell_ = nil;
7965 ignoredSwitch_ = nil;
7966 subscribedSwitch_ = nil;
7968 [super releaseSubviews];
7971 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7972 if ((self = [super init]) != nil) {
7973 database_ = database;
7978 - (void) reloadData {
7981 package_ = [database_ packageWithName:name_];
7983 if (package_ != nil) {
7984 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7985 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7986 } // XXX: what now, G?
7988 [table_ reloadData];
7994 /* Installed Controller {{{ */
7995 @interface InstalledController : FilteredPackageListController {
7999 - (id) initWithDatabase:(Database *)database;
8000 - (void) queueStatusDidChange;
8004 @implementation InstalledController
8006 - (NSURL *) referrerURL {
8007 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/installed/", UI_]];
8010 - (NSURL *) navigationURL {
8011 return [NSURL URLWithString:@"cydia://installed"];
8014 - (void) useRecent {
8017 @synchronized (self) {
8018 [self setFilter:[](Package *package) {
8019 return ![package uninstalled] && package->role_ < 7;
8022 [self setSorter:[](NSMutableArray *packages) {
8023 [packages radixSortUsingSelector:@selector(recent)];
8027 - (void) useFilter:(UISegmentedControl *)segmented {
8028 NSInteger selected([segmented selectedSegmentIndex]);
8030 return [self useRecent];
8031 bool simple(selected == 0);
8034 @synchronized (self) {
8035 [self setFilter:[=](Package *package) {
8036 return ![package uninstalled] && package->role_ <= (simple ? 1 : 3);
8039 [self setSorter:nullptr];
8042 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
8044 return [super sectionsForPackages:packages];
8046 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterLongStyle, kCFDateFormatterNoStyle));
8048 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
8049 Section *section(nil);
8052 for (size_t offset(0), count([packages count]); offset != count; ++offset) {
8053 Package *package([packages objectAtIndex:offset]);
8055 time_t upgraded([package upgraded]);
8056 if (upgraded < 1168364520)
8059 upgraded -= upgraded % (60 * 60 * 24);
8061 if (section == nil || upgraded != last) {
8066 continue; // XXX: name = UCLocalize("...");
8068 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:upgraded]);
8072 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
8073 [sections addObject:section];
8076 [section addToCount];
8079 CFRelease(formatter);
8083 - (id) initWithDatabase:(Database *)database {
8084 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED")]) != nil) {
8085 UISegmentedControl *segmented([[[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:UCLocalize("USER"), UCLocalize("EXPERT"), UCLocalize("RECENT"), nil]] autorelease]);
8086 [segmented setSelectedSegmentIndex:0];
8087 [segmented setSegmentedControlStyle:UISegmentedControlStyleBar];
8088 [[self navigationItem] setTitleView:segmented];
8090 [segmented addTarget:self action:@selector(modeChanged:) forEvents:UIControlEventValueChanged];
8091 [self useFilter:segmented];
8093 [self queueStatusDidChange];
8098 - (void) queueButtonClicked {
8103 - (void) queueStatusDidChange {
8106 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8107 initWithTitle:UCLocalize("QUEUE")
8108 style:UIBarButtonItemStyleDone
8110 action:@selector(queueButtonClicked)
8113 [[self navigationItem] setRightBarButtonItem:nil];
8118 - (void) modeChanged:(UISegmentedControl *)segmented {
8119 [self useFilter:segmented];
8126 /* Source Cell {{{ */
8127 @interface SourceCell : CyteTableViewCell <
8128 CyteTableViewCellDelegate,
8131 _H<Source, 1> source_;
8134 _H<NSString> origin_;
8135 _H<NSString> label_;
8136 _H<UIActivityIndicatorView> indicator_;
8139 - (void) setSource:(Source *)source;
8140 - (void) setFetch:(NSNumber *)fetch;
8144 @implementation SourceCell
8146 - (void) _setImage:(NSArray *)data {
8147 if ([url_ isEqual:[data objectAtIndex:0]]) {
8148 icon_ = [data objectAtIndex:1];
8149 [content_ setNeedsDisplay];
8153 - (void) _setSource:(NSURL *) url {
8154 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8156 if (NSData *data = [NSURLConnection
8157 sendSynchronousRequest:[NSURLRequest
8159 cachePolicy:NSURLRequestUseProtocolCachePolicy
8163 returningResponse:NULL
8166 if (UIImage *image = [UIImage imageWithData:data])
8167 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
8172 - (void) setSource:(Source *)source {
8174 [source_ setDelegate:self];
8176 [self setFetch:[NSNumber numberWithBool:[source_ fetch]]];
8178 icon_ = [UIImage imageNamed:@"unknown.png"];
8180 origin_ = [source name];
8181 label_ = [source rooturi];
8183 [content_ setNeedsDisplay];
8185 url_ = [source iconURL];
8186 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
8189 - (void) setAllSource {
8191 [indicator_ stopAnimating];
8193 icon_ = [UIImage imageNamed:@"folder.png"];
8194 origin_ = UCLocalize("ALL_SOURCES");
8195 label_ = UCLocalize("ALL_SOURCES_EX");
8196 [content_ setNeedsDisplay];
8199 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8200 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8201 UIView *content([self contentView]);
8202 CGRect bounds([content bounds]);
8204 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8205 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8206 [content_ setBackgroundColor:[UIColor whiteColor]];
8207 [content addSubview:content_];
8209 [content_ setDelegate:self];
8210 [content_ setOpaque:YES];
8212 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGraySmall] autorelease];
8213 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin];// | UIViewAutoresizingFlexibleBottomMargin];
8214 [content addSubview:indicator_];
8216 [[content_ layer] setContentsGravity:kCAGravityTopLeft];
8220 - (void) layoutSubviews {
8221 [super layoutSubviews];
8223 UIView *content([self contentView]);
8224 CGRect bounds([content bounds]);
8226 CGRect frame([indicator_ frame]);
8227 frame.origin.x = bounds.size.width - frame.size.width;
8228 frame.origin.y = Retina((bounds.size.height - frame.size.height) / 2);
8230 if (kCFCoreFoundationVersionNumber < 800)
8231 frame.origin.x -= 8;
8232 [indicator_ setFrame:frame];
8235 - (NSString *) accessibilityLabel {
8239 - (void) drawContentRect:(CGRect)rect {
8240 bool highlighted(highlighted_);
8241 float width(rect.size.width);
8245 rect.size = [(UIImage *) icon_ size];
8247 while (rect.size.width > 32 || rect.size.height > 32) {
8248 rect.size.width /= 2;
8249 rect.size.height /= 2;
8252 rect.origin.x = 26 - rect.size.width / 2;
8253 rect.origin.y = 26 - rect.size.height / 2;
8255 [icon_ drawInRect:Retina(rect)];
8258 if (highlighted && kCFCoreFoundationVersionNumber < 800)
8263 [origin_ drawAtPoint:CGPointMake(52, 8) forWidth:(width - 49) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
8267 [label_ drawAtPoint:CGPointMake(52, 29) forWidth:(width - 49) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
8270 - (void) setFetch:(NSNumber *)fetch {
8271 if ([fetch boolValue])
8272 [indicator_ startAnimating];
8274 [indicator_ stopAnimating];
8279 /* Sources Controller {{{ */
8280 @interface SourcesController : CyteViewController <
8281 UITableViewDataSource,
8284 _transient Database *database_;
8287 _H<UITableView, 2> list_;
8288 _H<NSMutableArray> sources_;
8292 _H<UIProgressHUD> hud_;
8295 NSURLConnection *trivial_bz2_;
8296 NSURLConnection *trivial_gz_;
8301 - (id) initWithDatabase:(Database *)database;
8302 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated;
8306 @implementation SourcesController
8308 - (void) _releaseConnection:(NSURLConnection *)connection {
8309 if (connection != nil) {
8310 [connection cancel];
8311 //[connection setDelegate:nil];
8312 [connection release];
8317 [self _releaseConnection:trivial_gz_];
8318 [self _releaseConnection:trivial_bz2_];
8323 - (NSURL *) navigationURL {
8324 return [NSURL URLWithString:@"cydia://sources"];
8327 - (void) viewDidAppear:(BOOL)animated {
8328 [super viewDidAppear:animated];
8329 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8332 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8336 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8338 return UCLocalize("INDIVIDUAL_SOURCES");
8342 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8345 case 1: return [sources_ count];
8350 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8351 @synchronized (database_) {
8352 if ([database_ era] != era_)
8354 if ([indexPath section] != 1)
8356 NSUInteger index([indexPath row]);
8357 if (index >= [sources_ count])
8359 return [sources_ objectAtIndex:index];
8362 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8363 static NSString *cellIdentifier = @"SourceCell";
8365 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8366 if (cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8367 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8369 Source *source([self sourceAtIndexPath:indexPath]);
8371 [cell setAllSource];
8373 [cell setSource:source];
8378 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8379 SectionsController *controller([[[SectionsController alloc]
8380 initWithDatabase:database_
8381 source:[self sourceAtIndexPath:indexPath]
8384 [controller setDelegate:delegate_];
8385 [[self navigationController] pushViewController:controller animated:YES];
8388 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8389 if ([indexPath section] != 1)
8391 Source *source = [self sourceAtIndexPath:indexPath];
8392 return [source record] != nil;
8395 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8396 _assert([indexPath section] == 1);
8397 if (editingStyle == UITableViewCellEditingStyleDelete) {
8398 Source *source = [self sourceAtIndexPath:indexPath];
8399 if (source == nil) return;
8401 [Sources_ removeObjectForKey:[source key]];
8403 [delegate_ _saveConfig];
8404 [delegate_ reloadDataWithInvocation:nil];
8408 - (void) tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath {
8409 [self updateButtonsForEditingStatusAnimated:YES];
8413 [delegate_ addTrivialSource:href_];
8416 [delegate_ syncData];
8419 - (NSString *) getWarning {
8420 NSString *href(href_);
8421 NSRange colon([href rangeOfString:@"://"]);
8422 if (colon.location != NSNotFound)
8423 href = [href substringFromIndex:(colon.location + 3)];
8424 href = [href stringByAddingPercentEscapes];
8425 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8427 NSURL *url([NSURL URLWithString:href]);
8429 NSStringEncoding encoding;
8430 NSError *error(nil);
8432 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8433 return [warning length] == 0 ? nil : warning;
8437 - (void) _endConnection:(NSURLConnection *)connection {
8438 // XXX: the memory management in this method is horribly awkward
8440 NSURLConnection **field = NULL;
8441 if (connection == trivial_bz2_)
8442 field = &trivial_bz2_;
8443 else if (connection == trivial_gz_)
8444 field = &trivial_gz_;
8445 _assert(field != NULL);
8446 [connection release];
8450 trivial_bz2_ == nil &&
8453 NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil);
8455 [delegate_ releaseNetworkActivityIndicator];
8457 [delegate_ removeProgressHUD:hud_];
8461 if (warning != nil) {
8462 UIAlertView *alert = [[[UIAlertView alloc]
8463 initWithTitle:UCLocalize("SOURCE_WARNING")
8466 cancelButtonTitle:UCLocalize("CANCEL")
8468 UCLocalize("ADD_ANYWAY"),
8472 [alert setContext:@"warning"];
8473 [alert setNumberOfRows:1];
8476 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
8482 } else if (error_ != nil) {
8483 UIAlertView *alert = [[[UIAlertView alloc]
8484 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8485 message:[error_ localizedDescription]
8487 cancelButtonTitle:UCLocalize("OK")
8488 otherButtonTitles:nil
8491 [alert setContext:@"urlerror"];
8496 UIAlertView *alert = [[[UIAlertView alloc]
8497 initWithTitle:UCLocalize("NOT_REPOSITORY")
8498 message:UCLocalize("NOT_REPOSITORY_EX")
8500 cancelButtonTitle:UCLocalize("OK")
8501 otherButtonTitles:nil
8504 [alert setContext:@"trivial"];
8514 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8515 switch ([response statusCode]) {
8521 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8522 lprintf("connection:\"%s\" didFailWithError:\"%s\"\n", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8524 [self _endConnection:connection];
8527 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8528 [self _endConnection:connection];
8531 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8532 NSURL *url([NSURL URLWithString:href]);
8534 NSMutableURLRequest *request = [NSMutableURLRequest
8536 cachePolicy:NSURLRequestUseProtocolCachePolicy
8540 [request setHTTPMethod:method];
8542 if (Machine_ != NULL)
8543 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8545 if (UniqueID_ != nil)
8546 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8548 if ([url isCydiaSecure]) {
8549 if (UniqueID_ != nil)
8550 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
8553 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8556 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8557 NSString *context([alert context]);
8559 if ([context isEqualToString:@"source"]) {
8562 NSString *href = [[alert textField] text];
8563 href = VerifySource(href);
8568 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8569 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8573 // XXX: this is stupid
8574 hud_ = [delegate_ addProgressHUD];
8575 [hud_ setText:UCLocalize("VERIFYING_URL")];
8576 [delegate_ retainNetworkActivityIndicator];
8585 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8586 } else if ([context isEqualToString:@"trivial"])
8587 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8588 else if ([context isEqualToString:@"urlerror"])
8589 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8590 else if ([context isEqualToString:@"warning"]) {
8593 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
8602 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8606 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated {
8607 BOOL editing([list_ isEditing]);
8610 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8611 initWithTitle:UCLocalize("ADD")
8612 style:UIBarButtonItemStylePlain
8614 action:@selector(addButtonClicked)
8615 ] autorelease] animated:animated];
8616 else if ([delegate_ updating])
8617 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8618 initWithTitle:UCLocalize("CANCEL")
8619 style:UIBarButtonItemStyleDone
8621 action:@selector(cancelButtonClicked)
8622 ] autorelease] animated:animated];
8624 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8625 initWithTitle:UCLocalize("REFRESH")
8626 style:UIBarButtonItemStylePlain
8628 action:@selector(refreshButtonClicked)
8629 ] autorelease] animated:animated];
8631 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8632 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8633 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8635 action:@selector(editButtonClicked)
8636 ] autorelease] animated:animated];
8640 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease];
8641 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8642 [list_ setRowHeight:53];
8643 [(UITableView *) list_ setDataSource:self];
8644 [list_ setDelegate:self];
8645 [self setView:list_];
8648 - (void) viewDidLoad {
8649 [super viewDidLoad];
8651 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8652 [self updateButtonsForEditingStatusAnimated:NO];
8655 - (void) viewWillAppear:(BOOL)animated {
8656 [super viewWillAppear:animated];
8658 [list_ setEditing:NO];
8659 [self updateButtonsForEditingStatusAnimated:NO];
8662 - (void) releaseSubviews {
8667 [super releaseSubviews];
8670 - (id) initWithDatabase:(Database *)database {
8671 if ((self = [super init]) != nil) {
8672 database_ = database;
8676 - (void) reloadData {
8678 [self updateButtonsForEditingStatusAnimated:YES];
8680 @synchronized (database_) {
8681 era_ = [database_ era];
8683 sources_ = [NSMutableArray arrayWithCapacity:16];
8684 [sources_ addObjectsFromArray:[database_ sources]];
8686 [sources_ sortUsingSelector:@selector(compareByName:)];
8689 int count([sources_ count]);
8691 for (int i = 0; i != count; i++) {
8692 if ([[sources_ objectAtIndex:i] record] == nil)
8700 - (void) showAddSourcePrompt {
8701 UIAlertView *alert = [[[UIAlertView alloc]
8702 initWithTitle:UCLocalize("ENTER_APT_URL")
8705 cancelButtonTitle:UCLocalize("CANCEL")
8707 UCLocalize("ADD_SOURCE"),
8711 [alert setContext:@"source"];
8713 [alert setNumberOfRows:1];
8714 [alert addTextFieldWithValue:@"http://" label:@""];
8716 UITextInputTraits *traits = [[alert textField] textInputTraits];
8717 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8718 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8719 [traits setKeyboardType:UIKeyboardTypeURL];
8720 // XXX: UIReturnKeyDone
8721 [traits setReturnKeyType:UIReturnKeyNext];
8726 - (void) addButtonClicked {
8727 [self showAddSourcePrompt];
8730 - (void) refreshButtonClicked {
8731 if ([delegate_ requestUpdate])
8732 [self updateButtonsForEditingStatusAnimated:YES];
8735 - (void) cancelButtonClicked {
8736 [delegate_ cancelUpdate];
8739 - (void) editButtonClicked {
8740 [list_ setEditing:![list_ isEditing] animated:YES];
8741 [self updateButtonsForEditingStatusAnimated:YES];
8747 /* Stash Controller {{{ */
8748 @interface StashController : CyteViewController {
8749 _H<UIActivityIndicatorView> spinner_;
8750 _H<UILabel> status_;
8751 _H<UILabel> caption_;
8756 @implementation StashController
8759 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8760 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8761 [self setView:view];
8763 [view setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8765 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8766 CGRect spinrect = [spinner_ frame];
8767 spinrect.origin.x = Retina([[self view] frame].size.width / 2 - spinrect.size.width / 2);
8768 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8769 [spinner_ setFrame:spinrect];
8770 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8771 [view addSubview:spinner_];
8772 [spinner_ startAnimating];
8775 captrect.size.width = [[self view] frame].size.width;
8776 captrect.size.height = 40.0f;
8777 captrect.origin.x = 0;
8778 captrect.origin.y = Retina([[self view] frame].size.height / 2 - captrect.size.height * 2);
8779 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8780 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8781 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8782 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8783 [caption_ setTextColor:[UIColor whiteColor]];
8784 [caption_ setBackgroundColor:[UIColor clearColor]];
8785 [caption_ setShadowColor:[UIColor blackColor]];
8786 [caption_ setTextAlignment:NSTextAlignmentCenter];
8787 [view addSubview:caption_];
8790 statusrect.size.width = [[self view] frame].size.width;
8791 statusrect.size.height = 30.0f;
8792 statusrect.origin.x = 0;
8793 statusrect.origin.y = Retina([[self view] frame].size.height / 2 - statusrect.size.height);
8794 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8795 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8796 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8797 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8798 [status_ setTextColor:[UIColor whiteColor]];
8799 [status_ setBackgroundColor:[UIColor clearColor]];
8800 [status_ setShadowColor:[UIColor blackColor]];
8801 [status_ setTextAlignment:NSTextAlignmentCenter];
8802 [view addSubview:status_];
8805 - (void) releaseSubviews {
8810 [super releaseSubviews];
8816 @interface CYURLCache : SDURLCache {
8821 @implementation CYURLCache
8823 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8826 else if ([event isEqualToString:@"no-cache"])
8828 else if ([event isEqualToString:@"store"])
8830 else if ([event isEqualToString:@"invalid"])
8832 else if ([event isEqualToString:@"memory"])
8834 else if ([event isEqualToString:@"disk"])
8836 else if ([event isEqualToString:@"miss"])
8839 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8843 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
8844 if (NSURLResponse *response = [cached response])
8845 if (NSString *mime = [response MIMEType])
8846 if ([mime isEqualToString:@"text/cache-manifest"]) {
8847 NSURL *url([response URL]);
8850 NSLog(@"###: %@", [url absoluteString]);
8853 @synchronized (HostConfig_) {
8854 [CachedURLs_ addObject:url];
8858 [super storeCachedResponse:cached forRequest:request];
8861 - (void) createDiskCachePath {
8862 [super createDiskCachePath];
8867 @interface Cydia : UIApplication <
8868 ConfirmationControllerDelegate,
8872 _H<UIWindow> window_;
8873 _H<CydiaTabBarController> tabbar_;
8874 _H<CyteTabBarController> emulated_;
8875 _H<AppCacheController> appcache_;
8877 _H<NSMutableArray> essential_;
8878 _H<NSMutableArray> broken_;
8880 Database *database_;
8882 _H<NSURL> starturl_;
8887 _H<StashController> stash_;
8896 @implementation Cydia
8898 - (void) lockSuspend {
8899 if (locked_++ == 0) {
8900 if ($SBSSetInterceptsMenuButtonForever != NULL)
8901 (*$SBSSetInterceptsMenuButtonForever)(true);
8903 [self setIdleTimerDisabled:YES];
8907 - (void) unlockSuspend {
8908 if (--locked_ == 0) {
8909 [self setIdleTimerDisabled:NO];
8911 if ($SBSSetInterceptsMenuButtonForever != NULL)
8912 (*$SBSSetInterceptsMenuButtonForever)(false);
8916 - (void) beginUpdate {
8917 [tabbar_ beginUpdate];
8920 - (void) cancelUpdate {
8921 [tabbar_ cancelUpdate];
8924 - (bool) requestUpdate {
8925 if (IsReachable("cydia.saurik.com")) {
8929 UIAlertView *alert = [[[UIAlertView alloc]
8930 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("REFRESH")]
8931 message:@"Host Unreachable" // XXX: Localize
8933 cancelButtonTitle:UCLocalize("OK")
8934 otherButtonTitles:nil
8937 [alert setContext:@"norefresh"];
8945 return [tabbar_ updating];
8949 if ([broken_ count] != 0) {
8950 int count = [broken_ count];
8952 UIAlertView *alert = [[[UIAlertView alloc]
8953 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8954 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8956 cancelButtonTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("FORCIBLY_CLEAR"), UCLocalize("UNSAFE")]
8958 UCLocalize("TEMPORARY_IGNORE"),
8962 [alert setContext:@"fixhalf"];
8963 [alert setNumberOfRows:2];
8965 } else if (!Ignored_ && [essential_ count] != 0) {
8966 int count = [essential_ count];
8968 UIAlertView *alert = [[[UIAlertView alloc]
8969 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8970 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8972 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8974 UCLocalize("UPGRADE_ESSENTIAL"),
8975 UCLocalize("COMPLETE_UPGRADE"),
8979 [alert setContext:@"upgrade"];
8984 - (void) returnToCydia {
8988 - (void) reloadSpringBoard {
8989 if (kCFCoreFoundationVersionNumber >= 700) // XXX: iOS 6.x
8990 system("/bin/launchctl stop com.apple.backboardd");
8992 system("/bin/launchctl stop com.apple.SpringBoard");
8994 system("/usr/bin/killall backboardd SpringBoard");
8997 - (void) _saveConfig {
8998 SaveConfig(database_);
9001 // Navigation controller for the queuing badge.
9002 - (UINavigationController *) queueNavigationController {
9003 NSArray *controllers = [tabbar_ viewControllers];
9004 return [controllers objectAtIndex:3];
9007 - (void) unloadData {
9008 [tabbar_ unloadData];
9011 - (void) _updateData {
9015 UINavigationController *navigation = [self queueNavigationController];
9017 id queuedelegate = nil;
9018 if ([[navigation viewControllers] count] > 0)
9019 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9021 [queuedelegate queueStatusDidChange];
9022 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9025 - (void) _refreshIfPossible {
9026 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9028 NSDate *update([[NSDictionary dictionaryWithContentsOfFile:@ CacheState_] objectForKey:@"LastUpdate"]);
9030 bool recently = false;
9031 if (update != nil) {
9032 NSTimeInterval interval([update timeIntervalSinceNow]);
9033 if (interval > -(15*60))
9037 // Don't automatic refresh if:
9038 // - We already refreshed recently.
9039 // - We already auto-refreshed this launch.
9040 // - Auto-refresh is disabled.
9041 // - Cydia's server is not reachable
9042 if (recently || loaded_ || ManualRefresh || !IsReachable("cydia.saurik.com")) {
9043 // If we are cancelling, we need to make sure it knows it's already loaded.
9046 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9048 // We are going to load, so remember that.
9051 [tabbar_ performSelectorOnMainThread:@selector(beginUpdate) withObject:nil waitUntilDone:NO];
9057 - (void) refreshIfPossible {
9058 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
9061 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9062 _profile(reloadDataWithInvocation)
9063 @synchronized (self) {
9064 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9066 [hud setText:UCLocalize("RELOADING_DATA")];
9068 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9072 [essential_ removeAllObjects];
9073 [broken_ removeAllObjects];
9075 _profile(reloadDataWithInvocation$Essential)
9076 NSArray *packages([database_ packages]);
9077 for (Package *package in packages) {
9079 [broken_ addObject:package];
9080 if ([package upgradableAndEssential:YES] && ![package ignored]) {
9081 if ([package essential] && [package installed] != nil)
9082 [essential_ addObject:package];
9088 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9091 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9092 [changesItem setBadgeValue:badge];
9093 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9094 [self setApplicationIconBadgeNumber:changes];
9097 [changesItem setBadgeValue:nil];
9098 [changesItem setAnimatedBadge:NO];
9099 [self setApplicationIconBadgeNumber:0];
9106 [self removeProgressHUD:hud];
9113 - (void) updateData {
9117 - (void) updateDataAndLoad {
9119 if ([database_ progressDelegate] == nil)
9125 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9128 - (void) disemulate {
9129 if (emulated_ == nil)
9132 if ([window_ respondsToSelector:@selector(setRootViewController:)])
9133 [window_ setRootViewController:tabbar_];
9135 [window_ addSubview:[tabbar_ view]];
9136 [[emulated_ view] removeFromSuperview];
9140 [window_ setUserInteractionEnabled:YES];
9143 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9144 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9146 UIViewController *parent;
9147 if (emulated_ == nil)
9157 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9158 [parent presentModalViewController:navigation animated:YES];
9161 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9162 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9164 if (navigation != nil)
9165 [navigation pushViewController:progress animated:YES];
9167 [self presentModalViewController:progress force:YES];
9169 [progress invoke:invocation withTitle:title];
9173 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9174 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9177 - (void) repairWithInvocation:(NSInvocation *)invocation {
9179 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9183 - (void) repairWithSelector:(SEL)selector {
9184 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9187 - (void) reloadData {
9188 [self reloadDataWithInvocation:nil];
9189 if ([database_ progressDelegate] == nil)
9195 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9198 - (void) addSource:(NSDictionary *) source {
9199 CydiaAddSource(source);
9202 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9203 CydiaAddSource(href, distribution, sections);
9206 // XXX: this method should not return anything
9207 - (BOOL) addTrivialSource:(NSString *)href {
9208 CydiaAddSource(href, @"./");
9213 pkgProblemResolver *resolver = [database_ resolver];
9215 resolver->InstallProtect();
9216 if (!resolver->Resolve(true))
9221 // XXX: this is a really crappy way of doing this.
9222 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9223 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9224 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9225 if ([tabbar_ updating])
9226 [tabbar_ cancelUpdate];
9228 if (![database_ prepare])
9231 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9232 [page setDelegate:self];
9233 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9236 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9237 [tabbar_ presentModalViewController:confirm_ animated:YES];
9243 @synchronized (self) {
9248 - (void) clearPackage:(Package *)package {
9249 @synchronized (self) {
9256 - (void) installPackages:(NSArray *)packages {
9257 @synchronized (self) {
9258 for (Package *package in packages)
9265 - (void) installPackage:(Package *)package {
9266 @synchronized (self) {
9273 - (void) removePackage:(Package *)package {
9274 @synchronized (self) {
9281 - (void) distUpgrade {
9282 @synchronized (self) {
9283 if (![database_ upgrade])
9291 system("/usr/bin/uicache");
9296 UIProgressHUD *hud([self addProgressHUD]);
9297 [hud setText:UCLocalize("LOADING")];
9298 [self yieldToSelector:@selector(_uicache)];
9299 [self removeProgressHUD:hud];
9303 [database_ perform];
9304 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9305 [self performSelectorOnMainThread:@selector(uicache) withObject:nil waitUntilDone:YES];
9308 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9311 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9312 [self unlockSuspend];
9315 - (void) retainNetworkActivityIndicator {
9316 if (activity_++ == 0)
9317 [self setNetworkActivityIndicatorVisible:YES];
9320 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9324 - (void) releaseNetworkActivityIndicator {
9325 if (--activity_ == 0)
9326 [self setNetworkActivityIndicatorVisible:NO];
9329 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9334 - (void) cancelAndClear:(bool)clear {
9335 @synchronized (self) {
9347 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9348 NSString *context([alert context]);
9350 if ([context isEqualToString:@"conffile"]) {
9351 FILE *input = [database_ input];
9352 if (button == [alert cancelButtonIndex])
9353 fprintf(input, "N\n");
9354 else if (button == [alert firstOtherButtonIndex])
9355 fprintf(input, "Y\n");
9358 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9359 } else if ([context isEqualToString:@"fixhalf"]) {
9360 if (button == [alert cancelButtonIndex]) {
9361 @synchronized (self) {
9362 for (Package *broken in (id) broken_) {
9364 NSString *id(ShellEscape([broken id]));
9365 system([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /bin/rm -f"
9366 " /var/lib/dpkg/info/%@.prerm"
9367 " /var/lib/dpkg/info/%@.postrm"
9368 " /var/lib/dpkg/info/%@.preinst"
9369 " /var/lib/dpkg/info/%@.postinst"
9370 " /var/lib/dpkg/info/%@.extrainst_"
9371 "", id, id, id, id, id] UTF8String]);
9377 } else if (button == [alert firstOtherButtonIndex]) {
9378 [broken_ removeAllObjects];
9382 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9383 } else if ([context isEqualToString:@"upgrade"]) {
9384 if (button == [alert firstOtherButtonIndex]) {
9385 @synchronized (self) {
9386 for (Package *essential in (id) essential_)
9387 [essential install];
9392 } else if (button == [alert firstOtherButtonIndex] + 1) {
9394 } else if (button == [alert cancelButtonIndex]) {
9398 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9402 - (void) system:(NSString *)command {
9403 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9406 system([command UTF8String]);
9412 - (void) applicationWillSuspend {
9414 [super applicationWillSuspend];
9417 - (BOOL) isSafeToSuspend {
9420 NSLog(@"isSafeToSuspend: locked_ != 0");
9425 if ([tabbar_ modalViewController] != nil)
9428 // Use external process status API internally.
9429 // This is probably a really bad idea.
9430 // XXX: what is the point of this? does this solve anything at all?
9431 uint64_t status = 0;
9433 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9434 notify_get_state(notify_token, &status);
9435 notify_cancel(notify_token);
9440 NSLog(@"isSafeToSuspend: status != 0");
9446 NSLog(@"isSafeToSuspend: -> true");
9451 - (void) suspendReturningToLastApp:(BOOL)returning {
9452 if ([self isSafeToSuspend])
9453 [super suspendReturningToLastApp:returning];
9457 if ([self isSafeToSuspend])
9461 - (void) applicationSuspend {
9462 if ([self isSafeToSuspend])
9463 [super applicationSuspend];
9466 - (void) applicationSuspend:(__GSEvent *)event {
9467 if ([self isSafeToSuspend])
9468 [super applicationSuspend:event];
9471 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9472 if ([self isSafeToSuspend])
9473 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9476 - (void) _setSuspended:(BOOL)value {
9477 if ([self isSafeToSuspend])
9478 [super _setSuspended:value];
9481 - (UIProgressHUD *) addProgressHUD {
9482 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9483 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9485 [window_ setUserInteractionEnabled:NO];
9487 UIViewController *target(tabbar_);
9488 if (UIViewController *modal = [target modalViewController])
9491 [hud showInView:[target view]];
9497 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9498 [self unlockSuspend];
9500 [hud removeFromSuperview];
9501 [window_ setUserInteractionEnabled:YES];
9504 - (CyteViewController *) pageForPackage:(NSString *)name withReferrer:(NSString *)referrer {
9505 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name withReferrer:referrer] autorelease];
9508 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external withReferrer:(NSString *)referrer {
9509 NSString *scheme([[url scheme] lowercaseString]);
9510 if ([[url absoluteString] length] <= [scheme length] + 3)
9512 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9513 NSArray *components([path componentsSeparatedByString:@"/"]);
9515 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"]) {
9516 CyteViewController *controller([self pageForPackage:[components objectAtIndex:1] withReferrer:referrer]);
9517 if (controller != nil)
9518 [controller setDelegate:self];
9522 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9525 NSString *base([components objectAtIndex:0]);
9527 CyteViewController *controller = nil;
9529 if ([base isEqualToString:@"url"]) {
9530 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9531 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9532 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9533 } else if (!external && [components count] == 1) {
9534 if ([base isEqualToString:@"sources"]) {
9535 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9538 if ([base isEqualToString:@"home"]) {
9539 controller = [[[HomeController alloc] init] autorelease];
9542 if ([base isEqualToString:@"sections"]) {
9543 controller = [[[SectionsController alloc] initWithDatabase:database_ source:nil] autorelease];
9546 if ([base isEqualToString:@"search"]) {
9547 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9550 if ([base isEqualToString:@"changes"]) {
9551 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9554 if ([base isEqualToString:@"installed"]) {
9555 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9557 } else if ([components count] == 2) {
9558 NSString *argument = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9560 if ([base isEqualToString:@"package"]) {
9561 controller = [self pageForPackage:argument withReferrer:referrer];
9564 if (!external && [base isEqualToString:@"search"]) {
9565 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9568 if (!external && [base isEqualToString:@"sections"]) {
9569 if ([argument isEqualToString:@"all"] || [argument isEqualToString:@"*"])
9571 controller = [[[SectionController alloc] initWithDatabase:database_ source:nil section:argument] autorelease];
9574 if ([base isEqualToString:@"sources"]) {
9575 if ([argument isEqualToString:@"add"]) {
9576 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9577 [(SourcesController *)controller showAddSourcePrompt];
9579 Source *source([database_ sourceWithKey:argument]);
9580 controller = [[[SectionsController alloc] initWithDatabase:database_ source:source] autorelease];
9584 if (!external && [base isEqualToString:@"launch"]) {
9585 [self launchApplicationWithIdentifier:argument suspended:NO];
9588 } else if (!external && [components count] == 3) {
9589 NSString *arg1 = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9590 NSString *arg2 = [[components objectAtIndex:2] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9592 if ([base isEqualToString:@"package"]) {
9593 if ([arg2 isEqualToString:@"settings"]) {
9594 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9595 } else if ([arg2 isEqualToString:@"files"]) {
9596 if (Package *package = [database_ packageWithName:arg1]) {
9597 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9598 [(FileTable *)controller setPackage:package];
9603 if ([base isEqualToString:@"sections"]) {
9604 Source *source([arg1 isEqualToString:@"*"] ? nil : [database_ sourceWithKey:arg1]);
9605 NSString *section([arg2 isEqualToString:@"*"] ? nil : arg2);
9606 controller = [[[SectionController alloc] initWithDatabase:database_ source:source section:section] autorelease];
9610 [controller setDelegate:self];
9614 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9615 CyteViewController *page([self pageForURL:url forExternal:external withReferrer:nil]);
9618 [tabbar_ setUnselectedViewController:page];
9623 - (void) applicationOpenURL:(NSURL *)url {
9624 [super applicationOpenURL:url];
9629 [self openCydiaURL:url forExternal:YES];
9632 - (void) applicationWillResignActive:(UIApplication *)application {
9633 // Stop refreshing if you get a phone call or lock the device.
9634 if ([tabbar_ updating])
9635 [tabbar_ cancelUpdate];
9637 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9638 [super applicationWillResignActive:application];
9641 - (void) saveState {
9642 [[NSDictionary dictionaryWithObjectsAndKeys:
9643 @"InterfaceState", [tabbar_ navigationURLCollection],
9644 @"LastClosed", [NSDate date],
9645 @"InterfaceIndex", [NSNumber numberWithInt:[tabbar_ selectedIndex]],
9646 nil] writeToFile:@ SavedState_ atomically:YES];
9651 - (void) applicationWillTerminate:(UIApplication *)application {
9655 - (void) applicationDidEnterBackground:(UIApplication *)application {
9656 if (kCFCoreFoundationVersionNumber < 1000 && [self isSafeToSuspend])
9657 return [self terminateWithSuccess];
9658 Backgrounded_ = [NSDate date];
9662 - (void) applicationWillEnterForeground:(UIApplication *)application {
9663 if (Backgrounded_ == nil)
9666 NSTimeInterval interval([Backgrounded_ timeIntervalSinceNow]);
9668 if (interval <= -(30*60)) {
9669 [tabbar_ setSelectedIndex:0];
9670 [[[tabbar_ viewControllers] objectAtIndex:0] popToRootViewControllerAnimated:NO];
9673 if (interval <= -(15*60)) {
9674 if (IsReachable("cydia.saurik.com")) {
9675 [tabbar_ beginUpdate];
9676 [appcache_ reloadURLWithCache:YES];
9680 if ([database_ delocked])
9684 - (void) setConfigurationData:(NSString *)data {
9685 static RegEx conffile_r("'(.*)' '(.*)' ([01]) ([01])");
9687 if (!conffile_r(data)) {
9688 lprintf("E:invalid conffile\n");
9692 NSString *ofile = conffile_r[1];
9693 //NSString *nfile = conffile_r[2];
9695 UIAlertView *alert = [[[UIAlertView alloc]
9696 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9697 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9699 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9701 UCLocalize("ACCEPT_NEW_COPY"),
9702 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9706 [alert setContext:@"conffile"];
9707 [alert setNumberOfRows:2];
9711 - (void) addStashController {
9713 stash_ = [[[StashController alloc] init] autorelease];
9714 [window_ addSubview:[stash_ view]];
9717 - (void) removeStashController {
9718 [[stash_ view] removeFromSuperview];
9720 [self unlockSuspend];
9724 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9725 UpdateExternalStatus(1);
9726 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/cydo /usr/libexec/cydia/free.sh"];
9727 UpdateExternalStatus(0);
9729 [self removeStashController];
9730 [self reloadSpringBoard];
9733 - (void) setupViewControllers {
9734 tabbar_ = [[[CydiaTabBarController alloc] initWithDatabase:database_] autorelease];
9736 NSMutableArray *items;
9737 if (kCFCoreFoundationVersionNumber < 800) {
9738 items = [NSMutableArray arrayWithObjects:
9739 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage imageNamed:@"home.png"] tag:0] autorelease],
9740 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage imageNamed:@"install.png"] tag:0] autorelease],
9741 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage imageNamed:@"changes.png"] tag:0] autorelease],
9742 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage imageNamed:@"manage.png"] tag:0] autorelease],
9743 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage imageNamed:@"search.png"] tag:0] autorelease],
9746 items = [NSMutableArray arrayWithObjects:
9747 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage imageNamed:@"home7.png"] selectedImage:[UIImage imageNamed:@"home7s.png"]] autorelease],
9748 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage imageNamed:@"install7.png"] selectedImage:[UIImage imageNamed:@"install7s.png"]] autorelease],
9749 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage imageNamed:@"changes7.png"] selectedImage:[UIImage imageNamed:@"changes7s.png"]] autorelease],
9750 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage imageNamed:@"manage7.png"] selectedImage:[UIImage imageNamed:@"manage7s.png"]] autorelease],
9751 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage imageNamed:@"search7.png"] selectedImage:[UIImage imageNamed:@"search7s.png"]] autorelease],
9755 NSMutableArray *controllers([NSMutableArray array]);
9756 for (UITabBarItem *item in items) {
9757 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9758 [controller setTabBarItem:item];
9759 [controllers addObject:controller];
9761 [tabbar_ setViewControllers:controllers];
9763 [tabbar_ setUpdateDelegate:self];
9766 - (void) _sendMemoryWarningNotification {
9767 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: maybe 4_0?
9768 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationMemoryWarningNotification" object:[UIApplication sharedApplication]];
9770 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
9773 - (void) _sendMemoryWarningNotifications {
9775 [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO];
9781 - (void) applicationDidReceiveMemoryWarning:(UIApplication *)application {
9783 [[NSURLCache sharedURLCache] removeAllCachedResponses];
9786 - (void) applicationDidFinishLaunching:(id)unused {
9787 //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil];
9790 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9791 [self setApplicationSupportsShakeToEdit:NO];
9793 @synchronized (HostConfig_) {
9794 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9797 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9798 initWithMemoryCapacity:524288
9799 diskCapacity:10485760
9800 diskPath:Cache("SDURLCache")
9803 [CydiaWebViewController _initialize];
9805 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9807 // this would disallow http{,s} URLs from accessing this data
9808 //[WebView registerURLSchemeAsLocal:@"cydia"];
9810 Font12_ = [UIFont systemFontOfSize:12];
9811 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9812 Font14_ = [UIFont systemFontOfSize:14];
9813 Font18_ = [UIFont systemFontOfSize:18];
9814 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9815 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9817 essential_ = [NSMutableArray arrayWithCapacity:4];
9818 broken_ = [NSMutableArray arrayWithCapacity:4];
9820 // XXX: I really need this thing... like, seriously... I'm sorry
9821 appcache_ = [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] autorelease];
9822 [appcache_ reloadData];
9824 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9825 [window_ orderFront:self];
9826 [window_ makeKey:self];
9827 [window_ setHidden:NO];
9830 [self addStashController];
9831 // XXX: this would be much cleaner as a yieldToSelector:
9832 // that way the removeStashController could happen right here inline
9833 // we also could no longer require the useless stash_ field anymore
9834 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9839 int error(stat("/", &root));
9840 _assert(error != -1);
9842 #define Stash_(path) do { \
9843 struct stat folder; \
9844 int error(lstat((path), &folder)); \
9845 if (error != -1 && ( \
9846 folder.st_dev == root.st_dev && \
9847 S_ISDIR(folder.st_mode) \
9848 ) || error == -1 && ( \
9849 errno == ENOENT || \
9854 Stash_("/Applications");
9855 Stash_("/Library/Ringtones");
9856 Stash_("/Library/Wallpaper");
9857 //Stash_("/usr/bin");
9858 Stash_("/usr/include");
9859 Stash_("/usr/share");
9860 //Stash_("/var/lib");
9862 database_ = [Database sharedInstance];
9863 [database_ setDelegate:self];
9865 [window_ setUserInteractionEnabled:NO];
9866 [self setupViewControllers];
9868 CydiaLoadingViewController *loading([[[CydiaLoadingViewController alloc] init] autorelease]);
9869 UINavigationController *navigation([[[UINavigationController alloc] init] autorelease]);
9870 [navigation setViewControllers:[NSArray arrayWithObject:loading]];
9872 emulated_ = [[[CyteTabBarController alloc] init] autorelease];
9873 [emulated_ setViewControllers:[NSArray arrayWithObject:navigation]];
9874 [emulated_ setSelectedIndex:0];
9876 if ([emulated_ respondsToSelector:@selector(concealTabBarSelection)])
9877 [emulated_ concealTabBarSelection];
9879 if ([window_ respondsToSelector:@selector(setRootViewController:)])
9880 [window_ setRootViewController:emulated_];
9882 [window_ addSubview:[emulated_ view]];
9884 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9888 - (NSArray *) defaultStartPages {
9889 NSMutableArray *standard = [NSMutableArray array];
9890 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9891 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9892 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9893 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9894 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9900 if ([emulated_ modalViewController] != nil)
9901 [emulated_ dismissModalViewControllerAnimated:YES];
9902 [window_ setUserInteractionEnabled:NO];
9904 [self reloadDataWithInvocation:nil];
9905 [self refreshIfPossible];
9908 NSDictionary *state([NSDictionary dictionaryWithContentsOfFile:@ SavedState_]);
9910 int savedIndex = [[state objectForKey:@"InterfaceIndex"] intValue];
9911 NSArray *saved = [[[state objectForKey:@"InterfaceState"] mutableCopy] autorelease];
9912 int standardIndex = 0;
9913 NSArray *standard = [self defaultStartPages];
9920 NSDate *closed = [state objectForKey:@"LastClosed"];
9921 if (valid && closed != nil) {
9922 NSTimeInterval interval([closed timeIntervalSinceNow]);
9923 if (interval <= -(30*60))
9927 if (valid && [saved count] != [standard count])
9931 for (unsigned int i = 0; i < [standard count]; i++) {
9932 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9933 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9934 // but it's good enough for now.
9935 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9942 NSArray *items = nil;
9944 [tabbar_ setSelectedIndex:savedIndex];
9947 [tabbar_ setSelectedIndex:standardIndex];
9951 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9952 NSArray *stack = [items objectAtIndex:tab];
9953 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9954 NSMutableArray *current = [NSMutableArray array];
9956 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9957 NSString *addr = [stack objectAtIndex:nav];
9958 NSURL *url = [NSURL URLWithString:addr];
9959 CyteViewController *page = [self pageForURL:url forExternal:NO withReferrer:nil];
9961 [current addObject:page];
9964 [navigation setViewControllers:current];
9967 // (Try to) show the startup URL.
9968 if (starturl_ != nil) {
9969 [self openCydiaURL:starturl_ forExternal:YES];
9974 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9975 if (item != nil && IsWildcat_) {
9976 [sheet showFromBarButtonItem:item animated:YES];
9978 [sheet showInView:window_];
9982 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9983 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9984 [progress setTitle:task];
9985 [progress addProgressEvent:event];
9988 - (void) addProgressEventForTask:(NSArray *)data {
9989 CydiaProgressEvent *event([data objectAtIndex:0]);
9990 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9991 [self addProgressEvent:event forTask:task];
9994 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9995 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
10001 id Alloc_(id self, SEL selector) {
10002 id object = alloc_(self, selector);
10003 lprintf("[%s]A-%p\n", self->isa->name, object);
10008 id Dealloc_(id self, SEL selector) {
10009 id object = dealloc_(self, selector);
10010 lprintf("[%s]D-%p\n", self->isa->name, object);
10014 Class $NSURLConnection;
10016 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
10017 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
10019 NSURL *url([copy URL]);
10021 NSString *host([url host]);
10022 NSString *scheme([[url scheme] lowercaseString]);
10024 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
10026 @synchronized (HostConfig_) {
10027 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
10028 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
10029 [copy setHTTPShouldUsePipelining:YES];
10031 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
10032 if ([control isEqualToString:@"max-age=0"])
10033 if ([CachedURLs_ containsObject:url]) {
10035 NSLog(@"~~~: %@", url);
10038 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
10040 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
10041 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
10042 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
10046 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
10052 static CGSize $WAKWindow$screenSize(WAKWindow *self, SEL _cmd) {
10053 CGSize size([[UIScreen mainScreen] bounds].size);
10054 /*if ([$WAKWindow respondsToSelector:@selector(hasLandscapeOrientation)])
10055 if ([$WAKWindow hasLandscapeOrientation])
10056 std::swap(size.width, size.height);*/
10060 Class $NSUserDefaults;
10062 MSHook(id, NSUserDefaults$objectForKey$, NSUserDefaults *self, SEL _cmd, NSString *key) {
10063 if ([key respondsToSelector:@selector(isEqualToString:)] && [key isEqualToString:@"WebKitLocalStorageDatabasePathPreferenceKey"])
10064 return Cache("LocalStorage");
10065 return _NSUserDefaults$objectForKey$(self, _cmd, key);
10068 static NSMutableDictionary *AutoreleaseDeepMutableCopyOfDictionary(CFTypeRef type) {
10071 if (CFGetTypeID(type) != CFDictionaryGetTypeID())
10073 CFTypeRef copy(CFPropertyListCreateDeepCopy(kCFAllocatorDefault, type, kCFPropertyListMutableContainers));
10075 return [(NSMutableDictionary *) copy autorelease];
10078 int main(int argc, char *argv[]) {
10079 int fd(open("/tmp/cydia.log", O_WRONLY | O_APPEND | O_CREAT, 0644));
10083 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10087 UpdateExternalStatus(0);
10089 UIScreen *screen([UIScreen mainScreen]);
10090 if ([screen respondsToSelector:@selector(scale)])
10091 ScreenScale_ = [screen scale];
10095 UIDevice *device([UIDevice currentDevice]);
10096 if ([device respondsToSelector:@selector(userInterfaceIdiom)]) {
10097 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10098 if (idiom == UIUserInterfaceIdiomPad)
10102 Idiom_ = IsWildcat_ ? @"ipad" : @"iphone";
10104 RegEx pattern("([0-9]+\\.[0-9]+).*");
10106 if (pattern([device systemVersion]))
10107 Firmware_ = pattern[1];
10108 if (pattern(Cydia_))
10109 Major_ = pattern[1];
10111 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
10113 HostConfig_ = [[[NSObject alloc] init] autorelease];
10114 @synchronized (HostConfig_) {
10115 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10116 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
10117 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
10118 CachedURLs_ = [NSMutableSet setWithCapacity:32];
10121 NSString *ui(@"ui/ios");
10123 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
10124 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"/%@", Major_]];
10125 UI_ = CydiaURL(ui);
10127 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10129 /* Library Hacks {{{ */
10130 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10132 $WAKWindow = objc_getClass("WAKWindow");
10133 if ($WAKWindow != NULL)
10134 if (Method method = class_getInstanceMethod($WAKWindow, @selector(screenSize)))
10135 method_setImplementation(method, (IMP) &$WAKWindow$screenSize);
10137 $NSURLConnection = objc_getClass("NSURLConnection");
10138 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10139 if (NSURLConnection$init$ != NULL) {
10140 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10141 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10144 $NSUserDefaults = objc_getClass("NSUserDefaults");
10145 Method NSUserDefaults$objectForKey$(class_getInstanceMethod($NSUserDefaults, @selector(objectForKey:)));
10146 if (NSUserDefaults$objectForKey$ != NULL) {
10147 _NSUserDefaults$objectForKey$ = reinterpret_cast<id (*)(NSUserDefaults *, SEL, NSString *)>(method_getImplementation(NSUserDefaults$objectForKey$));
10148 method_setImplementation(NSUserDefaults$objectForKey$, reinterpret_cast<IMP>(&$NSUserDefaults$objectForKey$));
10151 /* Set Locale {{{ */
10152 Locale_ = CFLocaleCopyCurrent();
10153 Languages_ = [NSLocale preferredLanguages];
10155 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10156 //NSLog(@"%@", [Languages_ description]);
10159 if (Locale_ != NULL)
10160 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10161 else if (Languages_ != nil && [Languages_ count] != 0)
10162 lang = [[Languages_ objectAtIndex:0] UTF8String];
10164 // XXX: consider just setting to C and then falling through?
10167 if (lang != NULL) {
10168 RegEx pattern("([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?");
10169 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10172 NSLog(@"Setting Language: %s", lang);
10174 if (lang != NULL) {
10175 setenv("LANG", lang, true);
10176 std::setlocale(LC_ALL, lang);
10179 /* Index Collation {{{ */
10180 if (Class $UILocalizedIndexedCollation = objc_getClass("UILocalizedIndexedCollation")) { @try {
10181 NSBundle *bundle([NSBundle bundleForClass:$UILocalizedIndexedCollation]);
10182 NSString *path([bundle pathForResource:@"UITableViewLocalizedSectionIndex" ofType:@"plist"]);
10183 //path = @"/System/Library/Frameworks/UIKit.framework/.lproj/UITableViewLocalizedSectionIndex.plist";
10184 NSDictionary *dictionary([NSDictionary dictionaryWithContentsOfFile:path]);
10185 _H<UILocalizedIndexedCollation> collation([[[$UILocalizedIndexedCollation alloc] initWithDictionary:dictionary] autorelease]);
10187 CollationLocale_ = MSHookIvar<NSLocale *>(collation, "_locale");
10189 if (kCFCoreFoundationVersionNumber >= 800 && [[CollationLocale_ localeIdentifier] isEqualToString:@"zh@collation=stroke"]) {
10190 CollationThumbs_ = [NSArray arrayWithObjects:@"1",@"•",@"4",@"•",@"7",@"•",@"10",@"•",@"13",@"•",@"16",@"•",@"19",@"A",@"•",@"E",@"•",@"I",@"•",@"M",@"•",@"R",@"•",@"V",@"•",@"Z",@"#",nil];
10191 for (NSInteger offset : (NSInteger[]) {0,1,3,4,6,7,9,10,12,13,15,16,18,25,26,29,30,33,34,37,38,42,43,46,47,50,51})
10192 CollationOffset_.push_back(offset);
10193 CollationTitles_ = [NSArray arrayWithObjects:@"1 畫",@"2 畫",@"3 畫",@"4 畫",@"5 畫",@"6 畫",@"7 畫",@"8 畫",@"9 畫",@"10 畫",@"11 畫",@"12 畫",@"13 畫",@"14 畫",@"15 畫",@"16 畫",@"17 畫",@"18 畫",@"19 畫",@"20 畫",@"21 畫",@"22 畫",@"23 畫",@"24 畫",@"25 畫以上",@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J",@"K",@"L",@"M",@"N",@"O",@"P",@"Q",@"R",@"S",@"T",@"U",@"V",@"W",@"X",@"Y",@"Z",@"#",nil];
10194 CollationStarts_ = [NSArray arrayWithObjects:@"一",@"丁",@"丈",@"不",@"且",@"丞",@"串",@"並",@"亭",@"乘",@"乾",@"傀",@"亂",@"僎",@"僵",@"儐",@"償",@"叢",@"儳",@"嚴",@"儷",@"儻",@"囌",@"囑",@"廳",@"a",@"b",@"c",@"d",@"e",@"f",@"g",@"h",@"i",@"j",@"k",@"l",@"m",@"n",@"o",@"p",@"q",@"r",@"s",@"t",@"u",@"v",@"w",@"x",@"y",@"z",@"ʒ",nil];
10197 CollationThumbs_ = [collation sectionIndexTitles];
10198 for (size_t index(0), end([CollationThumbs_ count]); index != end; ++index)
10199 CollationOffset_.push_back([collation sectionForSectionIndexTitleAtIndex:index]);
10201 CollationTitles_ = [collation sectionTitles];
10202 CollationStarts_ = MSHookIvar<NSArray *>(collation, "_sectionStartStrings");
10204 NSString *&transform(MSHookIvar<NSString *>(collation, "_transform"));
10205 if (&transform != NULL && transform != nil) {
10206 /*if ([collation respondsToSelector:@selector(transformedCollationStringForString:)])
10207 CollationModify_ = [=](NSString *value) { return [collation transformedCollationStringForString:value]; };*/
10208 const UChar *uid(reinterpret_cast<const UChar *>([transform cStringUsingEncoding:NSUnicodeStringEncoding]));
10209 UErrorCode code(U_ZERO_ERROR);
10210 CollationTransl_ = utrans_openU(uid, -1, UTRANS_FORWARD, NULL, 0, NULL, &code);
10211 if (!U_SUCCESS(code))
10212 NSLog(@"%s", u_errorName(code));
10216 } @catch (NSException *e) {
10220 CollationLocale_ = [[[NSLocale alloc] initWithLocaleIdentifier:@"en@collation=dictionary"] autorelease];
10222 CollationThumbs_ = [NSArray arrayWithObjects:@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J",@"K",@"L",@"M",@"N",@"O",@"P",@"Q",@"R",@"S",@"T",@"U",@"V",@"W",@"X",@"Y",@"Z",@"#",nil];
10223 for (NSInteger offset(0); offset != 28; ++offset)
10224 CollationOffset_.push_back(offset);
10226 CollationTitles_ = [NSArray arrayWithObjects:@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J",@"K",@"L",@"M",@"N",@"O",@"P",@"Q",@"R",@"S",@"T",@"U",@"V",@"W",@"X",@"Y",@"Z",@"#",nil];
10227 CollationStarts_ = [NSArray arrayWithObjects:@"a",@"b",@"c",@"d",@"e",@"f",@"g",@"h",@"i",@"j",@"k",@"l",@"m",@"n",@"o",@"p",@"q",@"r",@"s",@"t",@"u",@"v",@"w",@"x",@"y",@"z",@"ʒ",nil];
10230 /* Parse Arguments {{{ */
10231 bool substrate(false);
10237 for (int argi(1); argi != argc; ++argi)
10238 if (strcmp(argv[argi], "--") == 0) {
10240 argv[argi] = argv[0];
10246 for (int argi(1); argi != arge; ++argi)
10247 if (strcmp(args[argi], "--substrate") == 0)
10250 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10254 App_ = [[NSBundle mainBundle] bundlePath];
10257 Cache_ = [[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia", @"/var/mobile"] retain];
10259 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10260 alloc_ = alloc->method_imp;
10261 alloc->method_imp = (IMP) &Alloc_;*/
10263 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10264 dealloc_ = dealloc->method_imp;
10265 dealloc->method_imp = (IMP) &Dealloc_;*/
10267 void *gestalt(dlopen("/usr/lib/libMobileGestalt.dylib", RTLD_GLOBAL | RTLD_LAZY));
10268 $MGCopyAnswer = reinterpret_cast<CFStringRef (*)(CFStringRef)>(dlsym(gestalt, "MGCopyAnswer"));
10270 /* System Information {{{ */
10274 size = sizeof(maxproc);
10275 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10276 perror("sysctlbyname(\"kern.maxproc\", ?)");
10277 else if (maxproc < 64) {
10279 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10280 perror("sysctlbyname(\"kern.maxproc\", #)");
10283 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10284 char *osversion = new char[size];
10285 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10286 perror("sysctlbyname(\"kern.osversion\", ?)");
10288 System_ = [NSString stringWithUTF8String:osversion];
10290 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10291 char *machine = new char[size];
10292 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10293 perror("sysctlbyname(\"hw.machine\", ?)");
10295 Machine_ = machine;
10297 int64_t usermem(0);
10298 size = sizeof(usermem);
10299 if (sysctlbyname("hw.usermem", &usermem, &size, NULL, 0) == -1)
10302 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10303 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10304 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10306 UniqueID_ = UniqueIdentifier(device);
10308 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10309 Product_ = [info objectForKey:@"SafariProductVersion"];
10310 Safari_ = [info objectForKey:@"CFBundleVersion"];
10313 NSString *agent([NSString stringWithFormat:@"Cydia/%@ CyF/%.2f", Cydia_, kCFCoreFoundationVersionNumber]);
10315 if (RegEx match = RegEx("([0-9]+(\\.[0-9]+)+).*", Safari_))
10316 agent = [NSString stringWithFormat:@"Safari/%@ %@", match[1], agent];
10317 if (RegEx match = RegEx("([0-9]+[A-Z][0-9]+[a-z]?).*", System_))
10318 agent = [NSString stringWithFormat:@"Mobile/%@ %@", match[1], agent];
10319 if (RegEx match = RegEx("([0-9]+(\\.[0-9]+)+).*", Product_))
10320 agent = [NSString stringWithFormat:@"Version/%@ %@", match[1], agent];
10322 UserAgent_ = agent;
10324 /* Load Database {{{ */
10325 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10328 mkdir("/var/mobile/Library/Cydia", 0755);
10329 MetaFile_.Open("/var/mobile/Library/Cydia/metadata.cb0");
10332 Values_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaValues"), CFSTR("com.saurik.Cydia")));
10333 Sections_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaSections"), CFSTR("com.saurik.Cydia")));
10334 Sources_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaSources"), CFSTR("com.saurik.Cydia")));
10335 Version_ = [(NSNumber *) CFPreferencesCopyAppValue(CFSTR("CydiaVersion"), CFSTR("com.saurik.Cydia")) autorelease];
10338 NSDictionary *metadata([[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease]);
10340 if (Values_ == nil)
10341 Values_ = [metadata objectForKey:@"Values"];
10342 if (Values_ == nil)
10343 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10345 if (Sections_ == nil)
10346 Sections_ = [metadata objectForKey:@"Sections"];
10347 if (Sections_ == nil)
10348 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10350 if (Sources_ == nil)
10351 Sources_ = [metadata objectForKey:@"Sources"];
10352 if (Sources_ == nil)
10353 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10355 // XXX: this wrong, but in a way that doesn't matter :/
10356 if (Version_ == nil)
10357 Version_ = [metadata objectForKey:@"Version"];
10358 if (Version_ == nil)
10359 Version_ = [NSNumber numberWithUnsignedInt:0];
10361 if (NSDictionary *packages = [metadata objectForKey:@"Packages"]) {
10363 CFDictionaryApplyFunction((CFDictionaryRef) packages, &PackageImport, &fail);
10366 NSLog(@"unable to import package preferences... from 2010? oh well :/");
10369 if ([Version_ unsignedIntValue] == 0) {
10370 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10371 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10372 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10373 CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./");
10375 Version_ = [NSNumber numberWithUnsignedInt:1];
10377 if (NSMutableDictionary *cache = [NSMutableDictionary dictionaryWithContentsOfFile:@ CacheState_]) {
10378 [cache removeObjectForKey:@"LastUpdate"];
10379 [cache writeToFile:@ CacheState_ atomically:YES];
10383 _H<NSMutableArray> broken([NSMutableArray array]);
10384 for (NSString *key in (id) Sources_)
10385 if ([key rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"# "]].location != NSNotFound)
10386 [broken addObject:key];
10387 if ([broken count] != 0)
10388 for (NSString *key in (id) broken)
10389 [Sources_ removeObjectForKey:key];
10393 system("/usr/libexec/cydia/cydo /bin/rm -f /var/lib/cydia/metadata.plist");
10396 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10398 if (kCFCoreFoundationVersionNumber > 1000)
10399 system("/usr/libexec/cydia/cydo /usr/libexec/cydia/setnsfpn /var/lib");
10401 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10403 if (access("/User", F_OK) != 0 || version != 6) {
10405 system("/usr/libexec/cydia/cydo /usr/libexec/cydia/firmware.sh");
10409 if (access("/tmp/cydia.chk", F_OK) == 0) {
10410 if (unlink([Cache("pkgcache.bin") UTF8String]) == -1)
10411 _assert(errno == ENOENT);
10412 if (unlink([Cache("srcpkgcache.bin") UTF8String]) == -1)
10413 _assert(errno == ENOENT);
10416 system("/usr/libexec/cydia/cydo /bin/ln -sf /var/mobile/Library/Caches/com.saurik.Cydia/sources.list /etc/apt/sources.list.d/cydia.list");
10418 /* APT Initialization {{{ */
10419 _assert(pkgInitConfig(*_config));
10420 _assert(pkgInitSystem(*_config, _system));
10423 _config->Set("APT::Acquire::Translation", lang);
10425 // XXX: this timeout might be important :(
10426 //_config->Set("Acquire::http::Timeout", 15);
10428 _config->Set("Acquire::http::MaxParallel", usermem >= 384 * 1024 * 1024 ? 16 : 3);
10430 mkdir([Cache_ UTF8String], 0755);
10431 mkdir([Cache("archives") UTF8String], 0755);
10432 mkdir([Cache("archives/partial") UTF8String], 0755);
10433 _config->Set("Dir::Cache", [Cache_ UTF8String]);
10435 symlink("/var/lib/apt/extended_states", [Cache("extended_states") UTF8String]);
10436 _config->Set("Dir::State", [Cache_ UTF8String]);
10438 mkdir([Cache("lists") UTF8String], 0755);
10439 mkdir([Cache("lists/partial") UTF8String], 0755);
10440 mkdir([Cache("periodic") UTF8String], 0755);
10441 _config->Set("Dir::State::Lists", [Cache("lists") UTF8String]);
10443 std::string logs("/var/mobile/Library/Logs/Cydia");
10444 mkdir(logs.c_str(), 0755);
10445 _config->Set("Dir::Log::Terminal", logs + "/apt.log");
10447 _config->Set("Dir::Bin::dpkg", "/usr/libexec/cydia/cydo");
10449 /* Color Choices {{{ */
10450 space_ = CGColorSpaceCreateDeviceRGB();
10452 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10453 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10454 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10455 Folder_.Set(space_, 0x8e/255.f, 0x8e/255.f, 0x93/255.f, 1.0);
10456 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10457 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10458 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10459 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10460 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10461 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10463 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10464 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10466 /* UIKit Configuration {{{ */
10467 // XXX: I have a feeling this was important
10468 //UIKeyboardDisableAutomaticAppearance();
10471 $SBSSetInterceptsMenuButtonForever = reinterpret_cast<void (*)(bool)>(dlsym(RTLD_DEFAULT, "SBSSetInterceptsMenuButtonForever"));
10473 const char *symbol(kCFCoreFoundationVersionNumber >= 800 ? "MGGetBoolAnswer" : "GSSystemHasCapability");
10474 BOOL (*GSSystemHasCapability)(CFStringRef) = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, symbol));
10475 bool fast = GSSystemHasCapability != NULL && GSSystemHasCapability(CFSTR("armv7"));
10477 PulseInterval_ = fast ? 50000 : 500000;
10479 Colon_ = UCLocalize("COLON_DELIMITED");
10480 Elision_ = UCLocalize("ELISION");
10481 Error_ = UCLocalize("ERROR");
10482 Warning_ = UCLocalize("WARNING");
10485 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10487 CGColorSpaceRelease(space_);
10488 CFRelease(Locale_);