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"
116 #include "CyteKit/RegEx.hpp"
118 #include "Cydia/MIMEAddress.h"
119 #include "Cydia/LoadingViewController.h"
120 #include "Cydia/ProgressEvent.h"
127 #define _timestamp ({ \
129 gettimeofday(&tv, NULL); \
130 tv.tv_sec * 1000000 + tv.tv_usec; \
133 typedef std::vector<class ProfileTime *> TimeList;
143 ProfileTime(const char *name) :
147 times_.push_back(this);
150 void AddTime(uint64_t time) {
157 std::cerr << std::setw(7) << count_ << ", " << std::setw(8) << total_ << " : " << name_ << std::endl;
169 ProfileTimer(ProfileTime &time) :
176 time_.AddTime(_timestamp - start_);
181 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
183 std::cerr << "========" << std::endl;
186 #define _profile(name) { \
187 static ProfileTime name(#name); \
188 ProfileTimer _ ## name(name);
193 extern NSString *Cydia_;
195 #define lprintf(args...) fprintf(stderr, args)
198 #define TraceLogging (1 && !ForRelease)
199 #define HistogramInsertionSort (0 && !ForRelease)
200 #define ProfileTimes (0 && !ForRelease)
201 #define ForSaurik (0 && !ForRelease)
202 #define LogBrowser (0 && !ForRelease)
203 #define TrackResize (0 && !ForRelease)
204 #define ManualRefresh (1 && !ForRelease)
205 #define ShowInternals (0 && !ForRelease)
206 #define AlwaysReload (0 && !ForRelease)
210 #define _trace(args...)
215 #define _profile(name) {
218 #define PrintTimes() do {} while (false)
221 // Hash Functions/Structures {{{
222 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
230 @implementation NSDictionary (Cydia)
231 - (id) invokeUndefinedMethodFromWebScript:(NSString *)name withArguments:(NSArray *)arguments {
233 else if ([name isEqualToString:@"get"])
234 return [self objectForKey:[arguments objectAtIndex:0]];
235 else if ([name isEqualToString:@"keys"])
236 return [self allKeys];
240 static NSString *Colon_;
242 static NSString *Error_;
243 static NSString *Warning_;
245 static NSString *Cache_;
246 #define Cache(file) \
247 [NSString stringWithFormat:@"%@/%s", Cache_, file]
249 static void (*$SBSSetInterceptsMenuButtonForever)(bool);
250 static NSData *(*$SBSCopyIconImagePNGDataForDisplayIdentifier)(NSString *);
252 static CFStringRef (*$MGCopyAnswer)(CFStringRef);
254 static NSString *UniqueIdentifier(UIDevice *device = nil) {
255 if (kCFCoreFoundationVersionNumber < 800) // iOS 7.x
256 return [device ?: [UIDevice currentDevice] uniqueIdentifier];
258 return [(id)$MGCopyAnswer(CFSTR("UniqueDeviceID")) autorelease];
261 static bool IsReachable(const char *name) {
262 SCNetworkReachabilityFlags flags; {
263 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, name));
264 SCNetworkReachabilityGetFlags(reachability, &flags);
265 CFRelease(reachability);
268 // XXX: this elaborate mess is what Apple is using to determine this? :(
269 // XXX: do we care if the user has to intervene? maybe that's ok?
271 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
272 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
273 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
274 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
275 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
276 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
281 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
283 static _finline NSString *CydiaURL(NSString *path) {
285 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
286 page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
287 page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
288 page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
289 page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
291 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
294 static NSString *ShellEscape(NSString *value) {
295 return [NSString stringWithFormat:@"'%@'", [value stringByReplacingOccurrencesOfString:@"'" withString:@"'\\''"]];
298 static _finline void UpdateExternalStatus(uint64_t newStatus) {
300 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
301 notify_set_state(notify_token, newStatus);
302 notify_cancel(notify_token);
304 notify_post("com.saurik.Cydia.status");
307 static CGFloat CYStatusBarHeight() {
308 CGSize size([[UIApplication sharedApplication] statusBarFrame].size);
309 return UIInterfaceOrientationIsPortrait([[UIApplication sharedApplication] statusBarOrientation]) ? size.height : size.width;
312 /* NSForcedOrderingSearch doesn't work on the iPhone */
313 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
314 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
315 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
317 /* Insertion Sort {{{ */
319 template <typename Type_>
320 size_t CFBSearch_(const Type_ &element, const void *list, size_t count, CFComparisonResult (*comparator)(Type_, Type_, void *), void *context) {
321 const char *ptr = (const char *)list;
323 size_t half = count / 2;
324 const char *probe = ptr + sizeof(Type_) * half;
325 CFComparisonResult cr = comparator(element, * (const Type_ *) probe, context);
326 if (0 == cr) return (probe - (const char *)list) / sizeof(Type_);
327 ptr = (cr < 0) ? ptr : probe + sizeof(Type_);
328 count = (cr < 0) ? half : (half + (count & 1) - 1);
330 return (ptr - (const char *)list) / sizeof(Type_);
333 template <typename Type_>
334 void CYArrayInsertionSortValues(Type_ *values, size_t length, CFComparisonResult (*comparator)(Type_, Type_, void *), void *context) {
338 #if HistogramInsertionSort > 0
339 uint32_t total(0), *offsets(new uint32_t[length]);
342 for (size_t index(1); index != length; ++index) {
343 Type_ value(values[index]);
345 size_t correct(CFBSearch_(value, values, index, comparator, context));
347 size_t correct(index);
348 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
349 #if HistogramInsertionSort > 1
350 NSLog(@"%@ < %@", value, values[correct - 1]);
354 if (index - correct >= 8) {
355 correct = CFBSearch_(value, values, correct, comparator, context);
360 if (correct != index) {
361 size_t offset(index - correct);
362 #if HistogramInsertionSort
366 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
368 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
369 values[correct] = value;
373 #if HistogramInsertionSort > 0
374 for (size_t index(0); index != range.length; ++index)
375 if (offsets[index] != 0)
376 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
377 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
384 /* Cydia NSString Additions {{{ */
385 @interface NSString (Cydia)
386 - (NSComparisonResult) compareByPath:(NSString *)other;
387 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
390 @implementation NSString (Cydia)
392 - (NSComparisonResult) compareByPath:(NSString *)other {
393 NSString *prefix = [self commonPrefixWithString:other options:0];
394 size_t length = [prefix length];
396 NSRange lrange = NSMakeRange(length, [self length] - length);
397 NSRange rrange = NSMakeRange(length, [other length] - length);
399 lrange = [self rangeOfString:@"/" options:0 range:lrange];
400 rrange = [other rangeOfString:@"/" options:0 range:rrange];
402 NSComparisonResult value;
404 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
405 value = NSOrderedSame;
406 else if (lrange.location == NSNotFound)
407 value = NSOrderedAscending;
408 else if (rrange.location == NSNotFound)
409 value = NSOrderedDescending;
411 value = NSOrderedSame;
413 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
414 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
415 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
416 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
418 NSComparisonResult result = [lpath compare:rpath];
419 return result == NSOrderedSame ? value : result;
422 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
423 return [(id)CFURLCreateStringByAddingPercentEscapes(
428 kCFStringEncodingUTF8
435 /* C++ NSString Wrapper Cache {{{ */
436 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
437 return size == 0 ? NULL :
438 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
439 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
442 static _finline CFStringRef CYStringCreate(const std::string &data) {
443 return CYStringCreate(data.data(), data.size());
446 static _finline CFStringRef CYStringCreate(const char *data) {
447 return CYStringCreate(data, strlen(data));
456 _finline void clear_() {
457 if (cache_ != NULL) {
464 _finline bool empty() const {
468 _finline size_t size() const {
472 _finline char *data() const {
476 _finline void clear() {
481 _finline CYString() :
488 _finline ~CYString() {
492 void operator =(const CYString &rhs) {
496 if (rhs.cache_ == nil)
499 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
502 void copy(CYPool *pool) {
503 char *temp(pool->malloc<char>(size_ + 1));
504 memcpy(temp, data_, size_);
509 void set(CYPool *pool, const char *data, size_t size) {
515 data_ = const_cast<char *>(data);
523 _finline void set(CYPool *pool, const char *data) {
524 set(pool, data, data == NULL ? 0 : strlen(data));
527 _finline void set(CYPool *pool, const std::string &rhs) {
528 set(pool, rhs.data(), rhs.size());
531 bool operator ==(const CYString &rhs) const {
532 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
535 _finline operator CFStringRef() {
537 cache_ = CYStringCreate(data_, size_);
541 _finline operator id() {
542 return (NSString *) static_cast<CFStringRef>(*this);
545 _finline operator const char *() {
546 return reinterpret_cast<const char *>(data_);
550 /* C++ NSString Algorithm Adapters {{{ */
552 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
555 struct NSStringMapHash :
556 std::unary_function<NSString *, size_t>
558 _finline size_t operator ()(NSString *value) const {
559 return CFStringHashNSString((CFStringRef) value);
563 struct NSStringMapLess :
564 std::binary_function<NSString *, NSString *, bool>
566 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
567 return [lhs compare:rhs] == NSOrderedAscending;
571 struct NSStringMapEqual :
572 std::binary_function<NSString *, NSString *, bool>
574 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
575 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
576 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
577 //[lhs isEqualToString:rhs];
582 /* CoreGraphics Primitives {{{ */
587 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
588 CGFloat color[] = {red, green, blue, alpha};
589 return CGColorCreate(space, color);
598 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
599 color_(Create_(space, red, green, blue, alpha))
601 Set(space, red, green, blue, alpha);
606 CGColorRelease(color_);
613 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
615 color_ = Create_(space, red, green, blue, alpha);
618 operator CGColorRef() {
624 /* Random Global Variables {{{ */
625 static int PulseInterval_ = 500000;
627 static const NSString *UI_;
630 static bool RestartSubstrate_;
631 static NSArray *Finishes_;
633 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
634 #define NotifyConfig_ "/etc/notify.conf"
636 static bool Queuing_;
638 static CYColor Blue_;
639 static CYColor Blueish_;
640 static CYColor Black_;
641 static CYColor Folder_;
643 static CYColor White_;
644 static CYColor Gray_;
645 static CYColor Green_;
646 static CYColor Purple_;
647 static CYColor Purplish_;
649 static UIColor *InstallingColor_;
650 static UIColor *RemovingColor_;
652 static NSString *App_;
654 static BOOL Advanced_;
655 static BOOL Ignored_;
657 static _H<UIFont> Font12_;
658 static _H<UIFont> Font12Bold_;
659 static _H<UIFont> Font14_;
660 static _H<UIFont> Font18_;
661 static _H<UIFont> Font18Bold_;
662 static _H<UIFont> Font22Bold_;
664 static const char *Machine_ = NULL;
665 static _H<NSString> System_;
666 static NSString *SerialNumber_ = nil;
667 static NSString *ChipID_ = nil;
668 static NSString *BBSNum_ = nil;
669 static _H<NSString> UniqueID_;
670 static _H<NSString> UserAgent_;
671 static _H<NSString> Product_;
672 static _H<NSString> Safari_;
674 static _H<NSLocale> CollationLocale_;
675 static _H<NSArray> CollationThumbs_;
676 static std::vector<NSInteger> CollationOffset_;
677 static _H<NSArray> CollationTitles_;
678 static _H<NSArray> CollationStarts_;
679 static UTransliterator *CollationTransl_;
680 //static Function<NSString *, NSString *> CollationModify_;
682 typedef std::basic_string<UChar> ustring;
683 static ustring CollationString_;
685 #define CUC const ustring &str(*reinterpret_cast<const ustring *>(rep))
686 #define UC ustring &str(*reinterpret_cast<ustring *>(rep))
687 static struct UReplaceableCallbacks CollationUCalls_ = {
688 .length = [](const UReplaceable *rep) -> int32_t { CUC;
692 .charAt = [](const UReplaceable *rep, int32_t offset) -> UChar { CUC;
693 //fprintf(stderr, "charAt(%d) : %d\n", offset, str.size());
694 if (offset >= str.size())
699 .char32At = [](const UReplaceable *rep, int32_t offset) -> UChar32 { CUC;
700 //fprintf(stderr, "char32At(%d) : %d\n", offset, str.size());
701 if (offset >= str.size())
704 U16_GET(str.data(), 0, offset, str.size(), c);
708 .replace = [](UReplaceable *rep, int32_t start, int32_t limit, const UChar *text, int32_t length) -> void { UC;
709 //fprintf(stderr, "replace(%d, %d, %d) : %d\n", start, limit, length, str.size());
710 str.replace(start, limit - start, text, length);
713 .extract = [](UReplaceable *rep, int32_t start, int32_t limit, UChar *dst) -> void { UC;
714 //fprintf(stderr, "extract(%d, %d) : %d\n", start, limit, str.size());
715 str.copy(dst, limit - start, start);
718 .copy = [](UReplaceable *rep, int32_t start, int32_t limit, int32_t dest) -> void { UC;
719 //fprintf(stderr, "copy(%d, %d, %d) : %d\n", start, limit, dest, str.size());
720 str.replace(dest, 0, str, start, limit - start);
724 static CFLocaleRef Locale_;
725 static NSArray *Languages_;
726 static CGColorSpaceRef space_;
728 #define CacheState_ "/var/mobile/Library/Caches/com.saurik.Cydia/CacheState.plist"
729 #define SavedState_ "/var/mobile/Library/Caches/com.saurik.Cydia/SavedState.plist"
731 static NSDictionary *SectionMap_;
732 static _H<NSDate> Backgrounded_;
733 static _transient NSMutableDictionary *Values_;
734 static _transient NSMutableDictionary *Sections_;
735 _H<NSMutableDictionary> Sources_;
736 static _transient NSNumber *Version_;
739 static NSString *Idiom_;
740 static _H<NSString> Firmware_;
741 static NSString *Major_;
743 static _H<NSMutableDictionary> SessionData_;
744 static _H<NSObject> HostConfig_;
745 static _H<NSMutableSet> BridgedHosts_;
746 static _H<NSMutableSet> InsecureHosts_;
748 static NSString *kCydiaProgressEventTypeError = @"Error";
749 static NSString *kCydiaProgressEventTypeInformation = @"Information";
750 static NSString *kCydiaProgressEventTypeStatus = @"Status";
751 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
754 /* Display Helpers {{{ */
755 inline float Interpolate(float begin, float end, float fraction) {
756 return (end - begin) * fraction + begin;
759 static inline double Retina(double value) {
760 value *= ScreenScale_;
761 value = round(value);
762 value /= ScreenScale_;
766 static inline CGRect Retina(CGRect value) {
767 value.origin.x *= ScreenScale_;
768 value.origin.y *= ScreenScale_;
769 value.size.width *= ScreenScale_;
770 value.size.height *= ScreenScale_;
771 value = CGRectIntegral(value);
772 value.origin.x /= ScreenScale_;
773 value.origin.y /= ScreenScale_;
774 value.size.width /= ScreenScale_;
775 value.size.height /= ScreenScale_;
779 static _finline const char *StripVersion_(const char *version) {
780 const char *colon(strchr(version, ':'));
781 return colon == NULL ? version : colon + 1;
784 NSString *LocalizeSection(NSString *section) {
785 static RegEx title_r("(.*?) \\((.*)\\)");
786 if (title_r(section)) {
787 NSString *parent(title_r[1]);
788 NSString *child(title_r[2]);
790 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
791 LocalizeSection(parent),
792 LocalizeSection(child)
796 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
799 NSString *Simplify(NSString *title) {
800 const char *data = [title UTF8String];
801 size_t size = [title lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
803 static RegEx square_r("\\[(.*)\\]");
804 if (square_r(data, size))
805 return Simplify(square_r[1]);
807 static RegEx paren_r("\\((.*)\\)");
808 if (paren_r(data, size))
809 return Simplify(paren_r[1]);
811 static RegEx title_r("(.*?) \\((.*)\\)");
812 if (title_r(data, size))
813 return Simplify(title_r[1]);
819 bool isSectionVisible(NSString *section) {
820 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
821 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
822 return hidden == nil || ![hidden boolValue];
825 static NSObject *CYIOGetValue(const char *path, NSString *property) {
826 io_registry_entry_t entry(IORegistryEntryFromPath(kIOMasterPortDefault, path));
827 if (entry == MACH_PORT_NULL)
830 CFTypeRef value(IORegistryEntryCreateCFProperty(entry, (CFStringRef) property, kCFAllocatorDefault, 0));
831 IOObjectRelease(entry);
835 return [(id) value autorelease];
838 static NSString *CYHex(NSData *data, bool reverse = false) {
842 size_t length([data length]);
843 uint8_t bytes[length];
844 [data getBytes:bytes];
846 char string[length * 2 + 1];
847 for (size_t i(0); i != length; ++i)
848 sprintf(string + i * 2, "%.2x", bytes[reverse ? length - i - 1 : i]);
850 return [NSString stringWithUTF8String:string];
853 static NSString *VerifySource(NSString *href) {
854 static RegEx href_r("(http(s?)://|file:///)[^# ]*");
856 [[[[UIAlertView alloc]
857 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("INVALID_URL")]
858 message:UCLocalize("INVALID_URL_EX")
860 cancelButtonTitle:UCLocalize("OK")
861 otherButtonTitles:nil
862 ] autorelease] show];
867 if (![href hasSuffix:@"/"])
868 href = [href stringByAppendingString:@"/"];
874 /* Delegate Prototypes {{{ */
877 @class CydiaProgressEvent;
879 @protocol DatabaseDelegate
880 - (void) repairWithSelector:(SEL)selector;
881 - (void) setConfigurationData:(NSString *)data;
882 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
885 @class CYPackageController;
887 @protocol SourceDelegate
888 - (void) setFetch:(NSNumber *)fetch;
891 @protocol FetchDelegate
892 - (bool) isSourceCancelled;
893 - (void) startSourceFetch:(NSString *)uri;
894 - (void) stopSourceFetch:(NSString *)uri;
897 @protocol CydiaDelegate
898 - (void) returnToCydia;
900 - (void) retainNetworkActivityIndicator;
901 - (void) releaseNetworkActivityIndicator;
902 - (void) clearPackage:(Package *)package;
903 - (void) installPackage:(Package *)package;
904 - (void) installPackages:(NSArray *)packages;
905 - (void) removePackage:(Package *)package;
906 - (void) beginUpdate;
908 - (bool) requestUpdate;
909 - (void) distUpgrade;
912 - (void) _saveConfig;
914 - (void) addSource:(NSDictionary *)source;
915 - (BOOL) addTrivialSource:(NSString *)href;
916 - (UIProgressHUD *) addProgressHUD;
917 - (void) removeProgressHUD:(UIProgressHUD *)hud;
918 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
919 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
923 /* CancelStatus {{{ */
925 public pkgAcquireStatus
936 virtual bool MediaChange(std::string media, std::string drive) {
940 virtual void IMSHit(pkgAcquire::ItemDesc &desc) {
944 virtual bool Pulse_(pkgAcquire *Owner) = 0;
946 virtual bool Pulse(pkgAcquire *Owner) {
947 if (pkgAcquireStatus::Pulse(Owner) && Pulse_(Owner))
955 _finline bool WasCancelled() const {
960 /* DelegateStatus {{{ */
965 _transient NSObject<ProgressDelegate> *delegate_;
973 void setDelegate(NSObject<ProgressDelegate> *delegate) {
974 delegate_ = delegate;
977 virtual void Fetch(pkgAcquire::ItemDesc &desc) {
978 NSString *name([NSString stringWithUTF8String:desc.ShortDesc.c_str()]);
979 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItemDesc:desc]);
980 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
983 virtual void Done(pkgAcquire::ItemDesc &desc) {
984 NSString *name([NSString stringWithUTF8String:desc.ShortDesc.c_str()]);
985 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:Colon_, UCLocalize("DONE"), name] ofType:kCydiaProgressEventTypeStatus forItemDesc:desc]);
986 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
989 virtual void Fail(pkgAcquire::ItemDesc &desc) {
991 desc.Owner->Status == pkgAcquire::Item::StatIdle ||
992 desc.Owner->Status == pkgAcquire::Item::StatDone
996 std::string &error(desc.Owner->ErrorText);
1000 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItemDesc:desc]);
1001 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1004 virtual bool Pulse_(pkgAcquire *Owner) {
1006 double(CurrentBytes + CurrentItems) /
1007 double(TotalBytes + TotalItems)
1010 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
1011 [NSNumber numberWithDouble:percent], @"Percent",
1013 [NSNumber numberWithDouble:CurrentBytes], @"Current",
1014 [NSNumber numberWithDouble:TotalBytes], @"Total",
1015 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
1016 nil] waitUntilDone:YES];
1018 return ![delegate_ isProgressCancelled];
1021 virtual void Start() {
1022 pkgAcquireStatus::Start();
1023 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
1026 virtual void Stop() {
1027 pkgAcquireStatus::Stop();
1028 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
1029 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
1033 /* Database Interface {{{ */
1034 typedef std::map< unsigned long, _H<Source> > SourceMap;
1036 @interface Database : NSObject {
1043 pkgCacheFile cache_;
1044 pkgDepCache::Policy *policy_;
1045 pkgRecords *records_;
1046 pkgProblemResolver *resolver_;
1047 pkgAcquire *fetcher_;
1049 SPtr<pkgPackageManager> manager_;
1050 pkgSourceList *list_;
1052 SourceMap sourceMap_;
1053 _H<NSMutableArray> sourceList_;
1055 _H<NSArray> packages_;
1057 _transient NSObject<DatabaseDelegate> *delegate_;
1058 _transient NSObject<ProgressDelegate> *progress_;
1060 CydiaStatus status_;
1066 std::map<const char *, _H<NSString> > sections_;
1069 + (Database *) sharedInstance;
1071 - (bool) hasPackages;
1073 - (void) _readCydia:(NSNumber *)fd;
1074 - (void) _readStatus:(NSNumber *)fd;
1075 - (void) _readOutput:(NSNumber *)fd;
1079 - (Package *) packageWithName:(NSString *)name;
1081 - (pkgCacheFile &) cache;
1082 - (pkgDepCache::Policy *) policy;
1083 - (pkgRecords *) records;
1084 - (pkgProblemResolver *) resolver;
1085 - (pkgAcquire &) fetcher;
1086 - (pkgSourceList &) list;
1087 - (NSArray *) packages;
1088 - (NSArray *) sources;
1089 - (Source *) sourceWithKey:(NSString *)key;
1090 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1098 - (void) updateWithStatus:(CancelStatus &)status;
1100 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1102 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1103 - (NSObject<ProgressDelegate> *) progressDelegate;
1105 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1106 - (void) setFetch:(bool)fetch forURI:(const char *)uri;
1107 - (void) resetFetch;
1109 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1113 /* SourceStatus {{{ */
1114 class SourceStatus :
1118 _transient NSObject<FetchDelegate> *delegate_;
1119 _transient Database *database_;
1120 std::set<std::string> fetches_;
1123 SourceStatus(NSObject<FetchDelegate> *delegate, Database *database) :
1124 delegate_(delegate),
1129 void Set(bool fetch, const std::string &uri) {
1131 if (!fetches_.insert(uri).second)
1134 if (fetches_.erase(uri) == 0)
1138 //printf("Set(%s, %s)\n", fetch ? "true" : "false", uri.c_str());
1140 auto slash(uri.rfind('/'));
1141 if (slash != std::string::npos)
1142 [database_ setFetch:fetch forURI:uri.substr(0, slash).c_str()];
1145 _finline void Set(bool fetch, pkgAcquire::Item *item) {
1146 /*unsigned long ID(fetch ? 1 : 0);
1150 Set(fetch, item->DescURI());
1153 void Log(const char *tag, pkgAcquire::Item *item) {
1154 //printf("%s(%s) S:%u Q:%u\n", tag, item->DescURI().c_str(), item->Status, item->QueueCounter);
1157 virtual void Fetch(pkgAcquire::ItemDesc &desc) {
1158 Log("Fetch", desc.Owner);
1159 Set(true, desc.Owner);
1162 virtual void Done(pkgAcquire::ItemDesc &desc) {
1163 Log("Done", desc.Owner);
1164 Set(false, desc.Owner);
1167 virtual void Fail(pkgAcquire::ItemDesc &desc) {
1168 Log("Fail", desc.Owner);
1169 Set(false, desc.Owner);
1172 virtual bool Pulse_(pkgAcquire *Owner) {
1173 std::set<std::string> fetches;
1174 for (pkgAcquire::ItemCIterator item(Owner->ItemsBegin()); item != Owner->ItemsEnd(); ++item) {
1176 if ((*item)->QueueCounter == 0)
1178 else switch ((*item)->Status) {
1179 case pkgAcquire::Item::StatFetching:
1180 fetches.insert((*item)->DescURI());
1189 Log(fetch ? "Pulse<true>" : "Pulse<false>", *item);
1193 std::vector<std::string> stops;
1194 std::set_difference(fetches_.begin(), fetches_.end(), fetches.begin(), fetches.end(), std::back_insert_iterator<std::vector<std::string>>(stops));
1195 for (std::vector<std::string>::const_iterator stop(stops.begin()); stop != stops.end(); ++stop) {
1196 //printf("Stop(%s)\n", stop->c_str());
1200 return ![delegate_ isSourceCancelled];
1203 virtual void Stop() {
1204 pkgAcquireStatus::Stop();
1205 [database_ resetFetch];
1209 /* ProgressEvent Implementation {{{ */
1210 @implementation CydiaProgressEvent
1212 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1213 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1216 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1217 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1218 [event setPackage:package];
1222 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItemDesc:(pkgAcquire::ItemDesc &)desc {
1223 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1225 NSString *description([NSString stringWithUTF8String:desc.Description.c_str()]);
1226 NSArray *fields([description componentsSeparatedByString:@" "]);
1227 [event setItem:fields];
1229 if ([fields count] > 3) {
1230 [event setPackage:[fields objectAtIndex:2]];
1231 [event setVersion:[fields objectAtIndex:3]];
1234 [event setURL:[NSString stringWithUTF8String:desc.URI.c_str()]];
1239 + (NSArray *) _attributeKeys {
1240 return [NSArray arrayWithObjects:
1250 - (NSArray *) attributeKeys {
1251 return [[self class] _attributeKeys];
1254 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1255 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1258 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1259 if ((self = [super init]) != nil) {
1265 - (NSString *) message {
1269 - (NSString *) type {
1273 - (NSArray *) item {
1274 return (id) item_ ?: [NSNull null];
1277 - (void) setItem:(NSArray *)item {
1281 - (NSString *) package {
1282 return (id) package_ ?: [NSNull null];
1285 - (void) setPackage:(NSString *)package {
1289 - (NSString *) url {
1290 return (id) url_ ?: [NSNull null];
1293 - (void) setURL:(NSString *)url {
1297 - (void) setVersion:(NSString *)version {
1301 - (NSString *) version {
1302 return (id) version_ ?: [NSNull null];
1305 - (NSString *) compound:(NSString *)value {
1307 NSString *mode(nil); {
1308 NSString *type([self type]);
1309 if ([type isEqualToString:kCydiaProgressEventTypeError])
1310 mode = UCLocalize("ERROR");
1311 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1312 mode = UCLocalize("WARNING");
1316 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1322 - (NSString *) compoundMessage {
1323 return [self compound:[self message]];
1326 - (NSString *) compoundTitle {
1329 if (package_ == nil)
1331 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1332 title = [package name];
1336 return [self compound:title];
1342 // Cytore Definitions {{{
1343 struct PackageValue :
1346 Cytore::Offset<PackageValue> next_;
1348 uint32_t index_ : 23;
1349 uint32_t subscribed_ : 1;
1366 Cytore::Offset<PackageValue> packages_[1 << 16];
1369 static Cytore::File<MetaValue> MetaFile_;
1371 // Cytore Helper Functions {{{
1372 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1373 SplitHash nhash = { hashlittle(name, length) };
1375 PackageValue *metadata;
1377 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1378 for (;; offset = &metadata->next_) { if (offset->IsNull()) {
1379 *offset = MetaFile_.New<PackageValue>(length + 1);
1380 metadata = &MetaFile_.Get(*offset);
1382 if (metadata == NULL) {
1386 metadata = new PackageValue();
1387 memset(metadata, 0, sizeof(*metadata));
1390 memcpy(metadata->name_, name, length);
1391 metadata->name_[length] = '\0';
1392 metadata->nhash_ = nhash.u16[1];
1394 metadata = &MetaFile_.Get(*offset);
1395 if (metadata->nhash_ != nhash.u16[1])
1397 if (strncmp(metadata->name_, name, length) != 0)
1399 if (metadata->name_[length] != '\0')
1406 static void PackageImport(const void *key, const void *value, void *context) {
1407 bool &fail(*reinterpret_cast<bool *>(context));
1410 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1411 NSLog(@"failed to import package %@", key);
1415 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1416 NSDictionary *package((NSDictionary *) value);
1418 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1419 if ([subscribed boolValue] && !metadata->subscribed_)
1420 metadata->subscribed_ = true;
1422 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1423 time_t time([date timeIntervalSince1970]);
1424 if (metadata->first_ > time || metadata->first_ == 0)
1425 metadata->first_ = time;
1428 NSDate *date([package objectForKey:@"LastSeen"]);
1429 NSString *version([package objectForKey:@"LastVersion"]);
1431 if (date != nil && version != nil) {
1432 time_t time([date timeIntervalSince1970]);
1433 if (metadata->last_ < time || metadata->last_ == 0)
1434 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1435 size_t length(strlen(buffer));
1436 uint16_t vhash(hashlittle(buffer, length));
1438 size_t capped(std::min<size_t>(8, length));
1439 char *latest(buffer + length - capped);
1441 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1442 metadata->vhash_ = vhash;
1444 metadata->last_ = time;
1450 static NSDate *GetStatusDate() {
1451 return [[[NSFileManager defaultManager] attributesOfItemAtPath:@"/var/lib/dpkg/status" error:NULL] fileModificationDate];
1454 static void SaveConfig(NSObject *lock) {
1455 @synchronized (lock) {
1461 CFPreferencesSetMultiple((CFDictionaryRef) [NSDictionary dictionaryWithObjectsAndKeys:
1462 Values_, @"CydiaValues",
1463 Sections_, @"CydiaSections",
1464 (id) Sources_, @"CydiaSources",
1465 Version_, @"CydiaVersion",
1466 nil], NULL, CFSTR("com.saurik.Cydia"), kCFPreferencesCurrentUser, kCFPreferencesCurrentHost);
1468 if (!CFPreferencesAppSynchronize(CFSTR("com.saurik.Cydia")))
1469 NSLog(@"CFPreferencesAppSynchronize(com.saurik.Cydia) == false");
1471 CydiaWriteSources();
1474 /* Source Class {{{ */
1475 @interface Source : NSObject {
1477 Database *database_;
1480 CYString depiction_;
1481 CYString description_;
1487 CYString distribution_;
1493 _H<NSString> authority_;
1495 CYString defaultIcon_;
1497 _H<NSMutableDictionary> record_;
1500 std::set<std::string> fetches_;
1501 std::set<std::string> files_;
1502 _transient NSObject<SourceDelegate> *delegate_;
1505 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(CYPool *)pool;
1507 - (NSComparisonResult) compareByName:(Source *)source;
1509 - (NSString *) depictionForPackage:(NSString *)package;
1510 - (NSString *) supportForPackage:(NSString *)package;
1512 - (metaIndex *) metaIndex;
1513 - (NSDictionary *) record;
1516 - (NSString *) rooturi;
1517 - (NSString *) distribution;
1518 - (NSString *) type;
1521 - (NSString *) host;
1523 - (NSString *) name;
1524 - (NSString *) shortDescription;
1525 - (NSString *) label;
1526 - (NSString *) origin;
1527 - (NSString *) version;
1529 - (NSString *) defaultIcon;
1530 - (NSURL *) iconURL;
1532 - (void) setFetch:(bool)fetch forURI:(const char *)uri;
1533 - (void) resetFetch;
1537 @implementation Source
1539 + (NSString *) webScriptNameForSelector:(SEL)selector {
1541 else if (selector == @selector(addSection:))
1542 return @"addSection";
1543 else if (selector == @selector(getField:))
1545 else if (selector == @selector(removeSection:))
1546 return @"removeSection";
1547 else if (selector == @selector(remove))
1553 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1554 return [self webScriptNameForSelector:selector] == nil;
1557 + (NSArray *) _attributeKeys {
1558 return [NSArray arrayWithObjects:
1569 @"shortDescription",
1576 - (NSArray *) attributeKeys {
1577 return [[self class] _attributeKeys];
1580 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1581 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1584 - (metaIndex *) metaIndex {
1588 - (void) setMetaIndex:(metaIndex *)index inPool:(CYPool *)pool {
1589 trusted_ = index->IsTrusted();
1591 uri_.set(pool, index->GetURI());
1592 distribution_.set(pool, index->GetDist());
1593 type_.set(pool, index->GetType());
1595 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1596 if (dindex != NULL) {
1597 std::string file(dindex->MetaIndexURI(""));
1598 base_.set(pool, file);
1601 _profile(Source$setMetaIndex$GetIndexes)
1602 dindex->GetIndexes(&acquire, true);
1604 _profile(Source$setMetaIndex$DescURI)
1605 for (pkgAcquire::ItemIterator item(acquire.ItemsBegin()); item != acquire.ItemsEnd(); item++) {
1606 std::string file((*item)->DescURI());
1607 auto slash(file.rfind('/'));
1608 if (slash == std::string::npos)
1610 files_.insert(file.substr(0, slash));
1615 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1618 pkgTagFile tags(&fd);
1620 pkgTagSection section;
1627 {"default-icon", &defaultIcon_},
1628 {"depiction", &depiction_},
1629 {"description", &description_},
1631 {"origin", &origin_},
1632 {"support", &support_},
1633 {"version", &version_},
1636 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1637 const char *start, *end;
1639 if (section.Find(names[i].name_, start, end)) {
1640 CYString &value(*names[i].value_);
1641 value.set(pool, start, end - start);
1647 record_ = [Sources_ objectForKey:[self key]];
1649 NSURL *url([NSURL URLWithString:uri_]);
1653 host_ = [host_ lowercaseString];
1658 authority_ = [url path];
1661 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(CYPool *)pool {
1662 if ((self = [super init]) != nil) {
1663 era_ = [database era];
1664 database_ = database;
1667 _profile(Source$initWithMetaIndex$setMetaIndex)
1668 [self setMetaIndex:index inPool:pool];
1673 - (NSString *) getField:(NSString *)name {
1674 @synchronized (database_) {
1675 if ([database_ era] != era_ || index_ == NULL)
1678 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index_));
1683 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly)) {
1688 pkgTagFile tags(&fd);
1690 pkgTagSection section;
1693 const char *start, *end;
1694 if (!section.Find([name UTF8String], start, end))
1695 return (NSString *) [NSNull null];
1697 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
1700 - (NSComparisonResult) compareByName:(Source *)source {
1701 NSString *lhs = [self name];
1702 NSString *rhs = [source name];
1704 if ([lhs length] != 0 && [rhs length] != 0) {
1705 unichar lhc = [lhs characterAtIndex:0];
1706 unichar rhc = [rhs characterAtIndex:0];
1708 if (isalpha(lhc) && !isalpha(rhc))
1709 return NSOrderedAscending;
1710 else if (!isalpha(lhc) && isalpha(rhc))
1711 return NSOrderedDescending;
1714 return [lhs compare:rhs options:LaxCompareOptions_];
1717 - (NSString *) depictionForPackage:(NSString *)package {
1718 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1721 - (NSString *) supportForPackage:(NSString *)package {
1722 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1725 - (NSArray *) sections {
1726 return record_ == nil ? (id) [NSNull null] : [record_ objectForKey:@"Sections"] ?: [NSArray array];
1729 - (void) _addSection:(NSString *)section {
1732 else if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) {
1733 if (![sections containsObject:section])
1734 [sections addObject:section];
1736 [record_ setObject:[NSMutableArray arrayWithObject:section] forKey:@"Sections"];
1739 - (bool) addSection:(NSString *)section {
1743 [self performSelectorOnMainThread:@selector(_addSection:) withObject:section waitUntilDone:NO];
1747 - (void) _removeSection:(NSString *)section {
1751 if (NSMutableArray *sections = [record_ objectForKey:@"Sections"])
1752 if ([sections containsObject:section])
1753 [sections removeObject:section];
1756 - (bool) removeSection:(NSString *)section {
1760 [self performSelectorOnMainThread:@selector(_removeSection:) withObject:section waitUntilDone:NO];
1765 [Sources_ removeObjectForKey:[self key]];
1769 bool value(record_ != nil);
1770 [self performSelectorOnMainThread:@selector(_remove) withObject:nil waitUntilDone:NO];
1774 - (NSDictionary *) record {
1782 - (NSString *) rooturi {
1786 - (NSString *) distribution {
1787 return distribution_;
1790 - (NSString *) type {
1794 - (NSString *) baseuri {
1795 return base_.empty() ? nil : (id) base_;
1798 - (NSString *) iconuri {
1799 if (NSString *base = [self baseuri])
1800 return [base stringByAppendingString:@"CydiaIcon.png"];
1805 - (NSURL *) iconURL {
1806 if (NSString *uri = [self iconuri])
1807 return [NSURL URLWithString:uri];
1811 - (NSString *) key {
1812 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1815 - (NSString *) host {
1819 - (NSString *) name {
1820 return origin_.empty() ? (id) authority_ : origin_;
1823 - (NSString *) shortDescription {
1824 return description_;
1827 - (NSString *) label {
1828 return label_.empty() ? (id) authority_ : label_;
1831 - (NSString *) origin {
1835 - (NSString *) version {
1839 - (NSString *) defaultIcon {
1840 return defaultIcon_;
1843 - (void) setDelegate:(NSObject<SourceDelegate> *)delegate {
1844 delegate_ = delegate;
1848 return !fetches_.empty();
1851 - (void) setFetch:(bool)fetch forURI:(const char *)uri {
1853 if (fetches_.erase(uri) == 0)
1855 } else if (files_.find(uri) == files_.end())
1857 else if (!fetches_.insert(uri).second)
1860 [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:[self fetch]] waitUntilDone:NO];
1863 - (void) resetFetch {
1865 [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:NO];
1870 /* CydiaOperation Class {{{ */
1871 @interface CydiaOperation : NSObject {
1872 _H<NSString> operator_;
1873 _H<NSString> value_;
1876 - (NSString *) operator;
1877 - (NSString *) value;
1881 @implementation CydiaOperation
1883 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1884 if ((self = [super init]) != nil) {
1885 operator_ = [NSString stringWithUTF8String:_operator];
1886 value_ = [NSString stringWithUTF8String:value];
1890 + (NSArray *) _attributeKeys {
1891 return [NSArray arrayWithObjects:
1897 - (NSArray *) attributeKeys {
1898 return [[self class] _attributeKeys];
1901 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1902 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1905 - (NSString *) operator {
1909 - (NSString *) value {
1915 /* CydiaClause Class {{{ */
1916 @interface CydiaClause : NSObject {
1917 _H<NSString> package_;
1918 _H<CydiaOperation> version_;
1921 - (NSString *) package;
1922 - (CydiaOperation *) version;
1926 @implementation CydiaClause
1928 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1929 if ((self = [super init]) != nil) {
1930 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1932 if (const char *version = dep.TargetVer())
1933 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1935 version_ = (id) [NSNull null];
1939 + (NSArray *) _attributeKeys {
1940 return [NSArray arrayWithObjects:
1946 - (NSArray *) attributeKeys {
1947 return [[self class] _attributeKeys];
1950 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1951 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1954 - (NSString *) package {
1958 - (CydiaOperation *) version {
1964 /* CydiaRelation Class {{{ */
1965 @interface CydiaRelation : NSObject {
1966 _H<NSString> relationship_;
1967 _H<NSMutableArray> clauses_;
1970 - (NSString *) relationship;
1971 - (NSArray *) clauses;
1975 @implementation CydiaRelation
1977 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1978 if ((self = [super init]) != nil) {
1979 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
1980 clauses_ = [NSMutableArray arrayWithCapacity:8];
1982 pkgCache::DepIterator start;
1983 pkgCache::DepIterator end;
1984 dep.GlobOr(start, end); // ++dep
1987 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1989 // yes, seriously. (wtf?)
1997 + (NSArray *) _attributeKeys {
1998 return [NSArray arrayWithObjects:
2004 - (NSArray *) attributeKeys {
2005 return [[self class] _attributeKeys];
2008 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2009 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2012 - (NSString *) relationship {
2013 return relationship_;
2016 - (NSArray *) clauses {
2020 - (void) addClause:(CydiaClause *)clause {
2021 [clauses_ addObject:clause];
2026 /* Package Class {{{ */
2027 struct ParsedPackage {
2031 CYString architecture_;
2034 CYString depiction_;
2041 @interface Package : NSObject {
2043 @public uint32_t role_ : 3;
2044 uint32_t essential_ : 1;
2045 uint32_t obsolete_ : 1;
2046 uint32_t ignored_ : 1;
2047 uint32_t pooled_ : 1;
2053 _transient Database *database_;
2055 pkgCache::VerIterator version_;
2056 pkgCache::PkgIterator iterator_;
2057 pkgCache::VerFileIterator file_;
2061 CYString transform_;
2064 CYString installed_;
2067 const char *section_;
2068 _transient NSString *section$_;
2072 PackageValue *metadata_;
2073 ParsedPackage *parsed_;
2075 _H<NSMutableArray> tags_;
2078 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database;
2079 + (Package *) newPackageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database;
2081 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database;
2083 - (pkgCache::PkgIterator) iterator;
2086 - (NSString *) section;
2087 - (NSString *) simpleSection;
2089 - (NSString *) longSection;
2090 - (NSString *) shortSection;
2094 - (MIMEAddress *) maintainer;
2096 - (NSString *) longDescription;
2097 - (NSString *) shortDescription;
2100 - (PackageValue *) metadata;
2103 - (bool) subscribed;
2104 - (bool) setSubscribed:(bool)subscribed;
2108 - (NSString *) latest;
2109 - (NSString *) installed;
2110 - (BOOL) uninstalled;
2112 - (BOOL) upgradableAndEssential:(BOOL)essential;
2115 - (BOOL) unfiltered;
2119 - (BOOL) halfConfigured;
2120 - (BOOL) halfInstalled;
2122 - (NSString *) mode;
2125 - (NSString *) name;
2127 - (NSString *) homepage;
2128 - (NSString *) depiction;
2129 - (MIMEAddress *) author;
2131 - (NSString *) support;
2133 - (NSArray *) files;
2134 - (NSArray *) warnings;
2135 - (NSArray *) applications;
2137 - (Source *) source;
2140 - (BOOL) matches:(NSArray *)query;
2142 - (BOOL) hasTag:(NSString *)tag;
2143 - (NSString *) primaryPurpose;
2144 - (NSArray *) purposes;
2145 - (bool) isCommercial;
2147 - (void) setIndex:(size_t)index;
2149 - (CYString &) cyname;
2151 - (uint32_t) compareBySection:(NSArray *)sections;
2158 uint32_t PackageChangesRadix(Package *self, void *) {
2163 uint32_t timestamp : 30;
2164 uint32_t ignored : 1;
2165 uint32_t upgradable : 1;
2169 bool upgradable([self upgradableAndEssential:YES]);
2170 value.bits.upgradable = upgradable ? 1 : 0;
2173 value.bits.timestamp = 0;
2174 value.bits.ignored = [self ignored] ? 0 : 1;
2175 value.bits.upgradable = 1;
2177 value.bits.timestamp = [self seen] >> 2;
2178 value.bits.ignored = 0;
2179 value.bits.upgradable = 0;
2182 return _not(uint32_t) - value.key;
2185 CYString &(*PackageName)(Package *self, SEL sel);
2187 uint32_t PackagePrefixRadix(Package *self, void *context) {
2188 size_t offset(reinterpret_cast<size_t>(context));
2189 CYString &name(PackageName(self, @selector(cyname)));
2191 size_t size(name.size());
2194 char *text(name.data());
2197 if (!isdigit(text[0]))
2201 while (size != digits && isdigit(text[digits]))
2209 if (offset == 0 && zeros != 0) {
2210 memset(data, '0', zeros);
2211 memcpy(data + zeros, text, 4 - zeros);
2213 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2214 if (size <= offset - zeros)
2217 text += offset - zeros;
2218 size -= offset - zeros;
2221 memcpy(data, text, 4);
2223 memcpy(data, text, size);
2224 memset(data + size, 0, 4 - size);
2227 for (size_t i(0); i != 4; ++i)
2228 if (isalpha(data[i]))
2236 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2238 /* XXX: ntohl may be more honest */
2239 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2242 CFComparisonResult StringNameCompare(CFStringRef lhn, CFStringRef rhn, size_t length) {
2243 _profile(PackageNameCompare)
2245 return rhn == NULL ? kCFCompareEqualTo : kCFCompareLessThan;
2246 else if (rhn == NULL)
2247 return kCFCompareGreaterThan;
2249 CFIndex length(CFStringGetLength(lhn));
2251 _profile(PackageNameCompare$NumbersLast)
2252 if (length != 0 && CFStringGetLength(rhn) != 0) {
2253 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2254 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2255 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2256 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2257 return lha ? kCFCompareLessThan : kCFCompareGreaterThan;
2261 _profile(PackageNameCompare$Compare)
2262 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, (CFLocaleRef) (id) CollationLocale_);
2267 _finline CFComparisonResult StringNameCompare(NSString *lhn, NSString*rhn, size_t length) {
2268 return StringNameCompare((CFStringRef) lhn, (CFStringRef) rhn, length);
2271 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2272 CYString &lhn(PackageName(lhs, @selector(cyname)));
2273 NSString *rhn(PackageName(rhs, @selector(cyname)));
2274 return StringNameCompare(lhn, rhn, lhn.size());
2277 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *arg) {
2278 return PackageNameCompare(*lhs, *rhs, arg);
2281 struct PackageNameOrdering :
2282 std::binary_function<Package *, Package *, bool>
2284 _finline bool operator ()(Package *lhs, Package *rhs) const {
2285 return PackageNameCompare(lhs, rhs, NULL) == kCFCompareLessThan;
2289 @implementation Package
2291 - (NSString *) description {
2292 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2298 if (parsed_ != NULL)
2303 + (NSString *) webScriptNameForSelector:(SEL)selector {
2305 else if (selector == @selector(clear))
2307 else if (selector == @selector(getField:))
2309 else if (selector == @selector(getRecord))
2310 return @"getRecord";
2311 else if (selector == @selector(hasTag:))
2313 else if (selector == @selector(install))
2315 else if (selector == @selector(remove))
2321 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2322 return [self webScriptNameForSelector:selector] == nil;
2325 + (NSArray *) _attributeKeys {
2326 return [NSArray arrayWithObjects:
2347 @"shortDescription",
2360 - (NSArray *) attributeKeys {
2361 return [[self class] _attributeKeys];
2364 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2365 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2368 - (NSArray *) relations {
2369 @synchronized (database_) {
2370 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2371 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2372 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2376 - (NSString *) architecture {
2378 @synchronized (database_) {
2379 return parsed_->architecture_.empty() ? [NSNull null] : (id) parsed_->architecture_;
2382 - (NSString *) getField:(NSString *)name {
2383 @synchronized (database_) {
2384 if ([database_ era] != era_ || file_.end())
2387 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2389 const char *start, *end;
2390 if (!parser.Find([name UTF8String], start, end))
2391 return (NSString *) [NSNull null];
2393 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2396 - (NSString *) getRecord {
2397 @synchronized (database_) {
2398 if ([database_ era] != era_ || file_.end())
2401 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2403 const char *start, *end;
2404 parser.GetRec(start, end);
2406 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2410 if (parsed_ != NULL)
2412 @synchronized (database_) {
2413 if ([database_ era] != era_ || file_.end())
2416 ParsedPackage *parsed(new ParsedPackage);
2419 _profile(Package$parse)
2420 pkgRecords::Parser *parser;
2422 _profile(Package$parse$Lookup)
2423 parser = &[database_ records]->Lookup(file_);
2429 _profile(Package$parse$Find)
2434 {"architecture", &parsed->architecture_},
2435 {"icon", &parsed->icon_},
2436 {"depiction", &parsed->depiction_},
2437 {"homepage", &parsed->homepage_},
2438 {"website", &website},
2440 {"support", &parsed->support_},
2441 {"author", &parsed->author_},
2442 {"md5sum", &parsed->md5sum_},
2445 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2446 const char *start, *end;
2448 if (parser->Find(names[i].name_, start, end)) {
2449 CYString &value(*names[i].value_);
2450 _profile(Package$parse$Value)
2451 value.set(pool_, start, end - start);
2457 _profile(Package$parse$Tagline)
2458 parsed->tagline_.set(pool_, parser->ShortDesc());
2461 _profile(Package$parse$Retain)
2462 if (parsed->homepage_.empty())
2463 parsed->homepage_ = website;
2464 if (parsed->homepage_ == parsed->depiction_)
2465 parsed->homepage_.clear();
2466 if (parsed->support_.empty())
2467 parsed->support_ = bugs;
2472 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database {
2473 if ((self = [super init]) != nil) {
2474 _profile(Package$initWithVersion)
2476 pool_ = new CYPool();
2482 database_ = database;
2483 era_ = [database era];
2487 pkgCache::PkgIterator iterator(version_.ParentPkg());
2488 iterator_ = iterator;
2490 _profile(Package$initWithVersion$Version)
2491 file_ = version_.FileList();
2494 _profile(Package$initWithVersion$Cache)
2495 name_.set(NULL, version_.Display());
2497 latest_.set(NULL, StripVersion_(version_.VerStr()));
2499 pkgCache::VerIterator current(iterator.CurrentVer());
2501 installed_.set(NULL, StripVersion_(current.VerStr()));
2504 _profile(Package$initWithVersion$Transliterate) do {
2505 if (CollationTransl_ == NULL)
2510 _profile(Package$initWithVersion$Transliterate$utf8)
2511 const uint8_t *data(reinterpret_cast<const uint8_t *>(name_.data()));
2512 for (size_t i(0), e(name_.size()); i != e; ++i)
2513 if (data[i] >= 0x80)
2518 UErrorCode code(U_ZERO_ERROR);
2521 _profile(Package$initWithVersion$Transliterate$u_strFromUTF8WithSub)
2522 CollationString_.resize(name_.size());
2523 u_strFromUTF8WithSub(&CollationString_[0], CollationString_.size(), &length, name_.data(), name_.size(), 0xfffd, NULL, &code);
2524 if (!U_SUCCESS(code))
2526 CollationString_.resize(length);
2529 _profile(Package$initWithVersion$Transliterate$utrans_trans)
2530 length = CollationString_.size();
2531 utrans_trans(CollationTransl_, reinterpret_cast<UReplaceable *>(&CollationString_), &CollationUCalls_, 0, &length, &code);
2532 if (!U_SUCCESS(code))
2534 _assert(CollationString_.size() == length);
2537 _profile(Package$initWithVersion$Transliterate$u_strToUTF8WithSub$preflight)
2538 u_strToUTF8WithSub(NULL, 0, &length, CollationString_.data(), CollationString_.size(), 0xfffd, NULL, &code);
2539 if (code == U_BUFFER_OVERFLOW_ERROR)
2540 code = U_ZERO_ERROR;
2541 else if (!U_SUCCESS(code))
2546 _profile(Package$initWithVersion$Transliterate$apr_palloc)
2547 transform = pool_->malloc<char>(length);
2549 _profile(Package$initWithVersion$Transliterate$u_strToUTF8WithSub$transform)
2550 u_strToUTF8WithSub(transform, length, NULL, CollationString_.data(), CollationString_.size(), 0xfffd, NULL, &code);
2551 if (!U_SUCCESS(code))
2555 transform_.set(NULL, transform, length);
2556 } while (false); _end
2558 _profile(Package$initWithVersion$Tags)
2560 pkgCache::TagIterator tag(version_.TagList());
2562 pkgCache::TagIterator tag(iterator.TagList());
2565 tags_ = [NSMutableArray arrayWithCapacity:8];
2567 goto tag; for (; !tag.end(); ++tag) tag: {
2568 const char *name(tag.Name());
2569 NSString *string((NSString *) CYStringCreate(name));
2573 [tags_ addObject:[string autorelease]];
2575 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2576 if (strcmp(name + 6, "enduser") == 0)
2578 else if (strcmp(name + 6, "hacker") == 0)
2580 else if (strcmp(name + 6, "developer") == 0)
2582 else if (strcmp(name + 6, "cydia") == 0)
2588 if (strncmp(name, "cydia::", 7) == 0) {
2589 if (strcmp(name + 7, "essential") == 0)
2591 else if (strcmp(name + 7, "obsolete") == 0)
2598 _profile(Package$initWithVersion$Metadata)
2599 const char *mixed(iterator.Name());
2600 size_t size(strlen(mixed));
2601 static const size_t prefix(sizeof("/var/lib/dpkg/info/") - 1);
2602 char lower[prefix + size + 5 + 1];
2604 for (size_t i(0); i != size; ++i)
2605 lower[prefix + i] = mixed[i] | 0x20;
2607 if (!installed_.empty()) {
2608 memcpy(lower, "/var/lib/dpkg/info/", prefix);
2609 memcpy(lower + prefix + size, ".list", 6);
2611 if (stat(lower, &info) != -1)
2612 upgraded_ = info.st_birthtime;
2615 PackageValue *metadata(PackageFind(lower + prefix, size));
2616 metadata_ = metadata;
2618 id_.set(NULL, metadata->name_, size);
2620 const char *latest(version_.VerStr());
2621 size_t length(strlen(latest));
2623 uint16_t vhash(hashlittle(latest, length));
2625 size_t capped(std::min<size_t>(8, length));
2626 latest = latest + length - capped;
2628 if (metadata->first_ == 0)
2629 metadata->first_ = now_;
2631 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2632 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2633 metadata->vhash_ = vhash;
2634 metadata->last_ = now_;
2635 } else if (metadata->last_ == 0)
2636 metadata->last_ = metadata->first_;
2639 _profile(Package$initWithVersion$Section)
2640 section_ = version_.Section();
2643 _profile(Package$initWithVersion$Flags)
2644 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2645 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2650 + (Package *) newPackageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database {
2651 pkgCache::VerIterator version;
2653 _profile(Package$packageWithIterator$GetCandidateVer)
2654 version = [database policy]->GetCandidateVer(iterator);
2662 _profile(Package$packageWithIterator$Allocate)
2663 package = [Package allocWithZone:zone];
2666 _profile(Package$packageWithIterator$Initialize)
2668 initWithVersion:version
2678 // XXX: just in case a Cydia extension is using this (I bet this is unlikely, though, due to CYPool?)
2679 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database {
2680 return [[self newPackageWithIterator:iterator withZone:zone inPool:pool database:database] autorelease];
2683 - (pkgCache::PkgIterator) iterator {
2687 - (NSArray *) downgrades {
2688 NSMutableArray *versions([NSMutableArray arrayWithCapacity:4]);
2690 for (auto version(iterator_.VersionList()); !version.end(); ++version) {
2691 if (version == version_)
2693 Package *package([[[Package allocWithZone:NULL] initWithVersion:version withZone:NULL inPool:NULL database:database_] autorelease]);
2694 if ([package source] == nil)
2696 [versions addObject:package];
2702 - (NSString *) section {
2703 if (section$_ == nil) {
2704 if (section_ == NULL)
2707 _profile(Package$section$mappedSectionForPointer)
2708 section$_ = [database_ mappedSectionForPointer:section_];
2713 - (NSString *) simpleSection {
2714 if (NSString *section = [self section])
2715 return Simplify(section);
2720 - (NSString *) longSection {
2721 if (NSString *section = [self section])
2722 return LocalizeSection(section);
2727 - (NSString *) shortSection {
2728 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2731 - (NSString *) uri {
2734 pkgIndexFile *index;
2735 pkgCache::PkgFileIterator file(file_.File());
2736 if (![database_ list].FindIndex(file, index))
2738 return [NSString stringWithUTF8String:iterator_->Path];
2739 //return [NSString stringWithUTF8String:file.Site()];
2740 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2744 - (MIMEAddress *) maintainer {
2745 @synchronized (database_) {
2746 if ([database_ era] != era_ || file_.end())
2749 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2750 const std::string &maintainer(parser->Maintainer());
2751 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2754 - (NSString *) md5sum {
2755 return parsed_ == NULL ? nil : (id) parsed_->md5sum_;
2759 @synchronized (database_) {
2760 if ([database_ era] != era_ || version_.end())
2763 return version_->InstalledSize;
2766 - (NSString *) longDescription {
2767 @synchronized (database_) {
2768 if ([database_ era] != era_ || file_.end())
2771 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2772 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2774 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2775 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2776 if ([lines count] < 2)
2779 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2780 for (size_t i(1), e([lines count]); i != e; ++i) {
2781 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2782 [trimmed addObject:trim];
2785 return [trimmed componentsJoinedByString:@"\n"];
2788 - (NSString *) shortDescription {
2789 if (parsed_ != NULL)
2790 return static_cast<NSString *>(parsed_->tagline_);
2792 @synchronized (database_) {
2793 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2794 std::string value(parser.ShortDesc());
2797 if (value.size() > 200)
2799 return [(id) CYStringCreate(value) autorelease];
2803 _profile(Package$index)
2804 CFStringRef name((CFStringRef) [self name]);
2805 if (CFStringGetLength(name) == 0)
2807 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2808 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2810 return toupper(character);
2814 - (PackageValue *) metadata {
2819 PackageValue *metadata([self metadata]);
2820 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2823 - (bool) subscribed {
2824 return [self metadata]->subscribed_;
2827 - (bool) setSubscribed:(bool)subscribed {
2828 PackageValue *metadata([self metadata]);
2829 if (metadata->subscribed_ == subscribed)
2831 metadata->subscribed_ = subscribed;
2839 - (NSString *) latest {
2843 - (NSString *) installed {
2847 - (BOOL) uninstalled {
2848 return installed_.empty();
2851 - (BOOL) upgradableAndEssential:(BOOL)essential {
2852 _profile(Package$upgradableAndEssential)
2853 pkgCache::VerIterator current(iterator_.CurrentVer());
2855 return essential && essential_;
2857 return version_ != current;
2861 - (BOOL) essential {
2866 return [database_ cache][iterator_].InstBroken();
2869 - (BOOL) unfiltered {
2870 _profile(Package$unfiltered$obsolete)
2871 if (_unlikely(obsolete_))
2875 _profile(Package$unfiltered$role)
2876 if (_unlikely(role_ > 3))
2884 if (![self unfiltered])
2889 _profile(Package$visible$section)
2890 section = [self section];
2893 _profile(Package$visible$isSectionVisible)
2894 if (!isSectionVisible(section))
2902 unsigned char current(iterator_->CurrentState);
2903 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2906 - (BOOL) halfConfigured {
2907 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2910 - (BOOL) halfInstalled {
2911 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2915 @synchronized (database_) {
2916 if ([database_ era] != era_ || iterator_.end())
2919 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2920 return state.Mode != pkgDepCache::ModeKeep;
2923 - (NSString *) mode {
2924 @synchronized (database_) {
2925 if ([database_ era] != era_ || iterator_.end())
2928 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2930 switch (state.Mode) {
2931 case pkgDepCache::ModeDelete:
2932 if ((state.iFlags & pkgDepCache::Purge) != 0)
2936 case pkgDepCache::ModeKeep:
2937 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2938 return @"REINSTALL";
2939 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2943 case pkgDepCache::ModeInstall:
2944 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2945 return @"REINSTALL";
2946 else*/ switch (state.Status) {
2948 return @"DOWNGRADE";
2954 return @"NEW_INSTALL";
2965 - (NSString *) name {
2966 return name_.empty() ? id_ : name_;
2969 - (UIImage *) icon {
2970 NSString *section = [self simpleSection];
2973 if (parsed_ != NULL)
2974 if (NSString *href = parsed_->icon_)
2975 if ([href hasPrefix:@"file:///"])
2976 icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2977 if (icon == nil) if (section != nil)
2978 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]];
2979 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2980 if ([dicon hasPrefix:@"file:///"])
2981 icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2983 icon = [UIImage imageNamed:@"unknown.png"];
2987 - (NSString *) homepage {
2988 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2991 - (NSString *) depiction {
2992 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2995 - (MIMEAddress *) author {
2996 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
2999 - (NSString *) support {
3000 return parsed_ != NULL && !parsed_->support_.empty() ? parsed_->support_ : [[self source] supportForPackage:id_];
3003 - (NSArray *) files {
3004 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
3005 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
3008 fin.open([path UTF8String]);
3013 while (std::getline(fin, line))
3014 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
3019 - (NSString *) state {
3020 @synchronized (database_) {
3021 if ([database_ era] != era_ || file_.end())
3024 switch (iterator_->CurrentState) {
3025 case pkgCache::State::NotInstalled:
3026 return @"NotInstalled";
3027 case pkgCache::State::UnPacked:
3029 case pkgCache::State::HalfConfigured:
3030 return @"HalfConfigured";
3031 case pkgCache::State::HalfInstalled:
3032 return @"HalfInstalled";
3033 case pkgCache::State::ConfigFiles:
3034 return @"ConfigFiles";
3035 case pkgCache::State::Installed:
3036 return @"Installed";
3037 case pkgCache::State::TriggersAwaited:
3038 return @"TriggersAwaited";
3039 case pkgCache::State::TriggersPending:
3040 return @"TriggersPending";
3043 return (NSString *) [NSNull null];
3046 - (NSString *) selection {
3047 @synchronized (database_) {
3048 if ([database_ era] != era_ || file_.end())
3051 switch (iterator_->SelectedState) {
3052 case pkgCache::State::Unknown:
3054 case pkgCache::State::Install:
3056 case pkgCache::State::Hold:
3058 case pkgCache::State::DeInstall:
3059 return @"DeInstall";
3060 case pkgCache::State::Purge:
3064 return (NSString *) [NSNull null];
3067 - (NSArray *) warnings {
3068 @synchronized (database_) {
3069 if ([database_ era] != era_ || file_.end())
3072 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
3073 const char *name(iterator_.Name());
3075 size_t length(strlen(name));
3076 if (length < 2) invalid:
3077 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
3078 else for (size_t i(0); i != length; ++i)
3080 /* XXX: technically this is not allowed */
3081 (name[i] < 'A' || name[i] > 'Z') &&
3082 (name[i] < 'a' || name[i] > 'z') &&
3083 (name[i] < '0' || name[i] > '9') &&
3084 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
3087 if (strcmp(name, "cydia") != 0) {
3090 bool _private = false;
3092 bool dbstash = false;
3093 bool dsstore = false;
3095 bool repository = [[self section] isEqualToString:@"Repositories"];
3097 if (NSArray *files = [self files])
3098 for (NSString *file in files)
3099 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
3101 else if (!user && [file isEqualToString:@"/User"])
3103 else if (!_private && [file isEqualToString:@"/private"])
3105 else if (!stash && [file isEqualToString:@"/var/stash"])
3107 else if (!dbstash && [file isEqualToString:@"/var/db/stash"])
3109 else if (!dsstore && [file hasSuffix:@"/.DS_Store"])
3112 /* XXX: this is not sensitive enough. only some folders are valid. */
3113 if (cydia && !repository)
3114 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
3116 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
3118 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
3120 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
3122 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/db/stash"]];
3124 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @".DS_Store"]];
3127 return [warnings count] == 0 ? nil : warnings;
3130 - (NSArray *) applications {
3131 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
3133 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
3135 static RegEx application_r("/Applications/(.*)\\.app/Info.plist");
3136 if (NSArray *files = [self files])
3137 for (NSString *file in files)
3138 if (application_r(file)) {
3139 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
3142 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
3143 if (id == nil || [id isEqualToString:me])
3146 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
3148 display = application_r[1];
3150 NSString *bundle([file stringByDeletingLastPathComponent]);
3151 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
3152 // XXX: maybe this should check if this is really a string, not just for length
3153 if (icon == nil || ![icon respondsToSelector:@selector(length)] || [icon length] == 0)
3155 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
3157 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
3158 [applications addObject:application];
3160 [application addObject:id];
3161 [application addObject:display];
3162 [application addObject:url];
3165 return [applications count] == 0 ? nil : applications;
3168 - (Source *) source {
3169 if (source_ == nil) {
3170 @synchronized (database_) {
3171 if ([database_ era] != era_ || file_.end())
3172 source_ = (Source *) [NSNull null];
3174 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
3178 return source_ == (Source *) [NSNull null] ? nil : source_;
3181 - (time_t) upgraded {
3185 - (uint32_t) recent {
3186 return std::numeric_limits<uint32_t>::max() - upgraded_;
3193 - (BOOL) matches:(NSArray *)query {
3194 if (query == nil || [query count] == 0)
3203 string = [self name];
3204 length = [string length];
3207 for (NSString *term in query) {
3208 range = [string rangeOfString:term options:MatchCompareOptions_];
3209 if (range.location != NSNotFound)
3210 rank_ -= 6 * 1000000 / length;
3215 length = [string length];
3218 for (NSString *term in query) {
3219 range = [string rangeOfString:term options:MatchCompareOptions_];
3220 if (range.location != NSNotFound)
3221 rank_ -= 6 * 1000000 / length;
3225 string = [self shortDescription];
3226 length = [string length];
3227 NSUInteger stop(std::min<NSUInteger>(length, 200));
3230 for (NSString *term in query) {
3231 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
3232 if (range.location != NSNotFound)
3233 rank_ -= 2 * 100000;
3239 - (NSArray *) tags {
3243 - (BOOL) hasTag:(NSString *)tag {
3244 return tags_ == nil ? NO : [tags_ containsObject:tag];
3247 - (NSString *) primaryPurpose {
3248 for (NSString *tag in (NSArray *) tags_)
3249 if ([tag hasPrefix:@"purpose::"])
3250 return [tag substringFromIndex:9];
3254 - (NSArray *) purposes {
3255 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
3256 for (NSString *tag in (NSArray *) tags_)
3257 if ([tag hasPrefix:@"purpose::"])
3258 [purposes addObject:[tag substringFromIndex:9]];
3259 return [purposes count] == 0 ? nil : purposes;
3262 - (bool) isCommercial {
3263 return [self hasTag:@"cydia::commercial"];
3266 - (void) setIndex:(size_t)index {
3267 if (metadata_->index_ != index + 1)
3268 metadata_->index_ = index + 1;
3271 - (CYString &) cyname {
3272 return !transform_.empty() ? transform_ : !name_.empty() ? name_ : id_;
3275 - (uint32_t) compareBySection:(NSArray *)sections {
3276 NSString *section([self section]);
3277 for (size_t i(0), e([sections count]); i != e; ++i) {
3278 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3282 return _not(uint32_t);
3286 @synchronized (database_) {
3287 if ([database_ era] != era_ || file_.end())
3290 pkgProblemResolver *resolver = [database_ resolver];
3291 resolver->Clear(iterator_);
3293 pkgCacheFile &cache([database_ cache]);
3294 cache->SetReInstall(iterator_, false);
3295 cache->MarkKeep(iterator_, false);
3299 @synchronized (database_) {
3300 if ([database_ era] != era_ || file_.end())
3303 pkgProblemResolver *resolver = [database_ resolver];
3304 resolver->Clear(iterator_);
3305 resolver->Protect(iterator_);
3307 pkgCacheFile &cache([database_ cache]);
3308 cache->SetCandidateVersion(version_);
3309 cache->SetReInstall(iterator_, false);
3310 cache->MarkInstall(iterator_, false);
3312 pkgDepCache::StateCache &state((*cache)[iterator_]);
3313 if (!state.Install())
3314 cache->SetReInstall(iterator_, true);
3318 @synchronized (database_) {
3319 if ([database_ era] != era_ || file_.end())
3322 pkgProblemResolver *resolver = [database_ resolver];
3323 resolver->Clear(iterator_);
3324 resolver->Remove(iterator_);
3325 resolver->Protect(iterator_);
3327 pkgCacheFile &cache([database_ cache]);
3328 cache->SetReInstall(iterator_, false);
3329 cache->MarkDelete(iterator_, true);
3334 /* Section Class {{{ */
3335 @interface Section : NSObject {
3339 _H<NSString> localized_;
3342 - (NSComparisonResult) compareByLocalized:(Section *)section;
3343 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3344 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3345 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3347 - (NSString *) name;
3348 - (void) setName:(NSString *)name;
3354 - (void) addToCount;
3356 - (void) setCount:(size_t)count;
3357 - (NSString *) localized;
3361 @implementation Section
3363 - (NSComparisonResult) compareByLocalized:(Section *)section {
3364 NSString *lhs(localized_);
3365 NSString *rhs([section localized]);
3367 /*if ([lhs length] != 0 && [rhs length] != 0) {
3368 unichar lhc = [lhs characterAtIndex:0];
3369 unichar rhc = [rhs characterAtIndex:0];
3371 if (isalpha(lhc) && !isalpha(rhc))
3372 return NSOrderedAscending;
3373 else if (!isalpha(lhc) && isalpha(rhc))
3374 return NSOrderedDescending;
3377 return [lhs compare:rhs options:LaxCompareOptions_];
3380 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3381 if ((self = [self initWithName:name localize:NO]) != nil) {
3382 if (localized != nil)
3383 localized_ = localized;
3387 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3388 return [self initWithName:name row:0 localize:localize];
3391 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3392 if ((self = [super init]) != nil) {
3396 localized_ = LocalizeSection(name_);
3400 - (NSString *) name {
3404 - (void) setName:(NSString *)name {
3420 - (void) addToCount {
3424 - (void) setCount:(size_t)count {
3428 - (NSString *) localized {
3435 class CydiaLogCleaner :
3436 public pkgArchiveCleaner
3439 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3444 /* Database Implementation {{{ */
3445 @implementation Database
3447 + (Database *) sharedInstance {
3448 static _H<Database> instance;
3449 if (instance == nil)
3450 instance = [[[Database alloc] init] autorelease];
3458 - (void) releasePackages {
3462 - (bool) hasPackages {
3463 return [packages_ count] != 0;
3467 // XXX: actually implement this thing
3469 [self releasePackages];
3470 NSRecycleZone(zone_);
3474 - (void) _readCydia:(NSNumber *)fd {
3475 boost::fdistream is([fd intValue]);
3478 static RegEx finish_r("finish:([^:]*)");
3480 while (std::getline(is, line)) {
3481 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3483 const char *data(line.c_str());
3484 size_t size = line.size();
3485 lprintf("C:%s\n", data);
3487 if (finish_r(data, size)) {
3488 NSString *finish = finish_r[1];
3489 int index = [Finishes_ indexOfObject:finish];
3490 if (index != INT_MAX && index > Finish_)
3500 - (void) _readStatus:(NSNumber *)fd {
3501 boost::fdistream is([fd intValue]);
3504 static RegEx conffile_r("status: [^ ]* : conffile-prompt : (.*?) *");
3505 static RegEx pmstatus_r("([^:]*):([^:]*):([^:]*):(.*)");
3507 while (std::getline(is, line)) {
3508 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3510 const char *data(line.c_str());
3511 size_t size(line.size());
3512 lprintf("S:%s\n", data);
3514 if (conffile_r(data, size)) {
3515 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3516 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3517 } else if (strncmp(data, "status: ", 8) == 0) {
3518 // status: <package>: {unpacked,half-configured,installed}
3519 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3520 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3521 } else if (strncmp(data, "processing: ", 12) == 0) {
3522 // processing: configure: config-test
3523 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3524 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3525 } else if (pmstatus_r(data, size)) {
3526 std::string type([pmstatus_r[1] UTF8String]);
3528 NSString *package = pmstatus_r[2];
3529 if ([package isEqualToString:@"dpkg-exec"])
3532 float percent([pmstatus_r[3] floatValue]);
3533 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3535 NSString *string = pmstatus_r[4];
3537 if (type == "pmerror") {
3538 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3539 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3540 } else if (type == "pmstatus") {
3541 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3542 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3543 } else if (type == "pmconffile")
3544 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3546 lprintf("E:unknown pmstatus\n");
3548 lprintf("E:unknown status\n");
3556 - (void) _readOutput:(NSNumber *)fd {
3557 boost::fdistream is([fd intValue]);
3560 while (std::getline(is, line)) {
3561 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3563 lprintf("O:%s\n", line.c_str());
3565 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3566 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3578 - (Package *) packageWithName:(NSString *)name {
3581 @synchronized (self) {
3582 if (static_cast<pkgDepCache *>(cache_) == NULL)
3584 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]
3589 return iterator.end() ? nil : [[Package newPackageWithIterator:iterator withZone:NULL inPool:NULL database:self] autorelease];
3593 if ((self = [super init]) != nil) {
3600 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3602 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3606 _assert(pipe(fds) != -1);
3609 _config->Set("APT::Keep-Fds::", cydiafd_);
3610 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3613 detachNewThreadSelector:@selector(_readCydia:)
3615 withObject:[NSNumber numberWithInt:fds[0]]
3618 _assert(pipe(fds) != -1);
3622 detachNewThreadSelector:@selector(_readStatus:)
3624 withObject:[NSNumber numberWithInt:fds[0]]
3627 _assert(pipe(fds) != -1);
3628 _assert(dup2(fds[0], 0) != -1);
3629 _assert(close(fds[0]) != -1);
3631 input_ = fdopen(fds[1], "a");
3633 _assert(pipe(fds) != -1);
3634 _assert(dup2(fds[1], 1) != -1);
3635 _assert(close(fds[1]) != -1);
3638 detachNewThreadSelector:@selector(_readOutput:)
3640 withObject:[NSNumber numberWithInt:fds[0]]
3645 - (pkgCacheFile &) cache {
3649 - (pkgDepCache::Policy *) policy {
3653 - (pkgRecords *) records {
3657 - (pkgProblemResolver *) resolver {
3661 - (pkgAcquire &) fetcher {
3665 - (pkgSourceList &) list {
3669 - (NSArray *) packages {
3673 - (NSArray *) sources {
3677 - (Source *) sourceWithKey:(NSString *)key {
3678 for (Source *source in [self sources]) {
3679 if ([[source key] isEqualToString:key])
3684 - (bool) popErrorWithTitle:(NSString *)title {
3687 while (!_error->empty()) {
3689 bool warning(!_error->PopMessage(error));
3694 size_t size(error.size());
3695 if (size == 0 || error[size - 1] != '\n')
3697 error.resize(size - 1);
3700 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3702 static RegEx no_pubkey("GPG error:.* NO_PUBKEY .*");
3703 if (warning && no_pubkey(error.c_str()))
3706 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3712 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3713 return [self popErrorWithTitle:title] || !success;
3716 - (bool) popErrorWithTitle:(NSString *)title forReadList:(pkgSourceList &)list {
3717 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3725 if (access("/etc/apt/sources.list", F_OK) == 0)
3726 error |= [self popErrorWithTitle:title forOperation:list.ReadAppend("/etc/apt/sources.list")];
3728 std::string base("/etc/apt/sources.list.d");
3729 if (DIR *sources = opendir(base.c_str())) {
3730 while (dirent *source = readdir(sources))
3731 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)
3732 error |= [self popErrorWithTitle:title forOperation:list.ReadAppend((base + "/" + source->d_name).c_str())];
3736 error |= [self popErrorWithTitle:title forOperation:list.ReadAppend(SOURCES_LIST)];
3741 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3742 @synchronized (self) {
3745 [self releasePackages];
3748 [sourceList_ removeAllObjects];
3769 new (&pool_) CYPool();
3771 NSRecycleZone(zone_);
3772 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3774 int chk(creat("/tmp/cydia.chk", 0644));
3778 if (invocation != nil)
3779 [invocation invoke];
3781 NSString *title(UCLocalize("DATABASE"));
3783 list_ = new pkgSourceList();
3784 _profile(reloadDataWithInvocation$ReadMainList)
3785 if ([self popErrorWithTitle:title forReadList:*list_])
3789 _profile(reloadDataWithInvocation$Source$initWithMetaIndex)
3790 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3791 Source *object([[[Source alloc] initWithMetaIndex:*source forDatabase:self inPool:&pool_] autorelease]);
3792 [sourceList_ addObject:object];
3797 OpProgress progress;
3800 delock_ = GetStatusDate();
3801 _profile(reloadDataWithInvocation$pkgCacheFile)
3802 opened = cache_.Open(progress, false);
3805 // XXX: this block should probably be merged with popError: in some way
3806 while (!_error->empty()) {
3808 bool warning(!_error->PopMessage(error));
3810 lprintf("cache_.Open():[%s]\n", error.c_str());
3812 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3816 else if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3817 repair = @selector(configure);
3818 //else if (error == "The package lists or status file could not be parsed or opened.")
3819 // repair = @selector(update);
3820 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3821 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3822 // else if (error == "Malformed Status line")
3823 // else if (error == "The list of sources could not be read.")
3825 if (repair != NULL) {
3827 [delegate_ repairWithSelector:repair];
3833 } else if ([self popErrorWithTitle:title forOperation:true])
3837 unlink("/tmp/cydia.chk");
3839 now_ = [[NSDate date] timeIntervalSince1970];
3841 policy_ = new pkgDepCache::Policy();
3842 records_ = new pkgRecords(cache_);
3843 resolver_ = new pkgProblemResolver(cache_);
3844 fetcher_ = new pkgAcquire(&status_);
3847 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3848 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3852 _profile(reloadDataWithInvocation$pkgApplyStatus)
3853 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3857 if (cache_->BrokenCount() != 0) {
3858 _profile(pkgApplyStatus$pkgFixBroken)
3859 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3863 if (cache_->BrokenCount() != 0) {
3864 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3868 _profile(pkgApplyStatus$pkgMinimizeUpgrade)
3869 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3874 for (Source *object in (id) sourceList_) {
3875 metaIndex *source([object metaIndex]);
3876 std::vector<pkgIndexFile *> *indices = source->GetIndexFiles();
3877 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3878 // XXX: this could be more intelligent
3879 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3880 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3882 sourceMap_[cached->ID] = object;
3887 size_t capacity(MetaFile_->active_);
3889 capacity = 128*1024;
3893 std::vector<Package *> packages;
3894 packages.reserve(capacity);
3898 _profile(reloadDataWithInvocation$packageWithIterator)
3899 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3900 if (Package *package = [Package newPackageWithIterator:iterator withZone:zone_ inPool:&pool_ database:self]) {
3901 if (unsigned index = package.metadata->index_) {
3903 if (packages.size() == index) {
3904 packages.push_back(package);
3905 } else if (packages.size() <= index) {
3906 packages.resize(index + 1, nil);
3907 packages[index] = package;
3910 std::swap(package, packages[index]);
3911 if (package != nil) {
3912 if (package.metadata->index_ == index + 1)
3921 lost: if (last == packages.size())
3922 packages.push_back(package);
3924 packages[last] = package;
3928 for (; last != packages.size(); ++last)
3929 if (packages[last] == nil)
3934 for (size_t next(last + 1); last != packages.size(); ++last, ++next) {
3936 if (next == packages.size())
3938 if (packages[next] != nil)
3943 std::swap(packages[last], packages[next]);
3946 packages.resize(last);
3949 NSLog(@"lost = %zu", lost);
3951 _profile(reloadDataWithInvocation$radix$8)
3952 CYRadixSortUsingFunction(packages.data(), packages.size(), reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix), reinterpret_cast<void *>(8));
3955 _profile(reloadDataWithInvocation$radix$4)
3956 CYRadixSortUsingFunction(packages.data(), packages.size(), reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix), reinterpret_cast<void *>(4));
3959 _profile(reloadDataWithInvocation$radix$0)
3960 CYRadixSortUsingFunction(packages.data(), packages.size(), reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix), reinterpret_cast<void *>(0));
3964 _profile(reloadDataWithInvocation$insertion)
3965 CYArrayInsertionSortValues(packages.data(), packages.size(), &PackageNameCompare, NULL);
3968 packages_ = [[[NSArray alloc] initWithObjects:packages.data() count:packages.size()] autorelease];
3970 /*_profile(reloadDataWithInvocation$CFQSortArray)
3971 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);
3974 /*_profile(reloadDataWithInvocation$stdsort)
3975 std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3978 /*_profile(reloadDataWithInvocation$CFArraySortValues)
3979 CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3982 /*_profile(reloadDataWithInvocation$sortUsingFunction)
3983 [packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3986 MetaFile_->active_ = packages.size();
3987 for (size_t index(0), count(packages.size()); index != count; ++index) {
3988 auto package(packages[index]);
3989 [package setIndex:index];
3996 @synchronized (self) {
3998 resolver_ = new pkgProblemResolver(cache_);
4000 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
4001 if (!cache_[iterator].Keep())
4002 cache_->MarkKeep(iterator, false);
4003 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
4004 cache_->SetReInstall(iterator, false);
4007 - (void) configure {
4008 NSString *dpkg = [NSString stringWithFormat:@"/usr/libexec/cydo --configure -a --status-fd %u", statusfd_];
4010 system([dpkg UTF8String]);
4015 @synchronized (self) {
4016 // XXX: I don't remember this condition
4021 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
4023 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
4025 if ([self popErrorWithTitle:title])
4029 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
4031 CydiaLogCleaner cleaner;
4032 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
4039 fetcher_->Shutdown();
4041 pkgRecords records(cache_);
4043 lock_ = new FileFd();
4044 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
4046 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
4048 if ([self popErrorWithTitle:title])
4052 if ([self popErrorWithTitle:title forReadList:list])
4055 manager_ = (_system->CreatePM(cache_));
4056 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
4063 bool substrate(RestartSubstrate_);
4064 RestartSubstrate_ = false;
4066 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
4068 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
4070 if ([self popErrorWithTitle:title forReadList:list])
4072 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
4073 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
4076 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4078 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
4080 [self popErrorWithTitle:title];
4084 bool failed = false;
4085 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
4086 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
4088 if ((*item)->Status == pkgAcquire::Item::StatIdle)
4091 std::string uri = (*item)->DescURI();
4092 std::string error = (*item)->ErrorText;
4094 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
4097 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError]);
4098 [delegate_ addProgressEventOnMainThread:event forTask:title];
4101 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4109 RestartSubstrate_ = true;
4111 if (![delock_ isEqual:GetStatusDate()]) {
4112 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("DPKG_LOCKED") ofType:kCydiaProgressEventTypeError] forTask:title];
4118 pkgPackageManager::OrderResult result(manager_->DoInstall(statusfd_));
4120 NSString *oextended(@"/var/lib/apt/extended_states");
4121 NSString *nextended(Cache("extended_states"));
4124 if (stat([nextended UTF8String], &info) != -1 && (info.st_mode & S_IFMT) == S_IFREG)
4125 system([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /bin/cp --remove-destination %@ %@", ShellEscape(nextended), ShellEscape(oextended)] UTF8String]);
4127 unlink([nextended UTF8String]);
4128 symlink([oextended UTF8String], [nextended UTF8String]);
4130 if ([self popErrorWithTitle:title])
4133 if (result == pkgPackageManager::Failed) {
4138 if (result != pkgPackageManager::Completed) {
4143 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
4145 if ([self popErrorWithTitle:title forReadList:list])
4147 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
4148 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
4151 if (![before isEqualToArray:after])
4156 return ![delock_ isEqual:GetStatusDate()];
4160 NSString *title(UCLocalize("UPGRADE"));
4161 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
4167 [self updateWithStatus:status_];
4170 - (void) updateWithStatus:(CancelStatus &)status {
4171 NSString *title(UCLocalize("REFRESHING_DATA"));
4174 if ([self popErrorWithTitle:title forReadList:list])
4178 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
4179 if ([self popErrorWithTitle:title])
4182 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4184 bool success(ListUpdate(status, list, PulseInterval_));
4185 if (status.WasCancelled())
4188 [self popErrorWithTitle:title forOperation:success];
4190 [[NSDictionary dictionaryWithObjectsAndKeys:
4191 [NSDate date], @"LastUpdate",
4192 nil] writeToFile:@ CacheState_ atomically:YES];
4195 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4198 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
4199 delegate_ = delegate;
4202 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
4203 progress_ = delegate;
4204 status_.setDelegate(delegate);
4207 - (NSObject<ProgressDelegate> *) progressDelegate {
4211 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
4212 SourceMap::const_iterator i(sourceMap_.find(file->ID));
4213 return i == sourceMap_.end() ? nil : i->second;
4216 - (void) setFetch:(bool)fetch forURI:(const char *)uri {
4217 for (Source *source in (id) sourceList_)
4218 [source setFetch:fetch forURI:uri];
4221 - (void) resetFetch {
4222 for (Source *source in (id) sourceList_)
4223 [source resetFetch];
4226 - (NSString *) mappedSectionForPointer:(const char *)section {
4227 _H<NSString> *mapped;
4229 _profile(Database$mappedSectionForPointer$Cache)
4230 mapped = §ions_[section];
4233 if (*mapped == NULL) {
4234 size_t length(strlen(section));
4235 char spaced[length + 1];
4237 _profile(Database$mappedSectionForPointer$Replace)
4238 for (size_t index(0); index != length; ++index)
4239 spaced[index] = section[index] == '_' ? ' ' : section[index];
4240 spaced[length] = '\0';
4245 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
4246 string = [NSString stringWithUTF8String:spaced];
4249 _profile(Database$mappedSectionForPointer$Map)
4250 string = [SectionMap_ objectForKey:string] ?: string;
4260 static _H<NSMutableSet> Diversions_;
4262 @interface Diversion : NSObject {
4265 _H<NSString> format_;
4270 @implementation Diversion
4272 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
4273 if ((self = [super init]) != nil) {
4274 pattern_ = [from UTF8String];
4280 - (NSString *) divert:(NSString *)url {
4281 return !pattern_(url) ? nil : pattern_->*format_;
4284 + (NSURL *) divertURL:(NSURL *)url {
4286 NSString *href([url absoluteString]);
4288 for (Diversion *diversion in (id) Diversions_)
4289 if (NSString *diverted = [diversion divert:href]) {
4291 NSLog(@"div: %@", diverted);
4293 url = [NSURL URLWithString:diverted];
4300 - (NSString *) key {
4304 - (NSUInteger) hash {
4308 - (BOOL) isEqual:(Diversion *)object {
4309 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
4314 @interface CydiaObject : NSObject {
4315 _H<CyteWebViewController> indirect_;
4316 _transient id delegate_;
4319 - (id) initWithDelegate:(CyteWebViewController *)indirect;
4325 @interface CydiaWebViewController : CyteWebViewController {
4326 _H<CydiaObject> cydia_;
4329 + (void) addDiversion:(Diversion *)diversion;
4330 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request;
4331 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia;
4332 - (void) setDelegate:(id)delegate;
4336 /* Web Scripting {{{ */
4337 @implementation CydiaObject
4339 - (id) initWithDelegate:(CyteWebViewController *)indirect {
4340 if ((self = [super init]) != nil) {
4341 indirect_ = indirect;
4345 - (void) setDelegate:(id)delegate {
4346 delegate_ = delegate;
4349 + (NSArray *) _attributeKeys {
4350 return [NSArray arrayWithObjects:
4355 @"coreFoundationVersionNumber",
4371 - (NSArray *) attributeKeys {
4372 return [[self class] _attributeKeys];
4375 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4376 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4379 - (NSString *) version {
4383 - (unsigned) bittage {
4385 #elif defined(__arm64__)
4387 #elif defined(__arm__)
4394 - (NSString *) build {
4398 - (NSString *) coreFoundationVersionNumber {
4399 return [NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber];
4402 - (NSString *) device {
4403 return UniqueIdentifier();
4406 - (NSString *) firmware {
4407 return [[UIDevice currentDevice] systemVersion];
4410 - (NSString *) hostname {
4411 return [[UIDevice currentDevice] name];
4414 - (NSString *) idiom {
4415 return (id) Idiom_ ?: [NSNull null];
4418 - (NSArray *) cells {
4419 auto *$_CTServerConnectionCreate(reinterpret_cast<id (*)(void *, void *, void *)>(dlsym(RTLD_DEFAULT, "_CTServerConnectionCreate")));
4420 if ($_CTServerConnectionCreate == NULL)
4423 struct CTResult { int flag; int error; };
4424 auto *$_CTServerConnectionCellMonitorCopyCellInfo(reinterpret_cast<CTResult (*)(CFTypeRef, void *, CFArrayRef *)>(dlsym(RTLD_DEFAULT, "_CTServerConnectionCellMonitorCopyCellInfo")));
4425 if ($_CTServerConnectionCellMonitorCopyCellInfo == NULL)
4428 _H<const void> connection($_CTServerConnectionCreate(NULL, NULL, NULL), true);
4429 if (connection == nil)
4433 CFArrayRef cells(NULL);
4434 auto result($_CTServerConnectionCellMonitorCopyCellInfo(connection, &count, &cells));
4435 if (result.flag != 0)
4438 return [(NSArray *) cells autorelease];
4441 - (NSString *) mcc {
4442 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode")))
4443 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault) autorelease];
4447 - (NSString *) mnc {
4448 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberNetworkCode")))
4449 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault) autorelease];
4453 - (NSString *) operator {
4454 if (CFStringRef (*$CTRegistrationCopyOperatorName)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTRegistrationCopyOperatorName")))
4455 return [(NSString *) (*$CTRegistrationCopyOperatorName)(kCFAllocatorDefault) autorelease];
4459 - (NSString *) bbsnum {
4460 return (id) BBSNum_ ?: [NSNull null];
4463 - (NSString *) ecid {
4464 return (id) ChipID_ ?: [NSNull null];
4467 - (NSString *) serial {
4468 return SerialNumber_;
4471 - (NSString *) role {
4472 return (id) [NSNull null];
4475 - (NSString *) model {
4476 return [NSString stringWithUTF8String:Machine_];
4479 + (NSString *) webScriptNameForSelector:(SEL)selector {
4481 else if (selector == @selector(addBridgedHost:))
4482 return @"addBridgedHost";
4483 else if (selector == @selector(addInsecureHost:))
4484 return @"addInsecureHost";
4485 else if (selector == @selector(addInternalRedirect::))
4486 return @"addInternalRedirect";
4487 else if (selector == @selector(addSource:::))
4488 return @"addSource";
4489 else if (selector == @selector(addTrivialSource:))
4490 return @"addTrivialSource";
4491 else if (selector == @selector(close))
4493 else if (selector == @selector(du:))
4495 else if (selector == @selector(stringWithFormat:arguments:))
4497 else if (selector == @selector(getAllSources))
4498 return @"getAllSources";
4499 else if (selector == @selector(getApplicationInfo:value:))
4500 return @"getApplicationInfoValue";
4501 else if (selector == @selector(getDisplayIdentifiers))
4502 return @"getDisplayIdentifiers";
4503 else if (selector == @selector(getLocalizedNameForDisplayIdentifier:))
4504 return @"getLocalizedNameForDisplayIdentifier";
4505 else if (selector == @selector(getKernelNumber:))
4506 return @"getKernelNumber";
4507 else if (selector == @selector(getKernelString:))
4508 return @"getKernelString";
4509 else if (selector == @selector(getInstalledPackages))
4510 return @"getInstalledPackages";
4511 else if (selector == @selector(getIORegistryEntry::))
4512 return @"getIORegistryEntry";
4513 else if (selector == @selector(getLocaleIdentifier))
4514 return @"getLocaleIdentifier";
4515 else if (selector == @selector(getPreferredLanguages))
4516 return @"getPreferredLanguages";
4517 else if (selector == @selector(getPackageById:))
4518 return @"getPackageById";
4519 else if (selector == @selector(getMetadataKeys))
4520 return @"getMetadataKeys";
4521 else if (selector == @selector(getMetadataValue:))
4522 return @"getMetadataValue";
4523 else if (selector == @selector(getSessionValue:))
4524 return @"getSessionValue";
4525 else if (selector == @selector(installPackages:))
4526 return @"installPackages";
4527 else if (selector == @selector(isReachable:))
4528 return @"isReachable";
4529 else if (selector == @selector(localizedStringForKey:value:table:))
4531 else if (selector == @selector(popViewController:))
4532 return @"popViewController";
4533 else if (selector == @selector(refreshSources))
4534 return @"refreshSources";
4535 else if (selector == @selector(registerFrame:))
4536 return @"registerFrame";
4537 else if (selector == @selector(removeButton))
4538 return @"removeButton";
4539 else if (selector == @selector(saveConfig))
4540 return @"saveConfig";
4541 else if (selector == @selector(setMetadataValue::))
4542 return @"setMetadataValue";
4543 else if (selector == @selector(setSessionValue::))
4544 return @"setSessionValue";
4545 else if (selector == @selector(substitutePackageNames:))
4546 return @"substitutePackageNames";
4547 else if (selector == @selector(scrollToBottom:))
4548 return @"scrollToBottom";
4549 else if (selector == @selector(setAllowsNavigationAction:))
4550 return @"setAllowsNavigationAction";
4551 else if (selector == @selector(setBadgeValue:))
4552 return @"setBadgeValue";
4553 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4554 return @"setButtonImage";
4555 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4556 return @"setButtonTitle";
4557 else if (selector == @selector(setHidesBackButton:))
4558 return @"setHidesBackButton";
4559 else if (selector == @selector(setHidesNavigationBar:))
4560 return @"setHidesNavigationBar";
4561 else if (selector == @selector(setNavigationBarStyle:))
4562 return @"setNavigationBarStyle";
4563 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4564 return @"setNavigationBarTintColor";
4565 else if (selector == @selector(setPasteboardString:))
4566 return @"setPasteboardString";
4567 else if (selector == @selector(setPasteboardURL:))
4568 return @"setPasteboardURL";
4569 else if (selector == @selector(setScrollAlwaysBounceVertical:))
4570 return @"setScrollAlwaysBounceVertical";
4571 else if (selector == @selector(setScrollIndicatorStyle:))
4572 return @"setScrollIndicatorStyle";
4573 else if (selector == @selector(setToken:))
4575 else if (selector == @selector(setViewportWidth:))
4576 return @"setViewportWidth";
4577 else if (selector == @selector(statfs:))
4579 else if (selector == @selector(supports:))
4581 else if (selector == @selector(unload))
4587 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4588 return [self webScriptNameForSelector:selector] == nil;
4591 - (BOOL) supports:(NSString *)feature {
4592 return [feature isEqualToString:@"window.open"];
4596 [[indirect_ rootViewController] performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4599 - (void) setScrollAlwaysBounceVertical:(NSNumber *)value {
4600 [indirect_ performSelectorOnMainThread:@selector(setScrollAlwaysBounceVerticalNumber:) withObject:value waitUntilDone:NO];
4603 - (void) setScrollIndicatorStyle:(NSString *)style {
4604 [indirect_ performSelectorOnMainThread:@selector(setScrollIndicatorStyleWithName:) withObject:style waitUntilDone:NO];
4607 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4608 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4611 - (NSDictionary *) getApplicationInfo:(NSString *)display value:(NSString *)key {
4613 if (SBBundlePathForDisplayIdentifier(SBSSpringBoardServerPort(), [display UTF8String], path) != 0)
4614 return (id) [NSNull null];
4615 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:[[NSString stringWithUTF8String:path] stringByAppendingString:@"/Info.plist"]]);
4617 return (id) [NSNull null];
4618 return [info objectForKey:key];
4621 - (NSArray *) getDisplayIdentifiers {
4622 return SBSCopyApplicationDisplayIdentifiers(false, false);
4625 - (NSString *) getLocalizedNameForDisplayIdentifier:(NSString *)identifier {
4626 return [SBSCopyLocalizedApplicationNameForDisplayIdentifier(identifier) autorelease] ?: (id) [NSNull null];
4629 - (NSNumber *) getKernelNumber:(NSString *)name {
4630 const char *string([name UTF8String]);
4633 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4634 return (id) [NSNull null];
4636 if (size != sizeof(int))
4637 return (id) [NSNull null];
4640 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4641 return (id) [NSNull null];
4643 return [NSNumber numberWithInt:value];
4646 - (NSString *) getKernelString:(NSString *)name {
4647 const char *string([name UTF8String]);
4650 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4651 return (id) [NSNull null];
4653 char value[size + 1];
4654 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4655 return (id) [NSNull null];
4657 // XXX: just in case you request something ludicrous
4660 return [NSString stringWithCString:value];
4663 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4664 NSObject *value(CYIOGetValue([path UTF8String], entry));
4667 if ([value isKindOfClass:[NSData class]])
4668 value = CYHex((NSData *) value);
4673 - (NSArray *) getMetadataKeys {
4674 @synchronized (Values_) {
4675 return [Values_ allKeys];
4678 - (void) registerFrame:(DOMHTMLIFrameElement *)iframe {
4679 WebFrame *frame([iframe contentFrame]);
4680 [indirect_ registerFrame:frame];
4683 - (id) getMetadataValue:(NSString *)key {
4684 @synchronized (Values_) {
4685 return [Values_ objectForKey:key];
4688 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4689 @synchronized (Values_) {
4690 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4691 [Values_ removeObjectForKey:key];
4693 [Values_ setObject:value forKey:key];
4696 - (id) getSessionValue:(NSString *)key {
4697 @synchronized (SessionData_) {
4698 return [SessionData_ objectForKey:key];
4701 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4702 @synchronized (SessionData_) {
4703 if (value == (id) [WebUndefined undefined])
4704 [SessionData_ removeObjectForKey:key];
4706 [SessionData_ setObject:value forKey:key];
4709 - (void) addBridgedHost:(NSString *)host {
4710 @synchronized (HostConfig_) {
4711 [BridgedHosts_ addObject:host];
4714 - (void) addInsecureHost:(NSString *)host {
4715 @synchronized (HostConfig_) {
4716 [InsecureHosts_ addObject:host];
4719 - (void) popViewController:(NSNumber *)value {
4720 if (value == (id) [WebUndefined undefined])
4721 value = [NSNumber numberWithBool:YES];
4722 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4725 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4726 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4728 for (NSString *section in sections)
4729 [array addObject:section];
4731 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4734 distribution, @"Distribution",
4736 nil] waitUntilDone:NO];
4739 - (BOOL) addTrivialSource:(NSString *)href {
4740 href = VerifySource(href);
4743 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4747 - (void) refreshSources {
4748 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4751 - (void) saveConfig {
4752 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4755 - (NSArray *) getAllSources {
4756 return [[Database sharedInstance] sources];
4759 - (NSArray *) getInstalledPackages {
4760 Database *database([Database sharedInstance]);
4761 @synchronized (database) {
4762 NSArray *packages([database packages]);
4763 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4764 for (Package *package in packages)
4765 if (![package uninstalled])
4766 [installed addObject:package];
4770 - (Package *) getPackageById:(NSString *)id {
4771 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4775 return (Package *) [NSNull null];
4778 - (NSString *) getLocaleIdentifier {
4779 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4782 - (NSArray *) getPreferredLanguages {
4786 - (NSArray *) statfs:(NSString *)path {
4789 if (path == nil || statfs([path UTF8String], &stat) == -1)
4792 return [NSArray arrayWithObjects:
4793 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4794 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4795 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4799 - (NSNumber *) du:(NSString *)path {
4800 NSNumber *value(nil);
4802 FILE *du(popen([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /usr/libexec/cydia/du -ks %@", ShellEscape(path)] UTF8String], "r"));
4805 while (fgets(line, sizeof(line), du) != NULL) {
4806 size_t length(strlen(line));
4807 while (length != 0 && line[length - 1] == '\n')
4808 line[--length] = '\0';
4809 if (char *tab = strchr(line, '\t')) {
4811 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4821 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4824 - (NSNumber *) isReachable:(NSString *)name {
4825 return [NSNumber numberWithBool:IsReachable([name UTF8String])];
4828 - (void) installPackages:(NSArray *)packages {
4829 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4832 - (NSString *) substitutePackageNames:(NSString *)message {
4833 auto database([Database sharedInstance]);
4835 // XXX: this check is less racy than you'd expect, but this entire concept is a little awkward
4836 if (![database hasPackages])
4839 NSMutableArray *words([[[message componentsSeparatedByString:@" "] mutableCopy] autorelease]);
4840 for (size_t i(0), e([words count]); i != e; ++i) {
4841 NSString *word([words objectAtIndex:i]);
4842 if (Package *package = [database packageWithName:word])
4843 [words replaceObjectAtIndex:i withObject:[package name]];
4846 return [words componentsJoinedByString:@" "];
4849 - (void) removeButton {
4850 [indirect_ removeButton];
4853 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4854 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4857 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4858 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4861 - (void) setBadgeValue:(id)value {
4862 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4865 - (void) setAllowsNavigationAction:(NSString *)value {
4866 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4869 - (void) setHidesBackButton:(NSString *)value {
4870 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4873 - (void) setHidesNavigationBar:(NSString *)value {
4874 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4877 - (void) setNavigationBarStyle:(NSString *)value {
4878 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4881 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4882 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4883 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4884 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4887 - (void) setPasteboardString:(NSString *)value {
4888 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4891 - (void) setPasteboardURL:(NSString *)value {
4892 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4895 - (void) setToken:(NSString *)token {
4896 // XXX: the website expects this :/
4899 - (void) scrollToBottom:(NSNumber *)animated {
4900 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4903 - (void) setViewportWidth:(float)width {
4904 [indirect_ setViewportWidthOnMainThread:width];
4907 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4908 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4909 unsigned count([arguments count]);
4911 for (unsigned i(0); i != count; ++i)
4912 values[i] = [arguments objectAtIndex:i];
4913 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4916 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4917 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4919 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4921 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4927 @interface NSURL (CydiaSecure)
4930 @implementation NSURL (CydiaSecure)
4932 - (bool) isCydiaSecure {
4933 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4936 @synchronized (HostConfig_) {
4937 if ([InsecureHosts_ containsObject:[self host]])
4946 /* Cydia Browser Controller {{{ */
4947 @implementation CydiaWebViewController
4949 - (NSURL *) navigationURL {
4950 if (NSURLRequest *request = self.request)
4951 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request URL] absoluteString]]];
4956 + (void) _initialize {
4957 [super _initialize];
4959 Diversions_ = [NSMutableSet setWithCapacity:0];
4962 + (void) addDiversion:(Diversion *)diversion {
4963 [Diversions_ addObject:diversion];
4966 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4967 [super webView:view didClearWindowObject:window forFrame:frame];
4968 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
4971 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia {
4972 WebDataSource *source([frame dataSource]);
4973 NSURLResponse *response([source response]);
4974 NSURL *url([response URL]);
4975 NSString *scheme([[url scheme] lowercaseString]);
4977 bool bridged(false);
4979 @synchronized (HostConfig_) {
4980 if ([scheme isEqualToString:@"file"])
4982 else if ([scheme isEqualToString:@"https"])
4983 if ([BridgedHosts_ containsObject:[url host]])
4988 [window setValue:cydia forKey:@"cydia"];
4991 - (void) _setupMail:(MFMailComposeViewController *)controller {
4992 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4994 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4995 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4998 - (NSURL *) URLWithURL:(NSURL *)url {
4999 return [Diversion divertURL:url];
5002 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
5003 return [CydiaWebViewController requestWithHeaders:[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
5006 - (NSURLRequest *) webThreadWebView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
5007 return [CydiaWebViewController requestWithHeaders:[super webThreadWebView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
5010 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request {
5011 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
5013 NSURL *url([copy URL]);
5014 NSString *href([url absoluteString]);
5015 NSString *host([url host]);
5017 if ([href hasPrefix:@"https://cydia.saurik.com/TSS/"]) {
5018 if (NSString *agent = [copy valueForHTTPHeaderField:@"X-User-Agent"]) {
5019 [copy setValue:agent forHTTPHeaderField:@"User-Agent"];
5020 [copy setValue:nil forHTTPHeaderField:@"X-User-Agent"];
5023 [copy setValue:nil forHTTPHeaderField:@"Referer"];
5024 [copy setValue:nil forHTTPHeaderField:@"Origin"];
5026 [copy setURL:[NSURL URLWithString:[@"http://gs.apple.com/TSS/" stringByAppendingString:[href substringFromIndex:29]]]];
5030 if ([copy valueForHTTPHeaderField:@"X-Cydia-Cf"] == nil)
5031 [copy setValue:[NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber] forHTTPHeaderField:@"X-Cydia-Cf"];
5032 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
5033 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
5035 bool bridged; @synchronized (HostConfig_) {
5036 bridged = [BridgedHosts_ containsObject:host];
5039 if ([url isCydiaSecure] && bridged && UniqueID_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Id"] == nil)
5040 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
5045 - (void) setDelegate:(id)delegate {
5046 [super setDelegate:delegate];
5047 [cydia_ setDelegate:delegate];
5050 - (NSString *) applicationNameForUserAgent {
5055 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
5056 cydia_ = [[[CydiaObject alloc] initWithDelegate:self.indirect] autorelease];
5062 @interface AppCacheController : CydiaWebViewController {
5067 @implementation AppCacheController
5069 - (void) didReceiveMemoryWarning {
5070 // XXX: this doesn't work
5073 - (bool) retainsNetworkActivityIndicator {
5080 /* Confirmation Controller {{{ */
5081 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
5082 if (!iterator.end())
5083 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
5084 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
5086 pkgCache::PkgIterator package(dep.TargetPkg());
5089 if (strcmp(package.Name(), "mobilesubstrate") == 0)
5096 @protocol ConfirmationControllerDelegate
5097 - (void) cancelAndClear:(bool)clear;
5098 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
5102 @interface ConfirmationController : CydiaWebViewController {
5103 _transient Database *database_;
5105 _H<UIAlertView> essential_;
5107 _H<NSDictionary> changes_;
5108 _H<NSMutableArray> issues_;
5109 _H<NSDictionary> sizes_;
5114 - (id) initWithDatabase:(Database *)database;
5118 @implementation ConfirmationController
5122 RestartSubstrate_ = true;
5123 [self.delegate confirmWithNavigationController:[self navigationController]];
5126 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
5127 NSString *context([alert context]);
5129 if ([context isEqualToString:@"remove"]) {
5130 if (button == [alert cancelButtonIndex])
5132 else if (button == [alert firstOtherButtonIndex]) {
5133 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
5136 [alert dismissWithClickedButtonIndex:-1 animated:YES];
5137 } else if ([context isEqualToString:@"unable"]) {
5138 [self dismissModalViewControllerAnimated:YES];
5139 [alert dismissWithClickedButtonIndex:-1 animated:YES];
5141 [super alertView:alert clickedButtonAtIndex:button];
5145 - (void) _doContinue {
5146 [self.delegate cancelAndClear:NO];
5147 [self dismissModalViewControllerAnimated:YES];
5150 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
5151 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
5155 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5156 [super webView:view didClearWindowObject:window forFrame:frame];
5158 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
5159 (id) changes_, @"changes",
5160 (id) issues_, @"issues",
5161 (id) sizes_, @"sizes",
5163 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
5166 - (id) initWithDatabase:(Database *)database {
5167 if ((self = [super init]) != nil) {
5168 database_ = database;
5170 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
5171 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
5172 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
5173 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
5174 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
5178 pkgCacheFile &cache([database_ cache]);
5179 NSArray *packages([database_ packages]);
5180 pkgDepCache::Policy *policy([database_ policy]);
5182 issues_ = [NSMutableArray arrayWithCapacity:4];
5184 for (Package *package in packages) {
5185 pkgCache::PkgIterator iterator([package iterator]);
5186 NSString *name([package id]);
5188 if ([package broken]) {
5189 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
5191 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5193 reasons, @"reasons",
5196 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
5200 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
5201 pkgCache::DepIterator start;
5202 pkgCache::DepIterator end;
5203 dep.GlobOr(start, end); // ++dep
5205 if (!cache->IsImportantDep(end))
5207 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
5210 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
5212 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5213 [NSString stringWithUTF8String:start.DepType()], @"relationship",
5214 clauses, @"clauses",
5218 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
5220 pkgCache::PkgIterator target(start.TargetPkg());
5221 if (target->ProvidesList != 0)
5222 reason = @"missing";
5224 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
5226 reason = @"installed";
5227 installed = [NSString stringWithUTF8String:ver.VerStr()];
5228 } else if (!cache[target].CandidateVerIter(cache).end())
5229 reason = @"uninstalled";
5230 else if (target->ProvidesList == 0)
5231 reason = @"uninstallable";
5233 reason = @"virtual";
5236 NSDictionary *version(start.TargetVer() == 0 ? (NSDictionary *) [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
5237 [NSString stringWithUTF8String:start.CompType()], @"operator",
5238 [NSString stringWithUTF8String:start.TargetVer()], @"value",
5241 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5242 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
5243 version, @"version",
5245 installed, @"installed",
5248 // yes, seriously. (wtf?)
5256 pkgDepCache::StateCache &state(cache[iterator]);
5258 static RegEx special_r("(firmware|gsc\\..*|cy\\+.*)");
5260 if (state.NewInstall())
5261 [installs addObject:name];
5262 // XXX: else if (state.Install())
5263 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
5264 [reinstalls addObject:name];
5265 // XXX: move before previous if
5266 else if (state.Upgrade())
5267 [upgrades addObject:name];
5268 else if (state.Downgrade())
5269 [downgrades addObject:name];
5270 else if (!state.Delete())
5271 // XXX: _assert(state.Keep());
5273 else if (special_r(name))
5274 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5275 [NSNull null], @"package",
5276 [NSArray arrayWithObjects:
5277 [NSDictionary dictionaryWithObjectsAndKeys:
5278 @"Conflicts", @"relationship",
5279 [NSArray arrayWithObjects:
5280 [NSDictionary dictionaryWithObjectsAndKeys:
5282 [NSNull null], @"version",
5283 @"installed", @"reason",
5290 if ([package essential])
5292 [removes addObject:name];
5295 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
5296 substrate_ |= DepSubstrate(iterator.CurrentVer());
5301 else if (Advanced_) {
5302 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
5304 essential_ = [[[UIAlertView alloc]
5305 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
5306 message:UCLocalize("REMOVING_ESSENTIALS_EX")
5308 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
5310 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
5314 [essential_ setContext:@"remove"];
5315 [essential_ setNumberOfRows:2];
5317 essential_ = [[[UIAlertView alloc]
5318 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
5319 message:UCLocalize("UNABLE_TO_COMPLY_EX")
5321 cancelButtonTitle:UCLocalize("OKAY")
5322 otherButtonTitles:nil
5325 [essential_ setContext:@"unable"];
5328 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5329 installs, @"installs",
5330 reinstalls, @"reinstalls",
5331 upgrades, @"upgrades",
5332 downgrades, @"downgrades",
5333 removes, @"removes",
5336 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5337 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
5338 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
5341 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
5345 - (UIBarButtonItem *) leftButton {
5346 return [[[UIBarButtonItem alloc]
5347 initWithTitle:UCLocalize("CANCEL")
5348 style:UIBarButtonItemStylePlain
5350 action:@selector(cancelButtonClicked)
5355 - (void) applyRightButton {
5356 if ([issues_ count] == 0 && ![self isLoading])
5357 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
5358 initWithTitle:UCLocalize("CONFIRM")
5359 style:UIBarButtonItemStyleDone
5361 action:@selector(confirmButtonClicked)
5364 [[self navigationItem] setRightBarButtonItem:nil];
5368 - (void) cancelButtonClicked {
5369 [self.delegate cancelAndClear:YES];
5370 [self dismissModalViewControllerAnimated:YES];
5374 - (void) confirmButtonClicked {
5375 if (essential_ != nil)
5385 /* Progress Data {{{ */
5386 @interface CydiaProgressData : NSObject {
5387 _transient id delegate_;
5396 _H<NSMutableArray> events_;
5397 _H<NSString> title_;
5399 _H<NSString> status_;
5400 _H<NSString> finish_;
5405 @implementation CydiaProgressData
5407 + (NSArray *) _attributeKeys {
5408 return [NSArray arrayWithObjects:
5420 - (NSArray *) attributeKeys {
5421 return [[self class] _attributeKeys];
5424 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5425 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5429 if ((self = [super init]) != nil) {
5430 events_ = [NSMutableArray arrayWithCapacity:32];
5438 - (void) setDelegate:(id)delegate {
5439 delegate_ = delegate;
5442 - (void) setPercent:(float)value {
5446 - (NSNumber *) percent {
5447 return [NSNumber numberWithFloat:percent_];
5450 - (void) setCurrent:(float)value {
5454 - (NSNumber *) current {
5455 return [NSNumber numberWithFloat:current_];
5458 - (void) setTotal:(float)value {
5462 - (NSNumber *) total {
5463 return [NSNumber numberWithFloat:total_];
5466 - (void) setSpeed:(float)value {
5470 - (NSNumber *) speed {
5471 return [NSNumber numberWithFloat:speed_];
5474 - (NSArray *) events {
5478 - (void) removeAllEvents {
5479 [events_ removeAllObjects];
5482 - (void) addEvent:(CydiaProgressEvent *)event {
5483 [events_ addObject:event];
5486 - (void) setTitle:(NSString *)text {
5490 - (NSString *) title {
5494 - (void) setFinish:(NSString *)text {
5498 - (NSString *) finish {
5499 return (id) finish_ ?: [NSNull null];
5502 - (void) setRunning:(bool)running {
5506 - (NSNumber *) running {
5507 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5512 /* Progress Controller {{{ */
5513 @interface ProgressController : CydiaWebViewController <
5516 _transient Database *database_;
5517 _H<CydiaProgressData, 1> progress_;
5521 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5523 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5525 - (void) setTitle:(NSString *)title;
5526 - (void) setCancellable:(bool)cancellable;
5530 @implementation ProgressController
5533 [database_ setProgressDelegate:nil];
5537 - (UIBarButtonItem *) leftButton {
5538 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5539 initWithTitle:UCLocalize("CANCEL")
5540 style:UIBarButtonItemStylePlain
5542 action:@selector(cancel)
5543 ] autorelease] : nil;
5546 - (void) updateCancel {
5547 [super applyLeftButton];
5550 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5551 if ((self = [super init]) != nil) {
5552 database_ = database;
5553 self.delegate = delegate;
5555 [database_ setProgressDelegate:self];
5557 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5558 [progress_ setDelegate:self];
5560 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5562 [self setPageColor:[UIColor blackColor]];
5564 [[self navigationItem] setHidesBackButton:YES];
5566 [self updateCancel];
5570 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5571 [super webView:view didClearWindowObject:window forFrame:frame];
5572 [window setValue:progress_ forKey:@"cydiaProgress"];
5575 - (void) updateProgress {
5576 [self dispatchEvent:@"CydiaProgressUpdate"];
5579 - (void) viewWillAppear:(BOOL)animated {
5580 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5581 [super viewWillAppear:animated];
5585 UpdateExternalStatus(0);
5588 [self.delegate saveState];
5592 [self.delegate returnToCydia];
5596 [self.delegate terminateWithSuccess];
5597 /*if ([self.delegate respondsToSelector:@selector(suspendWithAnimation:)])
5598 [self.delegate suspendWithAnimation:YES];
5600 [self.delegate suspend];*/
5612 UIProgressHUD *hud([self.delegate addProgressHUD]);
5613 [hud setText:UCLocalize("LOADING")];
5614 [self.delegate performSelector:@selector(reloadSpringBoard) withObject:nil afterDelay:0.5];
5620 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5621 SBReboot(SBSSpringBoardServerPort());
5623 reboot2(RB_AUTOBOOT);
5630 - (void) setTitle:(NSString *)title {
5631 [progress_ setTitle:title];
5632 [self updateProgress];
5635 - (UIBarButtonItem *) rightButton {
5636 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5637 initWithTitle:UCLocalize("CLOSE")
5638 style:UIBarButtonItemStylePlain
5640 action:@selector(close)
5644 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5645 UpdateExternalStatus(1);
5647 [progress_ setRunning:true];
5648 [self setTitle:title];
5649 // implicit updateProgress
5651 SHA1SumValue notifyconf; {
5653 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5656 MMap mmap(file, MMap::ReadOnly);
5658 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5659 notifyconf = sha1.Result();
5663 SHA1SumValue springlist; {
5665 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5668 MMap mmap(file, MMap::ReadOnly);
5670 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5671 springlist = sha1.Result();
5675 if (invocation != nil) {
5676 [invocation yieldToSelector:@selector(invoke)];
5677 [self setTitle:@"COMPLETE"];
5682 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5685 MMap mmap(file, MMap::ReadOnly);
5687 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5688 if (!(notifyconf == sha1.Result()))
5695 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5698 MMap mmap(file, MMap::ReadOnly);
5700 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5701 if (!(springlist == sha1.Result()))
5707 if (RestartSubstrate_)
5711 RestartSubstrate_ = false;
5714 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5715 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5716 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5717 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5718 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5721 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5723 [progress_ setRunning:false];
5724 [self updateProgress];
5726 [self applyRightButton];
5729 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5730 [progress_ addEvent:event];
5731 [self updateProgress];
5734 - (bool) isProgressCancelled {
5735 return cancel_ == 2;
5740 [self updateCancel];
5743 - (void) setCancellable:(bool)cancellable {
5744 unsigned cancel(cancel_);
5748 else if (cancel_ == 0)
5751 if (cancel != cancel_)
5752 [self updateCancel];
5755 - (void) setProgressCancellable:(NSNumber *)cancellable {
5756 [self setCancellable:[cancellable boolValue]];
5759 - (void) setProgressPercent:(NSNumber *)percent {
5760 [progress_ setPercent:[percent floatValue]];
5761 [self updateProgress];
5764 - (void) setProgressStatus:(NSDictionary *)status {
5765 if (status == nil) {
5766 [progress_ setCurrent:0];
5767 [progress_ setTotal:0];
5768 [progress_ setSpeed:0];
5770 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5772 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5773 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5774 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5777 [self updateProgress];
5783 /* Package Cell {{{ */
5784 @interface PackageCell : CyteTableViewCell <
5785 CyteTableViewCellDelegate
5789 _H<NSString> description_;
5791 _H<NSString> source_;
5793 _H<UIImage> placard_;
5797 - (PackageCell *) init;
5798 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5800 - (void) drawContentRect:(CGRect)rect;
5804 @implementation PackageCell
5806 - (PackageCell *) init {
5807 CGRect frame(CGRectMake(0, 0, 320, 74));
5808 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5809 UIView *content([self contentView]);
5810 CGRect bounds([content bounds]);
5812 self.content = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5813 [self.content setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5814 [content addSubview:self.content];
5816 [self.content setDelegate:self];
5817 [self.content setOpaque:YES];
5821 - (NSString *) accessibilityLabel {
5825 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5826 summarized_ = summary;
5836 [self.content setBackgroundColor:[UIColor whiteColor]];
5840 Source *source = [package source];
5842 icon_ = [package icon];
5844 if (NSString *name = [package name])
5845 name_ = [NSString stringWithString:name];
5847 if (NSString *description = [package shortDescription])
5848 description_ = [NSString stringWithString:description];
5850 commercial_ = [package isCommercial];
5852 NSString *label = nil;
5853 bool trusted = false;
5855 if (source != nil) {
5856 label = [source label];
5857 trusted = [source trusted];
5858 } else if ([[package id] isEqualToString:@"firmware"])
5859 label = UCLocalize("APPLE");
5861 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5863 NSString *from(label);
5865 NSString *section = [package simpleSection];
5866 if (section != nil && ![section isEqualToString:label]) {
5867 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5868 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5871 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5873 if (NSString *purpose = [package primaryPurpose])
5874 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5879 if (NSString *mode = [package mode]) {
5880 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5881 color = RemovingColor_;
5882 placard = @"removing";
5884 color = InstallingColor_;
5885 placard = @"installing";
5888 color = [UIColor whiteColor];
5890 if ([package installed] != nil)
5891 placard = @"installed";
5896 [self.content setBackgroundColor:color];
5899 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5902 [self setNeedsDisplay];
5903 [self.content setNeedsDisplay];
5906 - (void) drawSummaryContentRect:(CGRect)rect {
5907 bool highlighted(self.highlighted);
5908 float width([self bounds].size.width);
5912 rect.size = [(UIImage *) icon_ size];
5914 while (rect.size.width > 16 || rect.size.height > 16) {
5915 rect.size.width /= 2;
5916 rect.size.height /= 2;
5919 rect.origin.x = 19 - rect.size.width / 2;
5920 rect.origin.y = 19 - rect.size.height / 2;
5922 [icon_ drawInRect:Retina(rect)];
5925 if (badge_ != nil) {
5927 rect.size = [(UIImage *) badge_ size];
5929 rect.size.width /= 4;
5930 rect.size.height /= 4;
5932 rect.origin.x = 25 - rect.size.width / 2;
5933 rect.origin.y = 25 - rect.size.height / 2;
5935 [badge_ drawInRect:Retina(rect)];
5938 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5942 UISetColor(commercial_ ? Purple_ : Black_);
5943 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
5945 if (placard_ != nil)
5946 [placard_ drawAtPoint:CGPointMake(width - 52, 11)];
5949 - (void) drawNormalContentRect:(CGRect)rect {
5950 bool highlighted(self.highlighted);
5951 float width([self bounds].size.width);
5955 rect.size = [(UIImage *) icon_ size];
5957 while (rect.size.width > 32 || rect.size.height > 32) {
5958 rect.size.width /= 2;
5959 rect.size.height /= 2;
5962 rect.origin.x = 25 - rect.size.width / 2;
5963 rect.origin.y = 25 - rect.size.height / 2;
5965 [icon_ drawInRect:Retina(rect)];
5968 if (badge_ != nil) {
5970 rect.size = [(UIImage *) badge_ size];
5972 rect.size.width /= 2;
5973 rect.size.height /= 2;
5975 rect.origin.x = 36 - rect.size.width / 2;
5976 rect.origin.y = 36 - rect.size.height / 2;
5978 [badge_ drawInRect:Retina(rect)];
5981 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5985 UISetColor(commercial_ ? Purple_ : Black_);
5986 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
5987 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
5990 UISetColor(commercial_ ? Purplish_ : Gray_);
5991 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:NSLineBreakByTruncatingTail];
5993 if (placard_ != nil)
5994 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5997 - (void) drawContentRect:(CGRect)rect {
5999 [self drawSummaryContentRect:rect];
6001 [self drawNormalContentRect:rect];
6006 /* Section Cell {{{ */
6007 @interface SectionCell : CyteTableViewCell <
6008 CyteTableViewCellDelegate
6010 _H<NSString> basic_;
6011 _H<NSString> section_;
6013 _H<NSString> count_;
6015 _H<UISwitch> switch_;
6019 - (void) setSection:(Section *)section editing:(BOOL)editing;
6023 @implementation SectionCell
6025 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
6026 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
6027 icon_ = [UIImage imageNamed:@"folder.png"];
6028 // XXX: this initial frame is wrong, but is fixed later
6029 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
6030 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
6032 UIView *content([self contentView]);
6033 CGRect bounds([content bounds]);
6035 self.content = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
6036 [self.content setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6037 [content addSubview:self.content];
6038 [self.content setBackgroundColor:[UIColor whiteColor]];
6040 [self.content setDelegate:self];
6044 - (void) onSwitch:(id)sender {
6045 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
6046 if (metadata == nil) {
6047 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
6048 [Sections_ setObject:metadata forKey:basic_];
6051 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
6054 - (void) setSection:(Section *)section editing:(BOOL)editing {
6055 if (editing != editing_) {
6057 [switch_ removeFromSuperview];
6059 [self addSubview:switch_];
6068 if (section == nil) {
6069 name_ = UCLocalize("ALL_PACKAGES");
6072 basic_ = [section name];
6073 section_ = [section localized];
6075 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
6076 count_ = [NSString stringWithFormat:@"%zd", [section count]];
6079 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
6082 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
6083 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
6085 [self.content setNeedsDisplay];
6088 - (void) setFrame:(CGRect)frame {
6089 [super setFrame:frame];
6091 CGRect rect([switch_ frame]);
6092 [switch_ setFrame:CGRectMake(frame.size.width - rect.size.width - 9, 9, rect.size.width, rect.size.height)];
6095 - (NSString *) accessibilityLabel {
6099 - (void) drawContentRect:(CGRect)rect {
6100 bool highlighted(self.highlighted && !editing_);
6102 [icon_ drawInRect:CGRectMake(7, 7, 32, 32)];
6104 if (highlighted && kCFCoreFoundationVersionNumber < 800)
6107 float width(rect.size.width);
6109 width -= 9 + [switch_ frame].size.width;
6113 [name_ drawAtPoint:CGPointMake(48, 12) forWidth:(width - 58) withFont:Font18_ lineBreakMode:NSLineBreakByTruncatingTail];
6115 CGSize size = [count_ sizeWithFont:Font14_];
6117 UISetColor(Folder_);
6119 [count_ drawAtPoint:CGPointMake(Retina(10 + (30 - size.width) / 2), 18) withFont:Font12Bold_];
6125 /* File Table {{{ */
6126 @interface FileTable : CyteViewController <
6127 UITableViewDataSource,
6130 _transient Database *database_;
6131 _H<Package> package_;
6133 _H<NSMutableArray> files_;
6134 _H<UITableView, 2> list_;
6137 - (id) initWithDatabase:(Database *)database;
6138 - (void) setPackage:(Package *)package;
6142 @implementation FileTable
6144 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6145 return files_ == nil ? 0 : [files_ count];
6148 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6152 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6153 static NSString *reuseIdentifier = @"Cell";
6155 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6157 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6158 [cell setFont:[UIFont systemFontOfSize:16]];
6160 [cell setText:[files_ objectAtIndex:indexPath.row]];
6161 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
6166 - (NSURL *) navigationURL {
6167 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
6171 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
6172 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6173 [list_ setRowHeight:24.0f];
6174 [(UITableView *) list_ setDataSource:self];
6175 [list_ setDelegate:self];
6176 [self setView:list_];
6179 - (void) viewDidLoad {
6180 [super viewDidLoad];
6182 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
6185 - (void) releaseSubviews {
6191 [super releaseSubviews];
6194 - (id) initWithDatabase:(Database *)database {
6195 if ((self = [super init]) != nil) {
6196 database_ = database;
6200 - (void) setPackage:(Package *)package {
6204 files_ = [NSMutableArray arrayWithCapacity:32];
6206 if (package != nil) {
6208 name_ = [package id];
6210 if (NSArray *files = [package files])
6211 [files_ addObjectsFromArray:files];
6213 if ([files_ count] != 0) {
6214 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
6215 [files_ removeObjectAtIndex:0];
6216 [files_ sortUsingSelector:@selector(compareByPath:)];
6218 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
6219 [stack addObject:@"/"];
6221 for (int i(0), e([files_ count]); i != e; ++i) {
6222 NSString *file = [files_ objectAtIndex:i];
6223 while (![file hasPrefix:[stack lastObject]])
6224 [stack removeLastObject];
6225 NSString *directory = [stack lastObject];
6226 [stack addObject:[file stringByAppendingString:@"/"]];
6227 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
6228 int(([stack count] - 2) * 3), "",
6229 [file substringFromIndex:[directory length]]
6238 - (void) reloadData {
6241 [self setPackage:[database_ packageWithName:name_]];
6246 /* Package Controller {{{ */
6247 @interface CYPackageController : CydiaWebViewController <
6248 UIActionSheetDelegate
6250 _transient Database *database_;
6251 _H<Package> package_;
6254 std::vector<std::pair<_H<NSString>, _H<NSString>>> buttons_;
6255 _H<UIActionSheet> sheet_;
6256 _H<UIBarButtonItem> button_;
6257 _H<NSArray> versions_;
6260 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer;
6264 @implementation CYPackageController
6266 - (NSURL *) navigationURL {
6267 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
6270 - (void) _clickButtonWithPackage:(Package *)package {
6271 [self.delegate installPackage:package];
6274 - (void) _clickButtonWithName:(NSString *)name {
6275 if ([name isEqualToString:@"CLEAR"])
6276 return [self.delegate clearPackage:package_];
6277 else if ([name isEqualToString:@"REMOVE"])
6278 return [self.delegate removePackage:package_];
6279 else if ([name isEqualToString:@"DOWNGRADE"]) {
6280 sheet_ = [[[UIActionSheet alloc]
6283 cancelButtonTitle:nil
6284 destructiveButtonTitle:nil
6285 otherButtonTitles:nil
6288 for (Package *version in (id) versions_)
6289 [sheet_ addButtonWithTitle:[version latest]];
6290 [sheet_ setContext:@"version"];
6292 [self.delegate showActionSheet:sheet_ fromItem:[[self navigationItem] rightBarButtonItem]];
6296 else if ([name isEqualToString:@"INSTALL"]);
6297 else if ([name isEqualToString:@"REINSTALL"]);
6298 else if ([name isEqualToString:@"UPGRADE"]);
6299 else _assert(false);
6301 [self.delegate installPackage:package_];
6304 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
6305 NSString *context([sheet context]);
6306 if (sheet_ == sheet)
6309 if ([context isEqualToString:@"modify"]) {
6310 if (button != [sheet cancelButtonIndex]) {
6312 [self performSelector:@selector(_clickButtonWithName:) withObject:buttons_[button].first afterDelay:0];
6314 [self _clickButtonWithName:buttons_[button].first];
6317 [sheet dismissWithClickedButtonIndex:button animated:YES];
6318 } else if ([context isEqualToString:@"version"]) {
6319 if (button != [sheet cancelButtonIndex]) {
6320 Package *version([versions_ objectAtIndex:button]);
6322 [self performSelector:@selector(_clickButtonWithPackage:) withObject:version afterDelay:0];
6324 [self _clickButtonWithPackage:version];
6327 [sheet dismissWithClickedButtonIndex:button animated:YES];
6331 - (bool) _allowJavaScriptPanel {
6336 - (void) _customButtonClicked {
6337 if (commercial_ && self.isLoading && [package_ uninstalled])
6338 return [self reloadURLWithCache:NO];
6340 size_t count(buttons_.size());
6345 [self _clickButtonWithName:buttons_[0].first];
6347 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
6348 for (const auto &button : buttons_)
6349 [buttons addObject:button.second];
6351 sheet_ = [[[UIActionSheet alloc]
6354 cancelButtonTitle:nil
6355 destructiveButtonTitle:nil
6356 otherButtonTitles:nil
6359 for (NSString *button in buttons)
6360 [sheet_ addButtonWithTitle:button];
6361 [sheet_ setContext:@"modify"];
6363 [self.delegate showActionSheet:sheet_ fromItem:[[self navigationItem] rightBarButtonItem]];
6367 - (void) applyLoadingTitle {
6368 // Don't show "Loading" as the title. Ever.
6371 - (UIBarButtonItem *) rightButton {
6376 - (void) setPageColor:(UIColor *)color {
6377 return [super setPageColor:nil];
6380 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer {
6381 if ((self = [super init]) != nil) {
6382 database_ = database;
6383 name_ = name == nil ? @"" : [NSString stringWithString:name];
6384 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]] withReferrer:referrer];
6388 - (void) reloadData {
6391 [sheet_ dismissWithClickedButtonIndex:[sheet_ cancelButtonIndex] animated:YES];
6394 package_ = [database_ packageWithName:name_];
6395 versions_ = [package_ downgrades];
6399 if (package_ != nil) {
6400 [(Package *) package_ parse];
6402 commercial_ = [package_ isCommercial];
6404 if ([package_ mode] != nil)
6405 buttons_.push_back(std::make_pair(@"CLEAR", UCLocalize("CLEAR")));
6406 if ([package_ source] == nil);
6407 else if ([package_ upgradableAndEssential:NO])
6408 buttons_.push_back(std::make_pair(@"UPGRADE", UCLocalize("UPGRADE")));
6409 else if ([package_ uninstalled])
6410 buttons_.push_back(std::make_pair(@"INSTALL", UCLocalize("INSTALL")));
6412 buttons_.push_back(std::make_pair(@"REINSTALL", UCLocalize("REINSTALL")));
6413 if (![package_ uninstalled])
6414 buttons_.push_back(std::make_pair(@"REMOVE", UCLocalize("REMOVE")));
6415 if ([versions_ count] != 0)
6416 buttons_.push_back(std::make_pair(@"DOWNGRADE", UCLocalize("DOWNGRADE")));
6420 switch (buttons_.size()) {
6421 case 0: title = nil; break;
6422 case 1: title = buttons_[0].second; break;
6423 default: title = UCLocalize("MODIFY"); break;
6426 button_ = [[[UIBarButtonItem alloc]
6428 style:UIBarButtonItemStylePlain
6430 action:@selector(customButtonClicked)
6434 - (bool) isLoading {
6435 return commercial_ ? [super isLoading] : false;
6441 /* Package List Controller {{{ */
6442 @interface PackageListController : CyteViewController <
6443 UITableViewDataSource,
6446 _transient Database *database_;
6448 _H<NSArray> packages_;
6449 _H<NSArray> sections_;
6450 _H<UITableView, 2> list_;
6452 _H<NSArray> thumbs_;
6453 std::vector<NSInteger> offset_;
6455 _H<NSString> title_;
6456 unsigned reloading_;
6459 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6460 - (void) resetCursor;
6463 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages;
6467 @implementation PackageListController
6469 - (NSURL *) referrerURL {
6470 return [self navigationURL];
6473 - (bool) isSummarized {
6477 - (bool) showsSections {
6481 - (void) deselectWithAnimation:(BOOL)animated {
6482 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6485 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6486 CGRect base = [[self view] bounds];
6487 base.size.height -= bounds.size.height;
6488 base.origin = [list_ frame].origin;
6490 [UIView beginAnimations:nil context:NULL];
6491 [UIView setAnimationBeginsFromCurrentState:YES];
6492 [UIView setAnimationCurve:curve];
6493 [UIView setAnimationDuration:duration];
6494 [list_ setFrame:base];
6495 [UIView commitAnimations];
6498 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6499 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6502 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6503 [self resizeForKeyboardBounds:bounds duration:0];
6506 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6507 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6508 *curve = UIViewAnimationCurveEaseInOut;
6510 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6512 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6515 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6518 - (void) keyboardWillShow:(NSNotification *)notification {
6521 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6522 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6524 NSTimeInterval duration;
6525 UIViewAnimationCurve curve;
6526 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6528 CGRect kbframe = CGRectMake(Retina(center.x - bounds.size.width / 2), Retina(center.y - bounds.size.height / 2), bounds.size.width, bounds.size.height);
6529 UIViewController *base([self rootViewController]);
6530 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6531 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6533 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6534 intersection.size.height += CYStatusBarHeight();
6536 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6539 - (void) keyboardWillHide:(NSNotification *)notification {
6540 NSTimeInterval duration;
6541 UIViewAnimationCurve curve;
6542 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6544 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6547 - (void) viewWillAppear:(BOOL)animated {
6548 [super viewWillAppear:animated];
6550 [self resizeForKeyboardBounds:CGRectZero];
6551 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6552 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6555 - (void) viewWillDisappear:(BOOL)animated {
6556 [super viewWillDisappear:animated];
6558 [self resizeForKeyboardBounds:CGRectZero];
6559 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6560 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6563 - (void) viewDidAppear:(BOOL)animated {
6564 [super viewDidAppear:animated];
6565 [self deselectWithAnimation:animated];
6568 - (void) didSelectPackage:(Package *)package {
6569 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[[self referrerURL] absoluteString]] autorelease]);
6570 [view setDelegate:self.delegate];
6571 [[self navigationController] pushViewController:view animated:YES];
6574 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6575 NSInteger count([sections_ count]);
6576 return count == 0 ? 1 : count;
6579 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6580 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6582 return [[sections_ objectAtIndex:section] name];
6585 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6586 if ([sections_ count] == 0)
6588 return [[sections_ objectAtIndex:section] count];
6591 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6592 @synchronized (database_) {
6593 if ([database_ era] != era_)
6596 Section *section([sections_ objectAtIndex:[path section]]);
6597 NSInteger row([path row]);
6598 Package *package([packages_ objectAtIndex:([section row] + row)]);
6599 return [[package retain] autorelease];
6602 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6603 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6605 cell = [[[PackageCell alloc] init] autorelease];
6607 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6608 [cell setPackage:package asSummary:[self isSummarized]];
6612 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6613 Package *package([self packageAtIndexPath:path]);
6614 package = [database_ packageWithName:[package id]];
6615 [self didSelectPackage:package];
6618 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6622 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6623 return offset_[index];
6626 - (void) updateHeight {
6627 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6630 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6631 if ((self = [super init]) != nil) {
6632 database_ = database;
6633 title_ = [title copy];
6634 [[self navigationItem] setTitle:title_];
6639 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
6640 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
6641 [self setView:view];
6643 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6644 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6645 [view addSubview:list_];
6647 // XXX: is 20 the most optimal number here?
6648 [list_ setSectionIndexMinimumDisplayRowCount:20];
6650 [(UITableView *) list_ setDataSource:self];
6651 [list_ setDelegate:self];
6653 [self updateHeight];
6656 - (void) releaseSubviews {
6665 [super releaseSubviews];
6668 - (bool) shouldYield {
6672 - (bool) shouldBlock {
6676 - (NSMutableArray *) _reloadPackages {
6677 @synchronized (database_) {
6678 era_ = [database_ era];
6679 NSArray *packages([database_ packages]);
6681 return [NSMutableArray arrayWithArray:packages];
6684 - (void) _reloadData {
6685 if (reloading_ != 0) {
6690 NSMutableArray *packages;
6693 if ([self shouldYield]) {
6697 if (![self shouldBlock])
6700 hud = [self.delegate addProgressHUD];
6701 [hud setText:UCLocalize("LOADING")];
6705 packages = [self yieldToSelector:@selector(_reloadPackages)];
6708 [self.delegate removeProgressHUD:hud];
6709 } while (reloading_ == 2);
6711 packages = [self _reloadPackages];
6714 @synchronized (database_) {
6715 if (era_ != [database_ era])
6722 packages_ = packages;
6724 if ([self showsSections])
6725 sections_ = [self sectionsForPackages:packages];
6727 Section *section([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6728 [section setCount:[packages_ count]];
6729 sections_ = [NSArray arrayWithObject:section];
6732 [self updateHeight];
6734 _profile(PackageTable$reloadData$List)
6735 [(UITableView *) list_ setDataSource:self];
6743 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
6744 Section *prefix([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6745 size_t end([packages count]);
6747 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
6748 Section *section(prefix);
6750 thumbs_ = CollationThumbs_;
6751 offset_ = CollationOffset_;
6754 size_t offsets([CollationStarts_ count]);
6756 NSString *start([CollationStarts_ objectAtIndex:offset]);
6757 size_t length([start length]);
6759 for (size_t index(0); index != end; ++index) {
6761 Package *package([packages objectAtIndex:index]);
6762 NSString *name(PackageName(package, @selector(cyname)));
6764 //while ([start compare:name options:NSNumericSearch range:NSMakeRange(0, length) locale:CollationLocale_] != NSOrderedDescending) {
6765 while (StringNameCompare(start, name, length) != kCFCompareGreaterThan) {
6766 NSString *title([CollationTitles_ objectAtIndex:offset]);
6767 section = [[[Section alloc] initWithName:title row:index localize:NO] autorelease];
6768 [sections addObject:section];
6770 start = ++offset == offsets ? nil : [CollationStarts_ objectAtIndex:offset];
6773 length = [start length];
6777 [section addToCount];
6780 for (; offset != offsets; ++offset) {
6781 NSString *title([CollationTitles_ objectAtIndex:offset]);
6782 Section *section([[[Section alloc] initWithName:title row:end localize:NO] autorelease]);
6783 [sections addObject:section];
6786 if ([prefix count] != 0) {
6787 Section *suffix([sections lastObject]);
6788 [prefix setName:[suffix name]];
6789 [suffix setName:nil];
6790 [sections insertObject:prefix atIndex:(offsets - 1)];
6796 - (void) reloadData {
6799 if ([self shouldYield])
6800 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6805 - (void) resetCursor {
6806 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6809 - (void) clearData {
6810 [self updateHeight];
6812 [list_ setDataSource:nil];
6820 /* Filtered Package List Controller {{{ */
6821 typedef Function<bool, Package *> PackageFilter;
6822 typedef Function<void, NSMutableArray *> PackageSorter;
6823 @interface FilteredPackageListController : PackageListController {
6824 PackageFilter filter_;
6825 PackageSorter sorter_;
6828 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter;
6830 - (void) setFilter:(PackageFilter)filter;
6831 - (void) setSorter:(PackageSorter)sorter;
6835 @implementation FilteredPackageListController
6837 - (void) setFilter:(PackageFilter)filter {
6838 @synchronized (self) {
6842 - (void) setSorter:(PackageSorter)sorter {
6843 @synchronized (self) {
6847 - (NSMutableArray *) _reloadPackages {
6848 @synchronized (database_) {
6849 era_ = [database_ era];
6851 NSArray *packages([database_ packages]);
6852 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6854 PackageFilter filter;
6855 PackageSorter sorter;
6857 @synchronized (self) {
6862 _profile(PackageTable$reloadData$Filter)
6863 for (Package *package in packages)
6864 if (filter(package))
6865 [filtered addObject:package];
6873 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter {
6874 if ((self = [super initWithDatabase:database title:title]) != nil) {
6875 [self setFilter:filter];
6882 /* Home Controller {{{ */
6883 @interface HomeController : CydiaWebViewController {
6884 CFRunLoopRef runloop_;
6885 SCNetworkReachabilityRef reachability_;
6890 @implementation HomeController
6892 static void HomeControllerReachabilityCallback(SCNetworkReachabilityRef reachability, SCNetworkReachabilityFlags flags, void *info) {
6893 [(HomeController *) info dispatchEvent:@"CydiaReachabilityCallback"];
6897 if ((self = [super init]) != nil) {
6898 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6901 reachability_ = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "cydia.saurik.com");
6902 if (reachability_ != NULL) {
6903 SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
6904 SCNetworkReachabilitySetCallback(reachability_, HomeControllerReachabilityCallback, &context);
6906 CFRunLoopRef runloop(CFRunLoopGetCurrent());
6907 if (SCNetworkReachabilityScheduleWithRunLoop(reachability_, runloop, kCFRunLoopDefaultMode))
6914 if (reachability_ != NULL && runloop_ != NULL)
6915 SCNetworkReachabilityUnscheduleFromRunLoop(reachability_, runloop_, kCFRunLoopDefaultMode);
6919 - (NSURL *) navigationURL {
6920 return [NSURL URLWithString:@"cydia://home"];
6923 - (void) aboutButtonClicked {
6924 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6926 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6927 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6928 [alert setCancelButtonIndex:0];
6931 @"Copyright \u00a9 2008-2015\n"
6934 "Jay Freeman (saurik)\n"
6935 "saurik@saurik.com\n"
6936 "http://www.saurik.com/"
6942 - (UIBarButtonItem *) leftButton {
6943 return [[[UIBarButtonItem alloc]
6944 initWithTitle:UCLocalize("ABOUT")
6945 style:UIBarButtonItemStylePlain
6947 action:@selector(aboutButtonClicked)
6954 /* Cydia Tab Bar Controller {{{ */
6955 @interface CydiaTabBarController : CyteTabBarController <
6956 UITabBarControllerDelegate,
6959 _transient Database *database_;
6961 _H<UIActivityIndicatorView> indicator_;
6964 // XXX: ok, "updatedelegate_"?...
6965 _transient NSObject<CydiaDelegate> *updatedelegate_;
6968 - (void) beginUpdate;
6973 @implementation CydiaTabBarController
6975 - (id) initWithDatabase:(Database *)database {
6976 if ((self = [super init]) != nil) {
6977 database_ = database;
6978 [self setDelegate:self];
6980 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteTiny] autorelease];
6981 [indicator_ setOrigin:CGPointMake(kCFCoreFoundationVersionNumber >= 800 ? 2 : 4, 2)];
6983 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6987 - (void) beginUpdate {
6991 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
6992 UITabBarItem *item([controller tabBarItem]);
6994 [item setBadgeValue:@""];
6995 UIView *badge(MSHookIvar<UIView *>([item view], "_badge"));
6997 [indicator_ startAnimating];
6998 [badge addSubview:indicator_];
7000 [updatedelegate_ retainNetworkActivityIndicator];
7004 detachNewThreadSelector:@selector(performUpdate)
7010 - (void) performUpdate {
7011 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
7013 SourceStatus status(self, database_);
7014 [database_ updateWithStatus:status];
7017 performSelectorOnMainThread:@selector(completeUpdate)
7025 - (void) stopUpdateWithSelector:(SEL)selector {
7027 [updatedelegate_ releaseNetworkActivityIndicator];
7029 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
7030 [[controller tabBarItem] setBadgeValue:nil];
7032 [indicator_ removeFromSuperview];
7033 [indicator_ stopAnimating];
7035 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
7038 - (void) completeUpdate {
7041 [self stopUpdateWithSelector:@selector(reloadData)];
7044 - (void) cancelUpdate {
7045 [self stopUpdateWithSelector:@selector(updateDataAndLoad)];
7048 - (void) cancelPressed {
7049 [self cancelUpdate];
7056 - (bool) isSourceCancelled {
7060 - (void) startSourceFetch:(NSString *)uri {
7063 - (void) stopSourceFetch:(NSString *)uri {
7066 - (void) setUpdateDelegate:(id)delegate {
7067 updatedelegate_ = delegate;
7073 /* Cydia:// Protocol {{{ */
7074 @interface CydiaURLProtocol : NSURLProtocol {
7079 @implementation CydiaURLProtocol
7081 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7082 NSURL *url([request URL]);
7086 NSString *scheme([[url scheme] lowercaseString]);
7087 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7089 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7095 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7099 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7100 id<NSURLProtocolClient> client([self client]);
7102 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7104 NSData *data(UIImagePNGRepresentation(icon));
7106 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7107 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7108 [client URLProtocol:self didLoadData:data];
7109 [client URLProtocolDidFinishLoading:self];
7113 - (void) startLoading {
7114 id<NSURLProtocolClient> client([self client]);
7115 NSURLRequest *request([self request]);
7117 NSURL *url([request URL]);
7118 NSString *href([url absoluteString]);
7119 NSString *scheme([[url scheme] lowercaseString]);
7123 if ([scheme isEqualToString:@"cydia"])
7124 path = [href substringFromIndex:8];
7125 else if ([scheme isEqualToString:@"about"])
7126 path = [href substringFromIndex:12];
7127 else _assert(false);
7129 NSRange slash([path rangeOfString:@"/"]);
7132 if (slash.location == NSNotFound) {
7136 command = [path substringToIndex:slash.location];
7137 path = [path substringFromIndex:(slash.location + 1)];
7140 Database *database([Database sharedInstance]);
7143 else if ([command isEqualToString:@"application-icon"]) {
7146 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7150 if (icon == nil && $SBSCopyIconImagePNGDataForDisplayIdentifier != NULL) {
7151 NSData *data([$SBSCopyIconImagePNGDataForDisplayIdentifier(path) autorelease]);
7152 icon = [UIImage imageWithData:data];
7156 if (NSString *file = SBSCopyIconImagePathForDisplayIdentifier(path))
7157 icon = [UIImage imageAtPath:file];
7160 icon = [UIImage imageNamed:@"unknown.png"];
7162 [self _returnPNGWithImage:icon forRequest:request];
7163 } else if ([command isEqualToString:@"package-icon"]) {
7166 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7167 Package *package([database packageWithName:path]);
7171 UIImage *icon([package icon]);
7172 [self _returnPNGWithImage:icon forRequest:request];
7173 } else if ([command isEqualToString:@"uikit-image"]) {
7176 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7177 UIImage *icon(_UIImageWithName(path));
7178 [self _returnPNGWithImage:icon forRequest:request];
7179 } else if ([command isEqualToString:@"section-icon"]) {
7182 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7183 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7185 icon = [UIImage imageNamed:@"unknown.png"];
7186 [self _returnPNGWithImage:icon forRequest:request];
7188 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7192 - (void) stopLoading {
7198 /* Section Controller {{{ */
7199 @interface SectionController : FilteredPackageListController {
7201 _H<NSString> section_;
7204 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section;
7208 @implementation SectionController
7210 - (NSURL *) referrerURL {
7211 NSString *name(section_);
7212 name = name ?: @"*";
7213 NSString *key(key_);
7215 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sections/%@/%@", UI_, [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7218 - (NSURL *) navigationURL {
7219 NSString *name(section_);
7220 name = name ?: @"*";
7221 NSString *key(key_);
7223 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@/%@", [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7226 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section {
7229 title = UCLocalize("ALL_PACKAGES");
7230 else if (![section isEqual:@""])
7231 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(section) value:nil table:@"Sections"];
7233 title = UCLocalize("NO_SECTION");
7235 if ((self = [super initWithDatabase:database title:title]) != nil) {
7236 key_ = [source key];
7241 - (void) reloadData {
7242 Source *source([database_ sourceWithKey:key_]);
7243 _H<NSString> name(section_);
7245 [self setFilter:[=](Package *package) {
7246 NSString *section([package section]);
7250 section == nil && [name length] == 0 ||
7251 [name isEqualToString:section]
7254 [package source] == source
7255 ) && [package visible];
7263 /* Sections Controller {{{ */
7264 @interface SectionsController : CyteViewController <
7265 UITableViewDataSource,
7268 _transient Database *database_;
7270 _H<NSMutableArray> sections_;
7271 _H<NSMutableArray> filtered_;
7272 _H<UITableView, 2> list_;
7275 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7276 - (void) editButtonClicked;
7280 @implementation SectionsController
7282 - (NSURL *) navigationURL {
7283 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
7286 - (Source *) source {
7289 return [database_ sourceWithKey:key_];
7292 - (void) updateNavigationItem {
7293 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7294 if ([sections_ count] == 0) {
7295 [[self navigationItem] setRightBarButtonItem:nil];
7297 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7298 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7300 action:@selector(editButtonClicked)
7301 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7305 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7306 [super setEditing:editing animated:animated];
7311 [self.delegate updateData];
7313 [self updateNavigationItem];
7316 - (void) viewDidAppear:(BOOL)animated {
7317 [super viewDidAppear:animated];
7318 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7321 - (void) viewWillDisappear:(BOOL)animated {
7322 [super viewWillDisappear:animated];
7323 [self setEditing:NO];
7326 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7327 Section *section = nil;
7328 int index = [indexPath row];
7329 if (![self isEditing]) {
7332 section = [filtered_ objectAtIndex:index];
7334 section = [sections_ objectAtIndex:index];
7339 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7340 if ([self isEditing])
7341 return [sections_ count];
7343 return [filtered_ count] + 1;
7346 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7350 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7351 static NSString *reuseIdentifier = @"SectionCell";
7353 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7355 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7357 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7362 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7363 if ([self isEditing])
7366 Section *section = [self sectionAtIndexPath:indexPath];
7368 SectionController *controller = [[[SectionController alloc]
7369 initWithDatabase:database_
7370 source:[self source]
7371 section:[section name]
7373 [controller setDelegate:self.delegate];
7375 [[self navigationController] pushViewController:controller animated:YES];
7379 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
7380 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7381 [list_ setRowHeight:46];
7382 [(UITableView *) list_ setDataSource:self];
7383 [list_ setDelegate:self];
7384 [self setView:list_];
7387 - (void) viewDidLoad {
7388 [super viewDidLoad];
7390 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7393 - (void) releaseSubviews {
7399 [super releaseSubviews];
7402 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7403 if ((self = [super init]) != nil) {
7404 database_ = database;
7405 key_ = [source key];
7409 - (void) reloadData {
7412 NSArray *packages = [database_ packages];
7414 sections_ = [NSMutableArray arrayWithCapacity:16];
7415 filtered_ = [NSMutableArray arrayWithCapacity:16];
7417 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7419 Source *source([self source]);
7422 for (Package *package in packages) {
7423 if (source != nil && [package source] != source)
7426 NSString *name([package section]);
7427 NSString *key(name == nil ? @"" : name);
7431 _profile(SectionsView$reloadData$Section)
7432 section = [sections objectForKey:key];
7433 if (section == nil) {
7434 _profile(SectionsView$reloadData$Section$Allocate)
7435 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7436 [sections setObject:section forKey:key];
7441 [section addToCount];
7443 _profile(SectionsView$reloadData$Filter)
7444 if (![package visible])
7452 [sections_ addObjectsFromArray:[sections allValues]];
7454 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7456 for (Section *section in (id) sections_) {
7457 size_t count([section row]);
7461 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7462 [section setCount:count];
7463 [filtered_ addObject:section];
7466 [self updateNavigationItem];
7471 - (void) editButtonClicked {
7472 [self setEditing:![self isEditing] animated:YES];
7478 /* Changes Controller {{{ */
7479 @interface ChangesController : FilteredPackageListController {
7483 - (id) initWithDatabase:(Database *)database;
7487 @implementation ChangesController
7489 - (NSURL *) referrerURL {
7490 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/changes/", UI_]];
7493 - (NSURL *) navigationURL {
7494 return [NSURL URLWithString:@"cydia://changes"];
7497 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7498 @synchronized (database_) {
7499 if ([database_ era] != era_)
7502 NSUInteger sectionIndex([path section]);
7503 if (sectionIndex >= [sections_ count])
7505 Section *section([sections_ objectAtIndex:sectionIndex]);
7506 NSInteger row([path row]);
7507 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7510 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7511 NSString *context([alert context]);
7513 if ([context isEqualToString:@"norefresh"])
7514 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7517 - (void) setLeftBarButtonItem {
7518 if ([self.delegate updating])
7519 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7520 initWithTitle:UCLocalize("CANCEL")
7521 style:UIBarButtonItemStyleDone
7523 action:@selector(cancelButtonClicked)
7524 ] autorelease] animated:YES];
7526 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7527 initWithTitle:UCLocalize("REFRESH")
7528 style:UIBarButtonItemStylePlain
7530 action:@selector(refreshButtonClicked)
7531 ] autorelease] animated:YES];
7534 - (void) refreshButtonClicked {
7535 if ([self.delegate requestUpdate])
7536 [self setLeftBarButtonItem];
7539 - (void) cancelButtonClicked {
7540 [self.delegate cancelUpdate];
7543 - (void) upgradeButtonClicked {
7544 [self.delegate distUpgrade];
7545 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7548 - (bool) shouldYield {
7552 - (bool) shouldBlock {
7556 - (void) useFilter {
7557 @synchronized (self) {
7558 [self setFilter:[](Package *package) {
7559 return [package upgradableAndEssential:YES] || [package visible];
7562 [self setSorter:[](NSMutableArray *packages) {
7563 [packages radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7567 - (id) initWithDatabase:(Database *)database {
7568 if ((self = [super initWithDatabase:database title:UCLocalize("CHANGES")]) != nil) {
7573 - (void) viewDidLoad {
7574 [super viewDidLoad];
7575 [self setLeftBarButtonItem];
7578 - (void) viewWillAppear:(BOOL)animated {
7579 [super viewWillAppear:animated];
7580 [self setLeftBarButtonItem];
7583 - (void) reloadData {
7584 [self setLeftBarButtonItem];
7588 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
7589 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
7591 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7592 Section *ignored = nil;
7593 Section *section = nil;
7597 bool unseens = false;
7599 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7601 for (size_t offset = 0, count = [packages count]; offset != count; ++offset) {
7602 Package *package = [packages objectAtIndex:offset];
7604 BOOL uae = [package upgradableAndEssential:YES];
7608 time_t seen([package seen]);
7610 if (section == nil || last != seen) {
7614 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7617 _profile(ChangesController$reloadData$Allocate)
7618 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7619 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7620 [sections addObject:section];
7624 [section addToCount];
7625 } else if ([package ignored]) {
7626 if (ignored == nil) {
7627 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7629 [ignored addToCount];
7632 [upgradable addToCount];
7637 CFRelease(formatter);
7640 Section *last = [sections lastObject];
7641 size_t count = [last count];
7642 [packages removeObjectsInRange:NSMakeRange([packages count] - count, count)];
7643 [sections removeLastObject];
7646 if ([ignored count] != 0)
7647 [sections insertObject:ignored atIndex:0];
7649 [sections insertObject:upgradable atIndex:0];
7653 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7654 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7655 style:UIBarButtonItemStylePlain
7657 action:@selector(upgradeButtonClicked)
7658 ] autorelease]) animated:YES];
7665 /* Search Controller {{{ */
7666 @interface SearchController : FilteredPackageListController <
7669 _H<UISearchBar, 1> search_;
7674 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7675 - (void) reloadData;
7679 @implementation SearchController
7681 - (NSURL *) referrerURL {
7682 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/search?q=%@", UI_, [([search_ text] ?: @"") stringByAddingPercentEscapesIncludingReserved]]];
7685 - (NSURL *) navigationURL {
7686 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7687 return [NSURL URLWithString:@"cydia://search"];
7689 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [[search_ text] stringByAddingPercentEscapesIncludingReserved]]];
7692 - (NSArray *) termsForQuery:(NSString *)query {
7693 NSMutableArray *terms([NSMutableArray arrayWithCapacity:2]);
7694 for (NSString *component in [query componentsSeparatedByString:@" "])
7695 if ([component length] != 0)
7696 [terms addObject:component];
7701 - (void) useSearch {
7702 _H<NSArray> query([self termsForQuery:[search_ text]]);
7705 @synchronized (self) {
7706 [self setFilter:[=](Package *package) {
7707 if (![package unfiltered])
7709 if (![package matches:query])
7714 [self setSorter:[](NSMutableArray *packages) {
7715 [packages radixSortUsingSelector:@selector(rank)];
7723 - (void) usePrefix:(NSString *)prefix {
7724 _H<NSString> query(prefix);
7727 @synchronized (self) {
7728 [self setFilter:[=](Package *package) {
7729 if ([query length] == 0)
7731 if (![package unfiltered])
7733 if ([[package name] compare:query options:MatchCompareOptions_ range:NSMakeRange(0, [query length])] != NSOrderedSame)
7738 [self setSorter:nullptr];
7744 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7746 [self usePrefix:[search_ text]];
7749 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7750 [search_ resignFirstResponder];
7754 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7755 [search_ setText:@""];
7756 [self searchBarButtonClicked:searchBar];
7759 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7760 [self searchBarButtonClicked:searchBar];
7763 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7764 [self usePrefix:text];
7767 - (bool) shouldYield {
7771 - (bool) shouldBlock {
7775 - (bool) isSummarized {
7779 - (bool) showsSections {
7783 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7784 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH")])) {
7785 search_ = [[[UISearchBar alloc] init] autorelease];
7786 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7787 [search_ setDelegate:self];
7789 UITextField *textField;
7790 if ([search_ respondsToSelector:@selector(searchField)])
7791 textField = [search_ searchField];
7793 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7795 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7796 [textField setEnablesReturnKeyAutomatically:NO];
7797 [[self navigationItem] setTitleView:textField];
7800 [search_ setText:query];
7805 - (void) viewDidAppear:(BOOL)animated {
7806 [super viewDidAppear:animated];
7808 if (!searchloaded_) {
7809 searchloaded_ = YES;
7810 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7811 [search_ layoutSubviews];
7814 if ([self isSummarized])
7815 [search_ becomeFirstResponder];
7818 - (void) reloadData {
7823 - (void) didSelectPackage:(Package *)package {
7824 [search_ resignFirstResponder];
7825 [super didSelectPackage:package];
7830 /* Package Settings Controller {{{ */
7831 @interface PackageSettingsController : CyteViewController <
7832 UITableViewDataSource,
7835 _transient Database *database_;
7837 _H<Package> package_;
7838 _H<UITableView, 2> table_;
7839 _H<UISwitch> subscribedSwitch_;
7840 _H<UISwitch> ignoredSwitch_;
7841 _H<UITableViewCell> subscribedCell_;
7842 _H<UITableViewCell> ignoredCell_;
7845 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7849 @implementation PackageSettingsController
7851 - (NSURL *) navigationURL {
7852 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
7855 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7856 if (package_ == nil)
7859 if ([package_ installed] == nil)
7865 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7866 if (package_ == nil)
7869 // both sections contain just one item right now.
7873 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7877 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7879 return UCLocalize("SHOW_ALL_CHANGES_EX");
7881 return UCLocalize("IGNORE_UPGRADES_EX");
7884 - (void) onSubscribed:(id)control {
7885 bool value([control isOn]);
7886 if (package_ == nil)
7888 if ([package_ setSubscribed:value])
7889 [self.delegate updateData];
7892 - (void) _updateIgnored {
7893 const char *package([name_ UTF8String]);
7894 bool on([ignoredSwitch_ isOn]);
7896 FILE *dpkg(popen("/usr/libexec/cydia/cydo --set-selections", "w"));
7897 fwrite(package, strlen(package), 1, dpkg);
7900 fwrite(" hold\n", 6, 1, dpkg);
7902 fwrite(" install\n", 9, 1, dpkg);
7907 - (void) onIgnored:(id)control {
7908 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7909 [invocation setTarget:self];
7910 [invocation setSelector:@selector(_updateIgnored)];
7912 [self.delegate reloadDataWithInvocation:invocation];
7915 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7916 if (package_ == nil)
7919 switch ([indexPath section]) {
7920 case 0: return subscribedCell_;
7921 case 1: return ignoredCell_;
7930 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
7931 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
7932 [self setView:view];
7934 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7935 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7936 [(UITableView *) table_ setDataSource:self];
7937 [table_ setDelegate:self];
7938 [view addSubview:table_];
7940 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7941 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7942 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7944 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7945 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7946 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7948 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7949 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7950 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7951 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7953 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7954 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7955 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7956 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7959 - (void) viewDidLoad {
7960 [super viewDidLoad];
7962 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7965 - (void) releaseSubviews {
7967 subscribedCell_ = nil;
7969 ignoredSwitch_ = nil;
7970 subscribedSwitch_ = nil;
7972 [super releaseSubviews];
7975 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7976 if ((self = [super init]) != nil) {
7977 database_ = database;
7982 - (void) reloadData {
7985 package_ = [database_ packageWithName:name_];
7987 if (package_ != nil) {
7988 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7989 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7990 } // XXX: what now, G?
7992 [table_ reloadData];
7998 /* Installed Controller {{{ */
7999 @interface InstalledController : FilteredPackageListController {
8003 - (id) initWithDatabase:(Database *)database;
8004 - (void) queueStatusDidChange;
8008 @implementation InstalledController
8010 - (NSURL *) referrerURL {
8011 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/installed/", UI_]];
8014 - (NSURL *) navigationURL {
8015 return [NSURL URLWithString:@"cydia://installed"];
8018 - (void) useRecent {
8021 @synchronized (self) {
8022 [self setFilter:[](Package *package) {
8023 return ![package uninstalled] && package->role_ < 7;
8026 [self setSorter:[](NSMutableArray *packages) {
8027 [packages radixSortUsingSelector:@selector(recent)];
8031 - (void) useFilter:(UISegmentedControl *)segmented {
8032 NSInteger selected([segmented selectedSegmentIndex]);
8034 return [self useRecent];
8035 bool simple(selected == 0);
8038 @synchronized (self) {
8039 [self setFilter:[=](Package *package) {
8040 return ![package uninstalled] && package->role_ <= (simple ? 1 : 3);
8043 [self setSorter:nullptr];
8046 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
8048 return [super sectionsForPackages:packages];
8050 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterLongStyle, kCFDateFormatterNoStyle));
8052 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
8053 Section *section(nil);
8056 for (size_t offset(0), count([packages count]); offset != count; ++offset) {
8057 Package *package([packages objectAtIndex:offset]);
8059 time_t upgraded([package upgraded]);
8060 if (upgraded < 1168364520)
8063 upgraded -= upgraded % (60 * 60 * 24);
8065 if (section == nil || upgraded != last) {
8070 continue; // XXX: name = UCLocalize("...");
8072 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:upgraded]);
8076 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
8077 [sections addObject:section];
8080 [section addToCount];
8083 CFRelease(formatter);
8087 - (id) initWithDatabase:(Database *)database {
8088 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED")]) != nil) {
8089 UISegmentedControl *segmented([[[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:UCLocalize("USER"), UCLocalize("EXPERT"), UCLocalize("RECENT"), nil]] autorelease]);
8090 [segmented setSelectedSegmentIndex:0];
8091 [segmented setSegmentedControlStyle:UISegmentedControlStyleBar];
8092 [[self navigationItem] setTitleView:segmented];
8094 [segmented addTarget:self action:@selector(modeChanged:) forEvents:UIControlEventValueChanged];
8095 [self useFilter:segmented];
8097 [self queueStatusDidChange];
8102 - (void) queueButtonClicked {
8103 [self.delegate queue];
8107 - (void) queueStatusDidChange {
8110 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8111 initWithTitle:UCLocalize("QUEUE")
8112 style:UIBarButtonItemStyleDone
8114 action:@selector(queueButtonClicked)
8117 [[self navigationItem] setRightBarButtonItem:nil];
8122 - (void) modeChanged:(UISegmentedControl *)segmented {
8123 [self useFilter:segmented];
8130 /* Source Cell {{{ */
8131 @interface SourceCell : CyteTableViewCell <
8132 CyteTableViewCellDelegate,
8135 _H<Source, 1> source_;
8138 _H<NSString> origin_;
8139 _H<NSString> label_;
8140 _H<UIActivityIndicatorView> indicator_;
8143 - (void) setSource:(Source *)source;
8144 - (void) setFetch:(NSNumber *)fetch;
8148 @implementation SourceCell
8150 - (void) _setImage:(NSArray *)data {
8151 if ([url_ isEqual:[data objectAtIndex:0]]) {
8152 icon_ = [data objectAtIndex:1];
8153 [self.content setNeedsDisplay];
8157 - (void) _setSource:(NSURL *) url {
8158 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8160 if (NSData *data = [NSURLConnection
8161 sendSynchronousRequest:[NSURLRequest
8163 cachePolicy:NSURLRequestUseProtocolCachePolicy
8167 returningResponse:NULL
8170 if (UIImage *image = [UIImage imageWithData:data])
8171 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
8176 - (void) setSource:(Source *)source {
8178 [source_ setDelegate:self];
8180 [self setFetch:[NSNumber numberWithBool:[source_ fetch]]];
8182 icon_ = [UIImage imageNamed:@"unknown.png"];
8184 origin_ = [source name];
8185 label_ = [source rooturi];
8187 [self.content setNeedsDisplay];
8189 url_ = [source iconURL];
8190 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
8193 - (void) setAllSource {
8195 [indicator_ stopAnimating];
8197 icon_ = [UIImage imageNamed:@"folder.png"];
8198 origin_ = UCLocalize("ALL_SOURCES");
8199 label_ = UCLocalize("ALL_SOURCES_EX");
8200 [self.content setNeedsDisplay];
8203 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8204 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8205 UIView *content([self contentView]);
8206 CGRect bounds([content bounds]);
8208 self.content = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8209 [self.content setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8210 [self.content setBackgroundColor:[UIColor whiteColor]];
8211 [content addSubview:self.content];
8213 [self.content setDelegate:self];
8214 [self.content setOpaque:YES];
8216 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGraySmall] autorelease];
8217 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin];// | UIViewAutoresizingFlexibleBottomMargin];
8218 [content addSubview:indicator_];
8220 [[self.content layer] setContentsGravity:kCAGravityTopLeft];
8224 - (void) layoutSubviews {
8225 [super layoutSubviews];
8227 UIView *content([self contentView]);
8228 CGRect bounds([content bounds]);
8230 CGRect frame([indicator_ frame]);
8231 frame.origin.x = bounds.size.width - frame.size.width;
8232 frame.origin.y = Retina((bounds.size.height - frame.size.height) / 2);
8234 if (kCFCoreFoundationVersionNumber < 800)
8235 frame.origin.x -= 8;
8236 [indicator_ setFrame:frame];
8239 - (NSString *) accessibilityLabel {
8243 - (void) drawContentRect:(CGRect)rect {
8244 bool highlighted(self.highlighted);
8245 float width(rect.size.width);
8249 rect.size = [(UIImage *) icon_ size];
8251 while (rect.size.width > 32 || rect.size.height > 32) {
8252 rect.size.width /= 2;
8253 rect.size.height /= 2;
8256 rect.origin.x = 26 - rect.size.width / 2;
8257 rect.origin.y = 26 - rect.size.height / 2;
8259 [icon_ drawInRect:Retina(rect)];
8262 if (highlighted && kCFCoreFoundationVersionNumber < 800)
8267 [origin_ drawAtPoint:CGPointMake(52, 8) forWidth:(width - 49) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
8271 [label_ drawAtPoint:CGPointMake(52, 29) forWidth:(width - 49) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
8274 - (void) setFetch:(NSNumber *)fetch {
8275 if ([fetch boolValue])
8276 [indicator_ startAnimating];
8278 [indicator_ stopAnimating];
8283 /* Sources Controller {{{ */
8284 @interface SourcesController : CyteViewController <
8285 UITableViewDataSource,
8288 _transient Database *database_;
8291 _H<UITableView, 2> list_;
8292 _H<NSMutableArray> sources_;
8296 _H<UIProgressHUD> hud_;
8299 NSURLConnection *trivial_bz2_;
8300 NSURLConnection *trivial_gz_;
8305 - (id) initWithDatabase:(Database *)database;
8306 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated;
8310 @implementation SourcesController
8312 - (void) _releaseConnection:(NSURLConnection *)connection {
8313 if (connection != nil) {
8314 [connection cancel];
8315 //[connection setDelegate:nil];
8316 [connection release];
8321 [self _releaseConnection:trivial_gz_];
8322 [self _releaseConnection:trivial_bz2_];
8327 - (NSURL *) navigationURL {
8328 return [NSURL URLWithString:@"cydia://sources"];
8331 - (void) viewDidAppear:(BOOL)animated {
8332 [super viewDidAppear:animated];
8333 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8336 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8340 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8342 return UCLocalize("INDIVIDUAL_SOURCES");
8346 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8349 case 1: return [sources_ count];
8354 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8355 @synchronized (database_) {
8356 if ([database_ era] != era_)
8358 if ([indexPath section] != 1)
8360 NSUInteger index([indexPath row]);
8361 if (index >= [sources_ count])
8363 return [sources_ objectAtIndex:index];
8366 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8367 static NSString *cellIdentifier = @"SourceCell";
8369 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8370 if (cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8371 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8373 Source *source([self sourceAtIndexPath:indexPath]);
8375 [cell setAllSource];
8377 [cell setSource:source];
8382 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8383 SectionsController *controller([[[SectionsController alloc]
8384 initWithDatabase:database_
8385 source:[self sourceAtIndexPath:indexPath]
8388 [controller setDelegate:self.delegate];
8389 [[self navigationController] pushViewController:controller animated:YES];
8392 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8393 if ([indexPath section] != 1)
8395 Source *source = [self sourceAtIndexPath:indexPath];
8396 return [source record] != nil;
8399 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8400 _assert([indexPath section] == 1);
8401 if (editingStyle == UITableViewCellEditingStyleDelete) {
8402 Source *source = [self sourceAtIndexPath:indexPath];
8403 if (source == nil) return;
8405 [Sources_ removeObjectForKey:[source key]];
8407 [self.delegate syncData];
8411 - (void) tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath {
8412 [self updateButtonsForEditingStatusAnimated:YES];
8416 [self.delegate addTrivialSource:href_];
8419 [self.delegate syncData];
8422 - (NSString *) getWarning {
8423 NSString *href(href_);
8424 NSRange colon([href rangeOfString:@"://"]);
8425 if (colon.location != NSNotFound)
8426 href = [href substringFromIndex:(colon.location + 3)];
8427 href = [href stringByAddingPercentEscapes];
8428 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8430 NSURL *url([NSURL URLWithString:href]);
8432 NSStringEncoding encoding;
8433 NSError *error(nil);
8435 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8436 return [warning length] == 0 ? nil : warning;
8440 - (void) _endConnection:(NSURLConnection *)connection {
8441 // XXX: the memory management in this method is horribly awkward
8443 NSURLConnection **field = NULL;
8444 if (connection == trivial_bz2_)
8445 field = &trivial_bz2_;
8446 else if (connection == trivial_gz_)
8447 field = &trivial_gz_;
8448 _assert(field != NULL);
8449 [connection release];
8453 trivial_bz2_ == nil &&
8456 NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil);
8458 [self.delegate releaseNetworkActivityIndicator];
8460 [self.delegate removeProgressHUD:hud_];
8464 if (warning != nil) {
8465 UIAlertView *alert = [[[UIAlertView alloc]
8466 initWithTitle:UCLocalize("SOURCE_WARNING")
8469 cancelButtonTitle:UCLocalize("CANCEL")
8471 UCLocalize("ADD_ANYWAY"),
8475 [alert setContext:@"warning"];
8476 [alert setNumberOfRows:1];
8479 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
8485 } else if (error_ != nil) {
8486 UIAlertView *alert = [[[UIAlertView alloc]
8487 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8488 message:[error_ localizedDescription]
8490 cancelButtonTitle:UCLocalize("OK")
8491 otherButtonTitles:nil
8494 [alert setContext:@"urlerror"];
8499 UIAlertView *alert = [[[UIAlertView alloc]
8500 initWithTitle:UCLocalize("NOT_REPOSITORY")
8501 message:UCLocalize("NOT_REPOSITORY_EX")
8503 cancelButtonTitle:UCLocalize("OK")
8504 otherButtonTitles:nil
8507 [alert setContext:@"trivial"];
8517 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8518 switch ([response statusCode]) {
8524 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8525 lprintf("connection:\"%s\" didFailWithError:\"%s\"\n", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8527 [self _endConnection:connection];
8530 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8531 [self _endConnection:connection];
8534 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8535 NSURL *url([NSURL URLWithString:href]);
8537 NSMutableURLRequest *request = [NSMutableURLRequest
8539 cachePolicy:NSURLRequestUseProtocolCachePolicy
8543 [request setHTTPMethod:method];
8545 if (Machine_ != NULL)
8546 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8548 if (UniqueID_ != nil)
8549 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8551 if ([url isCydiaSecure]) {
8552 if (UniqueID_ != nil)
8553 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
8556 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8559 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8560 NSString *context([alert context]);
8562 if ([context isEqualToString:@"source"]) {
8565 NSString *href = [[alert textField] text];
8566 href = VerifySource(href);
8571 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8572 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8576 // XXX: this is stupid
8577 hud_ = [self.delegate addProgressHUD];
8578 [hud_ setText:UCLocalize("VERIFYING_URL")];
8579 [self.delegate retainNetworkActivityIndicator];
8588 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8589 } else if ([context isEqualToString:@"trivial"])
8590 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8591 else if ([context isEqualToString:@"urlerror"])
8592 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8593 else if ([context isEqualToString:@"warning"]) {
8596 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
8605 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8609 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated {
8610 BOOL editing([list_ isEditing]);
8613 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8614 initWithTitle:UCLocalize("ADD")
8615 style:UIBarButtonItemStylePlain
8617 action:@selector(addButtonClicked)
8618 ] autorelease] animated:animated];
8619 else if ([self.delegate updating])
8620 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8621 initWithTitle:UCLocalize("CANCEL")
8622 style:UIBarButtonItemStyleDone
8624 action:@selector(cancelButtonClicked)
8625 ] autorelease] animated:animated];
8627 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8628 initWithTitle:UCLocalize("REFRESH")
8629 style:UIBarButtonItemStylePlain
8631 action:@selector(refreshButtonClicked)
8632 ] autorelease] animated:animated];
8634 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8635 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8636 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8638 action:@selector(editButtonClicked)
8639 ] autorelease] animated:animated];
8643 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease];
8644 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8645 [list_ setRowHeight:53];
8646 [(UITableView *) list_ setDataSource:self];
8647 [list_ setDelegate:self];
8648 [self setView:list_];
8651 - (void) viewDidLoad {
8652 [super viewDidLoad];
8654 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8655 [self updateButtonsForEditingStatusAnimated:NO];
8658 - (void) viewWillAppear:(BOOL)animated {
8659 [super viewWillAppear:animated];
8661 [list_ setEditing:NO];
8662 [self updateButtonsForEditingStatusAnimated:NO];
8665 - (void) releaseSubviews {
8670 [super releaseSubviews];
8673 - (id) initWithDatabase:(Database *)database {
8674 if ((self = [super init]) != nil) {
8675 database_ = database;
8679 - (void) reloadData {
8681 [self updateButtonsForEditingStatusAnimated:YES];
8683 @synchronized (database_) {
8684 era_ = [database_ era];
8686 sources_ = [NSMutableArray arrayWithCapacity:16];
8687 [sources_ addObjectsFromArray:[database_ sources]];
8689 [sources_ sortUsingSelector:@selector(compareByName:)];
8692 int count([sources_ count]);
8694 for (int i = 0; i != count; i++) {
8695 if ([[sources_ objectAtIndex:i] record] == nil)
8703 - (void) showAddSourcePrompt {
8704 UIAlertView *alert = [[[UIAlertView alloc]
8705 initWithTitle:UCLocalize("ENTER_APT_URL")
8708 cancelButtonTitle:UCLocalize("CANCEL")
8710 UCLocalize("ADD_SOURCE"),
8714 [alert setContext:@"source"];
8716 [alert setNumberOfRows:1];
8717 [alert addTextFieldWithValue:@"http://" label:@""];
8719 NSObject<UITextInputTraits> *traits = [[alert textField] textInputTraits];
8720 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8721 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8722 [traits setKeyboardType:UIKeyboardTypeURL];
8723 // XXX: UIReturnKeyDone
8724 [traits setReturnKeyType:UIReturnKeyNext];
8729 - (void) addButtonClicked {
8730 [self showAddSourcePrompt];
8733 - (void) refreshButtonClicked {
8734 if ([self.delegate requestUpdate])
8735 [self updateButtonsForEditingStatusAnimated:YES];
8738 - (void) cancelButtonClicked {
8739 [self.delegate cancelUpdate];
8742 - (void) editButtonClicked {
8743 [list_ setEditing:![list_ isEditing] animated:YES];
8744 [self updateButtonsForEditingStatusAnimated:YES];
8750 /* Stash Controller {{{ */
8751 @interface StashController : CyteViewController {
8752 _H<UIActivityIndicatorView> spinner_;
8753 _H<UILabel> status_;
8754 _H<UILabel> caption_;
8759 @implementation StashController
8762 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8763 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8764 [self setView:view];
8766 [view setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8768 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8769 CGRect spinrect = [spinner_ frame];
8770 spinrect.origin.x = Retina([[self view] frame].size.width / 2 - spinrect.size.width / 2);
8771 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8772 [spinner_ setFrame:spinrect];
8773 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8774 [view addSubview:spinner_];
8775 [spinner_ startAnimating];
8778 captrect.size.width = [[self view] frame].size.width;
8779 captrect.size.height = 40.0f;
8780 captrect.origin.x = 0;
8781 captrect.origin.y = Retina([[self view] frame].size.height / 2 - captrect.size.height * 2);
8782 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8783 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8784 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8785 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8786 [caption_ setTextColor:[UIColor whiteColor]];
8787 [caption_ setBackgroundColor:[UIColor clearColor]];
8788 [caption_ setShadowColor:[UIColor blackColor]];
8789 [caption_ setTextAlignment:NSTextAlignmentCenter];
8790 [view addSubview:caption_];
8793 statusrect.size.width = [[self view] frame].size.width;
8794 statusrect.size.height = 30.0f;
8795 statusrect.origin.x = 0;
8796 statusrect.origin.y = Retina([[self view] frame].size.height / 2 - statusrect.size.height);
8797 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8798 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8799 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8800 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8801 [status_ setTextColor:[UIColor whiteColor]];
8802 [status_ setBackgroundColor:[UIColor clearColor]];
8803 [status_ setShadowColor:[UIColor blackColor]];
8804 [status_ setTextAlignment:NSTextAlignmentCenter];
8805 [view addSubview:status_];
8808 - (void) releaseSubviews {
8813 [super releaseSubviews];
8819 @interface Cydia : CyteApplication <
8820 ConfirmationControllerDelegate,
8824 _H<CyteWindow> window_;
8825 _H<CydiaTabBarController> tabbar_;
8826 _H<CyteTabBarController> emulated_;
8827 _H<AppCacheController> appcache_;
8829 _H<NSMutableArray> essential_;
8830 _H<NSMutableArray> broken_;
8832 Database *database_;
8834 _H<NSURL> starturl_;
8839 _H<StashController> stash_;
8848 @implementation Cydia
8850 - (void) lockSuspend {
8851 if (locked_++ == 0) {
8852 if ($SBSSetInterceptsMenuButtonForever != NULL)
8853 (*$SBSSetInterceptsMenuButtonForever)(true);
8855 [self setIdleTimerDisabled:YES];
8859 - (void) unlockSuspend {
8860 if (--locked_ == 0) {
8861 [self setIdleTimerDisabled:NO];
8863 if ($SBSSetInterceptsMenuButtonForever != NULL)
8864 (*$SBSSetInterceptsMenuButtonForever)(false);
8868 - (void) beginUpdate {
8869 [tabbar_ beginUpdate];
8872 - (void) cancelUpdate {
8873 [tabbar_ cancelUpdate];
8876 - (bool) requestUpdate {
8877 if (IsReachable("cydia.saurik.com")) {
8881 UIAlertView *alert = [[[UIAlertView alloc]
8882 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("REFRESH")]
8883 message:@"Host Unreachable" // XXX: Localize
8885 cancelButtonTitle:UCLocalize("OK")
8886 otherButtonTitles:nil
8889 [alert setContext:@"norefresh"];
8897 return [tabbar_ updating];
8901 if ([broken_ count] != 0) {
8902 int count = [broken_ count];
8904 UIAlertView *alert = [[[UIAlertView alloc]
8905 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8906 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8908 cancelButtonTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("FORCIBLY_CLEAR"), UCLocalize("UNSAFE")]
8910 UCLocalize("TEMPORARY_IGNORE"),
8914 [alert setContext:@"fixhalf"];
8915 [alert setNumberOfRows:2];
8917 } else if (!Ignored_ && [essential_ count] != 0) {
8918 int count = [essential_ count];
8920 UIAlertView *alert = [[[UIAlertView alloc]
8921 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8922 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8924 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8926 UCLocalize("UPGRADE_ESSENTIAL"),
8927 UCLocalize("COMPLETE_UPGRADE"),
8931 [alert setContext:@"upgrade"];
8936 - (void) returnToCydia {
8940 - (void) reloadSpringBoard {
8941 if (kCFCoreFoundationVersionNumber >= 700) // XXX: iOS 6.x
8942 system("/usr/libexec/cydia/cydo /bin/launchctl stop com.apple.backboardd");
8944 system("/usr/libexec/cydia/cydo /bin/launchctl stop com.apple.SpringBoard");
8946 system("/usr/bin/killall backboardd SpringBoard");
8949 - (void) _saveConfig {
8950 SaveConfig(database_);
8953 // Navigation controller for the queuing badge.
8954 - (UINavigationController *) queueNavigationController {
8955 NSArray *controllers = [tabbar_ viewControllers];
8956 return [controllers objectAtIndex:3];
8959 - (void) _updateData {
8961 [window_ unloadData];
8963 UINavigationController *navigation = [self queueNavigationController];
8965 id queuedelegate = nil;
8966 if ([[navigation viewControllers] count] > 0)
8967 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8969 [queuedelegate queueStatusDidChange];
8970 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8973 - (void) _refreshIfPossible {
8974 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8976 NSDate *update([[NSDictionary dictionaryWithContentsOfFile:@ CacheState_] objectForKey:@"LastUpdate"]);
8978 bool recently = false;
8979 if (update != nil) {
8980 NSTimeInterval interval([update timeIntervalSinceNow]);
8981 if (interval > -(15*60))
8985 // Don't automatic refresh if:
8986 // - We already refreshed recently.
8987 // - We already auto-refreshed this launch.
8988 // - Auto-refresh is disabled.
8989 // - Cydia's server is not reachable
8990 if (recently || loaded_ || ManualRefresh || !IsReachable("cydia.saurik.com")) {
8991 // If we are cancelling, we need to make sure it knows it's already loaded.
8994 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8996 // We are going to load, so remember that.
8999 [tabbar_ performSelectorOnMainThread:@selector(beginUpdate) withObject:nil waitUntilDone:NO];
9005 - (void) refreshIfPossible {
9006 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
9009 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9010 _profile(reloadDataWithInvocation)
9011 @synchronized (self) {
9012 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9014 [hud setText:UCLocalize("RELOADING_DATA")];
9016 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9020 [essential_ removeAllObjects];
9021 [broken_ removeAllObjects];
9023 _profile(reloadDataWithInvocation$Essential)
9024 NSArray *packages([database_ packages]);
9025 for (Package *package in packages) {
9027 [broken_ addObject:package];
9028 if ([package upgradableAndEssential:YES] && ![package ignored]) {
9029 if ([package essential] && [package installed] != nil)
9030 [essential_ addObject:package];
9036 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9039 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9040 [changesItem setBadgeValue:badge];
9041 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9042 [self setApplicationIconBadgeNumber:changes];
9045 [changesItem setBadgeValue:nil];
9046 [changesItem setAnimatedBadge:NO];
9047 [self setApplicationIconBadgeNumber:0];
9054 [self removeProgressHUD:hud];
9061 - (void) updateData {
9065 - (void) updateDataAndLoad {
9067 if ([database_ progressDelegate] == nil)
9073 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9076 - (void) disemulate {
9077 if (emulated_ == nil)
9080 [window_ setRootViewController:tabbar_];
9083 [window_ setUserInteractionEnabled:YES];
9086 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9087 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9089 UIViewController *parent;
9090 if (emulated_ == nil)
9100 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9101 [parent presentModalViewController:navigation animated:YES];
9104 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9105 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9107 if (navigation != nil)
9108 [navigation pushViewController:progress animated:YES];
9110 [self presentModalViewController:progress force:YES];
9112 [progress invoke:invocation withTitle:title];
9116 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9117 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9120 - (void) repairWithInvocation:(NSInvocation *)invocation {
9122 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9126 - (void) repairWithSelector:(SEL)selector {
9127 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9130 - (void) reloadData {
9131 [self reloadDataWithInvocation:nil];
9132 if ([database_ progressDelegate] == nil)
9138 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9141 - (void) addSource:(NSDictionary *) source {
9142 CydiaAddSource(source);
9145 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9146 CydiaAddSource(href, distribution, sections);
9149 // XXX: this method should not return anything
9150 - (BOOL) addTrivialSource:(NSString *)href {
9151 CydiaAddSource(href, @"./");
9156 pkgProblemResolver *resolver = [database_ resolver];
9158 resolver->InstallProtect();
9159 if (!resolver->Resolve(true))
9164 // XXX: this is a really crappy way of doing this.
9165 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9166 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9167 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9168 if ([tabbar_ updating])
9169 [tabbar_ cancelUpdate];
9171 if (![database_ prepare])
9174 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9175 [page setDelegate:self];
9176 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9179 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9180 [tabbar_ presentModalViewController:confirm_ animated:YES];
9186 @synchronized (self) {
9191 - (void) clearPackage:(Package *)package {
9192 @synchronized (self) {
9199 - (void) installPackages:(NSArray *)packages {
9200 @synchronized (self) {
9201 for (Package *package in packages)
9208 - (void) installPackage:(Package *)package {
9209 @synchronized (self) {
9216 - (void) removePackage:(Package *)package {
9217 @synchronized (self) {
9224 - (void) distUpgrade {
9225 @synchronized (self) {
9226 if (![database_ upgrade])
9234 system("/usr/bin/uicache");
9239 UIProgressHUD *hud([self addProgressHUD]);
9240 [hud setText:UCLocalize("LOADING")];
9241 [self yieldToSelector:@selector(_uicache)];
9242 [self removeProgressHUD:hud];
9246 [database_ perform];
9247 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9248 [self performSelectorOnMainThread:@selector(uicache) withObject:nil waitUntilDone:YES];
9251 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9254 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9255 [self unlockSuspend];
9258 - (void) retainNetworkActivityIndicator {
9259 if (activity_++ == 0)
9260 [self setNetworkActivityIndicatorVisible:YES];
9263 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9267 - (void) releaseNetworkActivityIndicator {
9268 if (--activity_ == 0)
9269 [self setNetworkActivityIndicatorVisible:NO];
9272 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9277 - (void) cancelAndClear:(bool)clear {
9278 @synchronized (self) {
9290 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9291 NSString *context([alert context]);
9293 if ([context isEqualToString:@"conffile"]) {
9294 FILE *input = [database_ input];
9295 if (button == [alert cancelButtonIndex])
9296 fprintf(input, "N\n");
9297 else if (button == [alert firstOtherButtonIndex])
9298 fprintf(input, "Y\n");
9301 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9302 } else if ([context isEqualToString:@"fixhalf"]) {
9303 if (button == [alert cancelButtonIndex]) {
9304 @synchronized (self) {
9305 for (Package *broken in (id) broken_) {
9307 NSString *id(ShellEscape([broken id]));
9308 system([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /bin/rm -f"
9309 " /var/lib/dpkg/info/%@.prerm"
9310 " /var/lib/dpkg/info/%@.postrm"
9311 " /var/lib/dpkg/info/%@.preinst"
9312 " /var/lib/dpkg/info/%@.postinst"
9313 " /var/lib/dpkg/info/%@.extrainst_"
9314 "", id, id, id, id, id] UTF8String]);
9320 } else if (button == [alert firstOtherButtonIndex]) {
9321 [broken_ removeAllObjects];
9325 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9326 } else if ([context isEqualToString:@"upgrade"]) {
9327 if (button == [alert firstOtherButtonIndex]) {
9328 @synchronized (self) {
9329 for (Package *essential in (id) essential_)
9330 [essential install];
9335 } else if (button == [alert firstOtherButtonIndex] + 1) {
9337 } else if (button == [alert cancelButtonIndex]) {
9341 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9345 - (void) system:(NSString *)command {
9346 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9349 system([command UTF8String]);
9355 - (void) applicationWillSuspend {
9357 [super applicationWillSuspend];
9360 - (BOOL) isSafeToSuspend {
9363 NSLog(@"isSafeToSuspend: locked_ != 0");
9368 if ([tabbar_ modalViewController] != nil)
9371 // Use external process status API internally.
9372 // This is probably a really bad idea.
9373 // XXX: what is the point of this? does this solve anything at all?
9374 uint64_t status = 0;
9376 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9377 notify_get_state(notify_token, &status);
9378 notify_cancel(notify_token);
9383 NSLog(@"isSafeToSuspend: status != 0");
9389 NSLog(@"isSafeToSuspend: -> true");
9394 - (void) suspendReturningToLastApp:(BOOL)returning {
9395 if ([self isSafeToSuspend])
9396 [super suspendReturningToLastApp:returning];
9400 if ([self isSafeToSuspend])
9404 - (void) applicationSuspend {
9405 if ([self isSafeToSuspend])
9406 [super applicationSuspend];
9409 - (void) applicationSuspend:(GSEventRef)event {
9410 if ([self isSafeToSuspend])
9411 [super applicationSuspend:event];
9414 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9415 if ([self isSafeToSuspend])
9416 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9419 - (void) _setSuspended:(BOOL)value {
9420 if ([self isSafeToSuspend])
9421 [super _setSuspended:value];
9424 - (UIProgressHUD *) addProgressHUD {
9425 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9426 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9428 [window_ setUserInteractionEnabled:NO];
9430 UIViewController *target(tabbar_);
9431 if (UIViewController *modal = [target modalViewController])
9434 [hud showInView:[target view]];
9440 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9441 [self unlockSuspend];
9443 [hud removeFromSuperview];
9444 [window_ setUserInteractionEnabled:YES];
9447 - (CyteViewController *) pageForPackage:(NSString *)name withReferrer:(NSString *)referrer {
9448 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name withReferrer:referrer] autorelease];
9451 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external withReferrer:(NSString *)referrer {
9452 NSString *scheme([[url scheme] lowercaseString]);
9453 if ([[url absoluteString] length] <= [scheme length] + 3)
9455 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9456 NSArray *components([path componentsSeparatedByString:@"/"]);
9458 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"]) {
9459 CyteViewController *controller([self pageForPackage:[components objectAtIndex:1] withReferrer:referrer]);
9460 if (controller != nil)
9461 [controller setDelegate:self];
9465 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9468 NSString *base([components objectAtIndex:0]);
9470 CyteViewController *controller = nil;
9472 if ([base isEqualToString:@"url"]) {
9473 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9474 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9475 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9476 } else if (!external && [components count] == 1) {
9477 if ([base isEqualToString:@"sources"]) {
9478 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9481 if ([base isEqualToString:@"home"]) {
9482 controller = [[[HomeController alloc] init] autorelease];
9485 if ([base isEqualToString:@"sections"]) {
9486 controller = [[[SectionsController alloc] initWithDatabase:database_ source:nil] autorelease];
9489 if ([base isEqualToString:@"search"]) {
9490 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9493 if ([base isEqualToString:@"changes"]) {
9494 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9497 if ([base isEqualToString:@"installed"]) {
9498 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9500 } else if ([components count] == 2) {
9501 NSString *argument = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9503 if ([base isEqualToString:@"package"]) {
9504 controller = [self pageForPackage:argument withReferrer:referrer];
9507 if (!external && [base isEqualToString:@"search"]) {
9508 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9511 if (!external && [base isEqualToString:@"sections"]) {
9512 if ([argument isEqualToString:@"all"] || [argument isEqualToString:@"*"])
9514 controller = [[[SectionController alloc] initWithDatabase:database_ source:nil section:argument] autorelease];
9517 if ([base isEqualToString:@"sources"]) {
9518 if ([argument isEqualToString:@"add"]) {
9519 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9520 [(SourcesController *)controller showAddSourcePrompt];
9522 Source *source([database_ sourceWithKey:argument]);
9523 controller = [[[SectionsController alloc] initWithDatabase:database_ source:source] autorelease];
9527 if (!external && [base isEqualToString:@"launch"]) {
9528 [self launchApplicationWithIdentifier:argument suspended:NO];
9531 } else if (!external && [components count] == 3) {
9532 NSString *arg1 = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9533 NSString *arg2 = [[components objectAtIndex:2] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9535 if ([base isEqualToString:@"package"]) {
9536 if ([arg2 isEqualToString:@"settings"]) {
9537 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9538 } else if ([arg2 isEqualToString:@"files"]) {
9539 if (Package *package = [database_ packageWithName:arg1]) {
9540 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9541 [(FileTable *)controller setPackage:package];
9546 if ([base isEqualToString:@"sections"]) {
9547 Source *source([arg1 isEqualToString:@"*"] ? nil : [database_ sourceWithKey:arg1]);
9548 NSString *section([arg2 isEqualToString:@"*"] ? nil : arg2);
9549 controller = [[[SectionController alloc] initWithDatabase:database_ source:source section:section] autorelease];
9553 [controller setDelegate:self];
9557 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9558 CyteViewController *page([self pageForURL:url forExternal:external withReferrer:nil]);
9561 [tabbar_ setUnselectedViewController:page];
9566 - (void) applicationOpenURL:(NSURL *)url {
9567 [super applicationOpenURL:url];
9572 [self openCydiaURL:url forExternal:YES];
9575 - (void) applicationWillResignActive:(UIApplication *)application {
9576 // Stop refreshing if you get a phone call or lock the device.
9577 if ([tabbar_ updating])
9578 [tabbar_ cancelUpdate];
9580 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9581 [super applicationWillResignActive:application];
9584 - (void) saveState {
9585 [[NSDictionary dictionaryWithObjectsAndKeys:
9586 @"InterfaceState", [tabbar_ navigationURLCollection],
9587 @"LastClosed", [NSDate date],
9588 @"InterfaceIndex", [NSNumber numberWithInt:[tabbar_ selectedIndex]],
9589 nil] writeToFile:@ SavedState_ atomically:YES];
9594 - (void) applicationWillTerminate:(UIApplication *)application {
9598 - (void) applicationDidEnterBackground:(UIApplication *)application {
9599 if (kCFCoreFoundationVersionNumber < 1000 && [self isSafeToSuspend])
9600 return [self terminateWithSuccess];
9601 Backgrounded_ = [NSDate date];
9605 - (void) applicationWillEnterForeground:(UIApplication *)application {
9606 if (Backgrounded_ == nil)
9609 NSTimeInterval interval([Backgrounded_ timeIntervalSinceNow]);
9611 if (interval <= -(30*60)) {
9612 [tabbar_ setSelectedIndex:0];
9613 [[[tabbar_ viewControllers] objectAtIndex:0] popToRootViewControllerAnimated:NO];
9616 if (interval <= -(15*60)) {
9617 if (IsReachable("cydia.saurik.com")) {
9618 [tabbar_ beginUpdate];
9619 [appcache_ reloadURLWithCache:YES];
9623 if ([database_ delocked])
9627 - (void) setConfigurationData:(NSString *)data {
9628 static RegEx conffile_r("'(.*)' '(.*)' ([01]) ([01])");
9630 if (!conffile_r(data)) {
9631 lprintf("E:invalid conffile\n");
9635 NSString *ofile = conffile_r[1];
9636 //NSString *nfile = conffile_r[2];
9638 UIAlertView *alert = [[[UIAlertView alloc]
9639 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9640 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9642 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9644 UCLocalize("ACCEPT_NEW_COPY"),
9645 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9649 [alert setContext:@"conffile"];
9650 [alert setNumberOfRows:2];
9654 - (void) addStashController {
9656 stash_ = [[[StashController alloc] init] autorelease];
9657 [window_ addSubview:[stash_ view]];
9660 - (void) removeStashController {
9661 [[stash_ view] removeFromSuperview];
9663 [self unlockSuspend];
9667 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9668 UpdateExternalStatus(1);
9669 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/cydo /usr/libexec/cydia/free.sh"];
9670 UpdateExternalStatus(0);
9672 [self removeStashController];
9673 [self reloadSpringBoard];
9676 - (void) applicationDidFinishLaunching:(id)unused {
9677 [super applicationDidFinishLaunching:unused];
9680 @synchronized (HostConfig_) {
9681 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9684 [CydiaWebViewController _initialize];
9686 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9688 // this would disallow http{,s} URLs from accessing this data
9689 //[WebView registerURLSchemeAsLocal:@"cydia"];
9691 Font12_ = [UIFont systemFontOfSize:12];
9692 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9693 Font14_ = [UIFont systemFontOfSize:14];
9694 Font18_ = [UIFont systemFontOfSize:18];
9695 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9696 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9698 essential_ = [NSMutableArray arrayWithCapacity:4];
9699 broken_ = [NSMutableArray arrayWithCapacity:4];
9701 // XXX: I really need this thing... like, seriously... I'm sorry
9702 appcache_ = [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] autorelease];
9703 [appcache_ reloadData];
9705 window_ = [[[CyteWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9706 [window_ orderFront:self];
9707 [window_ makeKey:self];
9708 [window_ setHidden:NO];
9710 if (access("/.cydia_no_stash", F_OK) == 0);
9714 [self addStashController];
9715 // XXX: this would be much cleaner as a yieldToSelector:
9716 // that way the removeStashController could happen right here inline
9717 // we also could no longer require the useless stash_ field anymore
9718 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9723 int error(stat("/", &root));
9724 _assert(error != -1);
9726 #define Stash_(path) do { \
9727 struct stat folder; \
9728 int error(lstat((path), &folder)); \
9729 if (error != -1 && ( \
9730 folder.st_dev == root.st_dev && \
9731 S_ISDIR(folder.st_mode) \
9732 ) || error == -1 && ( \
9733 errno == ENOENT || \
9738 Stash_("/Applications");
9739 Stash_("/Library/Ringtones");
9740 Stash_("/Library/Wallpaper");
9741 //Stash_("/usr/bin");
9742 Stash_("/usr/include");
9743 Stash_("/usr/share");
9744 //Stash_("/var/lib");
9748 database_ = [Database sharedInstance];
9749 [database_ setDelegate:self];
9751 [window_ setUserInteractionEnabled:NO];
9753 tabbar_ = [[[CydiaTabBarController alloc] initWithDatabase:database_] autorelease];
9755 [tabbar_ addViewControllers:nil,
9756 @"Cydia", @"home.png", @"home7.png", @"home7s.png",
9757 UCLocalize("SOURCES"), @"install.png", @"install7.png", @"install7s.png",
9758 UCLocalize("CHANGES"), @"changes.png", @"changes7.png", @"changes7s.png",
9759 UCLocalize("INSTALLED"), @"manage.png", @"manage7.png", @"manage7s.png",
9760 UCLocalize("SEARCH"), @"search.png", @"search7.png", @"search7s.png",
9763 [tabbar_ setUpdateDelegate:self];
9765 CydiaLoadingViewController *loading([[[CydiaLoadingViewController alloc] init] autorelease]);
9766 UINavigationController *navigation([[[UINavigationController alloc] init] autorelease]);
9767 [navigation setViewControllers:[NSArray arrayWithObject:loading]];
9769 emulated_ = [[[CyteTabBarController alloc] init] autorelease];
9770 [emulated_ setViewControllers:[NSArray arrayWithObject:navigation]];
9771 [emulated_ setSelectedIndex:0];
9773 if ([emulated_ respondsToSelector:@selector(concealTabBarSelection)])
9774 [emulated_ concealTabBarSelection];
9776 [window_ setRootViewController:emulated_];
9778 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9782 - (NSArray *) defaultStartPages {
9783 NSMutableArray *standard = [NSMutableArray array];
9784 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9785 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9786 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9787 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9788 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9794 if ([emulated_ modalViewController] != nil)
9795 [emulated_ dismissModalViewControllerAnimated:YES];
9796 [window_ setUserInteractionEnabled:NO];
9798 [self reloadDataWithInvocation:nil];
9799 [self refreshIfPossible];
9802 NSDictionary *state([NSDictionary dictionaryWithContentsOfFile:@ SavedState_]);
9804 int savedIndex = [[state objectForKey:@"InterfaceIndex"] intValue];
9805 NSArray *saved = [[[state objectForKey:@"InterfaceState"] mutableCopy] autorelease];
9806 int standardIndex = 0;
9807 NSArray *standard = [self defaultStartPages];
9814 NSDate *closed = [state objectForKey:@"LastClosed"];
9815 if (valid && closed != nil) {
9816 NSTimeInterval interval([closed timeIntervalSinceNow]);
9817 if (interval <= -(30*60))
9821 if (valid && [saved count] != [standard count])
9825 for (unsigned int i = 0; i < [standard count]; i++) {
9826 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9827 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9828 // but it's good enough for now.
9829 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9836 NSArray *items = nil;
9838 [tabbar_ setSelectedIndex:savedIndex];
9841 [tabbar_ setSelectedIndex:standardIndex];
9845 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9846 NSArray *stack = [items objectAtIndex:tab];
9847 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9848 NSMutableArray *current = [NSMutableArray array];
9850 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9851 NSString *addr = [stack objectAtIndex:nav];
9852 NSURL *url = [NSURL URLWithString:addr];
9853 CyteViewController *page = [self pageForURL:url forExternal:NO withReferrer:nil];
9855 [current addObject:page];
9858 [navigation setViewControllers:current];
9861 // (Try to) show the startup URL.
9862 if (starturl_ != nil) {
9863 [self openCydiaURL:starturl_ forExternal:YES];
9868 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9870 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
9871 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
9874 if (item != nil && IsWildcat_) {
9875 [sheet showFromBarButtonItem:item animated:YES];
9877 [sheet showInView:window_];
9881 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9882 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9883 [progress setTitle:task];
9884 [progress addProgressEvent:event];
9887 - (void) addProgressEventForTask:(NSArray *)data {
9888 CydiaProgressEvent *event([data objectAtIndex:0]);
9889 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9890 [self addProgressEvent:event forTask:task];
9893 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9894 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9900 id Alloc_(id self, SEL selector) {
9901 id object = alloc_(self, selector);
9902 lprintf("[%s]A-%p\n", self->isa->name, object);
9907 id Dealloc_(id self, SEL selector) {
9908 id object = dealloc_(self, selector);
9909 lprintf("[%s]D-%p\n", self->isa->name, object);
9913 static NSMutableDictionary *AutoreleaseDeepMutableCopyOfDictionary(CFTypeRef type) {
9916 if (CFGetTypeID(type) != CFDictionaryGetTypeID())
9918 CFTypeRef copy(CFPropertyListCreateDeepCopy(kCFAllocatorDefault, type, kCFPropertyListMutableContainers));
9920 return [(NSMutableDictionary *) copy autorelease];
9923 int main_store(int, char *argv[]);
9925 int main(int argc, char *argv[]) {
9927 const char *argv0(argv[0]);
9928 if (const char *slash = strrchr(argv0, '/'))
9931 else if (!strcmp(argv0, "store"))
9932 return main_store(argc, argv);
9935 int fd(open("/tmp/cydia.log", O_WRONLY | O_APPEND | O_CREAT, 0644));
9939 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9943 UpdateExternalStatus(0);
9945 Idiom_ = IsWildcat_ ? @"ipad" : @"iphone";
9947 RegEx pattern("([0-9]+\\.[0-9]+).*");
9949 UIDevice *device([UIDevice currentDevice]);
9950 if (pattern([device systemVersion]))
9951 Firmware_ = pattern[1];
9953 if (pattern(Cydia_))
9954 Major_ = pattern[1];
9956 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
9958 HostConfig_ = [[[NSObject alloc] init] autorelease];
9959 @synchronized (HostConfig_) {
9960 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
9961 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
9964 NSString *ui(@"ui/ios");
9966 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
9967 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"/%@", Major_]];
9970 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9972 /* Set Locale {{{ */
9973 Locale_ = CFLocaleCopyCurrent();
9974 Languages_ = [NSLocale preferredLanguages];
9976 std::string languages;
9977 const char *translation(NULL);
9979 // XXX: this isn't really a language, but this is compatible with older Cydia builds
9980 if (Locale_ != NULL)
9981 if (const char *language = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String]) {
9982 RegEx pattern("([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?");
9983 if (pattern(language)) {
9984 translation = strdup([pattern->*@"%1$@%2$@" UTF8String]);
9985 languages += translation;
9990 if (Languages_ != nil)
9991 for (NSString *locale : Languages_) {
9992 auto components([NSLocale componentsFromLocaleIdentifier:locale]);
9993 NSString *language([components objectForKey:(id)kCFLocaleLanguageCode]);
9994 if (NSString *script = [components objectForKey:(id)kCFLocaleScriptCode])
9995 language = [NSString stringWithFormat:@"%@-%@", language, script];
9996 languages += [language UTF8String];
10001 NSLog(@"Setting Language: [%s] %s", translation, languages.c_str());
10003 /* Index Collation {{{ */
10004 if (Class $UILocalizedIndexedCollation = objc_getClass("UILocalizedIndexedCollation")) { @try {
10005 NSBundle *bundle([NSBundle bundleForClass:$UILocalizedIndexedCollation]);
10006 NSString *path([bundle pathForResource:@"UITableViewLocalizedSectionIndex" ofType:@"plist"]);
10007 //path = @"/System/Library/Frameworks/UIKit.framework/.lproj/UITableViewLocalizedSectionIndex.plist";
10008 NSDictionary *dictionary([NSDictionary dictionaryWithContentsOfFile:path]);
10009 _H<UILocalizedIndexedCollation> collation([[[$UILocalizedIndexedCollation alloc] initWithDictionary:dictionary] autorelease]);
10011 CollationLocale_ = MSHookIvar<NSLocale *>(collation, "_locale");
10013 if (kCFCoreFoundationVersionNumber >= 800 && [[CollationLocale_ localeIdentifier] isEqualToString:@"zh@collation=stroke"]) {
10014 CollationThumbs_ = [NSArray arrayWithObjects:@"1",@"•",@"4",@"•",@"7",@"•",@"10",@"•",@"13",@"•",@"16",@"•",@"19",@"A",@"•",@"E",@"•",@"I",@"•",@"M",@"•",@"R",@"•",@"V",@"•",@"Z",@"#",nil];
10015 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})
10016 CollationOffset_.push_back(offset);
10017 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];
10018 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];
10021 CollationThumbs_ = [collation sectionIndexTitles];
10022 for (size_t index(0), end([CollationThumbs_ count]); index != end; ++index)
10023 CollationOffset_.push_back([collation sectionForSectionIndexTitleAtIndex:index]);
10025 CollationTitles_ = [collation sectionTitles];
10026 CollationStarts_ = MSHookIvar<NSArray *>(collation, "_sectionStartStrings");
10028 NSString *&transform(MSHookIvar<NSString *>(collation, "_transform"));
10029 if (&transform != NULL && transform != nil) {
10030 /*if ([collation respondsToSelector:@selector(transformedCollationStringForString:)])
10031 CollationModify_ = [=](NSString *value) { return [collation transformedCollationStringForString:value]; };*/
10032 const UChar *uid(reinterpret_cast<const UChar *>([transform cStringUsingEncoding:NSUnicodeStringEncoding]));
10033 UErrorCode code(U_ZERO_ERROR);
10034 CollationTransl_ = utrans_openU(uid, -1, UTRANS_FORWARD, NULL, 0, NULL, &code);
10035 if (!U_SUCCESS(code))
10036 NSLog(@"%s", u_errorName(code));
10040 } @catch (NSException *e) {
10044 CollationLocale_ = [[[NSLocale alloc] initWithLocaleIdentifier:@"en@collation=dictionary"] autorelease];
10046 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];
10047 for (NSInteger offset(0); offset != 28; ++offset)
10048 CollationOffset_.push_back(offset);
10050 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];
10051 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];
10055 App_ = [[NSBundle mainBundle] bundlePath];
10058 Cache_ = [[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia", @"/var/mobile"] retain];
10059 mkdir([Cache_ UTF8String], 0755);
10061 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10062 alloc_ = alloc->method_imp;
10063 alloc->method_imp = (IMP) &Alloc_;*/
10065 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10066 dealloc_ = dealloc->method_imp;
10067 dealloc->method_imp = (IMP) &Dealloc_;*/
10069 void *gestalt(dlopen("/usr/lib/libMobileGestalt.dylib", RTLD_GLOBAL | RTLD_LAZY));
10070 $MGCopyAnswer = reinterpret_cast<CFStringRef (*)(CFStringRef)>(dlsym(gestalt, "MGCopyAnswer"));
10072 /* System Information {{{ */
10076 size = sizeof(maxproc);
10077 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10078 perror("sysctlbyname(\"kern.maxproc\", ?)");
10079 else if (maxproc < 64) {
10081 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10082 perror("sysctlbyname(\"kern.maxproc\", #)");
10085 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10086 char *osversion = new char[size];
10087 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10088 perror("sysctlbyname(\"kern.osversion\", ?)");
10090 System_ = [NSString stringWithUTF8String:osversion];
10092 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10093 char *machine = new char[size];
10094 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10095 perror("sysctlbyname(\"hw.machine\", ?)");
10097 Machine_ = machine;
10099 int64_t usermem(0);
10100 size = sizeof(usermem);
10101 if (sysctlbyname("hw.usermem", &usermem, &size, NULL, 0) == -1)
10104 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10105 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10106 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10108 UniqueID_ = UniqueIdentifier(device);
10110 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10111 Product_ = [info objectForKey:@"SafariProductVersion"];
10112 Safari_ = [info objectForKey:@"CFBundleVersion"];
10115 NSString *agent([NSString stringWithFormat:@"Cydia/%@ CyF/%.2f", Cydia_, kCFCoreFoundationVersionNumber]);
10117 if (RegEx match = RegEx("([0-9]+(\\.[0-9]+)+).*", Safari_))
10118 agent = [NSString stringWithFormat:@"Safari/%@ %@", match[1], agent];
10119 if (RegEx match = RegEx("([0-9]+[A-Z][0-9]+[a-z]?).*", System_))
10120 agent = [NSString stringWithFormat:@"Mobile/%@ %@", match[1], agent];
10121 if (RegEx match = RegEx("([0-9]+(\\.[0-9]+)+).*", Product_))
10122 agent = [NSString stringWithFormat:@"Version/%@ %@", match[1], agent];
10124 UserAgent_ = agent;
10126 /* Load Database {{{ */
10127 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10130 mkdir("/var/mobile/Library/Cydia", 0755);
10131 MetaFile_.Open("/var/mobile/Library/Cydia/metadata.cb0");
10134 Values_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaValues"), CFSTR("com.saurik.Cydia")));
10135 Sections_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaSections"), CFSTR("com.saurik.Cydia")));
10136 Sources_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaSources"), CFSTR("com.saurik.Cydia")));
10137 Version_ = [(NSNumber *) CFPreferencesCopyAppValue(CFSTR("CydiaVersion"), CFSTR("com.saurik.Cydia")) autorelease];
10140 NSDictionary *metadata([[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease]);
10142 if (Values_ == nil)
10143 Values_ = [metadata objectForKey:@"Values"];
10144 if (Values_ == nil)
10145 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10147 if (Sections_ == nil)
10148 Sections_ = [metadata objectForKey:@"Sections"];
10149 if (Sections_ == nil)
10150 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10152 if (Sources_ == nil)
10153 Sources_ = [metadata objectForKey:@"Sources"];
10154 if (Sources_ == nil)
10155 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10157 // XXX: this wrong, but in a way that doesn't matter :/
10158 if (Version_ == nil)
10159 Version_ = [metadata objectForKey:@"Version"];
10160 if (Version_ == nil)
10161 Version_ = [NSNumber numberWithUnsignedInt:0];
10163 if (NSDictionary *packages = [metadata objectForKey:@"Packages"]) {
10165 CFDictionaryApplyFunction((CFDictionaryRef) packages, &PackageImport, &fail);
10168 NSLog(@"unable to import package preferences... from 2010? oh well :/");
10171 if ([Version_ unsignedIntValue] == 0) {
10172 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10173 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10174 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10175 CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./");
10177 Version_ = [NSNumber numberWithUnsignedInt:1];
10179 if (NSMutableDictionary *cache = [NSMutableDictionary dictionaryWithContentsOfFile:@ CacheState_]) {
10180 [cache removeObjectForKey:@"LastUpdate"];
10181 [cache writeToFile:@ CacheState_ atomically:YES];
10185 _H<NSMutableArray> broken([NSMutableArray array]);
10186 for (NSString *key in (id) Sources_)
10187 if ([key rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"# "]].location != NSNotFound || ![([[Sources_ objectForKey:key] objectForKey:@"URI"] ?: @"/") hasSuffix:@"/"])
10188 [broken addObject:key];
10189 if ([broken count] != 0)
10190 for (NSString *key in (id) broken)
10191 [Sources_ removeObjectForKey:key];
10195 system("/usr/libexec/cydia/cydo /bin/rm -f /var/lib/cydia/metadata.plist");
10198 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10200 if (kCFCoreFoundationVersionNumber > 1000)
10201 system("/usr/libexec/cydia/cydo /usr/libexec/cydia/setnsfpn /var/lib");
10203 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10205 if (access("/User", F_OK) != 0 || version != 6) {
10207 system("/usr/libexec/cydia/cydo /usr/libexec/cydia/firmware.sh");
10211 if (access("/tmp/cydia.chk", F_OK) == 0) {
10212 if (unlink([Cache("pkgcache.bin") UTF8String]) == -1)
10213 _assert(errno == ENOENT);
10214 if (unlink([Cache("srcpkgcache.bin") UTF8String]) == -1)
10215 _assert(errno == ENOENT);
10218 system("/usr/libexec/cydia/cydo /bin/ln -sf /var/mobile/Library/Caches/com.saurik.Cydia/sources.list /etc/apt/sources.list.d/cydia.list");
10220 /* APT Initialization {{{ */
10221 _assert(pkgInitConfig(*_config));
10222 _assert(pkgInitSystem(*_config, _system));
10224 _config->Set("Acquire::AllowInsecureRepositories", true);
10225 _config->Set("Acquire::Check-Valid-Until", false);
10226 _config->Set("Dir::Bin::Methods::store", "/Applications/Cydia.app/store");
10228 _config->Set("pkgCacheGen::ForceEssential", "");
10230 if (translation != NULL)
10231 _config->Set("APT::Acquire::Translation", translation);
10232 _config->Set("Acquire::Languages", languages);
10234 // XXX: this timeout might be important :(
10235 //_config->Set("Acquire::http::Timeout", 15);
10237 _config->Set("Acquire::http::MaxParallel", usermem >= 384 * 1024 * 1024 ? 16 : 3);
10239 mkdir([Cache("archives") UTF8String], 0755);
10240 mkdir([Cache("archives/partial") UTF8String], 0755);
10241 _config->Set("Dir::Cache", [Cache_ UTF8String]);
10243 symlink("/var/lib/apt/extended_states", [Cache("extended_states") UTF8String]);
10244 _config->Set("Dir::State", [Cache_ UTF8String]);
10246 mkdir([Cache("lists") UTF8String], 0755);
10247 mkdir([Cache("lists/partial") UTF8String], 0755);
10248 mkdir([Cache("periodic") UTF8String], 0755);
10249 _config->Set("Dir::State::Lists", [Cache("lists") UTF8String]);
10251 std::string logs("/var/mobile/Library/Logs/Cydia");
10252 mkdir(logs.c_str(), 0755);
10253 _config->Set("Dir::Log", logs);
10255 _config->Set("Dir::Bin::dpkg", "/usr/libexec/cydia/cydo");
10257 /* Color Choices {{{ */
10258 space_ = CGColorSpaceCreateDeviceRGB();
10260 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10261 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10262 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10263 Folder_.Set(space_, 0x8e/255.f, 0x8e/255.f, 0x93/255.f, 1.0);
10264 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10265 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10266 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10267 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10268 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10269 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10271 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10272 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10274 /* UIKit Configuration {{{ */
10275 // XXX: I have a feeling this was important
10276 //UIKeyboardDisableAutomaticAppearance();
10279 $SBSSetInterceptsMenuButtonForever = reinterpret_cast<void (*)(bool)>(dlsym(RTLD_DEFAULT, "SBSSetInterceptsMenuButtonForever"));
10280 $SBSCopyIconImagePNGDataForDisplayIdentifier = reinterpret_cast<NSData *(*)(NSString *)>(dlsym(RTLD_DEFAULT, "SBSCopyIconImagePNGDataForDisplayIdentifier"));
10282 const char *symbol(kCFCoreFoundationVersionNumber >= 800 ? "MGGetBoolAnswer" : "GSSystemHasCapability");
10283 BOOL (*GSSystemHasCapability)(CFStringRef) = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, symbol));
10284 bool fast = GSSystemHasCapability != NULL && GSSystemHasCapability(CFSTR("armv7"));
10286 PulseInterval_ = fast ? 50000 : 500000;
10288 Colon_ = UCLocalize("COLON_DELIMITED");
10289 Elision_ = UCLocalize("ELISION");
10290 Error_ = UCLocalize("ERROR");
10291 Warning_ = UCLocalize("WARNING");
10294 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10296 CGColorSpaceRelease(space_);
10297 CFRelease(Locale_);