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>
64 #include "fdstream.hpp"
69 #include <apt-pkg/acquire.h>
70 #include <apt-pkg/acquire-item.h>
71 #include <apt-pkg/algorithms.h>
72 #include <apt-pkg/cachefile.h>
73 #include <apt-pkg/clean.h>
74 #include <apt-pkg/configuration.h>
75 #include <apt-pkg/debindexfile.h>
76 #include <apt-pkg/debmetaindex.h>
77 #include <apt-pkg/error.h>
78 #include <apt-pkg/init.h>
79 #include <apt-pkg/mmap.h>
80 #include <apt-pkg/pkgrecords.h>
81 #include <apt-pkg/sha1.h>
82 #include <apt-pkg/sourcelist.h>
83 #include <apt-pkg/sptr.h>
84 #include <apt-pkg/strutl.h>
85 #include <apt-pkg/tagfile.h>
87 #include <sys/types.h>
89 #include <sys/sysctl.h>
90 #include <sys/param.h>
91 #include <sys/mount.h>
92 #include <sys/reboot.h>
100 #include <mach-o/nlist.h>
109 #include <Cytore.hpp>
112 #include "Substrate.hpp"
113 #include "Menes/Menes.h"
115 #include "CyteKit/CyteKit.h"
117 #include "Cydia/MIMEAddress.h"
118 #include "Cydia/LoadingViewController.h"
119 #include "Cydia/ProgressEvent.h"
126 #define _timestamp ({ \
128 gettimeofday(&tv, NULL); \
129 tv.tv_sec * 1000000 + tv.tv_usec; \
132 typedef std::vector<class ProfileTime *> TimeList;
142 ProfileTime(const char *name) :
146 times_.push_back(this);
149 void AddTime(uint64_t time) {
156 std::cerr << std::setw(7) << count_ << ", " << std::setw(8) << total_ << " : " << name_ << std::endl;
168 ProfileTimer(ProfileTime &time) :
175 time_.AddTime(_timestamp - start_);
180 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
182 std::cerr << "========" << std::endl;
185 #define _profile(name) { \
186 static ProfileTime name(#name); \
187 ProfileTimer _ ## name(name);
192 extern NSString *Cydia_;
194 #define lprintf(args...) fprintf(stderr, args)
197 #define TraceLogging (1 && !ForRelease)
198 #define HistogramInsertionSort (0 && !ForRelease)
199 #define ProfileTimes (0 && !ForRelease)
200 #define ForSaurik (0 && !ForRelease)
201 #define LogBrowser (0 && !ForRelease)
202 #define TrackResize (0 && !ForRelease)
203 #define ManualRefresh (1 && !ForRelease)
204 #define ShowInternals (0 && !ForRelease)
205 #define AlwaysReload (0 && !ForRelease)
209 #define _trace(args...)
214 #define _profile(name) {
217 #define PrintTimes() do {} while (false)
220 // Hash Functions/Structures {{{
221 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
229 @implementation NSDictionary (Cydia)
230 - (id) invokeUndefinedMethodFromWebScript:(NSString *)name withArguments:(NSArray *)arguments {
232 else if ([name isEqualToString:@"get"])
233 return [self objectForKey:[arguments objectAtIndex:0]];
234 else if ([name isEqualToString:@"keys"])
235 return [self allKeys];
239 static NSString *Colon_;
241 static NSString *Error_;
242 static NSString *Warning_;
244 static NSString *Cache_;
245 #define Cache(file) \
246 [NSString stringWithFormat:@"%@/%s", Cache_, file]
248 static void (*$SBSSetInterceptsMenuButtonForever)(bool);
249 static NSData *(*$SBSCopyIconImagePNGDataForDisplayIdentifier)(NSString *);
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 template <typename Type_>
319 size_t CFBSearch_(const Type_ &element, const void *list, size_t count, CFComparisonResult (*comparator)(Type_, Type_, void *), void *context) {
320 const char *ptr = (const char *)list;
322 size_t half = count / 2;
323 const char *probe = ptr + sizeof(Type_) * half;
324 CFComparisonResult cr = comparator(element, * (const Type_ *) probe, context);
325 if (0 == cr) return (probe - (const char *)list) / sizeof(Type_);
326 ptr = (cr < 0) ? ptr : probe + sizeof(Type_);
327 count = (cr < 0) ? half : (half + (count & 1) - 1);
329 return (ptr - (const char *)list) / sizeof(Type_);
332 template <typename Type_>
333 void CYArrayInsertionSortValues(Type_ *values, size_t length, CFComparisonResult (*comparator)(Type_, Type_, void *), void *context) {
337 #if HistogramInsertionSort > 0
338 uint32_t total(0), *offsets(new uint32_t[length]);
341 for (size_t index(1); index != length; ++index) {
342 Type_ value(values[index]);
344 size_t correct(CFBSearch_(value, values, index, comparator, context));
346 size_t correct(index);
347 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
348 #if HistogramInsertionSort > 1
349 NSLog(@"%@ < %@", value, values[correct - 1]);
353 if (index - correct >= 8) {
354 correct = CFBSearch_(value, values, correct, comparator, context);
359 if (correct != index) {
360 size_t offset(index - correct);
361 #if HistogramInsertionSort
365 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
367 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
368 values[correct] = value;
372 #if HistogramInsertionSort > 0
373 for (size_t index(0); index != range.length; ++index)
374 if (offsets[index] != 0)
375 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
376 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
383 /* Cydia NSString Additions {{{ */
384 @interface NSString (Cydia)
385 - (NSComparisonResult) compareByPath:(NSString *)other;
386 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
389 @implementation NSString (Cydia)
391 - (NSComparisonResult) compareByPath:(NSString *)other {
392 NSString *prefix = [self commonPrefixWithString:other options:0];
393 size_t length = [prefix length];
395 NSRange lrange = NSMakeRange(length, [self length] - length);
396 NSRange rrange = NSMakeRange(length, [other length] - length);
398 lrange = [self rangeOfString:@"/" options:0 range:lrange];
399 rrange = [other rangeOfString:@"/" options:0 range:rrange];
401 NSComparisonResult value;
403 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
404 value = NSOrderedSame;
405 else if (lrange.location == NSNotFound)
406 value = NSOrderedAscending;
407 else if (rrange.location == NSNotFound)
408 value = NSOrderedDescending;
410 value = NSOrderedSame;
412 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
413 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
414 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
415 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
417 NSComparisonResult result = [lpath compare:rpath];
418 return result == NSOrderedSame ? value : result;
421 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
422 return [(id)CFURLCreateStringByAddingPercentEscapes(
427 kCFStringEncodingUTF8
434 /* C++ NSString Wrapper Cache {{{ */
435 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
436 return size == 0 ? NULL :
437 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
438 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
441 static _finline CFStringRef CYStringCreate(const std::string &data) {
442 return CYStringCreate(data.data(), data.size());
445 static _finline CFStringRef CYStringCreate(const char *data) {
446 return CYStringCreate(data, strlen(data));
455 _finline void clear_() {
456 if (cache_ != NULL) {
463 _finline bool empty() const {
467 _finline size_t size() const {
471 _finline char *data() const {
475 _finline void clear() {
480 _finline CYString() :
487 _finline ~CYString() {
491 void operator =(const CYString &rhs) {
495 if (rhs.cache_ == nil)
498 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
501 void copy(CYPool *pool) {
502 char *temp(pool->malloc<char>(size_ + 1));
503 memcpy(temp, data_, size_);
508 void set(CYPool *pool, const char *data, size_t size) {
514 data_ = const_cast<char *>(data);
522 _finline void set(CYPool *pool, const char *data) {
523 set(pool, data, data == NULL ? 0 : strlen(data));
526 _finline void set(CYPool *pool, const std::string &rhs) {
527 set(pool, rhs.data(), rhs.size());
530 bool operator ==(const CYString &rhs) const {
531 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
534 _finline operator CFStringRef() {
536 cache_ = CYStringCreate(data_, size_);
540 _finline operator id() {
541 return (NSString *) static_cast<CFStringRef>(*this);
544 _finline operator const char *() {
545 return reinterpret_cast<const char *>(data_);
549 /* C++ NSString Algorithm Adapters {{{ */
551 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
554 struct NSStringMapHash :
555 std::unary_function<NSString *, size_t>
557 _finline size_t operator ()(NSString *value) const {
558 return CFStringHashNSString((CFStringRef) value);
562 struct NSStringMapLess :
563 std::binary_function<NSString *, NSString *, bool>
565 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
566 return [lhs compare:rhs] == NSOrderedAscending;
570 struct NSStringMapEqual :
571 std::binary_function<NSString *, NSString *, bool>
573 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
574 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
575 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
576 //[lhs isEqualToString:rhs];
581 /* CoreGraphics Primitives {{{ */
586 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
587 CGFloat color[] = {red, green, blue, alpha};
588 return CGColorCreate(space, color);
597 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
598 color_(Create_(space, red, green, blue, alpha))
600 Set(space, red, green, blue, alpha);
605 CGColorRelease(color_);
612 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
614 color_ = Create_(space, red, green, blue, alpha);
617 operator CGColorRef() {
623 /* Random Global Variables {{{ */
624 static int PulseInterval_ = 500000;
626 static const NSString *UI_;
629 static bool RestartSubstrate_;
630 static NSArray *Finishes_;
632 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
633 #define NotifyConfig_ "/etc/notify.conf"
635 static bool Queuing_;
637 static CYColor Blue_;
638 static CYColor Blueish_;
639 static CYColor Black_;
640 static CYColor Folder_;
642 static CYColor White_;
643 static CYColor Gray_;
644 static CYColor Green_;
645 static CYColor Purple_;
646 static CYColor Purplish_;
648 static UIColor *InstallingColor_;
649 static UIColor *RemovingColor_;
651 static NSString *App_;
653 static BOOL Advanced_;
654 static BOOL Ignored_;
656 static _H<UIFont> Font12_;
657 static _H<UIFont> Font12Bold_;
658 static _H<UIFont> Font14_;
659 static _H<UIFont> Font18_;
660 static _H<UIFont> Font18Bold_;
661 static _H<UIFont> Font22Bold_;
663 static const char *Machine_ = NULL;
664 static _H<NSString> System_;
665 static NSString *SerialNumber_ = nil;
666 static NSString *ChipID_ = nil;
667 static NSString *BBSNum_ = nil;
668 static _H<NSString> UniqueID_;
669 static _H<NSString> UserAgent_;
670 static _H<NSString> Product_;
671 static _H<NSString> Safari_;
673 static _H<NSLocale> CollationLocale_;
674 static _H<NSArray> CollationThumbs_;
675 static std::vector<NSInteger> CollationOffset_;
676 static _H<NSArray> CollationTitles_;
677 static _H<NSArray> CollationStarts_;
678 static UTransliterator *CollationTransl_;
679 //static Function<NSString *, NSString *> CollationModify_;
681 typedef std::basic_string<UChar> ustring;
682 static ustring CollationString_;
684 #define CUC const ustring &str(*reinterpret_cast<const ustring *>(rep))
685 #define UC ustring &str(*reinterpret_cast<ustring *>(rep))
686 static struct UReplaceableCallbacks CollationUCalls_ = {
687 .length = [](const UReplaceable *rep) -> int32_t { CUC;
691 .charAt = [](const UReplaceable *rep, int32_t offset) -> UChar { CUC;
692 //fprintf(stderr, "charAt(%d) : %d\n", offset, str.size());
693 if (offset >= str.size())
698 .char32At = [](const UReplaceable *rep, int32_t offset) -> UChar32 { CUC;
699 //fprintf(stderr, "char32At(%d) : %d\n", offset, str.size());
700 if (offset >= str.size())
703 U16_GET(str.data(), 0, offset, str.size(), c);
707 .replace = [](UReplaceable *rep, int32_t start, int32_t limit, const UChar *text, int32_t length) -> void { UC;
708 //fprintf(stderr, "replace(%d, %d, %d) : %d\n", start, limit, length, str.size());
709 str.replace(start, limit - start, text, length);
712 .extract = [](UReplaceable *rep, int32_t start, int32_t limit, UChar *dst) -> void { UC;
713 //fprintf(stderr, "extract(%d, %d) : %d\n", start, limit, str.size());
714 str.copy(dst, limit - start, start);
717 .copy = [](UReplaceable *rep, int32_t start, int32_t limit, int32_t dest) -> void { UC;
718 //fprintf(stderr, "copy(%d, %d, %d) : %d\n", start, limit, dest, str.size());
719 str.replace(dest, 0, str, start, limit - start);
723 static CFLocaleRef Locale_;
724 static NSArray *Languages_;
725 static CGColorSpaceRef space_;
727 #define CacheState_ "/var/mobile/Library/Caches/com.saurik.Cydia/CacheState.plist"
728 #define SavedState_ "/var/mobile/Library/Caches/com.saurik.Cydia/SavedState.plist"
730 static NSDictionary *SectionMap_;
731 static _H<NSDate> Backgrounded_;
732 static _transient NSMutableDictionary *Values_;
733 static _transient NSMutableDictionary *Sections_;
734 _H<NSMutableDictionary> Sources_;
735 static _transient NSNumber *Version_;
739 CGFloat ScreenScale_;
740 static NSString *Idiom_;
741 static _H<NSString> Firmware_;
742 static NSString *Major_;
744 static _H<NSMutableDictionary> SessionData_;
745 static _H<NSObject> HostConfig_;
746 static _H<NSMutableSet> BridgedHosts_;
747 static _H<NSMutableSet> InsecureHosts_;
749 static NSString *kCydiaProgressEventTypeError = @"Error";
750 static NSString *kCydiaProgressEventTypeInformation = @"Information";
751 static NSString *kCydiaProgressEventTypeStatus = @"Status";
752 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
755 /* Display Helpers {{{ */
756 inline float Interpolate(float begin, float end, float fraction) {
757 return (end - begin) * fraction + begin;
760 static inline double Retina(double value) {
761 value *= ScreenScale_;
762 value = round(value);
763 value /= ScreenScale_;
767 static inline CGRect Retina(CGRect value) {
768 value.origin.x *= ScreenScale_;
769 value.origin.y *= ScreenScale_;
770 value.size.width *= ScreenScale_;
771 value.size.height *= ScreenScale_;
772 value = CGRectIntegral(value);
773 value.origin.x /= ScreenScale_;
774 value.origin.y /= ScreenScale_;
775 value.size.width /= ScreenScale_;
776 value.size.height /= ScreenScale_;
780 static _finline const char *StripVersion_(const char *version) {
781 const char *colon(strchr(version, ':'));
782 return colon == NULL ? version : colon + 1;
785 NSString *LocalizeSection(NSString *section) {
786 static RegEx title_r("(.*?) \\((.*)\\)");
787 if (title_r(section)) {
788 NSString *parent(title_r[1]);
789 NSString *child(title_r[2]);
791 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
792 LocalizeSection(parent),
793 LocalizeSection(child)
797 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
800 NSString *Simplify(NSString *title) {
801 const char *data = [title UTF8String];
802 size_t size = [title lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
804 static RegEx square_r("\\[(.*)\\]");
805 if (square_r(data, size))
806 return Simplify(square_r[1]);
808 static RegEx paren_r("\\((.*)\\)");
809 if (paren_r(data, size))
810 return Simplify(paren_r[1]);
812 static RegEx title_r("(.*?) \\((.*)\\)");
813 if (title_r(data, size))
814 return Simplify(title_r[1]);
820 bool isSectionVisible(NSString *section) {
821 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
822 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
823 return hidden == nil || ![hidden boolValue];
826 static NSObject *CYIOGetValue(const char *path, NSString *property) {
827 io_registry_entry_t entry(IORegistryEntryFromPath(kIOMasterPortDefault, path));
828 if (entry == MACH_PORT_NULL)
831 CFTypeRef value(IORegistryEntryCreateCFProperty(entry, (CFStringRef) property, kCFAllocatorDefault, 0));
832 IOObjectRelease(entry);
836 return [(id) value autorelease];
839 static NSString *CYHex(NSData *data, bool reverse = false) {
843 size_t length([data length]);
844 uint8_t bytes[length];
845 [data getBytes:bytes];
847 char string[length * 2 + 1];
848 for (size_t i(0); i != length; ++i)
849 sprintf(string + i * 2, "%.2x", bytes[reverse ? length - i - 1 : i]);
851 return [NSString stringWithUTF8String:string];
854 static NSString *VerifySource(NSString *href) {
855 static RegEx href_r("(http(s?)://|file:///)[^# ]*");
857 [[[[UIAlertView alloc]
858 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("INVALID_URL")]
859 message:UCLocalize("INVALID_URL_EX")
861 cancelButtonTitle:UCLocalize("OK")
862 otherButtonTitles:nil
863 ] autorelease] show];
868 if (![href hasSuffix:@"/"])
869 href = [href stringByAppendingString:@"/"];
875 /* Delegate Prototypes {{{ */
878 @class CydiaProgressEvent;
880 @protocol DatabaseDelegate
881 - (void) repairWithSelector:(SEL)selector;
882 - (void) setConfigurationData:(NSString *)data;
883 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
886 @class CYPackageController;
888 @protocol SourceDelegate
889 - (void) setFetch:(NSNumber *)fetch;
892 @protocol FetchDelegate
893 - (bool) isSourceCancelled;
894 - (void) startSourceFetch:(NSString *)uri;
895 - (void) stopSourceFetch:(NSString *)uri;
898 @protocol CydiaDelegate
899 - (void) returnToCydia;
901 - (void) retainNetworkActivityIndicator;
902 - (void) releaseNetworkActivityIndicator;
903 - (void) clearPackage:(Package *)package;
904 - (void) installPackage:(Package *)package;
905 - (void) installPackages:(NSArray *)packages;
906 - (void) removePackage:(Package *)package;
907 - (void) beginUpdate;
909 - (bool) requestUpdate;
910 - (void) distUpgrade;
913 - (void) _saveConfig;
915 - (void) addSource:(NSDictionary *)source;
916 - (BOOL) addTrivialSource:(NSString *)href;
917 - (UIProgressHUD *) addProgressHUD;
918 - (void) removeProgressHUD:(UIProgressHUD *)hud;
919 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
920 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
924 /* CancelStatus {{{ */
926 public pkgAcquireStatus
937 virtual bool MediaChange(std::string media, std::string drive) {
941 virtual void IMSHit(pkgAcquire::ItemDesc &desc) {
945 virtual bool Pulse_(pkgAcquire *Owner) = 0;
947 virtual bool Pulse(pkgAcquire *Owner) {
948 if (pkgAcquireStatus::Pulse(Owner) && Pulse_(Owner))
956 _finline bool WasCancelled() const {
961 /* DelegateStatus {{{ */
966 _transient NSObject<ProgressDelegate> *delegate_;
974 void setDelegate(NSObject<ProgressDelegate> *delegate) {
975 delegate_ = delegate;
978 virtual void Fetch(pkgAcquire::ItemDesc &desc) {
979 NSString *name([NSString stringWithUTF8String:desc.ShortDesc.c_str()]);
980 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItemDesc:desc]);
981 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
984 virtual void Done(pkgAcquire::ItemDesc &desc) {
985 NSString *name([NSString stringWithUTF8String:desc.ShortDesc.c_str()]);
986 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:Colon_, UCLocalize("DONE"), name] ofType:kCydiaProgressEventTypeStatus forItemDesc:desc]);
987 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
990 virtual void Fail(pkgAcquire::ItemDesc &desc) {
992 desc.Owner->Status == pkgAcquire::Item::StatIdle ||
993 desc.Owner->Status == pkgAcquire::Item::StatDone
997 std::string &error(desc.Owner->ErrorText);
1001 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItemDesc:desc]);
1002 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1005 virtual bool Pulse_(pkgAcquire *Owner) {
1007 double(CurrentBytes + CurrentItems) /
1008 double(TotalBytes + TotalItems)
1011 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
1012 [NSNumber numberWithDouble:percent], @"Percent",
1014 [NSNumber numberWithDouble:CurrentBytes], @"Current",
1015 [NSNumber numberWithDouble:TotalBytes], @"Total",
1016 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
1017 nil] waitUntilDone:YES];
1019 return ![delegate_ isProgressCancelled];
1022 virtual void Start() {
1023 pkgAcquireStatus::Start();
1024 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
1027 virtual void Stop() {
1028 pkgAcquireStatus::Stop();
1029 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
1030 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
1034 /* Database Interface {{{ */
1035 typedef std::map< unsigned long, _H<Source> > SourceMap;
1037 @interface Database : NSObject {
1044 pkgCacheFile cache_;
1045 pkgDepCache::Policy *policy_;
1046 pkgRecords *records_;
1047 pkgProblemResolver *resolver_;
1048 pkgAcquire *fetcher_;
1050 SPtr<pkgPackageManager> manager_;
1051 pkgSourceList *list_;
1053 SourceMap sourceMap_;
1054 _H<NSMutableArray> sourceList_;
1056 _H<NSArray> packages_;
1058 _transient NSObject<DatabaseDelegate> *delegate_;
1059 _transient NSObject<ProgressDelegate> *progress_;
1061 CydiaStatus status_;
1067 std::map<const char *, _H<NSString> > sections_;
1070 + (Database *) sharedInstance;
1072 - (bool) hasPackages;
1074 - (void) _readCydia:(NSNumber *)fd;
1075 - (void) _readStatus:(NSNumber *)fd;
1076 - (void) _readOutput:(NSNumber *)fd;
1080 - (Package *) packageWithName:(NSString *)name;
1082 - (pkgCacheFile &) cache;
1083 - (pkgDepCache::Policy *) policy;
1084 - (pkgRecords *) records;
1085 - (pkgProblemResolver *) resolver;
1086 - (pkgAcquire &) fetcher;
1087 - (pkgSourceList &) list;
1088 - (NSArray *) packages;
1089 - (NSArray *) sources;
1090 - (Source *) sourceWithKey:(NSString *)key;
1091 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1099 - (void) updateWithStatus:(CancelStatus &)status;
1101 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1103 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1104 - (NSObject<ProgressDelegate> *) progressDelegate;
1106 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1107 - (void) setFetch:(bool)fetch forURI:(const char *)uri;
1108 - (void) resetFetch;
1110 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1114 /* SourceStatus {{{ */
1115 class SourceStatus :
1119 _transient NSObject<FetchDelegate> *delegate_;
1120 _transient Database *database_;
1121 std::set<std::string> fetches_;
1124 SourceStatus(NSObject<FetchDelegate> *delegate, Database *database) :
1125 delegate_(delegate),
1130 void Set(bool fetch, const std::string &uri) {
1132 if (!fetches_.insert(uri).second)
1135 if (fetches_.erase(uri) == 0)
1139 //printf("Set(%s, %s)\n", fetch ? "true" : "false", uri.c_str());
1141 auto slash(uri.rfind('/'));
1142 if (slash != std::string::npos)
1143 [database_ setFetch:fetch forURI:uri.substr(0, slash).c_str()];
1146 _finline void Set(bool fetch, pkgAcquire::Item *item) {
1147 /*unsigned long ID(fetch ? 1 : 0);
1151 Set(fetch, item->DescURI());
1154 void Log(const char *tag, pkgAcquire::Item *item) {
1155 //printf("%s(%s) S:%u Q:%u\n", tag, item->DescURI().c_str(), item->Status, item->QueueCounter);
1158 virtual void Fetch(pkgAcquire::ItemDesc &desc) {
1159 Log("Fetch", desc.Owner);
1160 Set(true, desc.Owner);
1163 virtual void Done(pkgAcquire::ItemDesc &desc) {
1164 Log("Done", desc.Owner);
1165 Set(false, desc.Owner);
1168 virtual void Fail(pkgAcquire::ItemDesc &desc) {
1169 Log("Fail", desc.Owner);
1170 Set(false, desc.Owner);
1173 virtual bool Pulse_(pkgAcquire *Owner) {
1174 std::set<std::string> fetches;
1175 for (pkgAcquire::ItemCIterator item(Owner->ItemsBegin()); item != Owner->ItemsEnd(); ++item) {
1177 if ((*item)->QueueCounter == 0)
1179 else switch ((*item)->Status) {
1180 case pkgAcquire::Item::StatFetching:
1181 fetches.insert((*item)->DescURI());
1190 Log(fetch ? "Pulse<true>" : "Pulse<false>", *item);
1194 std::vector<std::string> stops;
1195 std::set_difference(fetches_.begin(), fetches_.end(), fetches.begin(), fetches.end(), std::back_insert_iterator<std::vector<std::string>>(stops));
1196 for (std::vector<std::string>::const_iterator stop(stops.begin()); stop != stops.end(); ++stop) {
1197 //printf("Stop(%s)\n", stop->c_str());
1201 return ![delegate_ isSourceCancelled];
1204 virtual void Stop() {
1205 pkgAcquireStatus::Stop();
1206 [database_ resetFetch];
1210 /* ProgressEvent Implementation {{{ */
1211 @implementation CydiaProgressEvent
1213 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1214 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1217 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1218 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1219 [event setPackage:package];
1223 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItemDesc:(pkgAcquire::ItemDesc &)desc {
1224 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1226 NSString *description([NSString stringWithUTF8String:desc.Description.c_str()]);
1227 NSArray *fields([description componentsSeparatedByString:@" "]);
1228 [event setItem:fields];
1230 if ([fields count] > 3) {
1231 [event setPackage:[fields objectAtIndex:2]];
1232 [event setVersion:[fields objectAtIndex:3]];
1235 [event setURL:[NSString stringWithUTF8String:desc.URI.c_str()]];
1240 + (NSArray *) _attributeKeys {
1241 return [NSArray arrayWithObjects:
1251 - (NSArray *) attributeKeys {
1252 return [[self class] _attributeKeys];
1255 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1256 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1259 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1260 if ((self = [super init]) != nil) {
1266 - (NSString *) message {
1270 - (NSString *) type {
1274 - (NSArray *) item {
1275 return (id) item_ ?: [NSNull null];
1278 - (void) setItem:(NSArray *)item {
1282 - (NSString *) package {
1283 return (id) package_ ?: [NSNull null];
1286 - (void) setPackage:(NSString *)package {
1290 - (NSString *) url {
1291 return (id) url_ ?: [NSNull null];
1294 - (void) setURL:(NSString *)url {
1298 - (void) setVersion:(NSString *)version {
1302 - (NSString *) version {
1303 return (id) version_ ?: [NSNull null];
1306 - (NSString *) compound:(NSString *)value {
1308 NSString *mode(nil); {
1309 NSString *type([self type]);
1310 if ([type isEqualToString:kCydiaProgressEventTypeError])
1311 mode = UCLocalize("ERROR");
1312 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1313 mode = UCLocalize("WARNING");
1317 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1323 - (NSString *) compoundMessage {
1324 return [self compound:[self message]];
1327 - (NSString *) compoundTitle {
1330 if (package_ == nil)
1332 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1333 title = [package name];
1337 return [self compound:title];
1343 // Cytore Definitions {{{
1344 struct PackageValue :
1347 Cytore::Offset<PackageValue> next_;
1349 uint32_t index_ : 23;
1350 uint32_t subscribed_ : 1;
1367 Cytore::Offset<PackageValue> packages_[1 << 16];
1370 static Cytore::File<MetaValue> MetaFile_;
1372 // Cytore Helper Functions {{{
1373 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1374 SplitHash nhash = { hashlittle(name, length) };
1376 PackageValue *metadata;
1378 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1379 for (;; offset = &metadata->next_) { if (offset->IsNull()) {
1380 *offset = MetaFile_.New<PackageValue>(length + 1);
1381 metadata = &MetaFile_.Get(*offset);
1383 if (metadata == NULL) {
1387 metadata = new PackageValue();
1388 memset(metadata, 0, sizeof(*metadata));
1391 memcpy(metadata->name_, name, length);
1392 metadata->name_[length] = '\0';
1393 metadata->nhash_ = nhash.u16[1];
1395 metadata = &MetaFile_.Get(*offset);
1396 if (metadata->nhash_ != nhash.u16[1])
1398 if (strncmp(metadata->name_, name, length) != 0)
1400 if (metadata->name_[length] != '\0')
1407 static void PackageImport(const void *key, const void *value, void *context) {
1408 bool &fail(*reinterpret_cast<bool *>(context));
1411 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1412 NSLog(@"failed to import package %@", key);
1416 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1417 NSDictionary *package((NSDictionary *) value);
1419 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1420 if ([subscribed boolValue] && !metadata->subscribed_)
1421 metadata->subscribed_ = true;
1423 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1424 time_t time([date timeIntervalSince1970]);
1425 if (metadata->first_ > time || metadata->first_ == 0)
1426 metadata->first_ = time;
1429 NSDate *date([package objectForKey:@"LastSeen"]);
1430 NSString *version([package objectForKey:@"LastVersion"]);
1432 if (date != nil && version != nil) {
1433 time_t time([date timeIntervalSince1970]);
1434 if (metadata->last_ < time || metadata->last_ == 0)
1435 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1436 size_t length(strlen(buffer));
1437 uint16_t vhash(hashlittle(buffer, length));
1439 size_t capped(std::min<size_t>(8, length));
1440 char *latest(buffer + length - capped);
1442 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1443 metadata->vhash_ = vhash;
1445 metadata->last_ = time;
1451 static NSDate *GetStatusDate() {
1452 return [[[NSFileManager defaultManager] attributesOfItemAtPath:@"/var/lib/dpkg/status" error:NULL] fileModificationDate];
1455 static void SaveConfig(NSObject *lock) {
1456 @synchronized (lock) {
1462 CFPreferencesSetMultiple((CFDictionaryRef) [NSDictionary dictionaryWithObjectsAndKeys:
1463 Values_, @"CydiaValues",
1464 Sections_, @"CydiaSections",
1465 (id) Sources_, @"CydiaSources",
1466 Version_, @"CydiaVersion",
1467 nil], NULL, CFSTR("com.saurik.Cydia"), kCFPreferencesCurrentUser, kCFPreferencesCurrentHost);
1469 if (!CFPreferencesAppSynchronize(CFSTR("com.saurik.Cydia")))
1470 NSLog(@"CFPreferencesAppSynchronize(com.saurik.Cydia) == false");
1472 CydiaWriteSources();
1475 /* Source Class {{{ */
1476 @interface Source : NSObject {
1478 Database *database_;
1481 CYString depiction_;
1482 CYString description_;
1488 CYString distribution_;
1494 _H<NSString> authority_;
1496 CYString defaultIcon_;
1498 _H<NSMutableDictionary> record_;
1501 std::set<std::string> fetches_;
1502 std::set<std::string> files_;
1503 _transient NSObject<SourceDelegate> *delegate_;
1506 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(CYPool *)pool;
1508 - (NSComparisonResult) compareByName:(Source *)source;
1510 - (NSString *) depictionForPackage:(NSString *)package;
1511 - (NSString *) supportForPackage:(NSString *)package;
1513 - (metaIndex *) metaIndex;
1514 - (NSDictionary *) record;
1517 - (NSString *) rooturi;
1518 - (NSString *) distribution;
1519 - (NSString *) type;
1522 - (NSString *) host;
1524 - (NSString *) name;
1525 - (NSString *) shortDescription;
1526 - (NSString *) label;
1527 - (NSString *) origin;
1528 - (NSString *) version;
1530 - (NSString *) defaultIcon;
1531 - (NSURL *) iconURL;
1533 - (void) setFetch:(bool)fetch forURI:(const char *)uri;
1534 - (void) resetFetch;
1538 @implementation Source
1540 + (NSString *) webScriptNameForSelector:(SEL)selector {
1542 else if (selector == @selector(addSection:))
1543 return @"addSection";
1544 else if (selector == @selector(getField:))
1546 else if (selector == @selector(removeSection:))
1547 return @"removeSection";
1548 else if (selector == @selector(remove))
1554 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1555 return [self webScriptNameForSelector:selector] == nil;
1558 + (NSArray *) _attributeKeys {
1559 return [NSArray arrayWithObjects:
1570 @"shortDescription",
1577 - (NSArray *) attributeKeys {
1578 return [[self class] _attributeKeys];
1581 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1582 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1585 - (metaIndex *) metaIndex {
1589 - (void) setMetaIndex:(metaIndex *)index inPool:(CYPool *)pool {
1590 trusted_ = index->IsTrusted();
1592 uri_.set(pool, index->GetURI());
1593 distribution_.set(pool, index->GetDist());
1594 type_.set(pool, index->GetType());
1596 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1597 if (dindex != NULL) {
1598 std::string file(dindex->MetaIndexURI(""));
1599 base_.set(pool, file);
1602 _profile(Source$setMetaIndex$GetIndexes)
1603 dindex->GetIndexes(&acquire, true);
1605 _profile(Source$setMetaIndex$DescURI)
1606 for (pkgAcquire::ItemIterator item(acquire.ItemsBegin()); item != acquire.ItemsEnd(); item++) {
1607 std::string file((*item)->DescURI());
1608 auto slash(file.rfind('/'));
1609 if (slash == std::string::npos)
1611 files_.insert(file.substr(0, slash));
1616 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1619 pkgTagFile tags(&fd);
1621 pkgTagSection section;
1628 {"default-icon", &defaultIcon_},
1629 {"depiction", &depiction_},
1630 {"description", &description_},
1632 {"origin", &origin_},
1633 {"support", &support_},
1634 {"version", &version_},
1637 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1638 const char *start, *end;
1640 if (section.Find(names[i].name_, start, end)) {
1641 CYString &value(*names[i].value_);
1642 value.set(pool, start, end - start);
1648 record_ = [Sources_ objectForKey:[self key]];
1650 NSURL *url([NSURL URLWithString:uri_]);
1654 host_ = [host_ lowercaseString];
1659 authority_ = [url path];
1662 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(CYPool *)pool {
1663 if ((self = [super init]) != nil) {
1664 era_ = [database era];
1665 database_ = database;
1668 _profile(Source$initWithMetaIndex$setMetaIndex)
1669 [self setMetaIndex:index inPool:pool];
1674 - (NSString *) getField:(NSString *)name {
1675 @synchronized (database_) {
1676 if ([database_ era] != era_ || index_ == NULL)
1679 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index_));
1684 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly)) {
1689 pkgTagFile tags(&fd);
1691 pkgTagSection section;
1694 const char *start, *end;
1695 if (!section.Find([name UTF8String], start, end))
1696 return (NSString *) [NSNull null];
1698 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
1701 - (NSComparisonResult) compareByName:(Source *)source {
1702 NSString *lhs = [self name];
1703 NSString *rhs = [source name];
1705 if ([lhs length] != 0 && [rhs length] != 0) {
1706 unichar lhc = [lhs characterAtIndex:0];
1707 unichar rhc = [rhs characterAtIndex:0];
1709 if (isalpha(lhc) && !isalpha(rhc))
1710 return NSOrderedAscending;
1711 else if (!isalpha(lhc) && isalpha(rhc))
1712 return NSOrderedDescending;
1715 return [lhs compare:rhs options:LaxCompareOptions_];
1718 - (NSString *) depictionForPackage:(NSString *)package {
1719 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1722 - (NSString *) supportForPackage:(NSString *)package {
1723 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1726 - (NSArray *) sections {
1727 return record_ == nil ? (id) [NSNull null] : [record_ objectForKey:@"Sections"] ?: [NSArray array];
1730 - (void) _addSection:(NSString *)section {
1733 else if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) {
1734 if (![sections containsObject:section])
1735 [sections addObject:section];
1737 [record_ setObject:[NSMutableArray arrayWithObject:section] forKey:@"Sections"];
1740 - (bool) addSection:(NSString *)section {
1744 [self performSelectorOnMainThread:@selector(_addSection:) withObject:section waitUntilDone:NO];
1748 - (void) _removeSection:(NSString *)section {
1752 if (NSMutableArray *sections = [record_ objectForKey:@"Sections"])
1753 if ([sections containsObject:section])
1754 [sections removeObject:section];
1757 - (bool) removeSection:(NSString *)section {
1761 [self performSelectorOnMainThread:@selector(_removeSection:) withObject:section waitUntilDone:NO];
1766 [Sources_ removeObjectForKey:[self key]];
1770 bool value(record_ != nil);
1771 [self performSelectorOnMainThread:@selector(_remove) withObject:nil waitUntilDone:NO];
1775 - (NSDictionary *) record {
1783 - (NSString *) rooturi {
1787 - (NSString *) distribution {
1788 return distribution_;
1791 - (NSString *) type {
1795 - (NSString *) baseuri {
1796 return base_.empty() ? nil : (id) base_;
1799 - (NSString *) iconuri {
1800 if (NSString *base = [self baseuri])
1801 return [base stringByAppendingString:@"CydiaIcon.png"];
1806 - (NSURL *) iconURL {
1807 if (NSString *uri = [self iconuri])
1808 return [NSURL URLWithString:uri];
1812 - (NSString *) key {
1813 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1816 - (NSString *) host {
1820 - (NSString *) name {
1821 return origin_.empty() ? (id) authority_ : origin_;
1824 - (NSString *) shortDescription {
1825 return description_;
1828 - (NSString *) label {
1829 return label_.empty() ? (id) authority_ : label_;
1832 - (NSString *) origin {
1836 - (NSString *) version {
1840 - (NSString *) defaultIcon {
1841 return defaultIcon_;
1844 - (void) setDelegate:(NSObject<SourceDelegate> *)delegate {
1845 delegate_ = delegate;
1849 return !fetches_.empty();
1852 - (void) setFetch:(bool)fetch forURI:(const char *)uri {
1854 if (fetches_.erase(uri) == 0)
1856 } else if (files_.find(uri) == files_.end())
1858 else if (!fetches_.insert(uri).second)
1861 [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:[self fetch]] waitUntilDone:NO];
1864 - (void) resetFetch {
1866 [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:NO];
1871 /* CydiaOperation Class {{{ */
1872 @interface CydiaOperation : NSObject {
1873 _H<NSString> operator_;
1874 _H<NSString> value_;
1877 - (NSString *) operator;
1878 - (NSString *) value;
1882 @implementation CydiaOperation
1884 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1885 if ((self = [super init]) != nil) {
1886 operator_ = [NSString stringWithUTF8String:_operator];
1887 value_ = [NSString stringWithUTF8String:value];
1891 + (NSArray *) _attributeKeys {
1892 return [NSArray arrayWithObjects:
1898 - (NSArray *) attributeKeys {
1899 return [[self class] _attributeKeys];
1902 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1903 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1906 - (NSString *) operator {
1910 - (NSString *) value {
1916 /* CydiaClause Class {{{ */
1917 @interface CydiaClause : NSObject {
1918 _H<NSString> package_;
1919 _H<CydiaOperation> version_;
1922 - (NSString *) package;
1923 - (CydiaOperation *) version;
1927 @implementation CydiaClause
1929 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1930 if ((self = [super init]) != nil) {
1931 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1933 if (const char *version = dep.TargetVer())
1934 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1936 version_ = (id) [NSNull null];
1940 + (NSArray *) _attributeKeys {
1941 return [NSArray arrayWithObjects:
1947 - (NSArray *) attributeKeys {
1948 return [[self class] _attributeKeys];
1951 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1952 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1955 - (NSString *) package {
1959 - (CydiaOperation *) version {
1965 /* CydiaRelation Class {{{ */
1966 @interface CydiaRelation : NSObject {
1967 _H<NSString> relationship_;
1968 _H<NSMutableArray> clauses_;
1971 - (NSString *) relationship;
1972 - (NSArray *) clauses;
1976 @implementation CydiaRelation
1978 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1979 if ((self = [super init]) != nil) {
1980 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
1981 clauses_ = [NSMutableArray arrayWithCapacity:8];
1983 pkgCache::DepIterator start;
1984 pkgCache::DepIterator end;
1985 dep.GlobOr(start, end); // ++dep
1988 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1990 // yes, seriously. (wtf?)
1998 + (NSArray *) _attributeKeys {
1999 return [NSArray arrayWithObjects:
2005 - (NSArray *) attributeKeys {
2006 return [[self class] _attributeKeys];
2009 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2010 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2013 - (NSString *) relationship {
2014 return relationship_;
2017 - (NSArray *) clauses {
2021 - (void) addClause:(CydiaClause *)clause {
2022 [clauses_ addObject:clause];
2027 /* Package Class {{{ */
2028 struct ParsedPackage {
2032 CYString architecture_;
2035 CYString depiction_;
2042 @interface Package : NSObject {
2044 @public uint32_t role_ : 3;
2045 uint32_t essential_ : 1;
2046 uint32_t obsolete_ : 1;
2047 uint32_t ignored_ : 1;
2048 uint32_t pooled_ : 1;
2054 _transient Database *database_;
2056 pkgCache::VerIterator version_;
2057 pkgCache::PkgIterator iterator_;
2058 pkgCache::VerFileIterator file_;
2062 CYString transform_;
2065 CYString installed_;
2068 const char *section_;
2069 _transient NSString *section$_;
2073 PackageValue *metadata_;
2074 ParsedPackage *parsed_;
2076 _H<NSMutableArray> tags_;
2079 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database;
2080 + (Package *) newPackageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database;
2082 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database;
2084 - (pkgCache::PkgIterator) iterator;
2087 - (NSString *) section;
2088 - (NSString *) simpleSection;
2090 - (NSString *) longSection;
2091 - (NSString *) shortSection;
2095 - (MIMEAddress *) maintainer;
2097 - (NSString *) longDescription;
2098 - (NSString *) shortDescription;
2101 - (PackageValue *) metadata;
2104 - (bool) subscribed;
2105 - (bool) setSubscribed:(bool)subscribed;
2109 - (NSString *) latest;
2110 - (NSString *) installed;
2111 - (BOOL) uninstalled;
2113 - (BOOL) upgradableAndEssential:(BOOL)essential;
2116 - (BOOL) unfiltered;
2120 - (BOOL) halfConfigured;
2121 - (BOOL) halfInstalled;
2123 - (NSString *) mode;
2126 - (NSString *) name;
2128 - (NSString *) homepage;
2129 - (NSString *) depiction;
2130 - (MIMEAddress *) author;
2132 - (NSString *) support;
2134 - (NSArray *) files;
2135 - (NSArray *) warnings;
2136 - (NSArray *) applications;
2138 - (Source *) source;
2141 - (BOOL) matches:(NSArray *)query;
2143 - (BOOL) hasTag:(NSString *)tag;
2144 - (NSString *) primaryPurpose;
2145 - (NSArray *) purposes;
2146 - (bool) isCommercial;
2148 - (void) setIndex:(size_t)index;
2150 - (CYString &) cyname;
2152 - (uint32_t) compareBySection:(NSArray *)sections;
2159 uint32_t PackageChangesRadix(Package *self, void *) {
2164 uint32_t timestamp : 30;
2165 uint32_t ignored : 1;
2166 uint32_t upgradable : 1;
2170 bool upgradable([self upgradableAndEssential:YES]);
2171 value.bits.upgradable = upgradable ? 1 : 0;
2174 value.bits.timestamp = 0;
2175 value.bits.ignored = [self ignored] ? 0 : 1;
2176 value.bits.upgradable = 1;
2178 value.bits.timestamp = [self seen] >> 2;
2179 value.bits.ignored = 0;
2180 value.bits.upgradable = 0;
2183 return _not(uint32_t) - value.key;
2186 CYString &(*PackageName)(Package *self, SEL sel);
2188 uint32_t PackagePrefixRadix(Package *self, void *context) {
2189 size_t offset(reinterpret_cast<size_t>(context));
2190 CYString &name(PackageName(self, @selector(cyname)));
2192 size_t size(name.size());
2195 char *text(name.data());
2198 if (!isdigit(text[0]))
2202 while (size != digits && isdigit(text[digits]))
2210 if (offset == 0 && zeros != 0) {
2211 memset(data, '0', zeros);
2212 memcpy(data + zeros, text, 4 - zeros);
2214 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2215 if (size <= offset - zeros)
2218 text += offset - zeros;
2219 size -= offset - zeros;
2222 memcpy(data, text, 4);
2224 memcpy(data, text, size);
2225 memset(data + size, 0, 4 - size);
2228 for (size_t i(0); i != 4; ++i)
2229 if (isalpha(data[i]))
2237 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2239 /* XXX: ntohl may be more honest */
2240 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2243 CFComparisonResult StringNameCompare(CFStringRef lhn, CFStringRef rhn, size_t length) {
2244 _profile(PackageNameCompare)
2246 return rhn == NULL ? kCFCompareEqualTo : kCFCompareLessThan;
2247 else if (rhn == NULL)
2248 return kCFCompareGreaterThan;
2250 CFIndex length(CFStringGetLength(lhn));
2252 _profile(PackageNameCompare$NumbersLast)
2253 if (length != 0 && CFStringGetLength(rhn) != 0) {
2254 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2255 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2256 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2257 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2258 return lha ? kCFCompareLessThan : kCFCompareGreaterThan;
2262 _profile(PackageNameCompare$Compare)
2263 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, (CFLocaleRef) (id) CollationLocale_);
2268 _finline CFComparisonResult StringNameCompare(NSString *lhn, NSString*rhn, size_t length) {
2269 return StringNameCompare((CFStringRef) lhn, (CFStringRef) rhn, length);
2272 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2273 CYString &lhn(PackageName(lhs, @selector(cyname)));
2274 NSString *rhn(PackageName(rhs, @selector(cyname)));
2275 return StringNameCompare(lhn, rhn, lhn.size());
2278 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *arg) {
2279 return PackageNameCompare(*lhs, *rhs, arg);
2282 struct PackageNameOrdering :
2283 std::binary_function<Package *, Package *, bool>
2285 _finline bool operator ()(Package *lhs, Package *rhs) const {
2286 return PackageNameCompare(lhs, rhs, NULL) == kCFCompareLessThan;
2290 @implementation Package
2292 - (NSString *) description {
2293 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2299 if (parsed_ != NULL)
2304 + (NSString *) webScriptNameForSelector:(SEL)selector {
2306 else if (selector == @selector(clear))
2308 else if (selector == @selector(getField:))
2310 else if (selector == @selector(getRecord))
2311 return @"getRecord";
2312 else if (selector == @selector(hasTag:))
2314 else if (selector == @selector(install))
2316 else if (selector == @selector(remove))
2322 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2323 return [self webScriptNameForSelector:selector] == nil;
2326 + (NSArray *) _attributeKeys {
2327 return [NSArray arrayWithObjects:
2348 @"shortDescription",
2361 - (NSArray *) attributeKeys {
2362 return [[self class] _attributeKeys];
2365 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2366 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2369 - (NSArray *) relations {
2370 @synchronized (database_) {
2371 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2372 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2373 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2377 - (NSString *) architecture {
2379 @synchronized (database_) {
2380 return parsed_->architecture_.empty() ? [NSNull null] : (id) parsed_->architecture_;
2383 - (NSString *) getField:(NSString *)name {
2384 @synchronized (database_) {
2385 if ([database_ era] != era_ || file_.end())
2388 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2390 const char *start, *end;
2391 if (!parser.Find([name UTF8String], start, end))
2392 return (NSString *) [NSNull null];
2394 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2397 - (NSString *) getRecord {
2398 @synchronized (database_) {
2399 if ([database_ era] != era_ || file_.end())
2402 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2404 const char *start, *end;
2405 parser.GetRec(start, end);
2407 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2411 if (parsed_ != NULL)
2413 @synchronized (database_) {
2414 if ([database_ era] != era_ || file_.end())
2417 ParsedPackage *parsed(new ParsedPackage);
2420 _profile(Package$parse)
2421 pkgRecords::Parser *parser;
2423 _profile(Package$parse$Lookup)
2424 parser = &[database_ records]->Lookup(file_);
2430 _profile(Package$parse$Find)
2435 {"architecture", &parsed->architecture_},
2436 {"icon", &parsed->icon_},
2437 {"depiction", &parsed->depiction_},
2438 {"homepage", &parsed->homepage_},
2439 {"website", &website},
2441 {"support", &parsed->support_},
2442 {"author", &parsed->author_},
2443 {"md5sum", &parsed->md5sum_},
2446 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2447 const char *start, *end;
2449 if (parser->Find(names[i].name_, start, end)) {
2450 CYString &value(*names[i].value_);
2451 _profile(Package$parse$Value)
2452 value.set(pool_, start, end - start);
2458 _profile(Package$parse$Tagline)
2459 parsed->tagline_.set(pool_, parser->ShortDesc());
2462 _profile(Package$parse$Retain)
2463 if (parsed->homepage_.empty())
2464 parsed->homepage_ = website;
2465 if (parsed->homepage_ == parsed->depiction_)
2466 parsed->homepage_.clear();
2467 if (parsed->support_.empty())
2468 parsed->support_ = bugs;
2473 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database {
2474 if ((self = [super init]) != nil) {
2475 _profile(Package$initWithVersion)
2477 pool_ = new CYPool();
2483 database_ = database;
2484 era_ = [database era];
2488 pkgCache::PkgIterator iterator(version_.ParentPkg());
2489 iterator_ = iterator;
2491 _profile(Package$initWithVersion$Version)
2492 file_ = version_.FileList();
2495 _profile(Package$initWithVersion$Cache)
2496 name_.set(NULL, version_.Display());
2498 latest_.set(NULL, StripVersion_(version_.VerStr()));
2500 pkgCache::VerIterator current(iterator.CurrentVer());
2502 installed_.set(NULL, StripVersion_(current.VerStr()));
2505 _profile(Package$initWithVersion$Transliterate) do {
2506 if (CollationTransl_ == NULL)
2511 _profile(Package$initWithVersion$Transliterate$utf8)
2512 const uint8_t *data(reinterpret_cast<const uint8_t *>(name_.data()));
2513 for (size_t i(0), e(name_.size()); i != e; ++i)
2514 if (data[i] >= 0x80)
2519 UErrorCode code(U_ZERO_ERROR);
2522 _profile(Package$initWithVersion$Transliterate$u_strFromUTF8WithSub)
2523 CollationString_.resize(name_.size());
2524 u_strFromUTF8WithSub(&CollationString_[0], CollationString_.size(), &length, name_.data(), name_.size(), 0xfffd, NULL, &code);
2525 if (!U_SUCCESS(code))
2527 CollationString_.resize(length);
2530 _profile(Package$initWithVersion$Transliterate$utrans_trans)
2531 length = CollationString_.size();
2532 utrans_trans(CollationTransl_, reinterpret_cast<UReplaceable *>(&CollationString_), &CollationUCalls_, 0, &length, &code);
2533 if (!U_SUCCESS(code))
2535 _assert(CollationString_.size() == length);
2538 _profile(Package$initWithVersion$Transliterate$u_strToUTF8WithSub$preflight)
2539 u_strToUTF8WithSub(NULL, 0, &length, CollationString_.data(), CollationString_.size(), 0xfffd, NULL, &code);
2540 if (code == U_BUFFER_OVERFLOW_ERROR)
2541 code = U_ZERO_ERROR;
2542 else if (!U_SUCCESS(code))
2547 _profile(Package$initWithVersion$Transliterate$apr_palloc)
2548 transform = pool_->malloc<char>(length);
2550 _profile(Package$initWithVersion$Transliterate$u_strToUTF8WithSub$transform)
2551 u_strToUTF8WithSub(transform, length, NULL, CollationString_.data(), CollationString_.size(), 0xfffd, NULL, &code);
2552 if (!U_SUCCESS(code))
2556 transform_.set(NULL, transform, length);
2557 } while (false); _end
2559 _profile(Package$initWithVersion$Tags)
2561 pkgCache::TagIterator tag(version_.TagList());
2563 pkgCache::TagIterator tag(iterator.TagList());
2566 tags_ = [NSMutableArray arrayWithCapacity:8];
2568 goto tag; for (; !tag.end(); ++tag) tag: {
2569 const char *name(tag.Name());
2570 NSString *string((NSString *) CYStringCreate(name));
2574 [tags_ addObject:[string autorelease]];
2576 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2577 if (strcmp(name + 6, "enduser") == 0)
2579 else if (strcmp(name + 6, "hacker") == 0)
2581 else if (strcmp(name + 6, "developer") == 0)
2583 else if (strcmp(name + 6, "cydia") == 0)
2589 if (strncmp(name, "cydia::", 7) == 0) {
2590 if (strcmp(name + 7, "essential") == 0)
2592 else if (strcmp(name + 7, "obsolete") == 0)
2599 _profile(Package$initWithVersion$Metadata)
2600 const char *mixed(iterator.Name());
2601 size_t size(strlen(mixed));
2602 static const size_t prefix(sizeof("/var/lib/dpkg/info/") - 1);
2603 char lower[prefix + size + 5 + 1];
2605 for (size_t i(0); i != size; ++i)
2606 lower[prefix + i] = mixed[i] | 0x20;
2608 if (!installed_.empty()) {
2609 memcpy(lower, "/var/lib/dpkg/info/", prefix);
2610 memcpy(lower + prefix + size, ".list", 6);
2612 if (stat(lower, &info) != -1)
2613 upgraded_ = info.st_birthtime;
2616 PackageValue *metadata(PackageFind(lower + prefix, size));
2617 metadata_ = metadata;
2619 id_.set(NULL, metadata->name_, size);
2621 const char *latest(version_.VerStr());
2622 size_t length(strlen(latest));
2624 uint16_t vhash(hashlittle(latest, length));
2626 size_t capped(std::min<size_t>(8, length));
2627 latest = latest + length - capped;
2629 if (metadata->first_ == 0)
2630 metadata->first_ = now_;
2632 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2633 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2634 metadata->vhash_ = vhash;
2635 metadata->last_ = now_;
2636 } else if (metadata->last_ == 0)
2637 metadata->last_ = metadata->first_;
2640 _profile(Package$initWithVersion$Section)
2641 section_ = version_.Section();
2644 _profile(Package$initWithVersion$Flags)
2645 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2646 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2651 + (Package *) newPackageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database {
2652 pkgCache::VerIterator version;
2654 _profile(Package$packageWithIterator$GetCandidateVer)
2655 version = [database policy]->GetCandidateVer(iterator);
2663 _profile(Package$packageWithIterator$Allocate)
2664 package = [Package allocWithZone:zone];
2667 _profile(Package$packageWithIterator$Initialize)
2669 initWithVersion:version
2679 // XXX: just in case a Cydia extension is using this (I bet this is unlikely, though, due to CYPool?)
2680 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database {
2681 return [[self newPackageWithIterator:iterator withZone:zone inPool:pool database:database] autorelease];
2684 - (pkgCache::PkgIterator) iterator {
2688 - (NSArray *) downgrades {
2689 NSMutableArray *versions([NSMutableArray arrayWithCapacity:4]);
2691 for (auto version(iterator_.VersionList()); !version.end(); ++version) {
2692 if (version == version_)
2694 Package *package([[[Package allocWithZone:NULL] initWithVersion:version withZone:NULL inPool:NULL database:database_] autorelease]);
2695 if ([package source] == nil)
2697 [versions addObject:package];
2703 - (NSString *) section {
2704 if (section$_ == nil) {
2705 if (section_ == NULL)
2708 _profile(Package$section$mappedSectionForPointer)
2709 section$_ = [database_ mappedSectionForPointer:section_];
2714 - (NSString *) simpleSection {
2715 if (NSString *section = [self section])
2716 return Simplify(section);
2721 - (NSString *) longSection {
2722 if (NSString *section = [self section])
2723 return LocalizeSection(section);
2728 - (NSString *) shortSection {
2729 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2732 - (NSString *) uri {
2735 pkgIndexFile *index;
2736 pkgCache::PkgFileIterator file(file_.File());
2737 if (![database_ list].FindIndex(file, index))
2739 return [NSString stringWithUTF8String:iterator_->Path];
2740 //return [NSString stringWithUTF8String:file.Site()];
2741 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2745 - (MIMEAddress *) maintainer {
2746 @synchronized (database_) {
2747 if ([database_ era] != era_ || file_.end())
2750 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2751 const std::string &maintainer(parser->Maintainer());
2752 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2755 - (NSString *) md5sum {
2756 return parsed_ == NULL ? nil : (id) parsed_->md5sum_;
2760 @synchronized (database_) {
2761 if ([database_ era] != era_ || version_.end())
2764 return version_->InstalledSize;
2767 - (NSString *) longDescription {
2768 @synchronized (database_) {
2769 if ([database_ era] != era_ || file_.end())
2772 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2773 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2775 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2776 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2777 if ([lines count] < 2)
2780 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2781 for (size_t i(1), e([lines count]); i != e; ++i) {
2782 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2783 [trimmed addObject:trim];
2786 return [trimmed componentsJoinedByString:@"\n"];
2789 - (NSString *) shortDescription {
2790 if (parsed_ != NULL)
2791 return static_cast<NSString *>(parsed_->tagline_);
2793 @synchronized (database_) {
2794 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2795 std::string value(parser.ShortDesc());
2798 if (value.size() > 200)
2800 return [(id) CYStringCreate(value) autorelease];
2804 _profile(Package$index)
2805 CFStringRef name((CFStringRef) [self name]);
2806 if (CFStringGetLength(name) == 0)
2808 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2809 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2811 return toupper(character);
2815 - (PackageValue *) metadata {
2820 PackageValue *metadata([self metadata]);
2821 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2824 - (bool) subscribed {
2825 return [self metadata]->subscribed_;
2828 - (bool) setSubscribed:(bool)subscribed {
2829 PackageValue *metadata([self metadata]);
2830 if (metadata->subscribed_ == subscribed)
2832 metadata->subscribed_ = subscribed;
2840 - (NSString *) latest {
2844 - (NSString *) installed {
2848 - (BOOL) uninstalled {
2849 return installed_.empty();
2852 - (BOOL) upgradableAndEssential:(BOOL)essential {
2853 _profile(Package$upgradableAndEssential)
2854 pkgCache::VerIterator current(iterator_.CurrentVer());
2856 return essential && essential_;
2858 return version_ != current;
2862 - (BOOL) essential {
2867 return [database_ cache][iterator_].InstBroken();
2870 - (BOOL) unfiltered {
2871 _profile(Package$unfiltered$obsolete)
2872 if (_unlikely(obsolete_))
2876 _profile(Package$unfiltered$role)
2877 if (_unlikely(role_ > 3))
2885 if (![self unfiltered])
2890 _profile(Package$visible$section)
2891 section = [self section];
2894 _profile(Package$visible$isSectionVisible)
2895 if (!isSectionVisible(section))
2903 unsigned char current(iterator_->CurrentState);
2904 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2907 - (BOOL) halfConfigured {
2908 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2911 - (BOOL) halfInstalled {
2912 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2916 @synchronized (database_) {
2917 if ([database_ era] != era_ || iterator_.end())
2920 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2921 return state.Mode != pkgDepCache::ModeKeep;
2924 - (NSString *) mode {
2925 @synchronized (database_) {
2926 if ([database_ era] != era_ || iterator_.end())
2929 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2931 switch (state.Mode) {
2932 case pkgDepCache::ModeDelete:
2933 if ((state.iFlags & pkgDepCache::Purge) != 0)
2937 case pkgDepCache::ModeKeep:
2938 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2939 return @"REINSTALL";
2940 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2944 case pkgDepCache::ModeInstall:
2945 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2946 return @"REINSTALL";
2947 else*/ switch (state.Status) {
2949 return @"DOWNGRADE";
2955 return @"NEW_INSTALL";
2966 - (NSString *) name {
2967 return name_.empty() ? id_ : name_;
2970 - (UIImage *) icon {
2971 NSString *section = [self simpleSection];
2974 if (parsed_ != NULL)
2975 if (NSString *href = parsed_->icon_)
2976 if ([href hasPrefix:@"file:///"])
2977 icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2978 if (icon == nil) if (section != nil)
2979 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]];
2980 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2981 if ([dicon hasPrefix:@"file:///"])
2982 icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2984 icon = [UIImage imageNamed:@"unknown.png"];
2988 - (NSString *) homepage {
2989 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2992 - (NSString *) depiction {
2993 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2996 - (MIMEAddress *) author {
2997 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
3000 - (NSString *) support {
3001 return parsed_ != NULL && !parsed_->support_.empty() ? parsed_->support_ : [[self source] supportForPackage:id_];
3004 - (NSArray *) files {
3005 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
3006 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
3009 fin.open([path UTF8String]);
3014 while (std::getline(fin, line))
3015 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
3020 - (NSString *) state {
3021 @synchronized (database_) {
3022 if ([database_ era] != era_ || file_.end())
3025 switch (iterator_->CurrentState) {
3026 case pkgCache::State::NotInstalled:
3027 return @"NotInstalled";
3028 case pkgCache::State::UnPacked:
3030 case pkgCache::State::HalfConfigured:
3031 return @"HalfConfigured";
3032 case pkgCache::State::HalfInstalled:
3033 return @"HalfInstalled";
3034 case pkgCache::State::ConfigFiles:
3035 return @"ConfigFiles";
3036 case pkgCache::State::Installed:
3037 return @"Installed";
3038 case pkgCache::State::TriggersAwaited:
3039 return @"TriggersAwaited";
3040 case pkgCache::State::TriggersPending:
3041 return @"TriggersPending";
3044 return (NSString *) [NSNull null];
3047 - (NSString *) selection {
3048 @synchronized (database_) {
3049 if ([database_ era] != era_ || file_.end())
3052 switch (iterator_->SelectedState) {
3053 case pkgCache::State::Unknown:
3055 case pkgCache::State::Install:
3057 case pkgCache::State::Hold:
3059 case pkgCache::State::DeInstall:
3060 return @"DeInstall";
3061 case pkgCache::State::Purge:
3065 return (NSString *) [NSNull null];
3068 - (NSArray *) warnings {
3069 @synchronized (database_) {
3070 if ([database_ era] != era_ || file_.end())
3073 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
3074 const char *name(iterator_.Name());
3076 size_t length(strlen(name));
3077 if (length < 2) invalid:
3078 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
3079 else for (size_t i(0); i != length; ++i)
3081 /* XXX: technically this is not allowed */
3082 (name[i] < 'A' || name[i] > 'Z') &&
3083 (name[i] < 'a' || name[i] > 'z') &&
3084 (name[i] < '0' || name[i] > '9') &&
3085 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
3088 if (strcmp(name, "cydia") != 0) {
3091 bool _private = false;
3093 bool dbstash = false;
3094 bool dsstore = false;
3096 bool repository = [[self section] isEqualToString:@"Repositories"];
3098 if (NSArray *files = [self files])
3099 for (NSString *file in files)
3100 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
3102 else if (!user && [file isEqualToString:@"/User"])
3104 else if (!_private && [file isEqualToString:@"/private"])
3106 else if (!stash && [file isEqualToString:@"/var/stash"])
3108 else if (!dbstash && [file isEqualToString:@"/var/db/stash"])
3110 else if (!dsstore && [file hasSuffix:@"/.DS_Store"])
3113 /* XXX: this is not sensitive enough. only some folders are valid. */
3114 if (cydia && !repository)
3115 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
3117 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
3119 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
3121 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
3123 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/db/stash"]];
3125 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @".DS_Store"]];
3128 return [warnings count] == 0 ? nil : warnings;
3131 - (NSArray *) applications {
3132 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
3134 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
3136 static RegEx application_r("/Applications/(.*)\\.app/Info.plist");
3137 if (NSArray *files = [self files])
3138 for (NSString *file in files)
3139 if (application_r(file)) {
3140 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
3143 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
3144 if (id == nil || [id isEqualToString:me])
3147 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
3149 display = application_r[1];
3151 NSString *bundle([file stringByDeletingLastPathComponent]);
3152 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
3153 // XXX: maybe this should check if this is really a string, not just for length
3154 if (icon == nil || ![icon respondsToSelector:@selector(length)] || [icon length] == 0)
3156 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
3158 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
3159 [applications addObject:application];
3161 [application addObject:id];
3162 [application addObject:display];
3163 [application addObject:url];
3166 return [applications count] == 0 ? nil : applications;
3169 - (Source *) source {
3170 if (source_ == nil) {
3171 @synchronized (database_) {
3172 if ([database_ era] != era_ || file_.end())
3173 source_ = (Source *) [NSNull null];
3175 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
3179 return source_ == (Source *) [NSNull null] ? nil : source_;
3182 - (time_t) upgraded {
3186 - (uint32_t) recent {
3187 return std::numeric_limits<uint32_t>::max() - upgraded_;
3194 - (BOOL) matches:(NSArray *)query {
3195 if (query == nil || [query count] == 0)
3204 string = [self name];
3205 length = [string length];
3208 for (NSString *term in query) {
3209 range = [string rangeOfString:term options:MatchCompareOptions_];
3210 if (range.location != NSNotFound)
3211 rank_ -= 6 * 1000000 / length;
3216 length = [string length];
3219 for (NSString *term in query) {
3220 range = [string rangeOfString:term options:MatchCompareOptions_];
3221 if (range.location != NSNotFound)
3222 rank_ -= 6 * 1000000 / length;
3226 string = [self shortDescription];
3227 length = [string length];
3228 NSUInteger stop(std::min<NSUInteger>(length, 200));
3231 for (NSString *term in query) {
3232 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
3233 if (range.location != NSNotFound)
3234 rank_ -= 2 * 100000;
3240 - (NSArray *) tags {
3244 - (BOOL) hasTag:(NSString *)tag {
3245 return tags_ == nil ? NO : [tags_ containsObject:tag];
3248 - (NSString *) primaryPurpose {
3249 for (NSString *tag in (NSArray *) tags_)
3250 if ([tag hasPrefix:@"purpose::"])
3251 return [tag substringFromIndex:9];
3255 - (NSArray *) purposes {
3256 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
3257 for (NSString *tag in (NSArray *) tags_)
3258 if ([tag hasPrefix:@"purpose::"])
3259 [purposes addObject:[tag substringFromIndex:9]];
3260 return [purposes count] == 0 ? nil : purposes;
3263 - (bool) isCommercial {
3264 return [self hasTag:@"cydia::commercial"];
3267 - (void) setIndex:(size_t)index {
3268 if (metadata_->index_ != index + 1)
3269 metadata_->index_ = index + 1;
3272 - (CYString &) cyname {
3273 return !transform_.empty() ? transform_ : !name_.empty() ? name_ : id_;
3276 - (uint32_t) compareBySection:(NSArray *)sections {
3277 NSString *section([self section]);
3278 for (size_t i(0), e([sections count]); i != e; ++i) {
3279 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3283 return _not(uint32_t);
3287 @synchronized (database_) {
3288 if ([database_ era] != era_ || file_.end())
3291 pkgProblemResolver *resolver = [database_ resolver];
3292 resolver->Clear(iterator_);
3294 pkgCacheFile &cache([database_ cache]);
3295 cache->SetReInstall(iterator_, false);
3296 cache->MarkKeep(iterator_, false);
3300 @synchronized (database_) {
3301 if ([database_ era] != era_ || file_.end())
3304 pkgProblemResolver *resolver = [database_ resolver];
3305 resolver->Clear(iterator_);
3306 resolver->Protect(iterator_);
3308 pkgCacheFile &cache([database_ cache]);
3309 cache->SetCandidateVersion(version_);
3310 cache->SetReInstall(iterator_, false);
3311 cache->MarkInstall(iterator_, false);
3313 pkgDepCache::StateCache &state((*cache)[iterator_]);
3314 if (!state.Install())
3315 cache->SetReInstall(iterator_, true);
3319 @synchronized (database_) {
3320 if ([database_ era] != era_ || file_.end())
3323 pkgProblemResolver *resolver = [database_ resolver];
3324 resolver->Clear(iterator_);
3325 resolver->Remove(iterator_);
3326 resolver->Protect(iterator_);
3328 pkgCacheFile &cache([database_ cache]);
3329 cache->SetReInstall(iterator_, false);
3330 cache->MarkDelete(iterator_, true);
3335 /* Section Class {{{ */
3336 @interface Section : NSObject {
3340 _H<NSString> localized_;
3343 - (NSComparisonResult) compareByLocalized:(Section *)section;
3344 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3345 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3346 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3348 - (NSString *) name;
3349 - (void) setName:(NSString *)name;
3355 - (void) addToCount;
3357 - (void) setCount:(size_t)count;
3358 - (NSString *) localized;
3362 @implementation Section
3364 - (NSComparisonResult) compareByLocalized:(Section *)section {
3365 NSString *lhs(localized_);
3366 NSString *rhs([section localized]);
3368 /*if ([lhs length] != 0 && [rhs length] != 0) {
3369 unichar lhc = [lhs characterAtIndex:0];
3370 unichar rhc = [rhs characterAtIndex:0];
3372 if (isalpha(lhc) && !isalpha(rhc))
3373 return NSOrderedAscending;
3374 else if (!isalpha(lhc) && isalpha(rhc))
3375 return NSOrderedDescending;
3378 return [lhs compare:rhs options:LaxCompareOptions_];
3381 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3382 if ((self = [self initWithName:name localize:NO]) != nil) {
3383 if (localized != nil)
3384 localized_ = localized;
3388 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3389 return [self initWithName:name row:0 localize:localize];
3392 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3393 if ((self = [super init]) != nil) {
3397 localized_ = LocalizeSection(name_);
3401 - (NSString *) name {
3405 - (void) setName:(NSString *)name {
3421 - (void) addToCount {
3425 - (void) setCount:(size_t)count {
3429 - (NSString *) localized {
3436 class CydiaLogCleaner :
3437 public pkgArchiveCleaner
3440 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3445 /* Database Implementation {{{ */
3446 @implementation Database
3448 + (Database *) sharedInstance {
3449 static _H<Database> instance;
3450 if (instance == nil)
3451 instance = [[[Database alloc] init] autorelease];
3459 - (void) releasePackages {
3463 - (bool) hasPackages {
3464 return [packages_ count] != 0;
3468 // XXX: actually implement this thing
3470 [self releasePackages];
3471 NSRecycleZone(zone_);
3475 - (void) _readCydia:(NSNumber *)fd {
3476 boost::fdistream is([fd intValue]);
3479 static RegEx finish_r("finish:([^:]*)");
3481 while (std::getline(is, line)) {
3482 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3484 const char *data(line.c_str());
3485 size_t size = line.size();
3486 lprintf("C:%s\n", data);
3488 if (finish_r(data, size)) {
3489 NSString *finish = finish_r[1];
3490 int index = [Finishes_ indexOfObject:finish];
3491 if (index != INT_MAX && index > Finish_)
3501 - (void) _readStatus:(NSNumber *)fd {
3502 boost::fdistream is([fd intValue]);
3505 static RegEx conffile_r("status: [^ ]* : conffile-prompt : (.*?) *");
3506 static RegEx pmstatus_r("([^:]*):([^:]*):([^:]*):(.*)");
3508 while (std::getline(is, line)) {
3509 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3511 const char *data(line.c_str());
3512 size_t size(line.size());
3513 lprintf("S:%s\n", data);
3515 if (conffile_r(data, size)) {
3516 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3517 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3518 } else if (strncmp(data, "status: ", 8) == 0) {
3519 // status: <package>: {unpacked,half-configured,installed}
3520 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3521 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3522 } else if (strncmp(data, "processing: ", 12) == 0) {
3523 // processing: configure: config-test
3524 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3525 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3526 } else if (pmstatus_r(data, size)) {
3527 std::string type([pmstatus_r[1] UTF8String]);
3529 NSString *package = pmstatus_r[2];
3530 if ([package isEqualToString:@"dpkg-exec"])
3533 float percent([pmstatus_r[3] floatValue]);
3534 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3536 NSString *string = pmstatus_r[4];
3538 if (type == "pmerror") {
3539 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3540 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3541 } else if (type == "pmstatus") {
3542 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3543 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3544 } else if (type == "pmconffile")
3545 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3547 lprintf("E:unknown pmstatus\n");
3549 lprintf("E:unknown status\n");
3557 - (void) _readOutput:(NSNumber *)fd {
3558 boost::fdistream is([fd intValue]);
3561 while (std::getline(is, line)) {
3562 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3564 lprintf("O:%s\n", line.c_str());
3566 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3567 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3579 - (Package *) packageWithName:(NSString *)name {
3582 @synchronized (self) {
3583 if (static_cast<pkgDepCache *>(cache_) == NULL)
3585 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]
3590 return iterator.end() ? nil : [[Package newPackageWithIterator:iterator withZone:NULL inPool:NULL database:self] autorelease];
3594 if ((self = [super init]) != nil) {
3601 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3603 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3607 _assert(pipe(fds) != -1);
3610 _config->Set("APT::Keep-Fds::", cydiafd_);
3611 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3614 detachNewThreadSelector:@selector(_readCydia:)
3616 withObject:[NSNumber numberWithInt:fds[0]]
3619 _assert(pipe(fds) != -1);
3623 detachNewThreadSelector:@selector(_readStatus:)
3625 withObject:[NSNumber numberWithInt:fds[0]]
3628 _assert(pipe(fds) != -1);
3629 _assert(dup2(fds[0], 0) != -1);
3630 _assert(close(fds[0]) != -1);
3632 input_ = fdopen(fds[1], "a");
3634 _assert(pipe(fds) != -1);
3635 _assert(dup2(fds[1], 1) != -1);
3636 _assert(close(fds[1]) != -1);
3639 detachNewThreadSelector:@selector(_readOutput:)
3641 withObject:[NSNumber numberWithInt:fds[0]]
3646 - (pkgCacheFile &) cache {
3650 - (pkgDepCache::Policy *) policy {
3654 - (pkgRecords *) records {
3658 - (pkgProblemResolver *) resolver {
3662 - (pkgAcquire &) fetcher {
3666 - (pkgSourceList &) list {
3670 - (NSArray *) packages {
3674 - (NSArray *) sources {
3678 - (Source *) sourceWithKey:(NSString *)key {
3679 for (Source *source in [self sources]) {
3680 if ([[source key] isEqualToString:key])
3685 - (bool) popErrorWithTitle:(NSString *)title {
3688 while (!_error->empty()) {
3690 bool warning(!_error->PopMessage(error));
3695 size_t size(error.size());
3696 if (size == 0 || error[size - 1] != '\n')
3698 error.resize(size - 1);
3701 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3703 static RegEx no_pubkey("GPG error:.* NO_PUBKEY .*");
3704 if (warning && no_pubkey(error.c_str()))
3707 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3713 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3714 return [self popErrorWithTitle:title] || !success;
3717 - (bool) popErrorWithTitle:(NSString *)title forReadList:(pkgSourceList &)list {
3718 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3726 if (access("/etc/apt/sources.list", F_OK) == 0)
3727 error |= [self popErrorWithTitle:title forOperation:list.ReadAppend("/etc/apt/sources.list")];
3729 std::string base("/etc/apt/sources.list.d");
3730 if (DIR *sources = opendir(base.c_str())) {
3731 while (dirent *source = readdir(sources))
3732 if (source->d_name[0] != '.' && source->d_namlen > 5 && strcmp(source->d_name + source->d_namlen - 5, ".list") == 0 && strcmp(source->d_name, "cydia.list") != 0)
3733 error |= [self popErrorWithTitle:title forOperation:list.ReadAppend((base + "/" + source->d_name).c_str())];
3737 error |= [self popErrorWithTitle:title forOperation:list.ReadAppend(SOURCES_LIST)];
3742 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3743 @synchronized (self) {
3746 [self releasePackages];
3749 [sourceList_ removeAllObjects];
3770 new (&pool_) CYPool();
3772 NSRecycleZone(zone_);
3773 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3775 int chk(creat("/tmp/cydia.chk", 0644));
3779 if (invocation != nil)
3780 [invocation invoke];
3782 NSString *title(UCLocalize("DATABASE"));
3784 list_ = new pkgSourceList();
3785 _profile(reloadDataWithInvocation$ReadMainList)
3786 if ([self popErrorWithTitle:title forReadList:*list_])
3790 _profile(reloadDataWithInvocation$Source$initWithMetaIndex)
3791 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3792 Source *object([[[Source alloc] initWithMetaIndex:*source forDatabase:self inPool:&pool_] autorelease]);
3793 [sourceList_ addObject:object];
3798 OpProgress progress;
3801 delock_ = GetStatusDate();
3802 _profile(reloadDataWithInvocation$pkgCacheFile)
3803 opened = cache_.Open(progress, false);
3806 // XXX: this block should probably be merged with popError: in some way
3807 while (!_error->empty()) {
3809 bool warning(!_error->PopMessage(error));
3811 lprintf("cache_.Open():[%s]\n", error.c_str());
3813 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3817 else if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3818 repair = @selector(configure);
3819 //else if (error == "The package lists or status file could not be parsed or opened.")
3820 // repair = @selector(update);
3821 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3822 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3823 // else if (error == "Malformed Status line")
3824 // else if (error == "The list of sources could not be read.")
3826 if (repair != NULL) {
3828 [delegate_ repairWithSelector:repair];
3834 } else if ([self popErrorWithTitle:title forOperation:true])
3838 unlink("/tmp/cydia.chk");
3840 now_ = [[NSDate date] timeIntervalSince1970];
3842 policy_ = new pkgDepCache::Policy();
3843 records_ = new pkgRecords(cache_);
3844 resolver_ = new pkgProblemResolver(cache_);
3845 fetcher_ = new pkgAcquire(&status_);
3848 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3849 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3853 _profile(reloadDataWithInvocation$pkgApplyStatus)
3854 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3858 if (cache_->BrokenCount() != 0) {
3859 _profile(pkgApplyStatus$pkgFixBroken)
3860 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3864 if (cache_->BrokenCount() != 0) {
3865 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3869 _profile(pkgApplyStatus$pkgMinimizeUpgrade)
3870 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3875 for (Source *object in (id) sourceList_) {
3876 metaIndex *source([object metaIndex]);
3877 std::vector<pkgIndexFile *> *indices = source->GetIndexFiles();
3878 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3879 // XXX: this could be more intelligent
3880 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3881 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3883 sourceMap_[cached->ID] = object;
3888 size_t capacity(MetaFile_->active_);
3890 capacity = 128*1024;
3894 std::vector<Package *> packages;
3895 packages.reserve(capacity);
3899 _profile(reloadDataWithInvocation$packageWithIterator)
3900 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3901 if (Package *package = [Package newPackageWithIterator:iterator withZone:zone_ inPool:&pool_ database:self]) {
3902 if (unsigned index = package.metadata->index_) {
3904 if (packages.size() == index) {
3905 packages.push_back(package);
3906 } else if (packages.size() <= index) {
3907 packages.resize(index + 1, nil);
3908 packages[index] = package;
3911 std::swap(package, packages[index]);
3912 if (package != nil) {
3913 if (package.metadata->index_ == index + 1)
3922 lost: if (last == packages.size())
3923 packages.push_back(package);
3925 packages[last] = package;
3929 for (; last != packages.size(); ++last)
3930 if (packages[last] == nil)
3935 for (size_t next(last + 1); last != packages.size(); ++last, ++next) {
3937 if (next == packages.size())
3939 if (packages[next] != nil)
3944 std::swap(packages[last], packages[next]);
3947 packages.resize(last);
3950 NSLog(@"lost = %zu", lost);
3952 _profile(reloadDataWithInvocation$radix$8)
3953 CYRadixSortUsingFunction(packages.data(), packages.size(), reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix), reinterpret_cast<void *>(8));
3956 _profile(reloadDataWithInvocation$radix$4)
3957 CYRadixSortUsingFunction(packages.data(), packages.size(), reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix), reinterpret_cast<void *>(4));
3960 _profile(reloadDataWithInvocation$radix$0)
3961 CYRadixSortUsingFunction(packages.data(), packages.size(), reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix), reinterpret_cast<void *>(0));
3965 _profile(reloadDataWithInvocation$insertion)
3966 CYArrayInsertionSortValues(packages.data(), packages.size(), &PackageNameCompare, NULL);
3969 packages_ = [[[NSArray alloc] initWithObjects:packages.data() count:packages.size()] autorelease];
3971 /*_profile(reloadDataWithInvocation$CFQSortArray)
3972 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);
3975 /*_profile(reloadDataWithInvocation$stdsort)
3976 std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3979 /*_profile(reloadDataWithInvocation$CFArraySortValues)
3980 CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3983 /*_profile(reloadDataWithInvocation$sortUsingFunction)
3984 [packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3987 MetaFile_->active_ = packages.size();
3988 for (size_t index(0), count(packages.size()); index != count; ++index) {
3989 auto package(packages[index]);
3990 [package setIndex:index];
3997 @synchronized (self) {
3999 resolver_ = new pkgProblemResolver(cache_);
4001 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
4002 if (!cache_[iterator].Keep())
4003 cache_->MarkKeep(iterator, false);
4004 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
4005 cache_->SetReInstall(iterator, false);
4008 - (void) configure {
4009 NSString *dpkg = [NSString stringWithFormat:@"/usr/libexec/cydo --configure -a --status-fd %u", statusfd_];
4011 system([dpkg UTF8String]);
4016 @synchronized (self) {
4017 // XXX: I don't remember this condition
4022 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
4024 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
4026 if ([self popErrorWithTitle:title])
4030 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
4032 CydiaLogCleaner cleaner;
4033 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
4040 fetcher_->Shutdown();
4042 pkgRecords records(cache_);
4044 lock_ = new FileFd();
4045 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
4047 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
4049 if ([self popErrorWithTitle:title])
4053 if ([self popErrorWithTitle:title forReadList:list])
4056 manager_ = (_system->CreatePM(cache_));
4057 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
4064 bool substrate(RestartSubstrate_);
4065 RestartSubstrate_ = false;
4067 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
4069 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
4071 if ([self popErrorWithTitle:title forReadList:list])
4073 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
4074 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
4077 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4079 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
4081 [self popErrorWithTitle:title];
4085 bool failed = false;
4086 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
4087 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
4089 if ((*item)->Status == pkgAcquire::Item::StatIdle)
4092 std::string uri = (*item)->DescURI();
4093 std::string error = (*item)->ErrorText;
4095 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
4098 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError]);
4099 [delegate_ addProgressEventOnMainThread:event forTask:title];
4102 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4110 RestartSubstrate_ = true;
4112 if (![delock_ isEqual:GetStatusDate()]) {
4113 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("DPKG_LOCKED") ofType:kCydiaProgressEventTypeError] forTask:title];
4119 pkgPackageManager::OrderResult result(manager_->DoInstall(statusfd_));
4121 NSString *oextended(@"/var/lib/apt/extended_states");
4122 NSString *nextended(Cache("extended_states"));
4125 if (stat([nextended UTF8String], &info) != -1 && (info.st_mode & S_IFMT) == S_IFREG)
4126 system([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /bin/cp --remove-destination %@ %@", ShellEscape(nextended), ShellEscape(oextended)] UTF8String]);
4128 unlink([nextended UTF8String]);
4129 symlink([oextended UTF8String], [nextended UTF8String]);
4131 if ([self popErrorWithTitle:title])
4134 if (result == pkgPackageManager::Failed) {
4139 if (result != pkgPackageManager::Completed) {
4144 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
4146 if ([self popErrorWithTitle:title forReadList:list])
4148 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
4149 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
4152 if (![before isEqualToArray:after])
4157 return ![delock_ isEqual:GetStatusDate()];
4161 NSString *title(UCLocalize("UPGRADE"));
4162 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
4168 [self updateWithStatus:status_];
4171 - (void) updateWithStatus:(CancelStatus &)status {
4172 NSString *title(UCLocalize("REFRESHING_DATA"));
4175 if ([self popErrorWithTitle:title forReadList:list])
4179 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
4180 if ([self popErrorWithTitle:title])
4183 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4185 bool success(ListUpdate(status, list, PulseInterval_));
4186 if (status.WasCancelled())
4189 [self popErrorWithTitle:title forOperation:success];
4191 [[NSDictionary dictionaryWithObjectsAndKeys:
4192 [NSDate date], @"LastUpdate",
4193 nil] writeToFile:@ CacheState_ atomically:YES];
4196 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4199 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
4200 delegate_ = delegate;
4203 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
4204 progress_ = delegate;
4205 status_.setDelegate(delegate);
4208 - (NSObject<ProgressDelegate> *) progressDelegate {
4212 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
4213 SourceMap::const_iterator i(sourceMap_.find(file->ID));
4214 return i == sourceMap_.end() ? nil : i->second;
4217 - (void) setFetch:(bool)fetch forURI:(const char *)uri {
4218 for (Source *source in (id) sourceList_)
4219 [source setFetch:fetch forURI:uri];
4222 - (void) resetFetch {
4223 for (Source *source in (id) sourceList_)
4224 [source resetFetch];
4227 - (NSString *) mappedSectionForPointer:(const char *)section {
4228 _H<NSString> *mapped;
4230 _profile(Database$mappedSectionForPointer$Cache)
4231 mapped = §ions_[section];
4234 if (*mapped == NULL) {
4235 size_t length(strlen(section));
4236 char spaced[length + 1];
4238 _profile(Database$mappedSectionForPointer$Replace)
4239 for (size_t index(0); index != length; ++index)
4240 spaced[index] = section[index] == '_' ? ' ' : section[index];
4241 spaced[length] = '\0';
4246 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
4247 string = [NSString stringWithUTF8String:spaced];
4250 _profile(Database$mappedSectionForPointer$Map)
4251 string = [SectionMap_ objectForKey:string] ?: string;
4261 static _H<NSMutableSet> Diversions_;
4263 @interface Diversion : NSObject {
4266 _H<NSString> format_;
4271 @implementation Diversion
4273 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
4274 if ((self = [super init]) != nil) {
4275 pattern_ = [from UTF8String];
4281 - (NSString *) divert:(NSString *)url {
4282 return !pattern_(url) ? nil : pattern_->*format_;
4285 + (NSURL *) divertURL:(NSURL *)url {
4287 NSString *href([url absoluteString]);
4289 for (Diversion *diversion in (id) Diversions_)
4290 if (NSString *diverted = [diversion divert:href]) {
4292 NSLog(@"div: %@", diverted);
4294 url = [NSURL URLWithString:diverted];
4301 - (NSString *) key {
4305 - (NSUInteger) hash {
4309 - (BOOL) isEqual:(Diversion *)object {
4310 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
4315 @interface CydiaObject : NSObject {
4316 _H<CyteWebViewController> indirect_;
4317 _transient id delegate_;
4320 - (id) initWithDelegate:(CyteWebViewController *)indirect;
4326 @interface CydiaWebViewController : CyteWebViewController {
4327 _H<CydiaObject> cydia_;
4330 + (void) addDiversion:(Diversion *)diversion;
4331 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request;
4332 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia;
4333 - (void) setDelegate:(id)delegate;
4337 /* Web Scripting {{{ */
4338 @implementation CydiaObject
4340 - (id) initWithDelegate:(CyteWebViewController *)indirect {
4341 if ((self = [super init]) != nil) {
4342 indirect_ = indirect;
4346 - (void) setDelegate:(id)delegate {
4347 delegate_ = delegate;
4350 + (NSArray *) _attributeKeys {
4351 return [NSArray arrayWithObjects:
4356 @"coreFoundationVersionNumber",
4372 - (NSArray *) attributeKeys {
4373 return [[self class] _attributeKeys];
4376 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4377 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4380 - (NSString *) version {
4384 - (unsigned) bittage {
4386 #elif defined(__arm64__)
4388 #elif defined(__arm__)
4395 - (NSString *) build {
4399 - (NSString *) coreFoundationVersionNumber {
4400 return [NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber];
4403 - (NSString *) device {
4404 return UniqueIdentifier();
4407 - (NSString *) firmware {
4408 return [[UIDevice currentDevice] systemVersion];
4411 - (NSString *) hostname {
4412 return [[UIDevice currentDevice] name];
4415 - (NSString *) idiom {
4416 return (id) Idiom_ ?: [NSNull null];
4419 - (NSArray *) cells {
4420 auto *$_CTServerConnectionCreate(reinterpret_cast<id (*)(void *, void *, void *)>(dlsym(RTLD_DEFAULT, "_CTServerConnectionCreate")));
4421 if ($_CTServerConnectionCreate == NULL)
4424 struct CTResult { int flag; int error; };
4425 auto *$_CTServerConnectionCellMonitorCopyCellInfo(reinterpret_cast<CTResult (*)(CFTypeRef, void *, CFArrayRef *)>(dlsym(RTLD_DEFAULT, "_CTServerConnectionCellMonitorCopyCellInfo")));
4426 if ($_CTServerConnectionCellMonitorCopyCellInfo == NULL)
4429 _H<const void> connection($_CTServerConnectionCreate(NULL, NULL, NULL), true);
4430 if (connection == nil)
4434 CFArrayRef cells(NULL);
4435 auto result($_CTServerConnectionCellMonitorCopyCellInfo(connection, &count, &cells));
4436 if (result.flag != 0)
4439 return [(NSArray *) cells autorelease];
4442 - (NSString *) mcc {
4443 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode")))
4444 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault) autorelease];
4448 - (NSString *) mnc {
4449 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberNetworkCode")))
4450 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault) autorelease];
4454 - (NSString *) operator {
4455 if (CFStringRef (*$CTRegistrationCopyOperatorName)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTRegistrationCopyOperatorName")))
4456 return [(NSString *) (*$CTRegistrationCopyOperatorName)(kCFAllocatorDefault) autorelease];
4460 - (NSString *) bbsnum {
4461 return (id) BBSNum_ ?: [NSNull null];
4464 - (NSString *) ecid {
4465 return (id) ChipID_ ?: [NSNull null];
4468 - (NSString *) serial {
4469 return SerialNumber_;
4472 - (NSString *) role {
4473 return (id) [NSNull null];
4476 - (NSString *) model {
4477 return [NSString stringWithUTF8String:Machine_];
4480 + (NSString *) webScriptNameForSelector:(SEL)selector {
4482 else if (selector == @selector(addBridgedHost:))
4483 return @"addBridgedHost";
4484 else if (selector == @selector(addInsecureHost:))
4485 return @"addInsecureHost";
4486 else if (selector == @selector(addInternalRedirect::))
4487 return @"addInternalRedirect";
4488 else if (selector == @selector(addSource:::))
4489 return @"addSource";
4490 else if (selector == @selector(addTrivialSource:))
4491 return @"addTrivialSource";
4492 else if (selector == @selector(close))
4494 else if (selector == @selector(du:))
4496 else if (selector == @selector(stringWithFormat:arguments:))
4498 else if (selector == @selector(getAllSources))
4499 return @"getAllSources";
4500 else if (selector == @selector(getApplicationInfo:value:))
4501 return @"getApplicationInfoValue";
4502 else if (selector == @selector(getDisplayIdentifiers))
4503 return @"getDisplayIdentifiers";
4504 else if (selector == @selector(getLocalizedNameForDisplayIdentifier:))
4505 return @"getLocalizedNameForDisplayIdentifier";
4506 else if (selector == @selector(getKernelNumber:))
4507 return @"getKernelNumber";
4508 else if (selector == @selector(getKernelString:))
4509 return @"getKernelString";
4510 else if (selector == @selector(getInstalledPackages))
4511 return @"getInstalledPackages";
4512 else if (selector == @selector(getIORegistryEntry::))
4513 return @"getIORegistryEntry";
4514 else if (selector == @selector(getLocaleIdentifier))
4515 return @"getLocaleIdentifier";
4516 else if (selector == @selector(getPreferredLanguages))
4517 return @"getPreferredLanguages";
4518 else if (selector == @selector(getPackageById:))
4519 return @"getPackageById";
4520 else if (selector == @selector(getMetadataKeys))
4521 return @"getMetadataKeys";
4522 else if (selector == @selector(getMetadataValue:))
4523 return @"getMetadataValue";
4524 else if (selector == @selector(getSessionValue:))
4525 return @"getSessionValue";
4526 else if (selector == @selector(installPackages:))
4527 return @"installPackages";
4528 else if (selector == @selector(isReachable:))
4529 return @"isReachable";
4530 else if (selector == @selector(localizedStringForKey:value:table:))
4532 else if (selector == @selector(popViewController:))
4533 return @"popViewController";
4534 else if (selector == @selector(refreshSources))
4535 return @"refreshSources";
4536 else if (selector == @selector(registerFrame:))
4537 return @"registerFrame";
4538 else if (selector == @selector(removeButton))
4539 return @"removeButton";
4540 else if (selector == @selector(saveConfig))
4541 return @"saveConfig";
4542 else if (selector == @selector(setMetadataValue::))
4543 return @"setMetadataValue";
4544 else if (selector == @selector(setSessionValue::))
4545 return @"setSessionValue";
4546 else if (selector == @selector(substitutePackageNames:))
4547 return @"substitutePackageNames";
4548 else if (selector == @selector(scrollToBottom:))
4549 return @"scrollToBottom";
4550 else if (selector == @selector(setAllowsNavigationAction:))
4551 return @"setAllowsNavigationAction";
4552 else if (selector == @selector(setBadgeValue:))
4553 return @"setBadgeValue";
4554 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4555 return @"setButtonImage";
4556 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4557 return @"setButtonTitle";
4558 else if (selector == @selector(setHidesBackButton:))
4559 return @"setHidesBackButton";
4560 else if (selector == @selector(setHidesNavigationBar:))
4561 return @"setHidesNavigationBar";
4562 else if (selector == @selector(setNavigationBarStyle:))
4563 return @"setNavigationBarStyle";
4564 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4565 return @"setNavigationBarTintColor";
4566 else if (selector == @selector(setPasteboardString:))
4567 return @"setPasteboardString";
4568 else if (selector == @selector(setPasteboardURL:))
4569 return @"setPasteboardURL";
4570 else if (selector == @selector(setScrollAlwaysBounceVertical:))
4571 return @"setScrollAlwaysBounceVertical";
4572 else if (selector == @selector(setScrollIndicatorStyle:))
4573 return @"setScrollIndicatorStyle";
4574 else if (selector == @selector(setToken:))
4576 else if (selector == @selector(setViewportWidth:))
4577 return @"setViewportWidth";
4578 else if (selector == @selector(statfs:))
4580 else if (selector == @selector(supports:))
4582 else if (selector == @selector(unload))
4588 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4589 return [self webScriptNameForSelector:selector] == nil;
4592 - (BOOL) supports:(NSString *)feature {
4593 return [feature isEqualToString:@"window.open"];
4597 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4600 - (void) setScrollAlwaysBounceVertical:(NSNumber *)value {
4601 [indirect_ performSelectorOnMainThread:@selector(setScrollAlwaysBounceVerticalNumber:) withObject:value waitUntilDone:NO];
4604 - (void) setScrollIndicatorStyle:(NSString *)style {
4605 [indirect_ performSelectorOnMainThread:@selector(setScrollIndicatorStyleWithName:) withObject:style waitUntilDone:NO];
4608 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4609 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4612 - (NSDictionary *) getApplicationInfo:(NSString *)display value:(NSString *)key {
4614 if (SBBundlePathForDisplayIdentifier(SBSSpringBoardServerPort(), [display UTF8String], path) != 0)
4615 return (id) [NSNull null];
4616 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:[[NSString stringWithUTF8String:path] stringByAppendingString:@"/Info.plist"]]);
4618 return (id) [NSNull null];
4619 return [info objectForKey:key];
4622 - (NSArray *) getDisplayIdentifiers {
4623 return SBSCopyApplicationDisplayIdentifiers(false, false);
4626 - (NSString *) getLocalizedNameForDisplayIdentifier:(NSString *)identifier {
4627 return [SBSCopyLocalizedApplicationNameForDisplayIdentifier(identifier) autorelease] ?: (id) [NSNull null];
4630 - (NSNumber *) getKernelNumber:(NSString *)name {
4631 const char *string([name UTF8String]);
4634 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4635 return (id) [NSNull null];
4637 if (size != sizeof(int))
4638 return (id) [NSNull null];
4641 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4642 return (id) [NSNull null];
4644 return [NSNumber numberWithInt:value];
4647 - (NSString *) getKernelString:(NSString *)name {
4648 const char *string([name UTF8String]);
4651 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4652 return (id) [NSNull null];
4654 char value[size + 1];
4655 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4656 return (id) [NSNull null];
4658 // XXX: just in case you request something ludicrous
4661 return [NSString stringWithCString:value];
4664 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4665 NSObject *value(CYIOGetValue([path UTF8String], entry));
4668 if ([value isKindOfClass:[NSData class]])
4669 value = CYHex((NSData *) value);
4674 - (NSArray *) getMetadataKeys {
4675 @synchronized (Values_) {
4676 return [Values_ allKeys];
4679 - (void) registerFrame:(DOMHTMLIFrameElement *)iframe {
4680 WebFrame *frame([iframe contentFrame]);
4681 [indirect_ registerFrame:frame];
4684 - (id) getMetadataValue:(NSString *)key {
4685 @synchronized (Values_) {
4686 return [Values_ objectForKey:key];
4689 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4690 @synchronized (Values_) {
4691 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4692 [Values_ removeObjectForKey:key];
4694 [Values_ setObject:value forKey:key];
4697 - (id) getSessionValue:(NSString *)key {
4698 @synchronized (SessionData_) {
4699 return [SessionData_ objectForKey:key];
4702 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4703 @synchronized (SessionData_) {
4704 if (value == (id) [WebUndefined undefined])
4705 [SessionData_ removeObjectForKey:key];
4707 [SessionData_ setObject:value forKey:key];
4710 - (void) addBridgedHost:(NSString *)host {
4711 @synchronized (HostConfig_) {
4712 [BridgedHosts_ addObject:host];
4715 - (void) addInsecureHost:(NSString *)host {
4716 @synchronized (HostConfig_) {
4717 [InsecureHosts_ addObject:host];
4720 - (void) popViewController:(NSNumber *)value {
4721 if (value == (id) [WebUndefined undefined])
4722 value = [NSNumber numberWithBool:YES];
4723 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4726 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4727 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4729 for (NSString *section in sections)
4730 [array addObject:section];
4732 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4735 distribution, @"Distribution",
4737 nil] waitUntilDone:NO];
4740 - (BOOL) addTrivialSource:(NSString *)href {
4741 href = VerifySource(href);
4744 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4748 - (void) refreshSources {
4749 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4752 - (void) saveConfig {
4753 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4756 - (NSArray *) getAllSources {
4757 return [[Database sharedInstance] sources];
4760 - (NSArray *) getInstalledPackages {
4761 Database *database([Database sharedInstance]);
4762 @synchronized (database) {
4763 NSArray *packages([database packages]);
4764 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4765 for (Package *package in packages)
4766 if (![package uninstalled])
4767 [installed addObject:package];
4771 - (Package *) getPackageById:(NSString *)id {
4772 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4776 return (Package *) [NSNull null];
4779 - (NSString *) getLocaleIdentifier {
4780 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4783 - (NSArray *) getPreferredLanguages {
4787 - (NSArray *) statfs:(NSString *)path {
4790 if (path == nil || statfs([path UTF8String], &stat) == -1)
4793 return [NSArray arrayWithObjects:
4794 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4795 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4796 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4800 - (NSNumber *) du:(NSString *)path {
4801 NSNumber *value(nil);
4803 FILE *du(popen([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /usr/libexec/cydia/du -ks %@", ShellEscape(path)] UTF8String], "r"));
4806 while (fgets(line, sizeof(line), du) != NULL) {
4807 size_t length(strlen(line));
4808 while (length != 0 && line[length - 1] == '\n')
4809 line[--length] = '\0';
4810 if (char *tab = strchr(line, '\t')) {
4812 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4822 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4825 - (NSNumber *) isReachable:(NSString *)name {
4826 return [NSNumber numberWithBool:IsReachable([name UTF8String])];
4829 - (void) installPackages:(NSArray *)packages {
4830 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4833 - (NSString *) substitutePackageNames:(NSString *)message {
4834 auto database([Database sharedInstance]);
4836 // XXX: this check is less racy than you'd expect, but this entire concept is a little awkward
4837 if (![database hasPackages])
4840 NSMutableArray *words([[[message componentsSeparatedByString:@" "] mutableCopy] autorelease]);
4841 for (size_t i(0), e([words count]); i != e; ++i) {
4842 NSString *word([words objectAtIndex:i]);
4843 if (Package *package = [database packageWithName:word])
4844 [words replaceObjectAtIndex:i withObject:[package name]];
4847 return [words componentsJoinedByString:@" "];
4850 - (void) removeButton {
4851 [indirect_ removeButton];
4854 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4855 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4858 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4859 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4862 - (void) setBadgeValue:(id)value {
4863 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4866 - (void) setAllowsNavigationAction:(NSString *)value {
4867 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4870 - (void) setHidesBackButton:(NSString *)value {
4871 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4874 - (void) setHidesNavigationBar:(NSString *)value {
4875 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4878 - (void) setNavigationBarStyle:(NSString *)value {
4879 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4882 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4883 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4884 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4885 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4888 - (void) setPasteboardString:(NSString *)value {
4889 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4892 - (void) setPasteboardURL:(NSString *)value {
4893 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4896 - (void) setToken:(NSString *)token {
4897 // XXX: the website expects this :/
4900 - (void) scrollToBottom:(NSNumber *)animated {
4901 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4904 - (void) setViewportWidth:(float)width {
4905 [indirect_ setViewportWidthOnMainThread:width];
4908 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4909 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4910 unsigned count([arguments count]);
4912 for (unsigned i(0); i != count; ++i)
4913 values[i] = [arguments objectAtIndex:i];
4914 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4917 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4918 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4920 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4922 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4928 @interface NSURL (CydiaSecure)
4931 @implementation NSURL (CydiaSecure)
4933 - (bool) isCydiaSecure {
4934 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4937 @synchronized (HostConfig_) {
4938 if ([InsecureHosts_ containsObject:[self host]])
4947 /* Cydia Browser Controller {{{ */
4948 @implementation CydiaWebViewController
4950 - (NSURL *) navigationURL {
4951 if (NSURLRequest *request = self.request)
4952 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request URL] absoluteString]]];
4957 + (void) _initialize {
4958 [super _initialize];
4960 Diversions_ = [NSMutableSet setWithCapacity:0];
4963 + (void) addDiversion:(Diversion *)diversion {
4964 [Diversions_ addObject:diversion];
4967 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4968 [super webView:view didClearWindowObject:window forFrame:frame];
4969 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
4972 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia {
4973 WebDataSource *source([frame dataSource]);
4974 NSURLResponse *response([source response]);
4975 NSURL *url([response URL]);
4976 NSString *scheme([[url scheme] lowercaseString]);
4978 bool bridged(false);
4980 @synchronized (HostConfig_) {
4981 if ([scheme isEqualToString:@"file"])
4983 else if ([scheme isEqualToString:@"https"])
4984 if ([BridgedHosts_ containsObject:[url host]])
4989 [window setValue:cydia forKey:@"cydia"];
4992 - (void) _setupMail:(MFMailComposeViewController *)controller {
4993 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4995 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4996 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4999 - (NSURL *) URLWithURL:(NSURL *)url {
5000 return [Diversion divertURL:url];
5003 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
5004 return [CydiaWebViewController requestWithHeaders:[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
5007 - (NSURLRequest *) webThreadWebView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
5008 return [CydiaWebViewController requestWithHeaders:[super webThreadWebView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
5011 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request {
5012 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
5014 NSURL *url([copy URL]);
5015 NSString *href([url absoluteString]);
5016 NSString *host([url host]);
5018 if ([href hasPrefix:@"https://cydia.saurik.com/TSS/"]) {
5019 if (NSString *agent = [copy valueForHTTPHeaderField:@"X-User-Agent"]) {
5020 [copy setValue:agent forHTTPHeaderField:@"User-Agent"];
5021 [copy setValue:nil forHTTPHeaderField:@"X-User-Agent"];
5024 [copy setValue:nil forHTTPHeaderField:@"Referer"];
5025 [copy setValue:nil forHTTPHeaderField:@"Origin"];
5027 [copy setURL:[NSURL URLWithString:[@"http://gs.apple.com/TSS/" stringByAppendingString:[href substringFromIndex:29]]]];
5031 if ([copy valueForHTTPHeaderField:@"X-Cydia-Cf"] == nil)
5032 [copy setValue:[NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber] forHTTPHeaderField:@"X-Cydia-Cf"];
5033 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
5034 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
5036 bool bridged; @synchronized (HostConfig_) {
5037 bridged = [BridgedHosts_ containsObject:host];
5040 if ([url isCydiaSecure] && bridged && UniqueID_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Id"] == nil)
5041 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
5046 - (void) setDelegate:(id)delegate {
5047 [super setDelegate:delegate];
5048 [cydia_ setDelegate:delegate];
5051 - (NSString *) applicationNameForUserAgent {
5056 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
5057 cydia_ = [[[CydiaObject alloc] initWithDelegate:self.indirect] autorelease];
5063 @interface AppCacheController : CydiaWebViewController {
5068 @implementation AppCacheController
5070 - (void) didReceiveMemoryWarning {
5071 // XXX: this doesn't work
5074 - (bool) retainsNetworkActivityIndicator {
5081 /* Confirmation Controller {{{ */
5082 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
5083 if (!iterator.end())
5084 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
5085 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
5087 pkgCache::PkgIterator package(dep.TargetPkg());
5090 if (strcmp(package.Name(), "mobilesubstrate") == 0)
5097 @protocol ConfirmationControllerDelegate
5098 - (void) cancelAndClear:(bool)clear;
5099 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
5103 @interface ConfirmationController : CydiaWebViewController {
5104 _transient Database *database_;
5106 _H<UIAlertView> essential_;
5108 _H<NSDictionary> changes_;
5109 _H<NSMutableArray> issues_;
5110 _H<NSDictionary> sizes_;
5115 - (id) initWithDatabase:(Database *)database;
5119 @implementation ConfirmationController
5123 RestartSubstrate_ = true;
5124 [self.delegate confirmWithNavigationController:[self navigationController]];
5127 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
5128 NSString *context([alert context]);
5130 if ([context isEqualToString:@"remove"]) {
5131 if (button == [alert cancelButtonIndex])
5133 else if (button == [alert firstOtherButtonIndex]) {
5134 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
5137 [alert dismissWithClickedButtonIndex:-1 animated:YES];
5138 } else if ([context isEqualToString:@"unable"]) {
5139 [self dismissModalViewControllerAnimated:YES];
5140 [alert dismissWithClickedButtonIndex:-1 animated:YES];
5142 [super alertView:alert clickedButtonAtIndex:button];
5146 - (void) _doContinue {
5147 [self.delegate cancelAndClear:NO];
5148 [self dismissModalViewControllerAnimated:YES];
5151 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
5152 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
5156 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5157 [super webView:view didClearWindowObject:window forFrame:frame];
5159 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
5160 (id) changes_, @"changes",
5161 (id) issues_, @"issues",
5162 (id) sizes_, @"sizes",
5164 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
5167 - (id) initWithDatabase:(Database *)database {
5168 if ((self = [super init]) != nil) {
5169 database_ = database;
5171 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
5172 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
5173 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
5174 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
5175 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
5179 pkgCacheFile &cache([database_ cache]);
5180 NSArray *packages([database_ packages]);
5181 pkgDepCache::Policy *policy([database_ policy]);
5183 issues_ = [NSMutableArray arrayWithCapacity:4];
5185 for (Package *package in packages) {
5186 pkgCache::PkgIterator iterator([package iterator]);
5187 NSString *name([package id]);
5189 if ([package broken]) {
5190 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
5192 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5194 reasons, @"reasons",
5197 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
5201 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
5202 pkgCache::DepIterator start;
5203 pkgCache::DepIterator end;
5204 dep.GlobOr(start, end); // ++dep
5206 if (!cache->IsImportantDep(end))
5208 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
5211 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
5213 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5214 [NSString stringWithUTF8String:start.DepType()], @"relationship",
5215 clauses, @"clauses",
5219 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
5221 pkgCache::PkgIterator target(start.TargetPkg());
5222 if (target->ProvidesList != 0)
5223 reason = @"missing";
5225 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
5227 reason = @"installed";
5228 installed = [NSString stringWithUTF8String:ver.VerStr()];
5229 } else if (!cache[target].CandidateVerIter(cache).end())
5230 reason = @"uninstalled";
5231 else if (target->ProvidesList == 0)
5232 reason = @"uninstallable";
5234 reason = @"virtual";
5237 NSDictionary *version(start.TargetVer() == 0 ? (NSDictionary *) [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
5238 [NSString stringWithUTF8String:start.CompType()], @"operator",
5239 [NSString stringWithUTF8String:start.TargetVer()], @"value",
5242 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5243 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
5244 version, @"version",
5246 installed, @"installed",
5249 // yes, seriously. (wtf?)
5257 pkgDepCache::StateCache &state(cache[iterator]);
5259 static RegEx special_r("(firmware|gsc\\..*|cy\\+.*)");
5261 if (state.NewInstall())
5262 [installs addObject:name];
5263 // XXX: else if (state.Install())
5264 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
5265 [reinstalls addObject:name];
5266 // XXX: move before previous if
5267 else if (state.Upgrade())
5268 [upgrades addObject:name];
5269 else if (state.Downgrade())
5270 [downgrades addObject:name];
5271 else if (!state.Delete())
5272 // XXX: _assert(state.Keep());
5274 else if (special_r(name))
5275 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5276 [NSNull null], @"package",
5277 [NSArray arrayWithObjects:
5278 [NSDictionary dictionaryWithObjectsAndKeys:
5279 @"Conflicts", @"relationship",
5280 [NSArray arrayWithObjects:
5281 [NSDictionary dictionaryWithObjectsAndKeys:
5283 [NSNull null], @"version",
5284 @"installed", @"reason",
5291 if ([package essential])
5293 [removes addObject:name];
5296 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
5297 substrate_ |= DepSubstrate(iterator.CurrentVer());
5302 else if (Advanced_) {
5303 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
5305 essential_ = [[[UIAlertView alloc]
5306 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
5307 message:UCLocalize("REMOVING_ESSENTIALS_EX")
5309 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
5311 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
5315 [essential_ setContext:@"remove"];
5316 [essential_ setNumberOfRows:2];
5318 essential_ = [[[UIAlertView alloc]
5319 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
5320 message:UCLocalize("UNABLE_TO_COMPLY_EX")
5322 cancelButtonTitle:UCLocalize("OKAY")
5323 otherButtonTitles:nil
5326 [essential_ setContext:@"unable"];
5329 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5330 installs, @"installs",
5331 reinstalls, @"reinstalls",
5332 upgrades, @"upgrades",
5333 downgrades, @"downgrades",
5334 removes, @"removes",
5337 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5338 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
5339 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
5342 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
5346 - (UIBarButtonItem *) leftButton {
5347 return [[[UIBarButtonItem alloc]
5348 initWithTitle:UCLocalize("CANCEL")
5349 style:UIBarButtonItemStylePlain
5351 action:@selector(cancelButtonClicked)
5356 - (void) applyRightButton {
5357 if ([issues_ count] == 0 && ![self isLoading])
5358 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
5359 initWithTitle:UCLocalize("CONFIRM")
5360 style:UIBarButtonItemStyleDone
5362 action:@selector(confirmButtonClicked)
5365 [[self navigationItem] setRightBarButtonItem:nil];
5369 - (void) cancelButtonClicked {
5370 [self.delegate cancelAndClear:YES];
5371 [self dismissModalViewControllerAnimated:YES];
5375 - (void) confirmButtonClicked {
5376 if (essential_ != nil)
5386 /* Progress Data {{{ */
5387 @interface CydiaProgressData : NSObject {
5388 _transient id delegate_;
5397 _H<NSMutableArray> events_;
5398 _H<NSString> title_;
5400 _H<NSString> status_;
5401 _H<NSString> finish_;
5406 @implementation CydiaProgressData
5408 + (NSArray *) _attributeKeys {
5409 return [NSArray arrayWithObjects:
5421 - (NSArray *) attributeKeys {
5422 return [[self class] _attributeKeys];
5425 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5426 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5430 if ((self = [super init]) != nil) {
5431 events_ = [NSMutableArray arrayWithCapacity:32];
5439 - (void) setDelegate:(id)delegate {
5440 delegate_ = delegate;
5443 - (void) setPercent:(float)value {
5447 - (NSNumber *) percent {
5448 return [NSNumber numberWithFloat:percent_];
5451 - (void) setCurrent:(float)value {
5455 - (NSNumber *) current {
5456 return [NSNumber numberWithFloat:current_];
5459 - (void) setTotal:(float)value {
5463 - (NSNumber *) total {
5464 return [NSNumber numberWithFloat:total_];
5467 - (void) setSpeed:(float)value {
5471 - (NSNumber *) speed {
5472 return [NSNumber numberWithFloat:speed_];
5475 - (NSArray *) events {
5479 - (void) removeAllEvents {
5480 [events_ removeAllObjects];
5483 - (void) addEvent:(CydiaProgressEvent *)event {
5484 [events_ addObject:event];
5487 - (void) setTitle:(NSString *)text {
5491 - (NSString *) title {
5495 - (void) setFinish:(NSString *)text {
5499 - (NSString *) finish {
5500 return (id) finish_ ?: [NSNull null];
5503 - (void) setRunning:(bool)running {
5507 - (NSNumber *) running {
5508 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5513 /* Progress Controller {{{ */
5514 @interface ProgressController : CydiaWebViewController <
5517 _transient Database *database_;
5518 _H<CydiaProgressData, 1> progress_;
5522 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5524 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5526 - (void) setTitle:(NSString *)title;
5527 - (void) setCancellable:(bool)cancellable;
5531 @implementation ProgressController
5534 [database_ setProgressDelegate:nil];
5538 - (UIBarButtonItem *) leftButton {
5539 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5540 initWithTitle:UCLocalize("CANCEL")
5541 style:UIBarButtonItemStylePlain
5543 action:@selector(cancel)
5544 ] autorelease] : nil;
5547 - (void) updateCancel {
5548 [super applyLeftButton];
5551 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5552 if ((self = [super init]) != nil) {
5553 database_ = database;
5554 self.delegate = delegate;
5556 [database_ setProgressDelegate:self];
5558 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5559 [progress_ setDelegate:self];
5561 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5563 [self setPageColor:[UIColor blackColor]];
5565 [[self navigationItem] setHidesBackButton:YES];
5567 [self updateCancel];
5571 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5572 [super webView:view didClearWindowObject:window forFrame:frame];
5573 [window setValue:progress_ forKey:@"cydiaProgress"];
5576 - (void) updateProgress {
5577 [self dispatchEvent:@"CydiaProgressUpdate"];
5580 - (void) viewWillAppear:(BOOL)animated {
5581 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5582 [super viewWillAppear:animated];
5586 UpdateExternalStatus(0);
5589 [self.delegate saveState];
5593 [self.delegate returnToCydia];
5597 [self.delegate terminateWithSuccess];
5598 /*if ([self.delegate respondsToSelector:@selector(suspendWithAnimation:)])
5599 [self.delegate suspendWithAnimation:YES];
5601 [self.delegate suspend];*/
5613 UIProgressHUD *hud([self.delegate addProgressHUD]);
5614 [hud setText:UCLocalize("LOADING")];
5615 [self.delegate performSelector:@selector(reloadSpringBoard) withObject:nil afterDelay:0.5];
5621 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5622 SBReboot(SBSSpringBoardServerPort());
5624 reboot2(RB_AUTOBOOT);
5631 - (void) setTitle:(NSString *)title {
5632 [progress_ setTitle:title];
5633 [self updateProgress];
5636 - (UIBarButtonItem *) rightButton {
5637 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5638 initWithTitle:UCLocalize("CLOSE")
5639 style:UIBarButtonItemStylePlain
5641 action:@selector(close)
5645 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5646 UpdateExternalStatus(1);
5648 [progress_ setRunning:true];
5649 [self setTitle:title];
5650 // implicit updateProgress
5652 SHA1SumValue notifyconf; {
5654 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5657 MMap mmap(file, MMap::ReadOnly);
5659 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5660 notifyconf = sha1.Result();
5664 SHA1SumValue springlist; {
5666 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5669 MMap mmap(file, MMap::ReadOnly);
5671 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5672 springlist = sha1.Result();
5676 if (invocation != nil) {
5677 [invocation yieldToSelector:@selector(invoke)];
5678 [self setTitle:@"COMPLETE"];
5683 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5686 MMap mmap(file, MMap::ReadOnly);
5688 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5689 if (!(notifyconf == sha1.Result()))
5696 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5699 MMap mmap(file, MMap::ReadOnly);
5701 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5702 if (!(springlist == sha1.Result()))
5708 if (RestartSubstrate_)
5712 RestartSubstrate_ = false;
5715 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5716 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5717 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5718 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5719 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5722 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5724 [progress_ setRunning:false];
5725 [self updateProgress];
5727 [self applyRightButton];
5730 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5731 [progress_ addEvent:event];
5732 [self updateProgress];
5735 - (bool) isProgressCancelled {
5736 return cancel_ == 2;
5741 [self updateCancel];
5744 - (void) setCancellable:(bool)cancellable {
5745 unsigned cancel(cancel_);
5749 else if (cancel_ == 0)
5752 if (cancel != cancel_)
5753 [self updateCancel];
5756 - (void) setProgressCancellable:(NSNumber *)cancellable {
5757 [self setCancellable:[cancellable boolValue]];
5760 - (void) setProgressPercent:(NSNumber *)percent {
5761 [progress_ setPercent:[percent floatValue]];
5762 [self updateProgress];
5765 - (void) setProgressStatus:(NSDictionary *)status {
5766 if (status == nil) {
5767 [progress_ setCurrent:0];
5768 [progress_ setTotal:0];
5769 [progress_ setSpeed:0];
5771 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5773 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5774 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5775 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5778 [self updateProgress];
5784 /* Package Cell {{{ */
5785 @interface PackageCell : CyteTableViewCell <
5786 CyteTableViewCellDelegate
5790 _H<NSString> description_;
5792 _H<NSString> source_;
5794 _H<UIImage> placard_;
5798 - (PackageCell *) init;
5799 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5801 - (void) drawContentRect:(CGRect)rect;
5805 @implementation PackageCell
5807 - (PackageCell *) init {
5808 CGRect frame(CGRectMake(0, 0, 320, 74));
5809 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5810 UIView *content([self contentView]);
5811 CGRect bounds([content bounds]);
5813 self.content = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5814 [self.content setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5815 [content addSubview:self.content];
5817 [self.content setDelegate:self];
5818 [self.content setOpaque:YES];
5822 - (NSString *) accessibilityLabel {
5826 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5827 summarized_ = summary;
5837 [self.content setBackgroundColor:[UIColor whiteColor]];
5841 Source *source = [package source];
5843 icon_ = [package icon];
5845 if (NSString *name = [package name])
5846 name_ = [NSString stringWithString:name];
5848 if (NSString *description = [package shortDescription])
5849 description_ = [NSString stringWithString:description];
5851 commercial_ = [package isCommercial];
5853 NSString *label = nil;
5854 bool trusted = false;
5856 if (source != nil) {
5857 label = [source label];
5858 trusted = [source trusted];
5859 } else if ([[package id] isEqualToString:@"firmware"])
5860 label = UCLocalize("APPLE");
5862 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5864 NSString *from(label);
5866 NSString *section = [package simpleSection];
5867 if (section != nil && ![section isEqualToString:label]) {
5868 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5869 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5872 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5874 if (NSString *purpose = [package primaryPurpose])
5875 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5880 if (NSString *mode = [package mode]) {
5881 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5882 color = RemovingColor_;
5883 placard = @"removing";
5885 color = InstallingColor_;
5886 placard = @"installing";
5889 color = [UIColor whiteColor];
5891 if ([package installed] != nil)
5892 placard = @"installed";
5897 [self.content setBackgroundColor:color];
5900 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5903 [self setNeedsDisplay];
5904 [self.content setNeedsDisplay];
5907 - (void) drawSummaryContentRect:(CGRect)rect {
5908 bool highlighted(self.highlighted);
5909 float width([self bounds].size.width);
5913 rect.size = [(UIImage *) icon_ size];
5915 while (rect.size.width > 16 || rect.size.height > 16) {
5916 rect.size.width /= 2;
5917 rect.size.height /= 2;
5920 rect.origin.x = 19 - rect.size.width / 2;
5921 rect.origin.y = 19 - rect.size.height / 2;
5923 [icon_ drawInRect:Retina(rect)];
5926 if (badge_ != nil) {
5928 rect.size = [(UIImage *) badge_ size];
5930 rect.size.width /= 4;
5931 rect.size.height /= 4;
5933 rect.origin.x = 25 - rect.size.width / 2;
5934 rect.origin.y = 25 - rect.size.height / 2;
5936 [badge_ drawInRect:Retina(rect)];
5939 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5943 UISetColor(commercial_ ? Purple_ : Black_);
5944 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
5946 if (placard_ != nil)
5947 [placard_ drawAtPoint:CGPointMake(width - 52, 11)];
5950 - (void) drawNormalContentRect:(CGRect)rect {
5951 bool highlighted(self.highlighted);
5952 float width([self bounds].size.width);
5956 rect.size = [(UIImage *) icon_ size];
5958 while (rect.size.width > 32 || rect.size.height > 32) {
5959 rect.size.width /= 2;
5960 rect.size.height /= 2;
5963 rect.origin.x = 25 - rect.size.width / 2;
5964 rect.origin.y = 25 - rect.size.height / 2;
5966 [icon_ drawInRect:Retina(rect)];
5969 if (badge_ != nil) {
5971 rect.size = [(UIImage *) badge_ size];
5973 rect.size.width /= 2;
5974 rect.size.height /= 2;
5976 rect.origin.x = 36 - rect.size.width / 2;
5977 rect.origin.y = 36 - rect.size.height / 2;
5979 [badge_ drawInRect:Retina(rect)];
5982 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5986 UISetColor(commercial_ ? Purple_ : Black_);
5987 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
5988 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
5991 UISetColor(commercial_ ? Purplish_ : Gray_);
5992 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:NSLineBreakByTruncatingTail];
5994 if (placard_ != nil)
5995 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5998 - (void) drawContentRect:(CGRect)rect {
6000 [self drawSummaryContentRect:rect];
6002 [self drawNormalContentRect:rect];
6007 /* Section Cell {{{ */
6008 @interface SectionCell : CyteTableViewCell <
6009 CyteTableViewCellDelegate
6011 _H<NSString> basic_;
6012 _H<NSString> section_;
6014 _H<NSString> count_;
6016 _H<UISwitch> switch_;
6020 - (void) setSection:(Section *)section editing:(BOOL)editing;
6024 @implementation SectionCell
6026 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
6027 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
6028 icon_ = [UIImage imageNamed:@"folder.png"];
6029 // XXX: this initial frame is wrong, but is fixed later
6030 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
6031 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
6033 UIView *content([self contentView]);
6034 CGRect bounds([content bounds]);
6036 self.content = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
6037 [self.content setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6038 [content addSubview:self.content];
6039 [self.content setBackgroundColor:[UIColor whiteColor]];
6041 [self.content setDelegate:self];
6045 - (void) onSwitch:(id)sender {
6046 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
6047 if (metadata == nil) {
6048 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
6049 [Sections_ setObject:metadata forKey:basic_];
6052 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
6055 - (void) setSection:(Section *)section editing:(BOOL)editing {
6056 if (editing != editing_) {
6058 [switch_ removeFromSuperview];
6060 [self addSubview:switch_];
6069 if (section == nil) {
6070 name_ = UCLocalize("ALL_PACKAGES");
6073 basic_ = [section name];
6074 section_ = [section localized];
6076 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
6077 count_ = [NSString stringWithFormat:@"%zd", [section count]];
6080 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
6083 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
6084 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
6086 [self.content setNeedsDisplay];
6089 - (void) setFrame:(CGRect)frame {
6090 [super setFrame:frame];
6092 CGRect rect([switch_ frame]);
6093 [switch_ setFrame:CGRectMake(frame.size.width - rect.size.width - 9, 9, rect.size.width, rect.size.height)];
6096 - (NSString *) accessibilityLabel {
6100 - (void) drawContentRect:(CGRect)rect {
6101 bool highlighted(self.highlighted && !editing_);
6103 [icon_ drawInRect:CGRectMake(7, 7, 32, 32)];
6105 if (highlighted && kCFCoreFoundationVersionNumber < 800)
6108 float width(rect.size.width);
6110 width -= 9 + [switch_ frame].size.width;
6114 [name_ drawAtPoint:CGPointMake(48, 12) forWidth:(width - 58) withFont:Font18_ lineBreakMode:NSLineBreakByTruncatingTail];
6116 CGSize size = [count_ sizeWithFont:Font14_];
6118 UISetColor(Folder_);
6120 [count_ drawAtPoint:CGPointMake(Retina(10 + (30 - size.width) / 2), 18) withFont:Font12Bold_];
6126 /* File Table {{{ */
6127 @interface FileTable : CyteViewController <
6128 UITableViewDataSource,
6131 _transient Database *database_;
6132 _H<Package> package_;
6134 _H<NSMutableArray> files_;
6135 _H<UITableView, 2> list_;
6138 - (id) initWithDatabase:(Database *)database;
6139 - (void) setPackage:(Package *)package;
6143 @implementation FileTable
6145 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6146 return files_ == nil ? 0 : [files_ count];
6149 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6153 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6154 static NSString *reuseIdentifier = @"Cell";
6156 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6158 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6159 [cell setFont:[UIFont systemFontOfSize:16]];
6161 [cell setText:[files_ objectAtIndex:indexPath.row]];
6162 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
6167 - (NSURL *) navigationURL {
6168 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
6172 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
6173 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6174 [list_ setRowHeight:24.0f];
6175 [(UITableView *) list_ setDataSource:self];
6176 [list_ setDelegate:self];
6177 [self setView:list_];
6180 - (void) viewDidLoad {
6181 [super viewDidLoad];
6183 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
6186 - (void) releaseSubviews {
6192 [super releaseSubviews];
6195 - (id) initWithDatabase:(Database *)database {
6196 if ((self = [super init]) != nil) {
6197 database_ = database;
6201 - (void) setPackage:(Package *)package {
6205 files_ = [NSMutableArray arrayWithCapacity:32];
6207 if (package != nil) {
6209 name_ = [package id];
6211 if (NSArray *files = [package files])
6212 [files_ addObjectsFromArray:files];
6214 if ([files_ count] != 0) {
6215 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
6216 [files_ removeObjectAtIndex:0];
6217 [files_ sortUsingSelector:@selector(compareByPath:)];
6219 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
6220 [stack addObject:@"/"];
6222 for (int i(0), e([files_ count]); i != e; ++i) {
6223 NSString *file = [files_ objectAtIndex:i];
6224 while (![file hasPrefix:[stack lastObject]])
6225 [stack removeLastObject];
6226 NSString *directory = [stack lastObject];
6227 [stack addObject:[file stringByAppendingString:@"/"]];
6228 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
6229 int(([stack count] - 2) * 3), "",
6230 [file substringFromIndex:[directory length]]
6239 - (void) reloadData {
6242 [self setPackage:[database_ packageWithName:name_]];
6247 /* Package Controller {{{ */
6248 @interface CYPackageController : CydiaWebViewController <
6249 UIActionSheetDelegate
6251 _transient Database *database_;
6252 _H<Package> package_;
6255 std::vector<std::pair<_H<NSString>, _H<NSString>>> buttons_;
6256 _H<UIActionSheet> sheet_;
6257 _H<UIBarButtonItem> button_;
6258 _H<NSArray> versions_;
6261 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer;
6265 @implementation CYPackageController
6267 - (NSURL *) navigationURL {
6268 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
6271 - (void) _clickButtonWithPackage:(Package *)package {
6272 [self.delegate installPackage:package];
6275 - (void) _clickButtonWithName:(NSString *)name {
6276 if ([name isEqualToString:@"CLEAR"])
6277 return [self.delegate clearPackage:package_];
6278 else if ([name isEqualToString:@"REMOVE"])
6279 return [self.delegate removePackage:package_];
6280 else if ([name isEqualToString:@"DOWNGRADE"]) {
6281 sheet_ = [[[UIActionSheet alloc]
6284 cancelButtonTitle:nil
6285 destructiveButtonTitle:nil
6286 otherButtonTitles:nil
6289 for (Package *version in (id) versions_)
6290 [sheet_ addButtonWithTitle:[version latest]];
6291 [sheet_ setContext:@"version"];
6293 [self.delegate showActionSheet:sheet_ fromItem:[[self navigationItem] rightBarButtonItem]];
6297 else if ([name isEqualToString:@"INSTALL"]);
6298 else if ([name isEqualToString:@"REINSTALL"]);
6299 else if ([name isEqualToString:@"UPGRADE"]);
6300 else _assert(false);
6302 [self.delegate installPackage:package_];
6305 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
6306 NSString *context([sheet context]);
6307 if (sheet_ == sheet)
6310 if ([context isEqualToString:@"modify"]) {
6311 if (button != [sheet cancelButtonIndex]) {
6313 [self performSelector:@selector(_clickButtonWithName:) withObject:buttons_[button].first afterDelay:0];
6315 [self _clickButtonWithName:buttons_[button].first];
6318 [sheet dismissWithClickedButtonIndex:button animated:YES];
6319 } else if ([context isEqualToString:@"version"]) {
6320 if (button != [sheet cancelButtonIndex]) {
6321 Package *version([versions_ objectAtIndex:button]);
6323 [self performSelector:@selector(_clickButtonWithPackage:) withObject:version afterDelay:0];
6325 [self _clickButtonWithPackage:version];
6328 [sheet dismissWithClickedButtonIndex:button animated:YES];
6332 - (bool) _allowJavaScriptPanel {
6337 - (void) _customButtonClicked {
6338 if (commercial_ && self.isLoading && [package_ uninstalled])
6339 return [self reloadURLWithCache:NO];
6341 size_t count(buttons_.size());
6346 [self _clickButtonWithName:buttons_[0].first];
6348 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
6349 for (const auto &button : buttons_)
6350 [buttons addObject:button.second];
6352 sheet_ = [[[UIActionSheet alloc]
6355 cancelButtonTitle:nil
6356 destructiveButtonTitle:nil
6357 otherButtonTitles:nil
6360 for (NSString *button in buttons)
6361 [sheet_ addButtonWithTitle:button];
6362 [sheet_ setContext:@"modify"];
6364 [self.delegate showActionSheet:sheet_ fromItem:[[self navigationItem] rightBarButtonItem]];
6368 - (void) applyLoadingTitle {
6369 // Don't show "Loading" as the title. Ever.
6372 - (UIBarButtonItem *) rightButton {
6377 - (void) setPageColor:(UIColor *)color {
6378 return [super setPageColor:nil];
6381 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer {
6382 if ((self = [super init]) != nil) {
6383 database_ = database;
6384 name_ = name == nil ? @"" : [NSString stringWithString:name];
6385 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]] withReferrer:referrer];
6389 - (void) reloadData {
6392 [sheet_ dismissWithClickedButtonIndex:[sheet_ cancelButtonIndex] animated:YES];
6395 package_ = [database_ packageWithName:name_];
6396 versions_ = [package_ downgrades];
6400 if (package_ != nil) {
6401 [(Package *) package_ parse];
6403 commercial_ = [package_ isCommercial];
6405 if ([package_ mode] != nil)
6406 buttons_.push_back(std::make_pair(@"CLEAR", UCLocalize("CLEAR")));
6407 if ([package_ source] == nil);
6408 else if ([package_ upgradableAndEssential:NO])
6409 buttons_.push_back(std::make_pair(@"UPGRADE", UCLocalize("UPGRADE")));
6410 else if ([package_ uninstalled])
6411 buttons_.push_back(std::make_pair(@"INSTALL", UCLocalize("INSTALL")));
6413 buttons_.push_back(std::make_pair(@"REINSTALL", UCLocalize("REINSTALL")));
6414 if (![package_ uninstalled])
6415 buttons_.push_back(std::make_pair(@"REMOVE", UCLocalize("REMOVE")));
6416 if ([versions_ count] != 0)
6417 buttons_.push_back(std::make_pair(@"DOWNGRADE", UCLocalize("DOWNGRADE")));
6421 switch (buttons_.size()) {
6422 case 0: title = nil; break;
6423 case 1: title = buttons_[0].second; break;
6424 default: title = UCLocalize("MODIFY"); break;
6427 button_ = [[[UIBarButtonItem alloc]
6429 style:UIBarButtonItemStylePlain
6431 action:@selector(customButtonClicked)
6435 - (bool) isLoading {
6436 return commercial_ ? [super isLoading] : false;
6442 /* Package List Controller {{{ */
6443 @interface PackageListController : CyteViewController <
6444 UITableViewDataSource,
6447 _transient Database *database_;
6449 _H<NSArray> packages_;
6450 _H<NSArray> sections_;
6451 _H<UITableView, 2> list_;
6453 _H<NSArray> thumbs_;
6454 std::vector<NSInteger> offset_;
6456 _H<NSString> title_;
6457 unsigned reloading_;
6460 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6461 - (void) resetCursor;
6464 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages;
6468 @implementation PackageListController
6470 - (NSURL *) referrerURL {
6471 return [self navigationURL];
6474 - (bool) isSummarized {
6478 - (bool) showsSections {
6482 - (void) deselectWithAnimation:(BOOL)animated {
6483 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6486 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6487 CGRect base = [[self view] bounds];
6488 base.size.height -= bounds.size.height;
6489 base.origin = [list_ frame].origin;
6491 [UIView beginAnimations:nil context:NULL];
6492 [UIView setAnimationBeginsFromCurrentState:YES];
6493 [UIView setAnimationCurve:curve];
6494 [UIView setAnimationDuration:duration];
6495 [list_ setFrame:base];
6496 [UIView commitAnimations];
6499 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6500 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6503 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6504 [self resizeForKeyboardBounds:bounds duration:0];
6507 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6508 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6509 *curve = UIViewAnimationCurveEaseInOut;
6511 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6513 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6516 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6519 - (void) keyboardWillShow:(NSNotification *)notification {
6522 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6523 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6525 NSTimeInterval duration;
6526 UIViewAnimationCurve curve;
6527 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6529 CGRect kbframe = CGRectMake(Retina(center.x - bounds.size.width / 2), Retina(center.y - bounds.size.height / 2), bounds.size.width, bounds.size.height);
6530 UIViewController *base = self;
6531 while ([base parentOrPresentingViewController] != nil)
6532 base = [base parentOrPresentingViewController];
6533 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6534 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6536 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6537 intersection.size.height += CYStatusBarHeight();
6539 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6542 - (void) keyboardWillHide:(NSNotification *)notification {
6543 NSTimeInterval duration;
6544 UIViewAnimationCurve curve;
6545 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6547 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6550 - (void) viewWillAppear:(BOOL)animated {
6551 [super viewWillAppear:animated];
6553 [self resizeForKeyboardBounds:CGRectZero];
6554 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6555 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6558 - (void) viewWillDisappear:(BOOL)animated {
6559 [super viewWillDisappear:animated];
6561 [self resizeForKeyboardBounds:CGRectZero];
6562 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6563 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6566 - (void) viewDidAppear:(BOOL)animated {
6567 [super viewDidAppear:animated];
6568 [self deselectWithAnimation:animated];
6571 - (void) didSelectPackage:(Package *)package {
6572 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[[self referrerURL] absoluteString]] autorelease]);
6573 [view setDelegate:self.delegate];
6574 [[self navigationController] pushViewController:view animated:YES];
6577 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6578 NSInteger count([sections_ count]);
6579 return count == 0 ? 1 : count;
6582 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6583 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6585 return [[sections_ objectAtIndex:section] name];
6588 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6589 if ([sections_ count] == 0)
6591 return [[sections_ objectAtIndex:section] count];
6594 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6595 @synchronized (database_) {
6596 if ([database_ era] != era_)
6599 Section *section([sections_ objectAtIndex:[path section]]);
6600 NSInteger row([path row]);
6601 Package *package([packages_ objectAtIndex:([section row] + row)]);
6602 return [[package retain] autorelease];
6605 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6606 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6608 cell = [[[PackageCell alloc] init] autorelease];
6610 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6611 [cell setPackage:package asSummary:[self isSummarized]];
6615 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6616 Package *package([self packageAtIndexPath:path]);
6617 package = [database_ packageWithName:[package id]];
6618 [self didSelectPackage:package];
6621 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6625 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6626 return offset_[index];
6629 - (void) updateHeight {
6630 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6633 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6634 if ((self = [super init]) != nil) {
6635 database_ = database;
6636 title_ = [title copy];
6637 [[self navigationItem] setTitle:title_];
6642 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
6643 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
6644 [self setView:view];
6646 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6647 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6648 [view addSubview:list_];
6650 // XXX: is 20 the most optimal number here?
6651 [list_ setSectionIndexMinimumDisplayRowCount:20];
6653 [(UITableView *) list_ setDataSource:self];
6654 [list_ setDelegate:self];
6656 [self updateHeight];
6659 - (void) releaseSubviews {
6668 [super releaseSubviews];
6671 - (bool) shouldYield {
6675 - (bool) shouldBlock {
6679 - (NSMutableArray *) _reloadPackages {
6680 @synchronized (database_) {
6681 era_ = [database_ era];
6682 NSArray *packages([database_ packages]);
6684 return [NSMutableArray arrayWithArray:packages];
6687 - (void) _reloadData {
6688 if (reloading_ != 0) {
6693 NSMutableArray *packages;
6696 if ([self shouldYield]) {
6700 if (![self shouldBlock])
6703 hud = [self.delegate addProgressHUD];
6704 [hud setText:UCLocalize("LOADING")];
6708 packages = [self yieldToSelector:@selector(_reloadPackages)];
6711 [self.delegate removeProgressHUD:hud];
6712 } while (reloading_ == 2);
6714 packages = [self _reloadPackages];
6717 @synchronized (database_) {
6718 if (era_ != [database_ era])
6725 packages_ = packages;
6727 if ([self showsSections])
6728 sections_ = [self sectionsForPackages:packages];
6730 Section *section([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6731 [section setCount:[packages_ count]];
6732 sections_ = [NSArray arrayWithObject:section];
6735 [self updateHeight];
6737 _profile(PackageTable$reloadData$List)
6738 [(UITableView *) list_ setDataSource:self];
6746 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
6747 Section *prefix([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6748 size_t end([packages count]);
6750 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
6751 Section *section(prefix);
6753 thumbs_ = CollationThumbs_;
6754 offset_ = CollationOffset_;
6757 size_t offsets([CollationStarts_ count]);
6759 NSString *start([CollationStarts_ objectAtIndex:offset]);
6760 size_t length([start length]);
6762 for (size_t index(0); index != end; ++index) {
6764 Package *package([packages objectAtIndex:index]);
6765 NSString *name(PackageName(package, @selector(cyname)));
6767 //while ([start compare:name options:NSNumericSearch range:NSMakeRange(0, length) locale:CollationLocale_] != NSOrderedDescending) {
6768 while (StringNameCompare(start, name, length) != kCFCompareGreaterThan) {
6769 NSString *title([CollationTitles_ objectAtIndex:offset]);
6770 section = [[[Section alloc] initWithName:title row:index localize:NO] autorelease];
6771 [sections addObject:section];
6773 start = ++offset == offsets ? nil : [CollationStarts_ objectAtIndex:offset];
6776 length = [start length];
6780 [section addToCount];
6783 for (; offset != offsets; ++offset) {
6784 NSString *title([CollationTitles_ objectAtIndex:offset]);
6785 Section *section([[[Section alloc] initWithName:title row:end localize:NO] autorelease]);
6786 [sections addObject:section];
6789 if ([prefix count] != 0) {
6790 Section *suffix([sections lastObject]);
6791 [prefix setName:[suffix name]];
6792 [suffix setName:nil];
6793 [sections insertObject:prefix atIndex:(offsets - 1)];
6799 - (void) reloadData {
6802 if ([self shouldYield])
6803 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6808 - (void) resetCursor {
6809 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6812 - (void) clearData {
6813 [self updateHeight];
6815 [list_ setDataSource:nil];
6823 /* Filtered Package List Controller {{{ */
6824 typedef Function<bool, Package *> PackageFilter;
6825 typedef Function<void, NSMutableArray *> PackageSorter;
6826 @interface FilteredPackageListController : PackageListController {
6827 PackageFilter filter_;
6828 PackageSorter sorter_;
6831 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter;
6833 - (void) setFilter:(PackageFilter)filter;
6834 - (void) setSorter:(PackageSorter)sorter;
6838 @implementation FilteredPackageListController
6840 - (void) setFilter:(PackageFilter)filter {
6841 @synchronized (self) {
6845 - (void) setSorter:(PackageSorter)sorter {
6846 @synchronized (self) {
6850 - (NSMutableArray *) _reloadPackages {
6851 @synchronized (database_) {
6852 era_ = [database_ era];
6854 NSArray *packages([database_ packages]);
6855 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6857 PackageFilter filter;
6858 PackageSorter sorter;
6860 @synchronized (self) {
6865 _profile(PackageTable$reloadData$Filter)
6866 for (Package *package in packages)
6867 if (filter(package))
6868 [filtered addObject:package];
6876 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter {
6877 if ((self = [super initWithDatabase:database title:title]) != nil) {
6878 [self setFilter:filter];
6885 /* Home Controller {{{ */
6886 @interface HomeController : CydiaWebViewController {
6887 CFRunLoopRef runloop_;
6888 SCNetworkReachabilityRef reachability_;
6893 @implementation HomeController
6895 static void HomeControllerReachabilityCallback(SCNetworkReachabilityRef reachability, SCNetworkReachabilityFlags flags, void *info) {
6896 [(HomeController *) info dispatchEvent:@"CydiaReachabilityCallback"];
6900 if ((self = [super init]) != nil) {
6901 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6904 reachability_ = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "cydia.saurik.com");
6905 if (reachability_ != NULL) {
6906 SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
6907 SCNetworkReachabilitySetCallback(reachability_, HomeControllerReachabilityCallback, &context);
6909 CFRunLoopRef runloop(CFRunLoopGetCurrent());
6910 if (SCNetworkReachabilityScheduleWithRunLoop(reachability_, runloop, kCFRunLoopDefaultMode))
6917 if (reachability_ != NULL && runloop_ != NULL)
6918 SCNetworkReachabilityUnscheduleFromRunLoop(reachability_, runloop_, kCFRunLoopDefaultMode);
6922 - (NSURL *) navigationURL {
6923 return [NSURL URLWithString:@"cydia://home"];
6926 - (void) aboutButtonClicked {
6927 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6929 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6930 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6931 [alert setCancelButtonIndex:0];
6934 @"Copyright \u00a9 2008-2015\n"
6937 "Jay Freeman (saurik)\n"
6938 "saurik@saurik.com\n"
6939 "http://www.saurik.com/"
6945 - (UIBarButtonItem *) leftButton {
6946 return [[[UIBarButtonItem alloc]
6947 initWithTitle:UCLocalize("ABOUT")
6948 style:UIBarButtonItemStylePlain
6950 action:@selector(aboutButtonClicked)
6957 /* Cydia Tab Bar Controller {{{ */
6958 @interface CydiaTabBarController : CyteTabBarController <
6959 UITabBarControllerDelegate,
6962 _transient Database *database_;
6964 _H<UIActivityIndicatorView> indicator_;
6967 // XXX: ok, "updatedelegate_"?...
6968 _transient NSObject<CydiaDelegate> *updatedelegate_;
6971 - (void) beginUpdate;
6976 @implementation CydiaTabBarController
6978 - (id) initWithDatabase:(Database *)database {
6979 if ((self = [super init]) != nil) {
6980 database_ = database;
6981 [self setDelegate:self];
6983 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteTiny] autorelease];
6984 [indicator_ setOrigin:CGPointMake(kCFCoreFoundationVersionNumber >= 800 ? 2 : 4, 2)];
6986 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6990 - (void) beginUpdate {
6994 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
6995 UITabBarItem *item([controller tabBarItem]);
6997 [item setBadgeValue:@""];
6998 UIView *badge(MSHookIvar<UIView *>([item view], "_badge"));
7000 [indicator_ startAnimating];
7001 [badge addSubview:indicator_];
7003 [updatedelegate_ retainNetworkActivityIndicator];
7007 detachNewThreadSelector:@selector(performUpdate)
7013 - (void) performUpdate {
7014 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
7016 SourceStatus status(self, database_);
7017 [database_ updateWithStatus:status];
7020 performSelectorOnMainThread:@selector(completeUpdate)
7028 - (void) stopUpdateWithSelector:(SEL)selector {
7030 [updatedelegate_ releaseNetworkActivityIndicator];
7032 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
7033 [[controller tabBarItem] setBadgeValue:nil];
7035 [indicator_ removeFromSuperview];
7036 [indicator_ stopAnimating];
7038 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
7041 - (void) completeUpdate {
7044 [self stopUpdateWithSelector:@selector(reloadData)];
7047 - (void) cancelUpdate {
7048 [self stopUpdateWithSelector:@selector(updateDataAndLoad)];
7051 - (void) cancelPressed {
7052 [self cancelUpdate];
7059 - (bool) isSourceCancelled {
7063 - (void) startSourceFetch:(NSString *)uri {
7066 - (void) stopSourceFetch:(NSString *)uri {
7069 - (void) setUpdateDelegate:(id)delegate {
7070 updatedelegate_ = delegate;
7076 /* Cydia:// Protocol {{{ */
7077 @interface CydiaURLProtocol : NSURLProtocol {
7082 @implementation CydiaURLProtocol
7084 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7085 NSURL *url([request URL]);
7089 NSString *scheme([[url scheme] lowercaseString]);
7090 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7092 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7098 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7102 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7103 id<NSURLProtocolClient> client([self client]);
7105 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7107 NSData *data(UIImagePNGRepresentation(icon));
7109 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7110 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7111 [client URLProtocol:self didLoadData:data];
7112 [client URLProtocolDidFinishLoading:self];
7116 - (void) startLoading {
7117 id<NSURLProtocolClient> client([self client]);
7118 NSURLRequest *request([self request]);
7120 NSURL *url([request URL]);
7121 NSString *href([url absoluteString]);
7122 NSString *scheme([[url scheme] lowercaseString]);
7126 if ([scheme isEqualToString:@"cydia"])
7127 path = [href substringFromIndex:8];
7128 else if ([scheme isEqualToString:@"about"])
7129 path = [href substringFromIndex:12];
7130 else _assert(false);
7132 NSRange slash([path rangeOfString:@"/"]);
7135 if (slash.location == NSNotFound) {
7139 command = [path substringToIndex:slash.location];
7140 path = [path substringFromIndex:(slash.location + 1)];
7143 Database *database([Database sharedInstance]);
7146 else if ([command isEqualToString:@"application-icon"]) {
7149 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7153 if (icon == nil && $SBSCopyIconImagePNGDataForDisplayIdentifier != NULL) {
7154 NSData *data([$SBSCopyIconImagePNGDataForDisplayIdentifier(path) autorelease]);
7155 icon = [UIImage imageWithData:data];
7159 if (NSString *file = SBSCopyIconImagePathForDisplayIdentifier(path))
7160 icon = [UIImage imageAtPath:file];
7163 icon = [UIImage imageNamed:@"unknown.png"];
7165 [self _returnPNGWithImage:icon forRequest:request];
7166 } else if ([command isEqualToString:@"package-icon"]) {
7169 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7170 Package *package([database packageWithName:path]);
7174 UIImage *icon([package icon]);
7175 [self _returnPNGWithImage:icon forRequest:request];
7176 } else if ([command isEqualToString:@"uikit-image"]) {
7179 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7180 UIImage *icon(_UIImageWithName(path));
7181 [self _returnPNGWithImage:icon forRequest:request];
7182 } else if ([command isEqualToString:@"section-icon"]) {
7185 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7186 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7188 icon = [UIImage imageNamed:@"unknown.png"];
7189 [self _returnPNGWithImage:icon forRequest:request];
7191 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7195 - (void) stopLoading {
7201 /* Section Controller {{{ */
7202 @interface SectionController : FilteredPackageListController {
7204 _H<NSString> section_;
7207 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section;
7211 @implementation SectionController
7213 - (NSURL *) referrerURL {
7214 NSString *name(section_);
7215 name = name ?: @"*";
7216 NSString *key(key_);
7218 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sections/%@/%@", UI_, [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7221 - (NSURL *) navigationURL {
7222 NSString *name(section_);
7223 name = name ?: @"*";
7224 NSString *key(key_);
7226 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@/%@", [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7229 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section {
7232 title = UCLocalize("ALL_PACKAGES");
7233 else if (![section isEqual:@""])
7234 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(section) value:nil table:@"Sections"];
7236 title = UCLocalize("NO_SECTION");
7238 if ((self = [super initWithDatabase:database title:title]) != nil) {
7239 key_ = [source key];
7244 - (void) reloadData {
7245 Source *source([database_ sourceWithKey:key_]);
7246 _H<NSString> name(section_);
7248 [self setFilter:[=](Package *package) {
7249 NSString *section([package section]);
7253 section == nil && [name length] == 0 ||
7254 [name isEqualToString:section]
7257 [package source] == source
7258 ) && [package visible];
7266 /* Sections Controller {{{ */
7267 @interface SectionsController : CyteViewController <
7268 UITableViewDataSource,
7271 _transient Database *database_;
7273 _H<NSMutableArray> sections_;
7274 _H<NSMutableArray> filtered_;
7275 _H<UITableView, 2> list_;
7278 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7279 - (void) editButtonClicked;
7283 @implementation SectionsController
7285 - (NSURL *) navigationURL {
7286 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
7289 - (Source *) source {
7292 return [database_ sourceWithKey:key_];
7295 - (void) updateNavigationItem {
7296 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7297 if ([sections_ count] == 0) {
7298 [[self navigationItem] setRightBarButtonItem:nil];
7300 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7301 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7303 action:@selector(editButtonClicked)
7304 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7308 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7309 [super setEditing:editing animated:animated];
7314 [self.delegate updateData];
7316 [self updateNavigationItem];
7319 - (void) viewDidAppear:(BOOL)animated {
7320 [super viewDidAppear:animated];
7321 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7324 - (void) viewWillDisappear:(BOOL)animated {
7325 [super viewWillDisappear:animated];
7326 [self setEditing:NO];
7329 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7330 Section *section = nil;
7331 int index = [indexPath row];
7332 if (![self isEditing]) {
7335 section = [filtered_ objectAtIndex:index];
7337 section = [sections_ objectAtIndex:index];
7342 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7343 if ([self isEditing])
7344 return [sections_ count];
7346 return [filtered_ count] + 1;
7349 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7353 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7354 static NSString *reuseIdentifier = @"SectionCell";
7356 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7358 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7360 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7365 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7366 if ([self isEditing])
7369 Section *section = [self sectionAtIndexPath:indexPath];
7371 SectionController *controller = [[[SectionController alloc]
7372 initWithDatabase:database_
7373 source:[self source]
7374 section:[section name]
7376 [controller setDelegate:self.delegate];
7378 [[self navigationController] pushViewController:controller animated:YES];
7382 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
7383 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7384 [list_ setRowHeight:46];
7385 [(UITableView *) list_ setDataSource:self];
7386 [list_ setDelegate:self];
7387 [self setView:list_];
7390 - (void) viewDidLoad {
7391 [super viewDidLoad];
7393 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7396 - (void) releaseSubviews {
7402 [super releaseSubviews];
7405 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7406 if ((self = [super init]) != nil) {
7407 database_ = database;
7408 key_ = [source key];
7412 - (void) reloadData {
7415 NSArray *packages = [database_ packages];
7417 sections_ = [NSMutableArray arrayWithCapacity:16];
7418 filtered_ = [NSMutableArray arrayWithCapacity:16];
7420 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7422 Source *source([self source]);
7425 for (Package *package in packages) {
7426 if (source != nil && [package source] != source)
7429 NSString *name([package section]);
7430 NSString *key(name == nil ? @"" : name);
7434 _profile(SectionsView$reloadData$Section)
7435 section = [sections objectForKey:key];
7436 if (section == nil) {
7437 _profile(SectionsView$reloadData$Section$Allocate)
7438 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7439 [sections setObject:section forKey:key];
7444 [section addToCount];
7446 _profile(SectionsView$reloadData$Filter)
7447 if (![package visible])
7455 [sections_ addObjectsFromArray:[sections allValues]];
7457 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7459 for (Section *section in (id) sections_) {
7460 size_t count([section row]);
7464 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7465 [section setCount:count];
7466 [filtered_ addObject:section];
7469 [self updateNavigationItem];
7474 - (void) editButtonClicked {
7475 [self setEditing:![self isEditing] animated:YES];
7481 /* Changes Controller {{{ */
7482 @interface ChangesController : FilteredPackageListController {
7486 - (id) initWithDatabase:(Database *)database;
7490 @implementation ChangesController
7492 - (NSURL *) referrerURL {
7493 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/changes/", UI_]];
7496 - (NSURL *) navigationURL {
7497 return [NSURL URLWithString:@"cydia://changes"];
7500 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7501 @synchronized (database_) {
7502 if ([database_ era] != era_)
7505 NSUInteger sectionIndex([path section]);
7506 if (sectionIndex >= [sections_ count])
7508 Section *section([sections_ objectAtIndex:sectionIndex]);
7509 NSInteger row([path row]);
7510 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7513 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7514 NSString *context([alert context]);
7516 if ([context isEqualToString:@"norefresh"])
7517 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7520 - (void) setLeftBarButtonItem {
7521 if ([self.delegate updating])
7522 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7523 initWithTitle:UCLocalize("CANCEL")
7524 style:UIBarButtonItemStyleDone
7526 action:@selector(cancelButtonClicked)
7527 ] autorelease] animated:YES];
7529 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7530 initWithTitle:UCLocalize("REFRESH")
7531 style:UIBarButtonItemStylePlain
7533 action:@selector(refreshButtonClicked)
7534 ] autorelease] animated:YES];
7537 - (void) refreshButtonClicked {
7538 if ([self.delegate requestUpdate])
7539 [self setLeftBarButtonItem];
7542 - (void) cancelButtonClicked {
7543 [self.delegate cancelUpdate];
7546 - (void) upgradeButtonClicked {
7547 [self.delegate distUpgrade];
7548 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7551 - (bool) shouldYield {
7555 - (bool) shouldBlock {
7559 - (void) useFilter {
7560 @synchronized (self) {
7561 [self setFilter:[](Package *package) {
7562 return [package upgradableAndEssential:YES] || [package visible];
7565 [self setSorter:[](NSMutableArray *packages) {
7566 [packages radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7570 - (id) initWithDatabase:(Database *)database {
7571 if ((self = [super initWithDatabase:database title:UCLocalize("CHANGES")]) != nil) {
7576 - (void) viewDidLoad {
7577 [super viewDidLoad];
7578 [self setLeftBarButtonItem];
7581 - (void) viewWillAppear:(BOOL)animated {
7582 [super viewWillAppear:animated];
7583 [self setLeftBarButtonItem];
7586 - (void) reloadData {
7587 [self setLeftBarButtonItem];
7591 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
7592 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
7594 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7595 Section *ignored = nil;
7596 Section *section = nil;
7600 bool unseens = false;
7602 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7604 for (size_t offset = 0, count = [packages count]; offset != count; ++offset) {
7605 Package *package = [packages objectAtIndex:offset];
7607 BOOL uae = [package upgradableAndEssential:YES];
7611 time_t seen([package seen]);
7613 if (section == nil || last != seen) {
7617 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7620 _profile(ChangesController$reloadData$Allocate)
7621 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7622 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7623 [sections addObject:section];
7627 [section addToCount];
7628 } else if ([package ignored]) {
7629 if (ignored == nil) {
7630 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7632 [ignored addToCount];
7635 [upgradable addToCount];
7640 CFRelease(formatter);
7643 Section *last = [sections lastObject];
7644 size_t count = [last count];
7645 [packages removeObjectsInRange:NSMakeRange([packages count] - count, count)];
7646 [sections removeLastObject];
7649 if ([ignored count] != 0)
7650 [sections insertObject:ignored atIndex:0];
7652 [sections insertObject:upgradable atIndex:0];
7656 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7657 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7658 style:UIBarButtonItemStylePlain
7660 action:@selector(upgradeButtonClicked)
7661 ] autorelease]) animated:YES];
7668 /* Search Controller {{{ */
7669 @interface SearchController : FilteredPackageListController <
7672 _H<UISearchBar, 1> search_;
7677 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7678 - (void) reloadData;
7682 @implementation SearchController
7684 - (NSURL *) referrerURL {
7685 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/search?q=%@", UI_, [([search_ text] ?: @"") stringByAddingPercentEscapesIncludingReserved]]];
7688 - (NSURL *) navigationURL {
7689 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7690 return [NSURL URLWithString:@"cydia://search"];
7692 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [[search_ text] stringByAddingPercentEscapesIncludingReserved]]];
7695 - (NSArray *) termsForQuery:(NSString *)query {
7696 NSMutableArray *terms([NSMutableArray arrayWithCapacity:2]);
7697 for (NSString *component in [query componentsSeparatedByString:@" "])
7698 if ([component length] != 0)
7699 [terms addObject:component];
7704 - (void) useSearch {
7705 _H<NSArray> query([self termsForQuery:[search_ text]]);
7708 @synchronized (self) {
7709 [self setFilter:[=](Package *package) {
7710 if (![package unfiltered])
7712 if (![package matches:query])
7717 [self setSorter:[](NSMutableArray *packages) {
7718 [packages radixSortUsingSelector:@selector(rank)];
7726 - (void) usePrefix:(NSString *)prefix {
7727 _H<NSString> query(prefix);
7730 @synchronized (self) {
7731 [self setFilter:[=](Package *package) {
7732 if ([query length] == 0)
7734 if (![package unfiltered])
7736 if ([[package name] compare:query options:MatchCompareOptions_ range:NSMakeRange(0, [query length])] != NSOrderedSame)
7741 [self setSorter:nullptr];
7747 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7749 [self usePrefix:[search_ text]];
7752 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7753 [search_ resignFirstResponder];
7757 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7758 [search_ setText:@""];
7759 [self searchBarButtonClicked:searchBar];
7762 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7763 [self searchBarButtonClicked:searchBar];
7766 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7767 [self usePrefix:text];
7770 - (bool) shouldYield {
7774 - (bool) shouldBlock {
7778 - (bool) isSummarized {
7782 - (bool) showsSections {
7786 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7787 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH")])) {
7788 search_ = [[[UISearchBar alloc] init] autorelease];
7789 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7790 [search_ setDelegate:self];
7792 UITextField *textField;
7793 if ([search_ respondsToSelector:@selector(searchField)])
7794 textField = [search_ searchField];
7796 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7798 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7799 [textField setEnablesReturnKeyAutomatically:NO];
7800 [[self navigationItem] setTitleView:textField];
7803 [search_ setText:query];
7808 - (void) viewDidAppear:(BOOL)animated {
7809 [super viewDidAppear:animated];
7811 if (!searchloaded_) {
7812 searchloaded_ = YES;
7813 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7814 [search_ layoutSubviews];
7817 if ([self isSummarized])
7818 [search_ becomeFirstResponder];
7821 - (void) reloadData {
7826 - (void) didSelectPackage:(Package *)package {
7827 [search_ resignFirstResponder];
7828 [super didSelectPackage:package];
7833 /* Package Settings Controller {{{ */
7834 @interface PackageSettingsController : CyteViewController <
7835 UITableViewDataSource,
7838 _transient Database *database_;
7840 _H<Package> package_;
7841 _H<UITableView, 2> table_;
7842 _H<UISwitch> subscribedSwitch_;
7843 _H<UISwitch> ignoredSwitch_;
7844 _H<UITableViewCell> subscribedCell_;
7845 _H<UITableViewCell> ignoredCell_;
7848 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7852 @implementation PackageSettingsController
7854 - (NSURL *) navigationURL {
7855 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
7858 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7859 if (package_ == nil)
7862 if ([package_ installed] == nil)
7868 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7869 if (package_ == nil)
7872 // both sections contain just one item right now.
7876 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7880 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7882 return UCLocalize("SHOW_ALL_CHANGES_EX");
7884 return UCLocalize("IGNORE_UPGRADES_EX");
7887 - (void) onSubscribed:(id)control {
7888 bool value([control isOn]);
7889 if (package_ == nil)
7891 if ([package_ setSubscribed:value])
7892 [self.delegate updateData];
7895 - (void) _updateIgnored {
7896 const char *package([name_ UTF8String]);
7897 bool on([ignoredSwitch_ isOn]);
7899 FILE *dpkg(popen("/usr/libexec/cydia/cydo --set-selections", "w"));
7900 fwrite(package, strlen(package), 1, dpkg);
7903 fwrite(" hold\n", 6, 1, dpkg);
7905 fwrite(" install\n", 9, 1, dpkg);
7910 - (void) onIgnored:(id)control {
7911 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7912 [invocation setTarget:self];
7913 [invocation setSelector:@selector(_updateIgnored)];
7915 [self.delegate reloadDataWithInvocation:invocation];
7918 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7919 if (package_ == nil)
7922 switch ([indexPath section]) {
7923 case 0: return subscribedCell_;
7924 case 1: return ignoredCell_;
7933 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
7934 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
7935 [self setView:view];
7937 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7938 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7939 [(UITableView *) table_ setDataSource:self];
7940 [table_ setDelegate:self];
7941 [view addSubview:table_];
7943 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7944 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7945 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7947 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7948 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7949 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7951 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7952 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7953 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7954 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7956 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7957 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7958 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7959 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7962 - (void) viewDidLoad {
7963 [super viewDidLoad];
7965 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7968 - (void) releaseSubviews {
7970 subscribedCell_ = nil;
7972 ignoredSwitch_ = nil;
7973 subscribedSwitch_ = nil;
7975 [super releaseSubviews];
7978 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7979 if ((self = [super init]) != nil) {
7980 database_ = database;
7985 - (void) reloadData {
7988 package_ = [database_ packageWithName:name_];
7990 if (package_ != nil) {
7991 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7992 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7993 } // XXX: what now, G?
7995 [table_ reloadData];
8001 /* Installed Controller {{{ */
8002 @interface InstalledController : FilteredPackageListController {
8006 - (id) initWithDatabase:(Database *)database;
8007 - (void) queueStatusDidChange;
8011 @implementation InstalledController
8013 - (NSURL *) referrerURL {
8014 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/installed/", UI_]];
8017 - (NSURL *) navigationURL {
8018 return [NSURL URLWithString:@"cydia://installed"];
8021 - (void) useRecent {
8024 @synchronized (self) {
8025 [self setFilter:[](Package *package) {
8026 return ![package uninstalled] && package->role_ < 7;
8029 [self setSorter:[](NSMutableArray *packages) {
8030 [packages radixSortUsingSelector:@selector(recent)];
8034 - (void) useFilter:(UISegmentedControl *)segmented {
8035 NSInteger selected([segmented selectedSegmentIndex]);
8037 return [self useRecent];
8038 bool simple(selected == 0);
8041 @synchronized (self) {
8042 [self setFilter:[=](Package *package) {
8043 return ![package uninstalled] && package->role_ <= (simple ? 1 : 3);
8046 [self setSorter:nullptr];
8049 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
8051 return [super sectionsForPackages:packages];
8053 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterLongStyle, kCFDateFormatterNoStyle));
8055 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
8056 Section *section(nil);
8059 for (size_t offset(0), count([packages count]); offset != count; ++offset) {
8060 Package *package([packages objectAtIndex:offset]);
8062 time_t upgraded([package upgraded]);
8063 if (upgraded < 1168364520)
8066 upgraded -= upgraded % (60 * 60 * 24);
8068 if (section == nil || upgraded != last) {
8073 continue; // XXX: name = UCLocalize("...");
8075 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:upgraded]);
8079 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
8080 [sections addObject:section];
8083 [section addToCount];
8086 CFRelease(formatter);
8090 - (id) initWithDatabase:(Database *)database {
8091 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED")]) != nil) {
8092 UISegmentedControl *segmented([[[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:UCLocalize("USER"), UCLocalize("EXPERT"), UCLocalize("RECENT"), nil]] autorelease]);
8093 [segmented setSelectedSegmentIndex:0];
8094 [segmented setSegmentedControlStyle:UISegmentedControlStyleBar];
8095 [[self navigationItem] setTitleView:segmented];
8097 [segmented addTarget:self action:@selector(modeChanged:) forEvents:UIControlEventValueChanged];
8098 [self useFilter:segmented];
8100 [self queueStatusDidChange];
8105 - (void) queueButtonClicked {
8106 [self.delegate queue];
8110 - (void) queueStatusDidChange {
8113 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8114 initWithTitle:UCLocalize("QUEUE")
8115 style:UIBarButtonItemStyleDone
8117 action:@selector(queueButtonClicked)
8120 [[self navigationItem] setRightBarButtonItem:nil];
8125 - (void) modeChanged:(UISegmentedControl *)segmented {
8126 [self useFilter:segmented];
8133 /* Source Cell {{{ */
8134 @interface SourceCell : CyteTableViewCell <
8135 CyteTableViewCellDelegate,
8138 _H<Source, 1> source_;
8141 _H<NSString> origin_;
8142 _H<NSString> label_;
8143 _H<UIActivityIndicatorView> indicator_;
8146 - (void) setSource:(Source *)source;
8147 - (void) setFetch:(NSNumber *)fetch;
8151 @implementation SourceCell
8153 - (void) _setImage:(NSArray *)data {
8154 if ([url_ isEqual:[data objectAtIndex:0]]) {
8155 icon_ = [data objectAtIndex:1];
8156 [self.content setNeedsDisplay];
8160 - (void) _setSource:(NSURL *) url {
8161 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8163 if (NSData *data = [NSURLConnection
8164 sendSynchronousRequest:[NSURLRequest
8166 cachePolicy:NSURLRequestUseProtocolCachePolicy
8170 returningResponse:NULL
8173 if (UIImage *image = [UIImage imageWithData:data])
8174 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
8179 - (void) setSource:(Source *)source {
8181 [source_ setDelegate:self];
8183 [self setFetch:[NSNumber numberWithBool:[source_ fetch]]];
8185 icon_ = [UIImage imageNamed:@"unknown.png"];
8187 origin_ = [source name];
8188 label_ = [source rooturi];
8190 [self.content setNeedsDisplay];
8192 url_ = [source iconURL];
8193 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
8196 - (void) setAllSource {
8198 [indicator_ stopAnimating];
8200 icon_ = [UIImage imageNamed:@"folder.png"];
8201 origin_ = UCLocalize("ALL_SOURCES");
8202 label_ = UCLocalize("ALL_SOURCES_EX");
8203 [self.content setNeedsDisplay];
8206 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8207 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8208 UIView *content([self contentView]);
8209 CGRect bounds([content bounds]);
8211 self.content = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8212 [self.content setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8213 [self.content setBackgroundColor:[UIColor whiteColor]];
8214 [content addSubview:self.content];
8216 [self.content setDelegate:self];
8217 [self.content setOpaque:YES];
8219 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGraySmall] autorelease];
8220 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin];// | UIViewAutoresizingFlexibleBottomMargin];
8221 [content addSubview:indicator_];
8223 [[self.content layer] setContentsGravity:kCAGravityTopLeft];
8227 - (void) layoutSubviews {
8228 [super layoutSubviews];
8230 UIView *content([self contentView]);
8231 CGRect bounds([content bounds]);
8233 CGRect frame([indicator_ frame]);
8234 frame.origin.x = bounds.size.width - frame.size.width;
8235 frame.origin.y = Retina((bounds.size.height - frame.size.height) / 2);
8237 if (kCFCoreFoundationVersionNumber < 800)
8238 frame.origin.x -= 8;
8239 [indicator_ setFrame:frame];
8242 - (NSString *) accessibilityLabel {
8246 - (void) drawContentRect:(CGRect)rect {
8247 bool highlighted(self.highlighted);
8248 float width(rect.size.width);
8252 rect.size = [(UIImage *) icon_ size];
8254 while (rect.size.width > 32 || rect.size.height > 32) {
8255 rect.size.width /= 2;
8256 rect.size.height /= 2;
8259 rect.origin.x = 26 - rect.size.width / 2;
8260 rect.origin.y = 26 - rect.size.height / 2;
8262 [icon_ drawInRect:Retina(rect)];
8265 if (highlighted && kCFCoreFoundationVersionNumber < 800)
8270 [origin_ drawAtPoint:CGPointMake(52, 8) forWidth:(width - 49) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
8274 [label_ drawAtPoint:CGPointMake(52, 29) forWidth:(width - 49) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
8277 - (void) setFetch:(NSNumber *)fetch {
8278 if ([fetch boolValue])
8279 [indicator_ startAnimating];
8281 [indicator_ stopAnimating];
8286 /* Sources Controller {{{ */
8287 @interface SourcesController : CyteViewController <
8288 UITableViewDataSource,
8291 _transient Database *database_;
8294 _H<UITableView, 2> list_;
8295 _H<NSMutableArray> sources_;
8299 _H<UIProgressHUD> hud_;
8302 NSURLConnection *trivial_bz2_;
8303 NSURLConnection *trivial_gz_;
8308 - (id) initWithDatabase:(Database *)database;
8309 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated;
8313 @implementation SourcesController
8315 - (void) _releaseConnection:(NSURLConnection *)connection {
8316 if (connection != nil) {
8317 [connection cancel];
8318 //[connection setDelegate:nil];
8319 [connection release];
8324 [self _releaseConnection:trivial_gz_];
8325 [self _releaseConnection:trivial_bz2_];
8330 - (NSURL *) navigationURL {
8331 return [NSURL URLWithString:@"cydia://sources"];
8334 - (void) viewDidAppear:(BOOL)animated {
8335 [super viewDidAppear:animated];
8336 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8339 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8343 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8345 return UCLocalize("INDIVIDUAL_SOURCES");
8349 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8352 case 1: return [sources_ count];
8357 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8358 @synchronized (database_) {
8359 if ([database_ era] != era_)
8361 if ([indexPath section] != 1)
8363 NSUInteger index([indexPath row]);
8364 if (index >= [sources_ count])
8366 return [sources_ objectAtIndex:index];
8369 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8370 static NSString *cellIdentifier = @"SourceCell";
8372 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8373 if (cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8374 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8376 Source *source([self sourceAtIndexPath:indexPath]);
8378 [cell setAllSource];
8380 [cell setSource:source];
8385 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8386 SectionsController *controller([[[SectionsController alloc]
8387 initWithDatabase:database_
8388 source:[self sourceAtIndexPath:indexPath]
8391 [controller setDelegate:self.delegate];
8392 [[self navigationController] pushViewController:controller animated:YES];
8395 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8396 if ([indexPath section] != 1)
8398 Source *source = [self sourceAtIndexPath:indexPath];
8399 return [source record] != nil;
8402 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8403 _assert([indexPath section] == 1);
8404 if (editingStyle == UITableViewCellEditingStyleDelete) {
8405 Source *source = [self sourceAtIndexPath:indexPath];
8406 if (source == nil) return;
8408 [Sources_ removeObjectForKey:[source key]];
8410 [self.delegate syncData];
8414 - (void) tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath {
8415 [self updateButtonsForEditingStatusAnimated:YES];
8419 [self.delegate addTrivialSource:href_];
8422 [self.delegate syncData];
8425 - (NSString *) getWarning {
8426 NSString *href(href_);
8427 NSRange colon([href rangeOfString:@"://"]);
8428 if (colon.location != NSNotFound)
8429 href = [href substringFromIndex:(colon.location + 3)];
8430 href = [href stringByAddingPercentEscapes];
8431 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8433 NSURL *url([NSURL URLWithString:href]);
8435 NSStringEncoding encoding;
8436 NSError *error(nil);
8438 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8439 return [warning length] == 0 ? nil : warning;
8443 - (void) _endConnection:(NSURLConnection *)connection {
8444 // XXX: the memory management in this method is horribly awkward
8446 NSURLConnection **field = NULL;
8447 if (connection == trivial_bz2_)
8448 field = &trivial_bz2_;
8449 else if (connection == trivial_gz_)
8450 field = &trivial_gz_;
8451 _assert(field != NULL);
8452 [connection release];
8456 trivial_bz2_ == nil &&
8459 NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil);
8461 [self.delegate releaseNetworkActivityIndicator];
8463 [self.delegate removeProgressHUD:hud_];
8467 if (warning != nil) {
8468 UIAlertView *alert = [[[UIAlertView alloc]
8469 initWithTitle:UCLocalize("SOURCE_WARNING")
8472 cancelButtonTitle:UCLocalize("CANCEL")
8474 UCLocalize("ADD_ANYWAY"),
8478 [alert setContext:@"warning"];
8479 [alert setNumberOfRows:1];
8482 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
8488 } else if (error_ != nil) {
8489 UIAlertView *alert = [[[UIAlertView alloc]
8490 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8491 message:[error_ localizedDescription]
8493 cancelButtonTitle:UCLocalize("OK")
8494 otherButtonTitles:nil
8497 [alert setContext:@"urlerror"];
8502 UIAlertView *alert = [[[UIAlertView alloc]
8503 initWithTitle:UCLocalize("NOT_REPOSITORY")
8504 message:UCLocalize("NOT_REPOSITORY_EX")
8506 cancelButtonTitle:UCLocalize("OK")
8507 otherButtonTitles:nil
8510 [alert setContext:@"trivial"];
8520 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8521 switch ([response statusCode]) {
8527 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8528 lprintf("connection:\"%s\" didFailWithError:\"%s\"\n", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8530 [self _endConnection:connection];
8533 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8534 [self _endConnection:connection];
8537 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8538 NSURL *url([NSURL URLWithString:href]);
8540 NSMutableURLRequest *request = [NSMutableURLRequest
8542 cachePolicy:NSURLRequestUseProtocolCachePolicy
8546 [request setHTTPMethod:method];
8548 if (Machine_ != NULL)
8549 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8551 if (UniqueID_ != nil)
8552 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8554 if ([url isCydiaSecure]) {
8555 if (UniqueID_ != nil)
8556 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
8559 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8562 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8563 NSString *context([alert context]);
8565 if ([context isEqualToString:@"source"]) {
8568 NSString *href = [[alert textField] text];
8569 href = VerifySource(href);
8574 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8575 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8579 // XXX: this is stupid
8580 hud_ = [self.delegate addProgressHUD];
8581 [hud_ setText:UCLocalize("VERIFYING_URL")];
8582 [self.delegate retainNetworkActivityIndicator];
8591 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8592 } else if ([context isEqualToString:@"trivial"])
8593 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8594 else if ([context isEqualToString:@"urlerror"])
8595 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8596 else if ([context isEqualToString:@"warning"]) {
8599 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
8608 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8612 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated {
8613 BOOL editing([list_ isEditing]);
8616 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8617 initWithTitle:UCLocalize("ADD")
8618 style:UIBarButtonItemStylePlain
8620 action:@selector(addButtonClicked)
8621 ] autorelease] animated:animated];
8622 else if ([self.delegate updating])
8623 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8624 initWithTitle:UCLocalize("CANCEL")
8625 style:UIBarButtonItemStyleDone
8627 action:@selector(cancelButtonClicked)
8628 ] autorelease] animated:animated];
8630 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8631 initWithTitle:UCLocalize("REFRESH")
8632 style:UIBarButtonItemStylePlain
8634 action:@selector(refreshButtonClicked)
8635 ] autorelease] animated:animated];
8637 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8638 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8639 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8641 action:@selector(editButtonClicked)
8642 ] autorelease] animated:animated];
8646 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease];
8647 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8648 [list_ setRowHeight:53];
8649 [(UITableView *) list_ setDataSource:self];
8650 [list_ setDelegate:self];
8651 [self setView:list_];
8654 - (void) viewDidLoad {
8655 [super viewDidLoad];
8657 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8658 [self updateButtonsForEditingStatusAnimated:NO];
8661 - (void) viewWillAppear:(BOOL)animated {
8662 [super viewWillAppear:animated];
8664 [list_ setEditing:NO];
8665 [self updateButtonsForEditingStatusAnimated:NO];
8668 - (void) releaseSubviews {
8673 [super releaseSubviews];
8676 - (id) initWithDatabase:(Database *)database {
8677 if ((self = [super init]) != nil) {
8678 database_ = database;
8682 - (void) reloadData {
8684 [self updateButtonsForEditingStatusAnimated:YES];
8686 @synchronized (database_) {
8687 era_ = [database_ era];
8689 sources_ = [NSMutableArray arrayWithCapacity:16];
8690 [sources_ addObjectsFromArray:[database_ sources]];
8692 [sources_ sortUsingSelector:@selector(compareByName:)];
8695 int count([sources_ count]);
8697 for (int i = 0; i != count; i++) {
8698 if ([[sources_ objectAtIndex:i] record] == nil)
8706 - (void) showAddSourcePrompt {
8707 UIAlertView *alert = [[[UIAlertView alloc]
8708 initWithTitle:UCLocalize("ENTER_APT_URL")
8711 cancelButtonTitle:UCLocalize("CANCEL")
8713 UCLocalize("ADD_SOURCE"),
8717 [alert setContext:@"source"];
8719 [alert setNumberOfRows:1];
8720 [alert addTextFieldWithValue:@"http://" label:@""];
8722 NSObject<UITextInputTraits> *traits = [[alert textField] textInputTraits];
8723 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8724 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8725 [traits setKeyboardType:UIKeyboardTypeURL];
8726 // XXX: UIReturnKeyDone
8727 [traits setReturnKeyType:UIReturnKeyNext];
8732 - (void) addButtonClicked {
8733 [self showAddSourcePrompt];
8736 - (void) refreshButtonClicked {
8737 if ([self.delegate requestUpdate])
8738 [self updateButtonsForEditingStatusAnimated:YES];
8741 - (void) cancelButtonClicked {
8742 [self.delegate cancelUpdate];
8745 - (void) editButtonClicked {
8746 [list_ setEditing:![list_ isEditing] animated:YES];
8747 [self updateButtonsForEditingStatusAnimated:YES];
8753 /* Stash Controller {{{ */
8754 @interface StashController : CyteViewController {
8755 _H<UIActivityIndicatorView> spinner_;
8756 _H<UILabel> status_;
8757 _H<UILabel> caption_;
8762 @implementation StashController
8765 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8766 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8767 [self setView:view];
8769 [view setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8771 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8772 CGRect spinrect = [spinner_ frame];
8773 spinrect.origin.x = Retina([[self view] frame].size.width / 2 - spinrect.size.width / 2);
8774 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8775 [spinner_ setFrame:spinrect];
8776 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8777 [view addSubview:spinner_];
8778 [spinner_ startAnimating];
8781 captrect.size.width = [[self view] frame].size.width;
8782 captrect.size.height = 40.0f;
8783 captrect.origin.x = 0;
8784 captrect.origin.y = Retina([[self view] frame].size.height / 2 - captrect.size.height * 2);
8785 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8786 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8787 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8788 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8789 [caption_ setTextColor:[UIColor whiteColor]];
8790 [caption_ setBackgroundColor:[UIColor clearColor]];
8791 [caption_ setShadowColor:[UIColor blackColor]];
8792 [caption_ setTextAlignment:NSTextAlignmentCenter];
8793 [view addSubview:caption_];
8796 statusrect.size.width = [[self view] frame].size.width;
8797 statusrect.size.height = 30.0f;
8798 statusrect.origin.x = 0;
8799 statusrect.origin.y = Retina([[self view] frame].size.height / 2 - statusrect.size.height);
8800 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8801 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8802 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8803 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8804 [status_ setTextColor:[UIColor whiteColor]];
8805 [status_ setBackgroundColor:[UIColor clearColor]];
8806 [status_ setShadowColor:[UIColor blackColor]];
8807 [status_ setTextAlignment:NSTextAlignmentCenter];
8808 [view addSubview:status_];
8811 - (void) releaseSubviews {
8816 [super releaseSubviews];
8822 @interface Cydia : CyteApplication <
8823 ConfirmationControllerDelegate,
8827 _H<UIWindow> window_;
8828 _H<CydiaTabBarController> tabbar_;
8829 _H<CyteTabBarController> emulated_;
8830 _H<AppCacheController> appcache_;
8832 _H<NSMutableArray> essential_;
8833 _H<NSMutableArray> broken_;
8835 Database *database_;
8837 _H<NSURL> starturl_;
8842 _H<StashController> stash_;
8851 @implementation Cydia
8853 - (void) lockSuspend {
8854 if (locked_++ == 0) {
8855 if ($SBSSetInterceptsMenuButtonForever != NULL)
8856 (*$SBSSetInterceptsMenuButtonForever)(true);
8858 [self setIdleTimerDisabled:YES];
8862 - (void) unlockSuspend {
8863 if (--locked_ == 0) {
8864 [self setIdleTimerDisabled:NO];
8866 if ($SBSSetInterceptsMenuButtonForever != NULL)
8867 (*$SBSSetInterceptsMenuButtonForever)(false);
8871 - (void) beginUpdate {
8872 [tabbar_ beginUpdate];
8875 - (void) cancelUpdate {
8876 [tabbar_ cancelUpdate];
8879 - (bool) requestUpdate {
8880 if (IsReachable("cydia.saurik.com")) {
8884 UIAlertView *alert = [[[UIAlertView alloc]
8885 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("REFRESH")]
8886 message:@"Host Unreachable" // XXX: Localize
8888 cancelButtonTitle:UCLocalize("OK")
8889 otherButtonTitles:nil
8892 [alert setContext:@"norefresh"];
8900 return [tabbar_ updating];
8904 if ([broken_ count] != 0) {
8905 int count = [broken_ count];
8907 UIAlertView *alert = [[[UIAlertView alloc]
8908 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8909 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8911 cancelButtonTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("FORCIBLY_CLEAR"), UCLocalize("UNSAFE")]
8913 UCLocalize("TEMPORARY_IGNORE"),
8917 [alert setContext:@"fixhalf"];
8918 [alert setNumberOfRows:2];
8920 } else if (!Ignored_ && [essential_ count] != 0) {
8921 int count = [essential_ count];
8923 UIAlertView *alert = [[[UIAlertView alloc]
8924 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8925 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8927 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8929 UCLocalize("UPGRADE_ESSENTIAL"),
8930 UCLocalize("COMPLETE_UPGRADE"),
8934 [alert setContext:@"upgrade"];
8939 - (void) returnToCydia {
8943 - (void) reloadSpringBoard {
8944 if (kCFCoreFoundationVersionNumber >= 700) // XXX: iOS 6.x
8945 system("/usr/libexec/cydia/cydo /bin/launchctl stop com.apple.backboardd");
8947 system("/usr/libexec/cydia/cydo /bin/launchctl stop com.apple.SpringBoard");
8949 system("/usr/bin/killall backboardd SpringBoard");
8952 - (void) _saveConfig {
8953 SaveConfig(database_);
8956 // Navigation controller for the queuing badge.
8957 - (UINavigationController *) queueNavigationController {
8958 NSArray *controllers = [tabbar_ viewControllers];
8959 return [controllers objectAtIndex:3];
8962 - (void) unloadData {
8963 [tabbar_ unloadData];
8966 - (void) _updateData {
8970 UINavigationController *navigation = [self queueNavigationController];
8972 id queuedelegate = nil;
8973 if ([[navigation viewControllers] count] > 0)
8974 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8976 [queuedelegate queueStatusDidChange];
8977 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8980 - (void) _refreshIfPossible {
8981 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8983 NSDate *update([[NSDictionary dictionaryWithContentsOfFile:@ CacheState_] objectForKey:@"LastUpdate"]);
8985 bool recently = false;
8986 if (update != nil) {
8987 NSTimeInterval interval([update timeIntervalSinceNow]);
8988 if (interval > -(15*60))
8992 // Don't automatic refresh if:
8993 // - We already refreshed recently.
8994 // - We already auto-refreshed this launch.
8995 // - Auto-refresh is disabled.
8996 // - Cydia's server is not reachable
8997 if (recently || loaded_ || ManualRefresh || !IsReachable("cydia.saurik.com")) {
8998 // If we are cancelling, we need to make sure it knows it's already loaded.
9001 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9003 // We are going to load, so remember that.
9006 [tabbar_ performSelectorOnMainThread:@selector(beginUpdate) withObject:nil waitUntilDone:NO];
9012 - (void) refreshIfPossible {
9013 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
9016 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9017 _profile(reloadDataWithInvocation)
9018 @synchronized (self) {
9019 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9021 [hud setText:UCLocalize("RELOADING_DATA")];
9023 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9027 [essential_ removeAllObjects];
9028 [broken_ removeAllObjects];
9030 _profile(reloadDataWithInvocation$Essential)
9031 NSArray *packages([database_ packages]);
9032 for (Package *package in packages) {
9034 [broken_ addObject:package];
9035 if ([package upgradableAndEssential:YES] && ![package ignored]) {
9036 if ([package essential] && [package installed] != nil)
9037 [essential_ addObject:package];
9043 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9046 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9047 [changesItem setBadgeValue:badge];
9048 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9049 [self setApplicationIconBadgeNumber:changes];
9052 [changesItem setBadgeValue:nil];
9053 [changesItem setAnimatedBadge:NO];
9054 [self setApplicationIconBadgeNumber:0];
9061 [self removeProgressHUD:hud];
9068 - (void) updateData {
9072 - (void) updateDataAndLoad {
9074 if ([database_ progressDelegate] == nil)
9080 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9083 - (void) disemulate {
9084 if (emulated_ == nil)
9087 if ([window_ respondsToSelector:@selector(setRootViewController:)])
9088 [window_ setRootViewController:tabbar_];
9090 [window_ addSubview:[tabbar_ view]];
9091 [[emulated_ view] removeFromSuperview];
9095 [window_ setUserInteractionEnabled:YES];
9098 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9099 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9101 UIViewController *parent;
9102 if (emulated_ == nil)
9112 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9113 [parent presentModalViewController:navigation animated:YES];
9116 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9117 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9119 if (navigation != nil)
9120 [navigation pushViewController:progress animated:YES];
9122 [self presentModalViewController:progress force:YES];
9124 [progress invoke:invocation withTitle:title];
9128 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9129 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9132 - (void) repairWithInvocation:(NSInvocation *)invocation {
9134 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9138 - (void) repairWithSelector:(SEL)selector {
9139 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9142 - (void) reloadData {
9143 [self reloadDataWithInvocation:nil];
9144 if ([database_ progressDelegate] == nil)
9150 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9153 - (void) addSource:(NSDictionary *) source {
9154 CydiaAddSource(source);
9157 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9158 CydiaAddSource(href, distribution, sections);
9161 // XXX: this method should not return anything
9162 - (BOOL) addTrivialSource:(NSString *)href {
9163 CydiaAddSource(href, @"./");
9168 pkgProblemResolver *resolver = [database_ resolver];
9170 resolver->InstallProtect();
9171 if (!resolver->Resolve(true))
9176 // XXX: this is a really crappy way of doing this.
9177 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9178 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9179 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9180 if ([tabbar_ updating])
9181 [tabbar_ cancelUpdate];
9183 if (![database_ prepare])
9186 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9187 [page setDelegate:self];
9188 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9191 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9192 [tabbar_ presentModalViewController:confirm_ animated:YES];
9198 @synchronized (self) {
9203 - (void) clearPackage:(Package *)package {
9204 @synchronized (self) {
9211 - (void) installPackages:(NSArray *)packages {
9212 @synchronized (self) {
9213 for (Package *package in packages)
9220 - (void) installPackage:(Package *)package {
9221 @synchronized (self) {
9228 - (void) removePackage:(Package *)package {
9229 @synchronized (self) {
9236 - (void) distUpgrade {
9237 @synchronized (self) {
9238 if (![database_ upgrade])
9246 system("/usr/bin/uicache");
9251 UIProgressHUD *hud([self addProgressHUD]);
9252 [hud setText:UCLocalize("LOADING")];
9253 [self yieldToSelector:@selector(_uicache)];
9254 [self removeProgressHUD:hud];
9258 [database_ perform];
9259 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9260 [self performSelectorOnMainThread:@selector(uicache) withObject:nil waitUntilDone:YES];
9263 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9266 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9267 [self unlockSuspend];
9270 - (void) retainNetworkActivityIndicator {
9271 if (activity_++ == 0)
9272 [self setNetworkActivityIndicatorVisible:YES];
9275 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9279 - (void) releaseNetworkActivityIndicator {
9280 if (--activity_ == 0)
9281 [self setNetworkActivityIndicatorVisible:NO];
9284 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9289 - (void) cancelAndClear:(bool)clear {
9290 @synchronized (self) {
9302 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9303 NSString *context([alert context]);
9305 if ([context isEqualToString:@"conffile"]) {
9306 FILE *input = [database_ input];
9307 if (button == [alert cancelButtonIndex])
9308 fprintf(input, "N\n");
9309 else if (button == [alert firstOtherButtonIndex])
9310 fprintf(input, "Y\n");
9313 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9314 } else if ([context isEqualToString:@"fixhalf"]) {
9315 if (button == [alert cancelButtonIndex]) {
9316 @synchronized (self) {
9317 for (Package *broken in (id) broken_) {
9319 NSString *id(ShellEscape([broken id]));
9320 system([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /bin/rm -f"
9321 " /var/lib/dpkg/info/%@.prerm"
9322 " /var/lib/dpkg/info/%@.postrm"
9323 " /var/lib/dpkg/info/%@.preinst"
9324 " /var/lib/dpkg/info/%@.postinst"
9325 " /var/lib/dpkg/info/%@.extrainst_"
9326 "", id, id, id, id, id] UTF8String]);
9332 } else if (button == [alert firstOtherButtonIndex]) {
9333 [broken_ removeAllObjects];
9337 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9338 } else if ([context isEqualToString:@"upgrade"]) {
9339 if (button == [alert firstOtherButtonIndex]) {
9340 @synchronized (self) {
9341 for (Package *essential in (id) essential_)
9342 [essential install];
9347 } else if (button == [alert firstOtherButtonIndex] + 1) {
9349 } else if (button == [alert cancelButtonIndex]) {
9353 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9357 - (void) system:(NSString *)command {
9358 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9361 system([command UTF8String]);
9367 - (void) applicationWillSuspend {
9369 [super applicationWillSuspend];
9372 - (BOOL) isSafeToSuspend {
9375 NSLog(@"isSafeToSuspend: locked_ != 0");
9380 if ([tabbar_ modalViewController] != nil)
9383 // Use external process status API internally.
9384 // This is probably a really bad idea.
9385 // XXX: what is the point of this? does this solve anything at all?
9386 uint64_t status = 0;
9388 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9389 notify_get_state(notify_token, &status);
9390 notify_cancel(notify_token);
9395 NSLog(@"isSafeToSuspend: status != 0");
9401 NSLog(@"isSafeToSuspend: -> true");
9406 - (void) suspendReturningToLastApp:(BOOL)returning {
9407 if ([self isSafeToSuspend])
9408 [super suspendReturningToLastApp:returning];
9412 if ([self isSafeToSuspend])
9416 - (void) applicationSuspend {
9417 if ([self isSafeToSuspend])
9418 [super applicationSuspend];
9421 - (void) applicationSuspend:(GSEventRef)event {
9422 if ([self isSafeToSuspend])
9423 [super applicationSuspend:event];
9426 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9427 if ([self isSafeToSuspend])
9428 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9431 - (void) _setSuspended:(BOOL)value {
9432 if ([self isSafeToSuspend])
9433 [super _setSuspended:value];
9436 - (UIProgressHUD *) addProgressHUD {
9437 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9438 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9440 [window_ setUserInteractionEnabled:NO];
9442 UIViewController *target(tabbar_);
9443 if (UIViewController *modal = [target modalViewController])
9446 [hud showInView:[target view]];
9452 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9453 [self unlockSuspend];
9455 [hud removeFromSuperview];
9456 [window_ setUserInteractionEnabled:YES];
9459 - (CyteViewController *) pageForPackage:(NSString *)name withReferrer:(NSString *)referrer {
9460 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name withReferrer:referrer] autorelease];
9463 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external withReferrer:(NSString *)referrer {
9464 NSString *scheme([[url scheme] lowercaseString]);
9465 if ([[url absoluteString] length] <= [scheme length] + 3)
9467 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9468 NSArray *components([path componentsSeparatedByString:@"/"]);
9470 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"]) {
9471 CyteViewController *controller([self pageForPackage:[components objectAtIndex:1] withReferrer:referrer]);
9472 if (controller != nil)
9473 [controller setDelegate:self];
9477 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9480 NSString *base([components objectAtIndex:0]);
9482 CyteViewController *controller = nil;
9484 if ([base isEqualToString:@"url"]) {
9485 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9486 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9487 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9488 } else if (!external && [components count] == 1) {
9489 if ([base isEqualToString:@"sources"]) {
9490 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9493 if ([base isEqualToString:@"home"]) {
9494 controller = [[[HomeController alloc] init] autorelease];
9497 if ([base isEqualToString:@"sections"]) {
9498 controller = [[[SectionsController alloc] initWithDatabase:database_ source:nil] autorelease];
9501 if ([base isEqualToString:@"search"]) {
9502 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9505 if ([base isEqualToString:@"changes"]) {
9506 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9509 if ([base isEqualToString:@"installed"]) {
9510 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9512 } else if ([components count] == 2) {
9513 NSString *argument = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9515 if ([base isEqualToString:@"package"]) {
9516 controller = [self pageForPackage:argument withReferrer:referrer];
9519 if (!external && [base isEqualToString:@"search"]) {
9520 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9523 if (!external && [base isEqualToString:@"sections"]) {
9524 if ([argument isEqualToString:@"all"] || [argument isEqualToString:@"*"])
9526 controller = [[[SectionController alloc] initWithDatabase:database_ source:nil section:argument] autorelease];
9529 if ([base isEqualToString:@"sources"]) {
9530 if ([argument isEqualToString:@"add"]) {
9531 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9532 [(SourcesController *)controller showAddSourcePrompt];
9534 Source *source([database_ sourceWithKey:argument]);
9535 controller = [[[SectionsController alloc] initWithDatabase:database_ source:source] autorelease];
9539 if (!external && [base isEqualToString:@"launch"]) {
9540 [self launchApplicationWithIdentifier:argument suspended:NO];
9543 } else if (!external && [components count] == 3) {
9544 NSString *arg1 = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9545 NSString *arg2 = [[components objectAtIndex:2] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9547 if ([base isEqualToString:@"package"]) {
9548 if ([arg2 isEqualToString:@"settings"]) {
9549 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9550 } else if ([arg2 isEqualToString:@"files"]) {
9551 if (Package *package = [database_ packageWithName:arg1]) {
9552 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9553 [(FileTable *)controller setPackage:package];
9558 if ([base isEqualToString:@"sections"]) {
9559 Source *source([arg1 isEqualToString:@"*"] ? nil : [database_ sourceWithKey:arg1]);
9560 NSString *section([arg2 isEqualToString:@"*"] ? nil : arg2);
9561 controller = [[[SectionController alloc] initWithDatabase:database_ source:source section:section] autorelease];
9565 [controller setDelegate:self];
9569 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9570 CyteViewController *page([self pageForURL:url forExternal:external withReferrer:nil]);
9573 [tabbar_ setUnselectedViewController:page];
9578 - (void) applicationOpenURL:(NSURL *)url {
9579 [super applicationOpenURL:url];
9584 [self openCydiaURL:url forExternal:YES];
9587 - (void) applicationWillResignActive:(UIApplication *)application {
9588 // Stop refreshing if you get a phone call or lock the device.
9589 if ([tabbar_ updating])
9590 [tabbar_ cancelUpdate];
9592 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9593 [super applicationWillResignActive:application];
9596 - (void) saveState {
9597 [[NSDictionary dictionaryWithObjectsAndKeys:
9598 @"InterfaceState", [tabbar_ navigationURLCollection],
9599 @"LastClosed", [NSDate date],
9600 @"InterfaceIndex", [NSNumber numberWithInt:[tabbar_ selectedIndex]],
9601 nil] writeToFile:@ SavedState_ atomically:YES];
9606 - (void) applicationWillTerminate:(UIApplication *)application {
9610 - (void) applicationDidEnterBackground:(UIApplication *)application {
9611 if (kCFCoreFoundationVersionNumber < 1000 && [self isSafeToSuspend])
9612 return [self terminateWithSuccess];
9613 Backgrounded_ = [NSDate date];
9617 - (void) applicationWillEnterForeground:(UIApplication *)application {
9618 if (Backgrounded_ == nil)
9621 NSTimeInterval interval([Backgrounded_ timeIntervalSinceNow]);
9623 if (interval <= -(30*60)) {
9624 [tabbar_ setSelectedIndex:0];
9625 [[[tabbar_ viewControllers] objectAtIndex:0] popToRootViewControllerAnimated:NO];
9628 if (interval <= -(15*60)) {
9629 if (IsReachable("cydia.saurik.com")) {
9630 [tabbar_ beginUpdate];
9631 [appcache_ reloadURLWithCache:YES];
9635 if ([database_ delocked])
9639 - (void) setConfigurationData:(NSString *)data {
9640 static RegEx conffile_r("'(.*)' '(.*)' ([01]) ([01])");
9642 if (!conffile_r(data)) {
9643 lprintf("E:invalid conffile\n");
9647 NSString *ofile = conffile_r[1];
9648 //NSString *nfile = conffile_r[2];
9650 UIAlertView *alert = [[[UIAlertView alloc]
9651 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9652 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9654 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9656 UCLocalize("ACCEPT_NEW_COPY"),
9657 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9661 [alert setContext:@"conffile"];
9662 [alert setNumberOfRows:2];
9666 - (void) addStashController {
9668 stash_ = [[[StashController alloc] init] autorelease];
9669 [window_ addSubview:[stash_ view]];
9672 - (void) removeStashController {
9673 [[stash_ view] removeFromSuperview];
9675 [self unlockSuspend];
9679 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9680 UpdateExternalStatus(1);
9681 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/cydo /usr/libexec/cydia/free.sh"];
9682 UpdateExternalStatus(0);
9684 [self removeStashController];
9685 [self reloadSpringBoard];
9688 - (void) setupViewControllers {
9689 tabbar_ = [[[CydiaTabBarController alloc] initWithDatabase:database_] autorelease];
9691 NSMutableArray *items;
9692 if (kCFCoreFoundationVersionNumber < 800) {
9693 items = [NSMutableArray arrayWithObjects:
9694 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage imageNamed:@"home.png"] tag:0] autorelease],
9695 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage imageNamed:@"install.png"] tag:0] autorelease],
9696 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage imageNamed:@"changes.png"] tag:0] autorelease],
9697 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage imageNamed:@"manage.png"] tag:0] autorelease],
9698 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage imageNamed:@"search.png"] tag:0] autorelease],
9701 items = [NSMutableArray arrayWithObjects:
9702 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage imageNamed:@"home7.png"] selectedImage:[UIImage imageNamed:@"home7s.png"]] autorelease],
9703 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage imageNamed:@"install7.png"] selectedImage:[UIImage imageNamed:@"install7s.png"]] autorelease],
9704 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage imageNamed:@"changes7.png"] selectedImage:[UIImage imageNamed:@"changes7s.png"]] autorelease],
9705 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage imageNamed:@"manage7.png"] selectedImage:[UIImage imageNamed:@"manage7s.png"]] autorelease],
9706 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage imageNamed:@"search7.png"] selectedImage:[UIImage imageNamed:@"search7s.png"]] autorelease],
9710 NSMutableArray *controllers([NSMutableArray array]);
9711 for (UITabBarItem *item in items) {
9712 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9713 [controller setTabBarItem:item];
9714 [controllers addObject:controller];
9716 [tabbar_ setViewControllers:controllers];
9718 [tabbar_ setUpdateDelegate:self];
9721 - (void) applicationDidFinishLaunching:(id)unused {
9722 [super applicationDidFinishLaunching:unused];
9725 @synchronized (HostConfig_) {
9726 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9729 [CydiaWebViewController _initialize];
9731 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9733 // this would disallow http{,s} URLs from accessing this data
9734 //[WebView registerURLSchemeAsLocal:@"cydia"];
9736 Font12_ = [UIFont systemFontOfSize:12];
9737 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9738 Font14_ = [UIFont systemFontOfSize:14];
9739 Font18_ = [UIFont systemFontOfSize:18];
9740 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9741 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9743 essential_ = [NSMutableArray arrayWithCapacity:4];
9744 broken_ = [NSMutableArray arrayWithCapacity:4];
9746 // XXX: I really need this thing... like, seriously... I'm sorry
9747 appcache_ = [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] autorelease];
9748 [appcache_ reloadData];
9750 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9751 [window_ orderFront:self];
9752 [window_ makeKey:self];
9753 [window_ setHidden:NO];
9755 if (access("/.cydia_no_stash", F_OK) == 0);
9759 [self addStashController];
9760 // XXX: this would be much cleaner as a yieldToSelector:
9761 // that way the removeStashController could happen right here inline
9762 // we also could no longer require the useless stash_ field anymore
9763 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9768 int error(stat("/", &root));
9769 _assert(error != -1);
9771 #define Stash_(path) do { \
9772 struct stat folder; \
9773 int error(lstat((path), &folder)); \
9774 if (error != -1 && ( \
9775 folder.st_dev == root.st_dev && \
9776 S_ISDIR(folder.st_mode) \
9777 ) || error == -1 && ( \
9778 errno == ENOENT || \
9783 Stash_("/Applications");
9784 Stash_("/Library/Ringtones");
9785 Stash_("/Library/Wallpaper");
9786 //Stash_("/usr/bin");
9787 Stash_("/usr/include");
9788 Stash_("/usr/share");
9789 //Stash_("/var/lib");
9793 database_ = [Database sharedInstance];
9794 [database_ setDelegate:self];
9796 [window_ setUserInteractionEnabled:NO];
9797 [self setupViewControllers];
9799 CydiaLoadingViewController *loading([[[CydiaLoadingViewController alloc] init] autorelease]);
9800 UINavigationController *navigation([[[UINavigationController alloc] init] autorelease]);
9801 [navigation setViewControllers:[NSArray arrayWithObject:loading]];
9803 emulated_ = [[[CyteTabBarController alloc] init] autorelease];
9804 [emulated_ setViewControllers:[NSArray arrayWithObject:navigation]];
9805 [emulated_ setSelectedIndex:0];
9807 if ([emulated_ respondsToSelector:@selector(concealTabBarSelection)])
9808 [emulated_ concealTabBarSelection];
9810 if ([window_ respondsToSelector:@selector(setRootViewController:)])
9811 [window_ setRootViewController:emulated_];
9813 [window_ addSubview:[emulated_ view]];
9815 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9819 - (NSArray *) defaultStartPages {
9820 NSMutableArray *standard = [NSMutableArray array];
9821 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9822 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9823 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9824 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9825 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9831 if ([emulated_ modalViewController] != nil)
9832 [emulated_ dismissModalViewControllerAnimated:YES];
9833 [window_ setUserInteractionEnabled:NO];
9835 [self reloadDataWithInvocation:nil];
9836 [self refreshIfPossible];
9839 NSDictionary *state([NSDictionary dictionaryWithContentsOfFile:@ SavedState_]);
9841 int savedIndex = [[state objectForKey:@"InterfaceIndex"] intValue];
9842 NSArray *saved = [[[state objectForKey:@"InterfaceState"] mutableCopy] autorelease];
9843 int standardIndex = 0;
9844 NSArray *standard = [self defaultStartPages];
9851 NSDate *closed = [state objectForKey:@"LastClosed"];
9852 if (valid && closed != nil) {
9853 NSTimeInterval interval([closed timeIntervalSinceNow]);
9854 if (interval <= -(30*60))
9858 if (valid && [saved count] != [standard count])
9862 for (unsigned int i = 0; i < [standard count]; i++) {
9863 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9864 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9865 // but it's good enough for now.
9866 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9873 NSArray *items = nil;
9875 [tabbar_ setSelectedIndex:savedIndex];
9878 [tabbar_ setSelectedIndex:standardIndex];
9882 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9883 NSArray *stack = [items objectAtIndex:tab];
9884 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9885 NSMutableArray *current = [NSMutableArray array];
9887 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9888 NSString *addr = [stack objectAtIndex:nav];
9889 NSURL *url = [NSURL URLWithString:addr];
9890 CyteViewController *page = [self pageForURL:url forExternal:NO withReferrer:nil];
9892 [current addObject:page];
9895 [navigation setViewControllers:current];
9898 // (Try to) show the startup URL.
9899 if (starturl_ != nil) {
9900 [self openCydiaURL:starturl_ forExternal:YES];
9905 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9907 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
9908 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
9911 if (item != nil && IsWildcat_) {
9912 [sheet showFromBarButtonItem:item animated:YES];
9914 [sheet showInView:window_];
9918 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9919 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9920 [progress setTitle:task];
9921 [progress addProgressEvent:event];
9924 - (void) addProgressEventForTask:(NSArray *)data {
9925 CydiaProgressEvent *event([data objectAtIndex:0]);
9926 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9927 [self addProgressEvent:event forTask:task];
9930 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9931 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9937 id Alloc_(id self, SEL selector) {
9938 id object = alloc_(self, selector);
9939 lprintf("[%s]A-%p\n", self->isa->name, object);
9944 id Dealloc_(id self, SEL selector) {
9945 id object = dealloc_(self, selector);
9946 lprintf("[%s]D-%p\n", self->isa->name, object);
9950 static NSMutableDictionary *AutoreleaseDeepMutableCopyOfDictionary(CFTypeRef type) {
9953 if (CFGetTypeID(type) != CFDictionaryGetTypeID())
9955 CFTypeRef copy(CFPropertyListCreateDeepCopy(kCFAllocatorDefault, type, kCFPropertyListMutableContainers));
9957 return [(NSMutableDictionary *) copy autorelease];
9960 int main_store(int, char *argv[]);
9962 int main(int argc, char *argv[]) {
9964 const char *argv0(argv[0]);
9965 if (const char *slash = strrchr(argv0, '/'))
9968 else if (!strcmp(argv0, "store"))
9969 return main_store(argc, argv);
9972 int fd(open("/tmp/cydia.log", O_WRONLY | O_APPEND | O_CREAT, 0644));
9976 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9980 UpdateExternalStatus(0);
9982 UIScreen *screen([UIScreen mainScreen]);
9983 if ([screen respondsToSelector:@selector(scale)])
9984 ScreenScale_ = [screen scale];
9988 UIDevice *device([UIDevice currentDevice]);
9989 if ([device respondsToSelector:@selector(userInterfaceIdiom)]) {
9990 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
9991 if (idiom == UIUserInterfaceIdiomPad)
9995 Idiom_ = IsWildcat_ ? @"ipad" : @"iphone";
9997 RegEx pattern("([0-9]+\\.[0-9]+).*");
9999 if (pattern([device systemVersion]))
10000 Firmware_ = pattern[1];
10001 if (pattern(Cydia_))
10002 Major_ = pattern[1];
10004 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
10006 HostConfig_ = [[[NSObject alloc] init] autorelease];
10007 @synchronized (HostConfig_) {
10008 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10009 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
10012 NSString *ui(@"ui/ios");
10014 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
10015 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"/%@", Major_]];
10016 UI_ = CydiaURL(ui);
10018 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10020 /* Set Locale {{{ */
10021 Locale_ = CFLocaleCopyCurrent();
10022 Languages_ = [NSLocale preferredLanguages];
10024 std::string languages;
10025 const char *translation(NULL);
10027 // XXX: this isn't really a language, but this is compatible with older Cydia builds
10028 if (Locale_ != NULL)
10029 if (const char *language = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String]) {
10030 RegEx pattern("([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?");
10031 if (pattern(language)) {
10032 translation = strdup([pattern->*@"%1$@%2$@" UTF8String]);
10033 languages += translation;
10038 if (Languages_ != nil)
10039 for (NSString *locale : Languages_) {
10040 auto components([NSLocale componentsFromLocaleIdentifier:locale]);
10041 NSString *language([components objectForKey:(id)kCFLocaleLanguageCode]);
10042 if (NSString *script = [components objectForKey:(id)kCFLocaleScriptCode])
10043 language = [NSString stringWithFormat:@"%@-%@", language, script];
10044 languages += [language UTF8String];
10049 NSLog(@"Setting Language: [%s] %s", translation, languages.c_str());
10051 /* Index Collation {{{ */
10052 if (Class $UILocalizedIndexedCollation = objc_getClass("UILocalizedIndexedCollation")) { @try {
10053 NSBundle *bundle([NSBundle bundleForClass:$UILocalizedIndexedCollation]);
10054 NSString *path([bundle pathForResource:@"UITableViewLocalizedSectionIndex" ofType:@"plist"]);
10055 //path = @"/System/Library/Frameworks/UIKit.framework/.lproj/UITableViewLocalizedSectionIndex.plist";
10056 NSDictionary *dictionary([NSDictionary dictionaryWithContentsOfFile:path]);
10057 _H<UILocalizedIndexedCollation> collation([[[$UILocalizedIndexedCollation alloc] initWithDictionary:dictionary] autorelease]);
10059 CollationLocale_ = MSHookIvar<NSLocale *>(collation, "_locale");
10061 if (kCFCoreFoundationVersionNumber >= 800 && [[CollationLocale_ localeIdentifier] isEqualToString:@"zh@collation=stroke"]) {
10062 CollationThumbs_ = [NSArray arrayWithObjects:@"1",@"•",@"4",@"•",@"7",@"•",@"10",@"•",@"13",@"•",@"16",@"•",@"19",@"A",@"•",@"E",@"•",@"I",@"•",@"M",@"•",@"R",@"•",@"V",@"•",@"Z",@"#",nil];
10063 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})
10064 CollationOffset_.push_back(offset);
10065 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];
10066 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];
10069 CollationThumbs_ = [collation sectionIndexTitles];
10070 for (size_t index(0), end([CollationThumbs_ count]); index != end; ++index)
10071 CollationOffset_.push_back([collation sectionForSectionIndexTitleAtIndex:index]);
10073 CollationTitles_ = [collation sectionTitles];
10074 CollationStarts_ = MSHookIvar<NSArray *>(collation, "_sectionStartStrings");
10076 NSString *&transform(MSHookIvar<NSString *>(collation, "_transform"));
10077 if (&transform != NULL && transform != nil) {
10078 /*if ([collation respondsToSelector:@selector(transformedCollationStringForString:)])
10079 CollationModify_ = [=](NSString *value) { return [collation transformedCollationStringForString:value]; };*/
10080 const UChar *uid(reinterpret_cast<const UChar *>([transform cStringUsingEncoding:NSUnicodeStringEncoding]));
10081 UErrorCode code(U_ZERO_ERROR);
10082 CollationTransl_ = utrans_openU(uid, -1, UTRANS_FORWARD, NULL, 0, NULL, &code);
10083 if (!U_SUCCESS(code))
10084 NSLog(@"%s", u_errorName(code));
10088 } @catch (NSException *e) {
10092 CollationLocale_ = [[[NSLocale alloc] initWithLocaleIdentifier:@"en@collation=dictionary"] autorelease];
10094 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];
10095 for (NSInteger offset(0); offset != 28; ++offset)
10096 CollationOffset_.push_back(offset);
10098 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];
10099 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];
10103 App_ = [[NSBundle mainBundle] bundlePath];
10106 Cache_ = [[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia", @"/var/mobile"] retain];
10107 mkdir([Cache_ UTF8String], 0755);
10109 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10110 alloc_ = alloc->method_imp;
10111 alloc->method_imp = (IMP) &Alloc_;*/
10113 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10114 dealloc_ = dealloc->method_imp;
10115 dealloc->method_imp = (IMP) &Dealloc_;*/
10117 void *gestalt(dlopen("/usr/lib/libMobileGestalt.dylib", RTLD_GLOBAL | RTLD_LAZY));
10118 $MGCopyAnswer = reinterpret_cast<CFStringRef (*)(CFStringRef)>(dlsym(gestalt, "MGCopyAnswer"));
10120 /* System Information {{{ */
10124 size = sizeof(maxproc);
10125 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10126 perror("sysctlbyname(\"kern.maxproc\", ?)");
10127 else if (maxproc < 64) {
10129 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10130 perror("sysctlbyname(\"kern.maxproc\", #)");
10133 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10134 char *osversion = new char[size];
10135 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10136 perror("sysctlbyname(\"kern.osversion\", ?)");
10138 System_ = [NSString stringWithUTF8String:osversion];
10140 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10141 char *machine = new char[size];
10142 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10143 perror("sysctlbyname(\"hw.machine\", ?)");
10145 Machine_ = machine;
10147 int64_t usermem(0);
10148 size = sizeof(usermem);
10149 if (sysctlbyname("hw.usermem", &usermem, &size, NULL, 0) == -1)
10152 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10153 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10154 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10156 UniqueID_ = UniqueIdentifier(device);
10158 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10159 Product_ = [info objectForKey:@"SafariProductVersion"];
10160 Safari_ = [info objectForKey:@"CFBundleVersion"];
10163 NSString *agent([NSString stringWithFormat:@"Cydia/%@ CyF/%.2f", Cydia_, kCFCoreFoundationVersionNumber]);
10165 if (RegEx match = RegEx("([0-9]+(\\.[0-9]+)+).*", Safari_))
10166 agent = [NSString stringWithFormat:@"Safari/%@ %@", match[1], agent];
10167 if (RegEx match = RegEx("([0-9]+[A-Z][0-9]+[a-z]?).*", System_))
10168 agent = [NSString stringWithFormat:@"Mobile/%@ %@", match[1], agent];
10169 if (RegEx match = RegEx("([0-9]+(\\.[0-9]+)+).*", Product_))
10170 agent = [NSString stringWithFormat:@"Version/%@ %@", match[1], agent];
10172 UserAgent_ = agent;
10174 /* Load Database {{{ */
10175 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10178 mkdir("/var/mobile/Library/Cydia", 0755);
10179 MetaFile_.Open("/var/mobile/Library/Cydia/metadata.cb0");
10182 Values_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaValues"), CFSTR("com.saurik.Cydia")));
10183 Sections_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaSections"), CFSTR("com.saurik.Cydia")));
10184 Sources_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaSources"), CFSTR("com.saurik.Cydia")));
10185 Version_ = [(NSNumber *) CFPreferencesCopyAppValue(CFSTR("CydiaVersion"), CFSTR("com.saurik.Cydia")) autorelease];
10188 NSDictionary *metadata([[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease]);
10190 if (Values_ == nil)
10191 Values_ = [metadata objectForKey:@"Values"];
10192 if (Values_ == nil)
10193 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10195 if (Sections_ == nil)
10196 Sections_ = [metadata objectForKey:@"Sections"];
10197 if (Sections_ == nil)
10198 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10200 if (Sources_ == nil)
10201 Sources_ = [metadata objectForKey:@"Sources"];
10202 if (Sources_ == nil)
10203 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10205 // XXX: this wrong, but in a way that doesn't matter :/
10206 if (Version_ == nil)
10207 Version_ = [metadata objectForKey:@"Version"];
10208 if (Version_ == nil)
10209 Version_ = [NSNumber numberWithUnsignedInt:0];
10211 if (NSDictionary *packages = [metadata objectForKey:@"Packages"]) {
10213 CFDictionaryApplyFunction((CFDictionaryRef) packages, &PackageImport, &fail);
10216 NSLog(@"unable to import package preferences... from 2010? oh well :/");
10219 if ([Version_ unsignedIntValue] == 0) {
10220 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10221 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10222 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10223 CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./");
10225 Version_ = [NSNumber numberWithUnsignedInt:1];
10227 if (NSMutableDictionary *cache = [NSMutableDictionary dictionaryWithContentsOfFile:@ CacheState_]) {
10228 [cache removeObjectForKey:@"LastUpdate"];
10229 [cache writeToFile:@ CacheState_ atomically:YES];
10233 _H<NSMutableArray> broken([NSMutableArray array]);
10234 for (NSString *key in (id) Sources_)
10235 if ([key rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"# "]].location != NSNotFound || ![([[Sources_ objectForKey:key] objectForKey:@"URI"] ?: @"/") hasSuffix:@"/"])
10236 [broken addObject:key];
10237 if ([broken count] != 0)
10238 for (NSString *key in (id) broken)
10239 [Sources_ removeObjectForKey:key];
10243 system("/usr/libexec/cydia/cydo /bin/rm -f /var/lib/cydia/metadata.plist");
10246 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10248 if (kCFCoreFoundationVersionNumber > 1000)
10249 system("/usr/libexec/cydia/cydo /usr/libexec/cydia/setnsfpn /var/lib");
10251 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10253 if (access("/User", F_OK) != 0 || version != 6) {
10255 system("/usr/libexec/cydia/cydo /usr/libexec/cydia/firmware.sh");
10259 if (access("/tmp/cydia.chk", F_OK) == 0) {
10260 if (unlink([Cache("pkgcache.bin") UTF8String]) == -1)
10261 _assert(errno == ENOENT);
10262 if (unlink([Cache("srcpkgcache.bin") UTF8String]) == -1)
10263 _assert(errno == ENOENT);
10266 system("/usr/libexec/cydia/cydo /bin/ln -sf /var/mobile/Library/Caches/com.saurik.Cydia/sources.list /etc/apt/sources.list.d/cydia.list");
10268 /* APT Initialization {{{ */
10269 _assert(pkgInitConfig(*_config));
10270 _assert(pkgInitSystem(*_config, _system));
10272 _config->Set("Acquire::AllowInsecureRepositories", true);
10273 _config->Set("Acquire::Check-Valid-Until", false);
10274 _config->Set("Dir::Bin::Methods::store", "/Applications/Cydia.app/store");
10276 _config->Set("pkgCacheGen::ForceEssential", "");
10278 if (translation != NULL)
10279 _config->Set("APT::Acquire::Translation", translation);
10280 _config->Set("Acquire::Languages", languages);
10282 // XXX: this timeout might be important :(
10283 //_config->Set("Acquire::http::Timeout", 15);
10285 _config->Set("Acquire::http::MaxParallel", usermem >= 384 * 1024 * 1024 ? 16 : 3);
10287 mkdir([Cache("archives") UTF8String], 0755);
10288 mkdir([Cache("archives/partial") UTF8String], 0755);
10289 _config->Set("Dir::Cache", [Cache_ UTF8String]);
10291 symlink("/var/lib/apt/extended_states", [Cache("extended_states") UTF8String]);
10292 _config->Set("Dir::State", [Cache_ UTF8String]);
10294 mkdir([Cache("lists") UTF8String], 0755);
10295 mkdir([Cache("lists/partial") UTF8String], 0755);
10296 mkdir([Cache("periodic") UTF8String], 0755);
10297 _config->Set("Dir::State::Lists", [Cache("lists") UTF8String]);
10299 std::string logs("/var/mobile/Library/Logs/Cydia");
10300 mkdir(logs.c_str(), 0755);
10301 _config->Set("Dir::Log", logs);
10303 _config->Set("Dir::Bin::dpkg", "/usr/libexec/cydia/cydo");
10305 /* Color Choices {{{ */
10306 space_ = CGColorSpaceCreateDeviceRGB();
10308 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10309 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10310 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10311 Folder_.Set(space_, 0x8e/255.f, 0x8e/255.f, 0x93/255.f, 1.0);
10312 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10313 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10314 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10315 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10316 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10317 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10319 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10320 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10322 /* UIKit Configuration {{{ */
10323 // XXX: I have a feeling this was important
10324 //UIKeyboardDisableAutomaticAppearance();
10327 $SBSSetInterceptsMenuButtonForever = reinterpret_cast<void (*)(bool)>(dlsym(RTLD_DEFAULT, "SBSSetInterceptsMenuButtonForever"));
10328 $SBSCopyIconImagePNGDataForDisplayIdentifier = reinterpret_cast<NSData *(*)(NSString *)>(dlsym(RTLD_DEFAULT, "SBSCopyIconImagePNGDataForDisplayIdentifier"));
10330 const char *symbol(kCFCoreFoundationVersionNumber >= 800 ? "MGGetBoolAnswer" : "GSSystemHasCapability");
10331 BOOL (*GSSystemHasCapability)(CFStringRef) = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, symbol));
10332 bool fast = GSSystemHasCapability != NULL && GSSystemHasCapability(CFSTR("armv7"));
10334 PulseInterval_ = fast ? 50000 : 500000;
10336 Colon_ = UCLocalize("COLON_DELIMITED");
10337 Elision_ = UCLocalize("ELISION");
10338 Error_ = UCLocalize("ERROR");
10339 Warning_ = UCLocalize("WARNING");
10342 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10344 CGColorSpaceRelease(space_);
10345 CFRelease(Locale_);