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/Application.h"
116 #include "CyteKit/NavigationController.h"
117 #include "CyteKit/RegEx.hpp"
118 #include "CyteKit/TableViewCell.h"
119 #include "CyteKit/TabBarController.h"
120 #include "CyteKit/WebScriptObject-Cyte.h"
121 #include "CyteKit/WebViewController.h"
122 #include "CyteKit/WebViewTableViewCell.h"
123 #include "CyteKit/stringWithUTF8Bytes.h"
125 #include "Cydia/MIMEAddress.h"
126 #include "Cydia/LoadingViewController.h"
127 #include "Cydia/ProgressEvent.h"
129 #include "SDURLCache/SDURLCache.h"
136 #define _timestamp ({ \
138 gettimeofday(&tv, NULL); \
139 tv.tv_sec * 1000000 + tv.tv_usec; \
142 typedef std::vector<class ProfileTime *> TimeList;
152 ProfileTime(const char *name) :
156 times_.push_back(this);
159 void AddTime(uint64_t time) {
166 std::cerr << std::setw(7) << count_ << ", " << std::setw(8) << total_ << " : " << name_ << std::endl;
178 ProfileTimer(ProfileTime &time) :
185 time_.AddTime(_timestamp - start_);
190 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
192 std::cerr << "========" << std::endl;
195 #define _profile(name) { \
196 static ProfileTime name(#name); \
197 ProfileTimer _ ## name(name);
202 // XXX: I hate clang. Apple: please get over your petty hatred of GPL and fix your gcc fork
203 #define synchronized(lock) \
204 synchronized(static_cast<NSObject *>(lock))
206 extern NSString *Cydia_;
208 #define lprintf(args...) fprintf(stderr, args)
211 #define TraceLogging (1 && !ForRelease)
212 #define HistogramInsertionSort (0 && !ForRelease)
213 #define ProfileTimes (0 && !ForRelease)
214 #define ForSaurik (0 && !ForRelease)
215 #define LogBrowser (0 && !ForRelease)
216 #define TrackResize (0 && !ForRelease)
217 #define ManualRefresh (1 && !ForRelease)
218 #define ShowInternals (0 && !ForRelease)
219 #define AlwaysReload (0 && !ForRelease)
223 #define _trace(args...)
228 #define _profile(name) {
231 #define PrintTimes() do {} while (false)
234 // Hash Functions/Structures {{{
235 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
243 @implementation NSDictionary (Cydia)
244 - (id) invokeUndefinedMethodFromWebScript:(NSString *)name withArguments:(NSArray *)arguments {
246 else if ([name isEqualToString:@"get"])
247 return [self objectForKey:[arguments objectAtIndex:0]];
248 else if ([name isEqualToString:@"keys"])
249 return [self allKeys];
253 static NSString *Colon_;
255 static NSString *Error_;
256 static NSString *Warning_;
258 static NSString *Cache_;
259 #define Cache(file) \
260 [NSString stringWithFormat:@"%@/%s", Cache_, file]
262 static void (*$SBSSetInterceptsMenuButtonForever)(bool);
263 static NSData *(*$SBSCopyIconImagePNGDataForDisplayIdentifier)(NSString *);
265 static CFStringRef (*$MGCopyAnswer)(CFStringRef);
267 static NSString *UniqueIdentifier(UIDevice *device = nil) {
268 if (kCFCoreFoundationVersionNumber < 800) // iOS 7.x
269 return [device ?: [UIDevice currentDevice] uniqueIdentifier];
271 return [(id)$MGCopyAnswer(CFSTR("UniqueDeviceID")) autorelease];
274 static bool IsReachable(const char *name) {
275 SCNetworkReachabilityFlags flags; {
276 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, name));
277 SCNetworkReachabilityGetFlags(reachability, &flags);
278 CFRelease(reachability);
281 // XXX: this elaborate mess is what Apple is using to determine this? :(
282 // XXX: do we care if the user has to intervene? maybe that's ok?
284 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
285 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
286 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
287 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
288 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
289 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
294 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
296 static _finline NSString *CydiaURL(NSString *path) {
298 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
299 page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
300 page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
301 page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
302 page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
304 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
307 static NSString *ShellEscape(NSString *value) {
308 return [NSString stringWithFormat:@"'%@'", [value stringByReplacingOccurrencesOfString:@"'" withString:@"'\\''"]];
311 static _finline void UpdateExternalStatus(uint64_t newStatus) {
313 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
314 notify_set_state(notify_token, newStatus);
315 notify_cancel(notify_token);
317 notify_post("com.saurik.Cydia.status");
320 static CGFloat CYStatusBarHeight() {
321 CGSize size([[UIApplication sharedApplication] statusBarFrame].size);
322 return UIInterfaceOrientationIsPortrait([[UIApplication sharedApplication] statusBarOrientation]) ? size.height : size.width;
325 /* NSForcedOrderingSearch doesn't work on the iPhone */
326 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
327 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
328 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
330 /* Insertion Sort {{{ */
332 template <typename Type_>
333 size_t CFBSearch_(const Type_ &element, const void *list, size_t count, CFComparisonResult (*comparator)(Type_, Type_, void *), void *context) {
334 const char *ptr = (const char *)list;
336 size_t half = count / 2;
337 const char *probe = ptr + sizeof(Type_) * half;
338 CFComparisonResult cr = comparator(element, * (const Type_ *) probe, context);
339 if (0 == cr) return (probe - (const char *)list) / sizeof(Type_);
340 ptr = (cr < 0) ? ptr : probe + sizeof(Type_);
341 count = (cr < 0) ? half : (half + (count & 1) - 1);
343 return (ptr - (const char *)list) / sizeof(Type_);
346 template <typename Type_>
347 void CYArrayInsertionSortValues(Type_ *values, size_t length, CFComparisonResult (*comparator)(Type_, Type_, void *), void *context) {
351 #if HistogramInsertionSort > 0
352 uint32_t total(0), *offsets(new uint32_t[length]);
355 for (size_t index(1); index != length; ++index) {
356 Type_ value(values[index]);
358 size_t correct(CFBSearch_(value, values, index, comparator, context));
360 size_t correct(index);
361 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
362 #if HistogramInsertionSort > 1
363 NSLog(@"%@ < %@", value, values[correct - 1]);
367 if (index - correct >= 8) {
368 correct = CFBSearch_(value, values, correct, comparator, context);
373 if (correct != index) {
374 size_t offset(index - correct);
375 #if HistogramInsertionSort
379 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
381 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
382 values[correct] = value;
386 #if HistogramInsertionSort > 0
387 for (size_t index(0); index != range.length; ++index)
388 if (offsets[index] != 0)
389 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
390 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
397 /* Apple Bug Fixes {{{ */
398 @implementation UIWebDocumentView (Cydia)
400 - (void) _setScrollerOffset:(CGPoint)offset {
401 UIScroller *scroller([self _scroller]);
403 CGSize size([scroller contentSize]);
404 CGSize bounds([scroller bounds].size);
407 max.x = size.width - bounds.width;
408 max.y = size.height - bounds.height;
416 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
417 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
419 [scroller setOffset:offset];
425 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
426 size_t length([self length] - state->state);
429 else if (length > count)
431 for (size_t i(0); i != length; ++i)
432 objects[i] = [self item:state->state++];
433 state->itemsPtr = objects;
434 state->mutationsPtr = (unsigned long *) self;
438 /* Cydia NSString Additions {{{ */
439 @interface NSString (Cydia)
440 - (NSComparisonResult) compareByPath:(NSString *)other;
441 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
444 @implementation NSString (Cydia)
446 - (NSComparisonResult) compareByPath:(NSString *)other {
447 NSString *prefix = [self commonPrefixWithString:other options:0];
448 size_t length = [prefix length];
450 NSRange lrange = NSMakeRange(length, [self length] - length);
451 NSRange rrange = NSMakeRange(length, [other length] - length);
453 lrange = [self rangeOfString:@"/" options:0 range:lrange];
454 rrange = [other rangeOfString:@"/" options:0 range:rrange];
456 NSComparisonResult value;
458 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
459 value = NSOrderedSame;
460 else if (lrange.location == NSNotFound)
461 value = NSOrderedAscending;
462 else if (rrange.location == NSNotFound)
463 value = NSOrderedDescending;
465 value = NSOrderedSame;
467 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
468 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
469 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
470 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
472 NSComparisonResult result = [lpath compare:rpath];
473 return result == NSOrderedSame ? value : result;
476 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
477 return [(id)CFURLCreateStringByAddingPercentEscapes(
482 kCFStringEncodingUTF8
489 /* C++ NSString Wrapper Cache {{{ */
490 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
491 return size == 0 ? NULL :
492 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
493 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
496 static _finline CFStringRef CYStringCreate(const std::string &data) {
497 return CYStringCreate(data.data(), data.size());
500 static _finline CFStringRef CYStringCreate(const char *data) {
501 return CYStringCreate(data, strlen(data));
510 _finline void clear_() {
511 if (cache_ != NULL) {
518 _finline bool empty() const {
522 _finline size_t size() const {
526 _finline char *data() const {
530 _finline void clear() {
535 _finline CYString() :
542 _finline ~CYString() {
546 void operator =(const CYString &rhs) {
550 if (rhs.cache_ == nil)
553 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
556 void copy(CYPool *pool) {
557 char *temp(pool->malloc<char>(size_ + 1));
558 memcpy(temp, data_, size_);
563 void set(CYPool *pool, const char *data, size_t size) {
569 data_ = const_cast<char *>(data);
577 _finline void set(CYPool *pool, const char *data) {
578 set(pool, data, data == NULL ? 0 : strlen(data));
581 _finline void set(CYPool *pool, const std::string &rhs) {
582 set(pool, rhs.data(), rhs.size());
585 bool operator ==(const CYString &rhs) const {
586 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
589 _finline operator CFStringRef() {
591 cache_ = CYStringCreate(data_, size_);
595 _finline operator id() {
596 return (NSString *) static_cast<CFStringRef>(*this);
599 _finline operator const char *() {
600 return reinterpret_cast<const char *>(data_);
604 /* C++ NSString Algorithm Adapters {{{ */
606 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
609 struct NSStringMapHash :
610 std::unary_function<NSString *, size_t>
612 _finline size_t operator ()(NSString *value) const {
613 return CFStringHashNSString((CFStringRef) value);
617 struct NSStringMapLess :
618 std::binary_function<NSString *, NSString *, bool>
620 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
621 return [lhs compare:rhs] == NSOrderedAscending;
625 struct NSStringMapEqual :
626 std::binary_function<NSString *, NSString *, bool>
628 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
629 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
630 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
631 //[lhs isEqualToString:rhs];
636 /* CoreGraphics Primitives {{{ */
641 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
642 CGFloat color[] = {red, green, blue, alpha};
643 return CGColorCreate(space, color);
652 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
653 color_(Create_(space, red, green, blue, alpha))
655 Set(space, red, green, blue, alpha);
660 CGColorRelease(color_);
667 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
669 color_ = Create_(space, red, green, blue, alpha);
672 operator CGColorRef() {
678 /* Random Global Variables {{{ */
679 static int PulseInterval_ = 500000;
681 static const NSString *UI_;
684 static bool RestartSubstrate_;
685 static NSArray *Finishes_;
687 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
688 #define NotifyConfig_ "/etc/notify.conf"
690 static bool Queuing_;
692 static CYColor Blue_;
693 static CYColor Blueish_;
694 static CYColor Black_;
695 static CYColor Folder_;
697 static CYColor White_;
698 static CYColor Gray_;
699 static CYColor Green_;
700 static CYColor Purple_;
701 static CYColor Purplish_;
703 static UIColor *InstallingColor_;
704 static UIColor *RemovingColor_;
706 static NSString *App_;
708 static BOOL Advanced_;
709 static BOOL Ignored_;
711 static _H<UIFont> Font12_;
712 static _H<UIFont> Font12Bold_;
713 static _H<UIFont> Font14_;
714 static _H<UIFont> Font18_;
715 static _H<UIFont> Font18Bold_;
716 static _H<UIFont> Font22Bold_;
718 static const char *Machine_ = NULL;
719 static _H<NSString> System_;
720 static NSString *SerialNumber_ = nil;
721 static NSString *ChipID_ = nil;
722 static NSString *BBSNum_ = nil;
723 static _H<NSString> UniqueID_;
724 static _H<NSString> UserAgent_;
725 static _H<NSString> Product_;
726 static _H<NSString> Safari_;
728 static _H<NSLocale> CollationLocale_;
729 static _H<NSArray> CollationThumbs_;
730 static std::vector<NSInteger> CollationOffset_;
731 static _H<NSArray> CollationTitles_;
732 static _H<NSArray> CollationStarts_;
733 static UTransliterator *CollationTransl_;
734 //static Function<NSString *, NSString *> CollationModify_;
736 typedef std::basic_string<UChar> ustring;
737 static ustring CollationString_;
739 #define CUC const ustring &str(*reinterpret_cast<const ustring *>(rep))
740 #define UC ustring &str(*reinterpret_cast<ustring *>(rep))
741 static struct UReplaceableCallbacks CollationUCalls_ = {
742 .length = [](const UReplaceable *rep) -> int32_t { CUC;
746 .charAt = [](const UReplaceable *rep, int32_t offset) -> UChar { CUC;
747 //fprintf(stderr, "charAt(%d) : %d\n", offset, str.size());
748 if (offset >= str.size())
753 .char32At = [](const UReplaceable *rep, int32_t offset) -> UChar32 { CUC;
754 //fprintf(stderr, "char32At(%d) : %d\n", offset, str.size());
755 if (offset >= str.size())
758 U16_GET(str.data(), 0, offset, str.size(), c);
762 .replace = [](UReplaceable *rep, int32_t start, int32_t limit, const UChar *text, int32_t length) -> void { UC;
763 //fprintf(stderr, "replace(%d, %d, %d) : %d\n", start, limit, length, str.size());
764 str.replace(start, limit - start, text, length);
767 .extract = [](UReplaceable *rep, int32_t start, int32_t limit, UChar *dst) -> void { UC;
768 //fprintf(stderr, "extract(%d, %d) : %d\n", start, limit, str.size());
769 str.copy(dst, limit - start, start);
772 .copy = [](UReplaceable *rep, int32_t start, int32_t limit, int32_t dest) -> void { UC;
773 //fprintf(stderr, "copy(%d, %d, %d) : %d\n", start, limit, dest, str.size());
774 str.replace(dest, 0, str, start, limit - start);
778 static CFLocaleRef Locale_;
779 static NSArray *Languages_;
780 static CGColorSpaceRef space_;
782 #define CacheState_ "/var/mobile/Library/Caches/com.saurik.Cydia/CacheState.plist"
783 #define SavedState_ "/var/mobile/Library/Caches/com.saurik.Cydia/SavedState.plist"
785 static NSDictionary *SectionMap_;
786 static _H<NSDate> Backgrounded_;
787 static _transient NSMutableDictionary *Values_;
788 static _transient NSMutableDictionary *Sections_;
789 _H<NSMutableDictionary> Sources_;
790 static _transient NSNumber *Version_;
794 CGFloat ScreenScale_;
795 static NSString *Idiom_;
796 static _H<NSString> Firmware_;
797 static NSString *Major_;
799 static _H<NSMutableDictionary> SessionData_;
800 static _H<NSObject> HostConfig_;
801 static _H<NSMutableSet> BridgedHosts_;
802 static _H<NSMutableSet> InsecureHosts_;
803 static _H<NSMutableSet> CachedURLs_;
805 static NSString *kCydiaProgressEventTypeError = @"Error";
806 static NSString *kCydiaProgressEventTypeInformation = @"Information";
807 static NSString *kCydiaProgressEventTypeStatus = @"Status";
808 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
811 /* Display Helpers {{{ */
812 inline float Interpolate(float begin, float end, float fraction) {
813 return (end - begin) * fraction + begin;
816 static inline double Retina(double value) {
817 value *= ScreenScale_;
818 value = round(value);
819 value /= ScreenScale_;
823 static inline CGRect Retina(CGRect value) {
824 value.origin.x *= ScreenScale_;
825 value.origin.y *= ScreenScale_;
826 value.size.width *= ScreenScale_;
827 value.size.height *= ScreenScale_;
828 value = CGRectIntegral(value);
829 value.origin.x /= ScreenScale_;
830 value.origin.y /= ScreenScale_;
831 value.size.width /= ScreenScale_;
832 value.size.height /= ScreenScale_;
836 static _finline const char *StripVersion_(const char *version) {
837 const char *colon(strchr(version, ':'));
838 return colon == NULL ? version : colon + 1;
841 NSString *LocalizeSection(NSString *section) {
842 static RegEx title_r("(.*?) \\((.*)\\)");
843 if (title_r(section)) {
844 NSString *parent(title_r[1]);
845 NSString *child(title_r[2]);
847 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
848 LocalizeSection(parent),
849 LocalizeSection(child)
853 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
856 NSString *Simplify(NSString *title) {
857 const char *data = [title UTF8String];
858 size_t size = [title lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
860 static RegEx square_r("\\[(.*)\\]");
861 if (square_r(data, size))
862 return Simplify(square_r[1]);
864 static RegEx paren_r("\\((.*)\\)");
865 if (paren_r(data, size))
866 return Simplify(paren_r[1]);
868 static RegEx title_r("(.*?) \\((.*)\\)");
869 if (title_r(data, size))
870 return Simplify(title_r[1]);
876 bool isSectionVisible(NSString *section) {
877 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
878 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
879 return hidden == nil || ![hidden boolValue];
882 static NSObject *CYIOGetValue(const char *path, NSString *property) {
883 io_registry_entry_t entry(IORegistryEntryFromPath(kIOMasterPortDefault, path));
884 if (entry == MACH_PORT_NULL)
887 CFTypeRef value(IORegistryEntryCreateCFProperty(entry, (CFStringRef) property, kCFAllocatorDefault, 0));
888 IOObjectRelease(entry);
892 return [(id) value autorelease];
895 static NSString *CYHex(NSData *data, bool reverse = false) {
899 size_t length([data length]);
900 uint8_t bytes[length];
901 [data getBytes:bytes];
903 char string[length * 2 + 1];
904 for (size_t i(0); i != length; ++i)
905 sprintf(string + i * 2, "%.2x", bytes[reverse ? length - i - 1 : i]);
907 return [NSString stringWithUTF8String:string];
910 static NSString *VerifySource(NSString *href) {
911 static RegEx href_r("(http(s?)://|file:///)[^# ]*");
913 [[[[UIAlertView alloc]
914 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("INVALID_URL")]
915 message:UCLocalize("INVALID_URL_EX")
917 cancelButtonTitle:UCLocalize("OK")
918 otherButtonTitles:nil
919 ] autorelease] show];
924 if (![href hasSuffix:@"/"])
925 href = [href stringByAppendingString:@"/"];
931 /* Delegate Prototypes {{{ */
934 @class CydiaProgressEvent;
936 @protocol DatabaseDelegate
937 - (void) repairWithSelector:(SEL)selector;
938 - (void) setConfigurationData:(NSString *)data;
939 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
942 @class CYPackageController;
944 @protocol SourceDelegate
945 - (void) setFetch:(NSNumber *)fetch;
948 @protocol FetchDelegate
949 - (bool) isSourceCancelled;
950 - (void) startSourceFetch:(NSString *)uri;
951 - (void) stopSourceFetch:(NSString *)uri;
954 @protocol CydiaDelegate
955 - (void) returnToCydia;
957 - (void) retainNetworkActivityIndicator;
958 - (void) releaseNetworkActivityIndicator;
959 - (void) clearPackage:(Package *)package;
960 - (void) installPackage:(Package *)package;
961 - (void) installPackages:(NSArray *)packages;
962 - (void) removePackage:(Package *)package;
963 - (void) beginUpdate;
965 - (bool) requestUpdate;
966 - (void) distUpgrade;
969 - (void) _saveConfig;
971 - (void) addSource:(NSDictionary *)source;
972 - (BOOL) addTrivialSource:(NSString *)href;
973 - (UIProgressHUD *) addProgressHUD;
974 - (void) removeProgressHUD:(UIProgressHUD *)hud;
975 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
976 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
980 /* CancelStatus {{{ */
982 public pkgAcquireStatus
993 virtual bool MediaChange(std::string media, std::string drive) {
997 virtual void IMSHit(pkgAcquire::ItemDesc &desc) {
1001 virtual bool Pulse_(pkgAcquire *Owner) = 0;
1003 virtual bool Pulse(pkgAcquire *Owner) {
1004 if (pkgAcquireStatus::Pulse(Owner) && Pulse_(Owner))
1012 _finline bool WasCancelled() const {
1017 /* DelegateStatus {{{ */
1022 _transient NSObject<ProgressDelegate> *delegate_;
1030 void setDelegate(NSObject<ProgressDelegate> *delegate) {
1031 delegate_ = delegate;
1034 virtual void Fetch(pkgAcquire::ItemDesc &desc) {
1035 NSString *name([NSString stringWithUTF8String:desc.ShortDesc.c_str()]);
1036 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItemDesc:desc]);
1037 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1040 virtual void Done(pkgAcquire::ItemDesc &desc) {
1041 NSString *name([NSString stringWithUTF8String:desc.ShortDesc.c_str()]);
1042 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:Colon_, UCLocalize("DONE"), name] ofType:kCydiaProgressEventTypeStatus forItemDesc:desc]);
1043 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1046 virtual void Fail(pkgAcquire::ItemDesc &desc) {
1048 desc.Owner->Status == pkgAcquire::Item::StatIdle ||
1049 desc.Owner->Status == pkgAcquire::Item::StatDone
1053 std::string &error(desc.Owner->ErrorText);
1057 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItemDesc:desc]);
1058 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1061 virtual bool Pulse_(pkgAcquire *Owner) {
1063 double(CurrentBytes + CurrentItems) /
1064 double(TotalBytes + TotalItems)
1067 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
1068 [NSNumber numberWithDouble:percent], @"Percent",
1070 [NSNumber numberWithDouble:CurrentBytes], @"Current",
1071 [NSNumber numberWithDouble:TotalBytes], @"Total",
1072 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
1073 nil] waitUntilDone:YES];
1075 return ![delegate_ isProgressCancelled];
1078 virtual void Start() {
1079 pkgAcquireStatus::Start();
1080 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
1083 virtual void Stop() {
1084 pkgAcquireStatus::Stop();
1085 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
1086 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
1090 /* Database Interface {{{ */
1091 typedef std::map< unsigned long, _H<Source> > SourceMap;
1093 @interface Database : NSObject {
1100 pkgCacheFile cache_;
1101 pkgDepCache::Policy *policy_;
1102 pkgRecords *records_;
1103 pkgProblemResolver *resolver_;
1104 pkgAcquire *fetcher_;
1106 SPtr<pkgPackageManager> manager_;
1107 pkgSourceList *list_;
1109 SourceMap sourceMap_;
1110 _H<NSMutableArray> sourceList_;
1112 _H<NSArray> packages_;
1114 _transient NSObject<DatabaseDelegate> *delegate_;
1115 _transient NSObject<ProgressDelegate> *progress_;
1117 CydiaStatus status_;
1123 std::map<const char *, _H<NSString> > sections_;
1126 + (Database *) sharedInstance;
1128 - (bool) hasPackages;
1130 - (void) _readCydia:(NSNumber *)fd;
1131 - (void) _readStatus:(NSNumber *)fd;
1132 - (void) _readOutput:(NSNumber *)fd;
1136 - (Package *) packageWithName:(NSString *)name;
1138 - (pkgCacheFile &) cache;
1139 - (pkgDepCache::Policy *) policy;
1140 - (pkgRecords *) records;
1141 - (pkgProblemResolver *) resolver;
1142 - (pkgAcquire &) fetcher;
1143 - (pkgSourceList &) list;
1144 - (NSArray *) packages;
1145 - (NSArray *) sources;
1146 - (Source *) sourceWithKey:(NSString *)key;
1147 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1155 - (void) updateWithStatus:(CancelStatus &)status;
1157 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1159 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1160 - (NSObject<ProgressDelegate> *) progressDelegate;
1162 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1163 - (void) setFetch:(bool)fetch forURI:(const char *)uri;
1164 - (void) resetFetch;
1166 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1170 /* SourceStatus {{{ */
1171 class SourceStatus :
1175 _transient NSObject<FetchDelegate> *delegate_;
1176 _transient Database *database_;
1177 std::set<std::string> fetches_;
1180 SourceStatus(NSObject<FetchDelegate> *delegate, Database *database) :
1181 delegate_(delegate),
1186 void Set(bool fetch, const std::string &uri) {
1188 if (!fetches_.insert(uri).second)
1191 if (fetches_.erase(uri) == 0)
1195 //printf("Set(%s, %s)\n", fetch ? "true" : "false", uri.c_str());
1197 auto slash(uri.rfind('/'));
1198 if (slash != std::string::npos)
1199 [database_ setFetch:fetch forURI:uri.substr(0, slash).c_str()];
1202 _finline void Set(bool fetch, pkgAcquire::Item *item) {
1203 /*unsigned long ID(fetch ? 1 : 0);
1207 Set(fetch, item->DescURI());
1210 void Log(const char *tag, pkgAcquire::Item *item) {
1211 //printf("%s(%s) S:%u Q:%u\n", tag, item->DescURI().c_str(), item->Status, item->QueueCounter);
1214 virtual void Fetch(pkgAcquire::ItemDesc &desc) {
1215 Log("Fetch", desc.Owner);
1216 Set(true, desc.Owner);
1219 virtual void Done(pkgAcquire::ItemDesc &desc) {
1220 Log("Done", desc.Owner);
1221 Set(false, desc.Owner);
1224 virtual void Fail(pkgAcquire::ItemDesc &desc) {
1225 Log("Fail", desc.Owner);
1226 Set(false, desc.Owner);
1229 virtual bool Pulse_(pkgAcquire *Owner) {
1230 std::set<std::string> fetches;
1231 for (pkgAcquire::ItemCIterator item(Owner->ItemsBegin()); item != Owner->ItemsEnd(); ++item) {
1233 if ((*item)->QueueCounter == 0)
1235 else switch ((*item)->Status) {
1236 case pkgAcquire::Item::StatFetching:
1237 fetches.insert((*item)->DescURI());
1246 Log(fetch ? "Pulse<true>" : "Pulse<false>", *item);
1250 std::vector<std::string> stops;
1251 std::set_difference(fetches_.begin(), fetches_.end(), fetches.begin(), fetches.end(), std::back_insert_iterator<std::vector<std::string>>(stops));
1252 for (std::vector<std::string>::const_iterator stop(stops.begin()); stop != stops.end(); ++stop) {
1253 //printf("Stop(%s)\n", stop->c_str());
1257 return ![delegate_ isSourceCancelled];
1260 virtual void Stop() {
1261 pkgAcquireStatus::Stop();
1262 [database_ resetFetch];
1266 /* ProgressEvent Implementation {{{ */
1267 @implementation CydiaProgressEvent
1269 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1270 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1273 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1274 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1275 [event setPackage:package];
1279 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItemDesc:(pkgAcquire::ItemDesc &)desc {
1280 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1282 NSString *description([NSString stringWithUTF8String:desc.Description.c_str()]);
1283 NSArray *fields([description componentsSeparatedByString:@" "]);
1284 [event setItem:fields];
1286 if ([fields count] > 3) {
1287 [event setPackage:[fields objectAtIndex:2]];
1288 [event setVersion:[fields objectAtIndex:3]];
1291 [event setURL:[NSString stringWithUTF8String:desc.URI.c_str()]];
1296 + (NSArray *) _attributeKeys {
1297 return [NSArray arrayWithObjects:
1307 - (NSArray *) attributeKeys {
1308 return [[self class] _attributeKeys];
1311 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1312 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1315 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1316 if ((self = [super init]) != nil) {
1322 - (NSString *) message {
1326 - (NSString *) type {
1330 - (NSArray *) item {
1331 return (id) item_ ?: [NSNull null];
1334 - (void) setItem:(NSArray *)item {
1338 - (NSString *) package {
1339 return (id) package_ ?: [NSNull null];
1342 - (void) setPackage:(NSString *)package {
1346 - (NSString *) url {
1347 return (id) url_ ?: [NSNull null];
1350 - (void) setURL:(NSString *)url {
1354 - (void) setVersion:(NSString *)version {
1358 - (NSString *) version {
1359 return (id) version_ ?: [NSNull null];
1362 - (NSString *) compound:(NSString *)value {
1364 NSString *mode(nil); {
1365 NSString *type([self type]);
1366 if ([type isEqualToString:kCydiaProgressEventTypeError])
1367 mode = UCLocalize("ERROR");
1368 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1369 mode = UCLocalize("WARNING");
1373 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1379 - (NSString *) compoundMessage {
1380 return [self compound:[self message]];
1383 - (NSString *) compoundTitle {
1386 if (package_ == nil)
1388 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1389 title = [package name];
1393 return [self compound:title];
1399 // Cytore Definitions {{{
1400 struct PackageValue :
1403 Cytore::Offset<PackageValue> next_;
1405 uint32_t index_ : 23;
1406 uint32_t subscribed_ : 1;
1423 Cytore::Offset<PackageValue> packages_[1 << 16];
1426 static Cytore::File<MetaValue> MetaFile_;
1428 // Cytore Helper Functions {{{
1429 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1430 SplitHash nhash = { hashlittle(name, length) };
1432 PackageValue *metadata;
1434 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1435 for (;; offset = &metadata->next_) { if (offset->IsNull()) {
1436 *offset = MetaFile_.New<PackageValue>(length + 1);
1437 metadata = &MetaFile_.Get(*offset);
1439 if (metadata == NULL) {
1443 metadata = new PackageValue();
1444 memset(metadata, 0, sizeof(*metadata));
1447 memcpy(metadata->name_, name, length);
1448 metadata->name_[length] = '\0';
1449 metadata->nhash_ = nhash.u16[1];
1451 metadata = &MetaFile_.Get(*offset);
1452 if (metadata->nhash_ != nhash.u16[1])
1454 if (strncmp(metadata->name_, name, length) != 0)
1456 if (metadata->name_[length] != '\0')
1463 static void PackageImport(const void *key, const void *value, void *context) {
1464 bool &fail(*reinterpret_cast<bool *>(context));
1467 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1468 NSLog(@"failed to import package %@", key);
1472 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1473 NSDictionary *package((NSDictionary *) value);
1475 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1476 if ([subscribed boolValue] && !metadata->subscribed_)
1477 metadata->subscribed_ = true;
1479 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1480 time_t time([date timeIntervalSince1970]);
1481 if (metadata->first_ > time || metadata->first_ == 0)
1482 metadata->first_ = time;
1485 NSDate *date([package objectForKey:@"LastSeen"]);
1486 NSString *version([package objectForKey:@"LastVersion"]);
1488 if (date != nil && version != nil) {
1489 time_t time([date timeIntervalSince1970]);
1490 if (metadata->last_ < time || metadata->last_ == 0)
1491 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1492 size_t length(strlen(buffer));
1493 uint16_t vhash(hashlittle(buffer, length));
1495 size_t capped(std::min<size_t>(8, length));
1496 char *latest(buffer + length - capped);
1498 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1499 metadata->vhash_ = vhash;
1501 metadata->last_ = time;
1507 static NSDate *GetStatusDate() {
1508 return [[[NSFileManager defaultManager] attributesOfItemAtPath:@"/var/lib/dpkg/status" error:NULL] fileModificationDate];
1511 static void SaveConfig(NSObject *lock) {
1512 @synchronized (lock) {
1518 CFPreferencesSetMultiple((CFDictionaryRef) [NSDictionary dictionaryWithObjectsAndKeys:
1519 Values_, @"CydiaValues",
1520 Sections_, @"CydiaSections",
1521 (id) Sources_, @"CydiaSources",
1522 Version_, @"CydiaVersion",
1523 nil], NULL, CFSTR("com.saurik.Cydia"), kCFPreferencesCurrentUser, kCFPreferencesCurrentHost);
1525 if (!CFPreferencesAppSynchronize(CFSTR("com.saurik.Cydia")))
1526 NSLog(@"CFPreferencesAppSynchronize(com.saurik.Cydia) == false");
1528 CydiaWriteSources();
1531 /* Source Class {{{ */
1532 @interface Source : NSObject {
1534 Database *database_;
1537 CYString depiction_;
1538 CYString description_;
1544 CYString distribution_;
1550 _H<NSString> authority_;
1552 CYString defaultIcon_;
1554 _H<NSMutableDictionary> record_;
1557 std::set<std::string> fetches_;
1558 std::set<std::string> files_;
1559 _transient NSObject<SourceDelegate> *delegate_;
1562 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(CYPool *)pool;
1564 - (NSComparisonResult) compareByName:(Source *)source;
1566 - (NSString *) depictionForPackage:(NSString *)package;
1567 - (NSString *) supportForPackage:(NSString *)package;
1569 - (metaIndex *) metaIndex;
1570 - (NSDictionary *) record;
1573 - (NSString *) rooturi;
1574 - (NSString *) distribution;
1575 - (NSString *) type;
1578 - (NSString *) host;
1580 - (NSString *) name;
1581 - (NSString *) shortDescription;
1582 - (NSString *) label;
1583 - (NSString *) origin;
1584 - (NSString *) version;
1586 - (NSString *) defaultIcon;
1587 - (NSURL *) iconURL;
1589 - (void) setFetch:(bool)fetch forURI:(const char *)uri;
1590 - (void) resetFetch;
1594 @implementation Source
1596 + (NSString *) webScriptNameForSelector:(SEL)selector {
1598 else if (selector == @selector(addSection:))
1599 return @"addSection";
1600 else if (selector == @selector(getField:))
1602 else if (selector == @selector(removeSection:))
1603 return @"removeSection";
1604 else if (selector == @selector(remove))
1610 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1611 return [self webScriptNameForSelector:selector] == nil;
1614 + (NSArray *) _attributeKeys {
1615 return [NSArray arrayWithObjects:
1626 @"shortDescription",
1633 - (NSArray *) attributeKeys {
1634 return [[self class] _attributeKeys];
1637 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1638 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1641 - (metaIndex *) metaIndex {
1645 - (void) setMetaIndex:(metaIndex *)index inPool:(CYPool *)pool {
1646 trusted_ = index->IsTrusted();
1648 uri_.set(pool, index->GetURI());
1649 distribution_.set(pool, index->GetDist());
1650 type_.set(pool, index->GetType());
1652 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1653 if (dindex != NULL) {
1654 std::string file(dindex->MetaIndexURI(""));
1655 base_.set(pool, file);
1658 _profile(Source$setMetaIndex$GetIndexes)
1659 dindex->GetIndexes(&acquire, true);
1661 _profile(Source$setMetaIndex$DescURI)
1662 for (pkgAcquire::ItemIterator item(acquire.ItemsBegin()); item != acquire.ItemsEnd(); item++) {
1663 std::string file((*item)->DescURI());
1664 auto slash(file.rfind('/'));
1665 if (slash == std::string::npos)
1667 files_.insert(file.substr(0, slash));
1672 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1675 pkgTagFile tags(&fd);
1677 pkgTagSection section;
1684 {"default-icon", &defaultIcon_},
1685 {"depiction", &depiction_},
1686 {"description", &description_},
1688 {"origin", &origin_},
1689 {"support", &support_},
1690 {"version", &version_},
1693 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1694 const char *start, *end;
1696 if (section.Find(names[i].name_, start, end)) {
1697 CYString &value(*names[i].value_);
1698 value.set(pool, start, end - start);
1704 record_ = [Sources_ objectForKey:[self key]];
1706 NSURL *url([NSURL URLWithString:uri_]);
1710 host_ = [host_ lowercaseString];
1715 authority_ = [url path];
1718 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(CYPool *)pool {
1719 if ((self = [super init]) != nil) {
1720 era_ = [database era];
1721 database_ = database;
1724 _profile(Source$initWithMetaIndex$setMetaIndex)
1725 [self setMetaIndex:index inPool:pool];
1730 - (NSString *) getField:(NSString *)name {
1731 @synchronized (database_) {
1732 if ([database_ era] != era_ || index_ == NULL)
1735 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index_));
1740 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly)) {
1745 pkgTagFile tags(&fd);
1747 pkgTagSection section;
1750 const char *start, *end;
1751 if (!section.Find([name UTF8String], start, end))
1752 return (NSString *) [NSNull null];
1754 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
1757 - (NSComparisonResult) compareByName:(Source *)source {
1758 NSString *lhs = [self name];
1759 NSString *rhs = [source name];
1761 if ([lhs length] != 0 && [rhs length] != 0) {
1762 unichar lhc = [lhs characterAtIndex:0];
1763 unichar rhc = [rhs characterAtIndex:0];
1765 if (isalpha(lhc) && !isalpha(rhc))
1766 return NSOrderedAscending;
1767 else if (!isalpha(lhc) && isalpha(rhc))
1768 return NSOrderedDescending;
1771 return [lhs compare:rhs options:LaxCompareOptions_];
1774 - (NSString *) depictionForPackage:(NSString *)package {
1775 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1778 - (NSString *) supportForPackage:(NSString *)package {
1779 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1782 - (NSArray *) sections {
1783 return record_ == nil ? (id) [NSNull null] : [record_ objectForKey:@"Sections"] ?: [NSArray array];
1786 - (void) _addSection:(NSString *)section {
1789 else if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) {
1790 if (![sections containsObject:section])
1791 [sections addObject:section];
1793 [record_ setObject:[NSMutableArray arrayWithObject:section] forKey:@"Sections"];
1796 - (bool) addSection:(NSString *)section {
1800 [self performSelectorOnMainThread:@selector(_addSection:) withObject:section waitUntilDone:NO];
1804 - (void) _removeSection:(NSString *)section {
1808 if (NSMutableArray *sections = [record_ objectForKey:@"Sections"])
1809 if ([sections containsObject:section])
1810 [sections removeObject:section];
1813 - (bool) removeSection:(NSString *)section {
1817 [self performSelectorOnMainThread:@selector(_removeSection:) withObject:section waitUntilDone:NO];
1822 [Sources_ removeObjectForKey:[self key]];
1826 bool value(record_ != nil);
1827 [self performSelectorOnMainThread:@selector(_remove) withObject:nil waitUntilDone:NO];
1831 - (NSDictionary *) record {
1839 - (NSString *) rooturi {
1843 - (NSString *) distribution {
1844 return distribution_;
1847 - (NSString *) type {
1851 - (NSString *) baseuri {
1852 return base_.empty() ? nil : (id) base_;
1855 - (NSString *) iconuri {
1856 if (NSString *base = [self baseuri])
1857 return [base stringByAppendingString:@"CydiaIcon.png"];
1862 - (NSURL *) iconURL {
1863 if (NSString *uri = [self iconuri])
1864 return [NSURL URLWithString:uri];
1868 - (NSString *) key {
1869 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1872 - (NSString *) host {
1876 - (NSString *) name {
1877 return origin_.empty() ? (id) authority_ : origin_;
1880 - (NSString *) shortDescription {
1881 return description_;
1884 - (NSString *) label {
1885 return label_.empty() ? (id) authority_ : label_;
1888 - (NSString *) origin {
1892 - (NSString *) version {
1896 - (NSString *) defaultIcon {
1897 return defaultIcon_;
1900 - (void) setDelegate:(NSObject<SourceDelegate> *)delegate {
1901 delegate_ = delegate;
1905 return !fetches_.empty();
1908 - (void) setFetch:(bool)fetch forURI:(const char *)uri {
1910 if (fetches_.erase(uri) == 0)
1912 } else if (files_.find(uri) == files_.end())
1914 else if (!fetches_.insert(uri).second)
1917 [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:[self fetch]] waitUntilDone:NO];
1920 - (void) resetFetch {
1922 [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:NO];
1927 /* CydiaOperation Class {{{ */
1928 @interface CydiaOperation : NSObject {
1929 _H<NSString> operator_;
1930 _H<NSString> value_;
1933 - (NSString *) operator;
1934 - (NSString *) value;
1938 @implementation CydiaOperation
1940 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1941 if ((self = [super init]) != nil) {
1942 operator_ = [NSString stringWithUTF8String:_operator];
1943 value_ = [NSString stringWithUTF8String:value];
1947 + (NSArray *) _attributeKeys {
1948 return [NSArray arrayWithObjects:
1954 - (NSArray *) attributeKeys {
1955 return [[self class] _attributeKeys];
1958 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1959 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1962 - (NSString *) operator {
1966 - (NSString *) value {
1972 /* CydiaClause Class {{{ */
1973 @interface CydiaClause : NSObject {
1974 _H<NSString> package_;
1975 _H<CydiaOperation> version_;
1978 - (NSString *) package;
1979 - (CydiaOperation *) version;
1983 @implementation CydiaClause
1985 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1986 if ((self = [super init]) != nil) {
1987 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1989 if (const char *version = dep.TargetVer())
1990 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1992 version_ = (id) [NSNull null];
1996 + (NSArray *) _attributeKeys {
1997 return [NSArray arrayWithObjects:
2003 - (NSArray *) attributeKeys {
2004 return [[self class] _attributeKeys];
2007 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2008 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2011 - (NSString *) package {
2015 - (CydiaOperation *) version {
2021 /* CydiaRelation Class {{{ */
2022 @interface CydiaRelation : NSObject {
2023 _H<NSString> relationship_;
2024 _H<NSMutableArray> clauses_;
2027 - (NSString *) relationship;
2028 - (NSArray *) clauses;
2032 @implementation CydiaRelation
2034 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
2035 if ((self = [super init]) != nil) {
2036 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
2037 clauses_ = [NSMutableArray arrayWithCapacity:8];
2039 pkgCache::DepIterator start;
2040 pkgCache::DepIterator end;
2041 dep.GlobOr(start, end); // ++dep
2044 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
2046 // yes, seriously. (wtf?)
2054 + (NSArray *) _attributeKeys {
2055 return [NSArray arrayWithObjects:
2061 - (NSArray *) attributeKeys {
2062 return [[self class] _attributeKeys];
2065 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2066 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2069 - (NSString *) relationship {
2070 return relationship_;
2073 - (NSArray *) clauses {
2077 - (void) addClause:(CydiaClause *)clause {
2078 [clauses_ addObject:clause];
2083 /* Package Class {{{ */
2084 struct ParsedPackage {
2088 CYString architecture_;
2091 CYString depiction_;
2098 @interface Package : NSObject {
2100 @public uint32_t role_ : 3;
2101 uint32_t essential_ : 1;
2102 uint32_t obsolete_ : 1;
2103 uint32_t ignored_ : 1;
2104 uint32_t pooled_ : 1;
2110 _transient Database *database_;
2112 pkgCache::VerIterator version_;
2113 pkgCache::PkgIterator iterator_;
2114 pkgCache::VerFileIterator file_;
2118 CYString transform_;
2121 CYString installed_;
2124 const char *section_;
2125 _transient NSString *section$_;
2129 PackageValue *metadata_;
2130 ParsedPackage *parsed_;
2132 _H<NSMutableArray> tags_;
2135 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database;
2136 + (Package *) newPackageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database;
2138 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database;
2140 - (pkgCache::PkgIterator) iterator;
2143 - (NSString *) section;
2144 - (NSString *) simpleSection;
2146 - (NSString *) longSection;
2147 - (NSString *) shortSection;
2151 - (MIMEAddress *) maintainer;
2153 - (NSString *) longDescription;
2154 - (NSString *) shortDescription;
2157 - (PackageValue *) metadata;
2160 - (bool) subscribed;
2161 - (bool) setSubscribed:(bool)subscribed;
2165 - (NSString *) latest;
2166 - (NSString *) installed;
2167 - (BOOL) uninstalled;
2169 - (BOOL) upgradableAndEssential:(BOOL)essential;
2172 - (BOOL) unfiltered;
2176 - (BOOL) halfConfigured;
2177 - (BOOL) halfInstalled;
2179 - (NSString *) mode;
2182 - (NSString *) name;
2184 - (NSString *) homepage;
2185 - (NSString *) depiction;
2186 - (MIMEAddress *) author;
2188 - (NSString *) support;
2190 - (NSArray *) files;
2191 - (NSArray *) warnings;
2192 - (NSArray *) applications;
2194 - (Source *) source;
2197 - (BOOL) matches:(NSArray *)query;
2199 - (BOOL) hasTag:(NSString *)tag;
2200 - (NSString *) primaryPurpose;
2201 - (NSArray *) purposes;
2202 - (bool) isCommercial;
2204 - (void) setIndex:(size_t)index;
2206 - (CYString &) cyname;
2208 - (uint32_t) compareBySection:(NSArray *)sections;
2215 uint32_t PackageChangesRadix(Package *self, void *) {
2220 uint32_t timestamp : 30;
2221 uint32_t ignored : 1;
2222 uint32_t upgradable : 1;
2226 bool upgradable([self upgradableAndEssential:YES]);
2227 value.bits.upgradable = upgradable ? 1 : 0;
2230 value.bits.timestamp = 0;
2231 value.bits.ignored = [self ignored] ? 0 : 1;
2232 value.bits.upgradable = 1;
2234 value.bits.timestamp = [self seen] >> 2;
2235 value.bits.ignored = 0;
2236 value.bits.upgradable = 0;
2239 return _not(uint32_t) - value.key;
2242 CYString &(*PackageName)(Package *self, SEL sel);
2244 uint32_t PackagePrefixRadix(Package *self, void *context) {
2245 size_t offset(reinterpret_cast<size_t>(context));
2246 CYString &name(PackageName(self, @selector(cyname)));
2248 size_t size(name.size());
2251 char *text(name.data());
2254 if (!isdigit(text[0]))
2258 while (size != digits && isdigit(text[digits]))
2266 if (offset == 0 && zeros != 0) {
2267 memset(data, '0', zeros);
2268 memcpy(data + zeros, text, 4 - zeros);
2270 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2271 if (size <= offset - zeros)
2274 text += offset - zeros;
2275 size -= offset - zeros;
2278 memcpy(data, text, 4);
2280 memcpy(data, text, size);
2281 memset(data + size, 0, 4 - size);
2284 for (size_t i(0); i != 4; ++i)
2285 if (isalpha(data[i]))
2293 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2295 /* XXX: ntohl may be more honest */
2296 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2299 CFComparisonResult StringNameCompare(CFStringRef lhn, CFStringRef rhn, size_t length) {
2300 _profile(PackageNameCompare)
2302 return rhn == NULL ? kCFCompareEqualTo : kCFCompareLessThan;
2303 else if (rhn == NULL)
2304 return kCFCompareGreaterThan;
2306 CFIndex length(CFStringGetLength(lhn));
2308 _profile(PackageNameCompare$NumbersLast)
2309 if (length != 0 && CFStringGetLength(rhn) != 0) {
2310 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2311 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2312 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2313 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2314 return lha ? kCFCompareLessThan : kCFCompareGreaterThan;
2318 _profile(PackageNameCompare$Compare)
2319 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, (CFLocaleRef) (id) CollationLocale_);
2324 _finline CFComparisonResult StringNameCompare(NSString *lhn, NSString*rhn, size_t length) {
2325 return StringNameCompare((CFStringRef) lhn, (CFStringRef) rhn, length);
2328 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2329 CYString &lhn(PackageName(lhs, @selector(cyname)));
2330 NSString *rhn(PackageName(rhs, @selector(cyname)));
2331 return StringNameCompare(lhn, rhn, lhn.size());
2334 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *arg) {
2335 return PackageNameCompare(*lhs, *rhs, arg);
2338 struct PackageNameOrdering :
2339 std::binary_function<Package *, Package *, bool>
2341 _finline bool operator ()(Package *lhs, Package *rhs) const {
2342 return PackageNameCompare(lhs, rhs, NULL) == kCFCompareLessThan;
2346 @implementation Package
2348 - (NSString *) description {
2349 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2355 if (parsed_ != NULL)
2360 + (NSString *) webScriptNameForSelector:(SEL)selector {
2362 else if (selector == @selector(clear))
2364 else if (selector == @selector(getField:))
2366 else if (selector == @selector(getRecord))
2367 return @"getRecord";
2368 else if (selector == @selector(hasTag:))
2370 else if (selector == @selector(install))
2372 else if (selector == @selector(remove))
2378 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2379 return [self webScriptNameForSelector:selector] == nil;
2382 + (NSArray *) _attributeKeys {
2383 return [NSArray arrayWithObjects:
2404 @"shortDescription",
2417 - (NSArray *) attributeKeys {
2418 return [[self class] _attributeKeys];
2421 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2422 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2425 - (NSArray *) relations {
2426 @synchronized (database_) {
2427 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2428 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2429 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2433 - (NSString *) architecture {
2435 @synchronized (database_) {
2436 return parsed_->architecture_.empty() ? [NSNull null] : (id) parsed_->architecture_;
2439 - (NSString *) getField:(NSString *)name {
2440 @synchronized (database_) {
2441 if ([database_ era] != era_ || file_.end())
2444 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2446 const char *start, *end;
2447 if (!parser.Find([name UTF8String], start, end))
2448 return (NSString *) [NSNull null];
2450 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2453 - (NSString *) getRecord {
2454 @synchronized (database_) {
2455 if ([database_ era] != era_ || file_.end())
2458 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2460 const char *start, *end;
2461 parser.GetRec(start, end);
2463 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2467 if (parsed_ != NULL)
2469 @synchronized (database_) {
2470 if ([database_ era] != era_ || file_.end())
2473 ParsedPackage *parsed(new ParsedPackage);
2476 _profile(Package$parse)
2477 pkgRecords::Parser *parser;
2479 _profile(Package$parse$Lookup)
2480 parser = &[database_ records]->Lookup(file_);
2486 _profile(Package$parse$Find)
2491 {"architecture", &parsed->architecture_},
2492 {"icon", &parsed->icon_},
2493 {"depiction", &parsed->depiction_},
2494 {"homepage", &parsed->homepage_},
2495 {"website", &website},
2497 {"support", &parsed->support_},
2498 {"author", &parsed->author_},
2499 {"md5sum", &parsed->md5sum_},
2502 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2503 const char *start, *end;
2505 if (parser->Find(names[i].name_, start, end)) {
2506 CYString &value(*names[i].value_);
2507 _profile(Package$parse$Value)
2508 value.set(pool_, start, end - start);
2514 _profile(Package$parse$Tagline)
2515 parsed->tagline_.set(pool_, parser->ShortDesc());
2518 _profile(Package$parse$Retain)
2519 if (parsed->homepage_.empty())
2520 parsed->homepage_ = website;
2521 if (parsed->homepage_ == parsed->depiction_)
2522 parsed->homepage_.clear();
2523 if (parsed->support_.empty())
2524 parsed->support_ = bugs;
2529 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database {
2530 if ((self = [super init]) != nil) {
2531 _profile(Package$initWithVersion)
2533 pool_ = new CYPool();
2539 database_ = database;
2540 era_ = [database era];
2544 pkgCache::PkgIterator iterator(version_.ParentPkg());
2545 iterator_ = iterator;
2547 _profile(Package$initWithVersion$Version)
2548 file_ = version_.FileList();
2551 _profile(Package$initWithVersion$Cache)
2552 name_.set(NULL, version_.Display());
2554 latest_.set(NULL, StripVersion_(version_.VerStr()));
2556 pkgCache::VerIterator current(iterator.CurrentVer());
2558 installed_.set(NULL, StripVersion_(current.VerStr()));
2561 _profile(Package$initWithVersion$Transliterate) do {
2562 if (CollationTransl_ == NULL)
2567 _profile(Package$initWithVersion$Transliterate$utf8)
2568 const uint8_t *data(reinterpret_cast<const uint8_t *>(name_.data()));
2569 for (size_t i(0), e(name_.size()); i != e; ++i)
2570 if (data[i] >= 0x80)
2575 UErrorCode code(U_ZERO_ERROR);
2578 _profile(Package$initWithVersion$Transliterate$u_strFromUTF8WithSub)
2579 CollationString_.resize(name_.size());
2580 u_strFromUTF8WithSub(&CollationString_[0], CollationString_.size(), &length, name_.data(), name_.size(), 0xfffd, NULL, &code);
2581 if (!U_SUCCESS(code))
2583 CollationString_.resize(length);
2586 _profile(Package$initWithVersion$Transliterate$utrans_trans)
2587 length = CollationString_.size();
2588 utrans_trans(CollationTransl_, reinterpret_cast<UReplaceable *>(&CollationString_), &CollationUCalls_, 0, &length, &code);
2589 if (!U_SUCCESS(code))
2591 _assert(CollationString_.size() == length);
2594 _profile(Package$initWithVersion$Transliterate$u_strToUTF8WithSub$preflight)
2595 u_strToUTF8WithSub(NULL, 0, &length, CollationString_.data(), CollationString_.size(), 0xfffd, NULL, &code);
2596 if (code == U_BUFFER_OVERFLOW_ERROR)
2597 code = U_ZERO_ERROR;
2598 else if (!U_SUCCESS(code))
2603 _profile(Package$initWithVersion$Transliterate$apr_palloc)
2604 transform = pool_->malloc<char>(length);
2606 _profile(Package$initWithVersion$Transliterate$u_strToUTF8WithSub$transform)
2607 u_strToUTF8WithSub(transform, length, NULL, CollationString_.data(), CollationString_.size(), 0xfffd, NULL, &code);
2608 if (!U_SUCCESS(code))
2612 transform_.set(NULL, transform, length);
2613 } while (false); _end
2615 _profile(Package$initWithVersion$Tags)
2617 pkgCache::TagIterator tag(version_.TagList());
2619 pkgCache::TagIterator tag(iterator.TagList());
2622 tags_ = [NSMutableArray arrayWithCapacity:8];
2624 goto tag; for (; !tag.end(); ++tag) tag: {
2625 const char *name(tag.Name());
2626 NSString *string((NSString *) CYStringCreate(name));
2630 [tags_ addObject:[string autorelease]];
2632 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2633 if (strcmp(name + 6, "enduser") == 0)
2635 else if (strcmp(name + 6, "hacker") == 0)
2637 else if (strcmp(name + 6, "developer") == 0)
2639 else if (strcmp(name + 6, "cydia") == 0)
2645 if (strncmp(name, "cydia::", 7) == 0) {
2646 if (strcmp(name + 7, "essential") == 0)
2648 else if (strcmp(name + 7, "obsolete") == 0)
2655 _profile(Package$initWithVersion$Metadata)
2656 const char *mixed(iterator.Name());
2657 size_t size(strlen(mixed));
2658 static const size_t prefix(sizeof("/var/lib/dpkg/info/") - 1);
2659 char lower[prefix + size + 5 + 1];
2661 for (size_t i(0); i != size; ++i)
2662 lower[prefix + i] = mixed[i] | 0x20;
2664 if (!installed_.empty()) {
2665 memcpy(lower, "/var/lib/dpkg/info/", prefix);
2666 memcpy(lower + prefix + size, ".list", 6);
2668 if (stat(lower, &info) != -1)
2669 upgraded_ = info.st_birthtime;
2672 PackageValue *metadata(PackageFind(lower + prefix, size));
2673 metadata_ = metadata;
2675 id_.set(NULL, metadata->name_, size);
2677 const char *latest(version_.VerStr());
2678 size_t length(strlen(latest));
2680 uint16_t vhash(hashlittle(latest, length));
2682 size_t capped(std::min<size_t>(8, length));
2683 latest = latest + length - capped;
2685 if (metadata->first_ == 0)
2686 metadata->first_ = now_;
2688 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2689 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2690 metadata->vhash_ = vhash;
2691 metadata->last_ = now_;
2692 } else if (metadata->last_ == 0)
2693 metadata->last_ = metadata->first_;
2696 _profile(Package$initWithVersion$Section)
2697 section_ = version_.Section();
2700 _profile(Package$initWithVersion$Flags)
2701 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2702 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2707 + (Package *) newPackageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database {
2708 pkgCache::VerIterator version;
2710 _profile(Package$packageWithIterator$GetCandidateVer)
2711 version = [database policy]->GetCandidateVer(iterator);
2719 _profile(Package$packageWithIterator$Allocate)
2720 package = [Package allocWithZone:zone];
2723 _profile(Package$packageWithIterator$Initialize)
2725 initWithVersion:version
2735 // XXX: just in case a Cydia extension is using this (I bet this is unlikely, though, due to CYPool?)
2736 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database {
2737 return [[self newPackageWithIterator:iterator withZone:zone inPool:pool database:database] autorelease];
2740 - (pkgCache::PkgIterator) iterator {
2744 - (NSArray *) downgrades {
2745 NSMutableArray *versions([NSMutableArray arrayWithCapacity:4]);
2747 for (auto version(iterator_.VersionList()); !version.end(); ++version) {
2748 if (version == version_)
2750 Package *package([[[Package allocWithZone:NULL] initWithVersion:version withZone:NULL inPool:NULL database:database_] autorelease]);
2751 if ([package source] == nil)
2753 [versions addObject:package];
2759 - (NSString *) section {
2760 if (section$_ == nil) {
2761 if (section_ == NULL)
2764 _profile(Package$section$mappedSectionForPointer)
2765 section$_ = [database_ mappedSectionForPointer:section_];
2770 - (NSString *) simpleSection {
2771 if (NSString *section = [self section])
2772 return Simplify(section);
2777 - (NSString *) longSection {
2778 if (NSString *section = [self section])
2779 return LocalizeSection(section);
2784 - (NSString *) shortSection {
2785 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2788 - (NSString *) uri {
2791 pkgIndexFile *index;
2792 pkgCache::PkgFileIterator file(file_.File());
2793 if (![database_ list].FindIndex(file, index))
2795 return [NSString stringWithUTF8String:iterator_->Path];
2796 //return [NSString stringWithUTF8String:file.Site()];
2797 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2801 - (MIMEAddress *) maintainer {
2802 @synchronized (database_) {
2803 if ([database_ era] != era_ || file_.end())
2806 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2807 const std::string &maintainer(parser->Maintainer());
2808 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2811 - (NSString *) md5sum {
2812 return parsed_ == NULL ? nil : (id) parsed_->md5sum_;
2816 @synchronized (database_) {
2817 if ([database_ era] != era_ || version_.end())
2820 return version_->InstalledSize;
2823 - (NSString *) longDescription {
2824 @synchronized (database_) {
2825 if ([database_ era] != era_ || file_.end())
2828 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2829 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2831 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2832 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2833 if ([lines count] < 2)
2836 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2837 for (size_t i(1), e([lines count]); i != e; ++i) {
2838 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2839 [trimmed addObject:trim];
2842 return [trimmed componentsJoinedByString:@"\n"];
2845 - (NSString *) shortDescription {
2846 if (parsed_ != NULL)
2847 return static_cast<NSString *>(parsed_->tagline_);
2849 @synchronized (database_) {
2850 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2851 std::string value(parser.ShortDesc());
2854 if (value.size() > 200)
2856 return [(id) CYStringCreate(value) autorelease];
2860 _profile(Package$index)
2861 CFStringRef name((CFStringRef) [self name]);
2862 if (CFStringGetLength(name) == 0)
2864 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2865 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2867 return toupper(character);
2871 - (PackageValue *) metadata {
2876 PackageValue *metadata([self metadata]);
2877 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2880 - (bool) subscribed {
2881 return [self metadata]->subscribed_;
2884 - (bool) setSubscribed:(bool)subscribed {
2885 PackageValue *metadata([self metadata]);
2886 if (metadata->subscribed_ == subscribed)
2888 metadata->subscribed_ = subscribed;
2896 - (NSString *) latest {
2900 - (NSString *) installed {
2904 - (BOOL) uninstalled {
2905 return installed_.empty();
2908 - (BOOL) upgradableAndEssential:(BOOL)essential {
2909 _profile(Package$upgradableAndEssential)
2910 pkgCache::VerIterator current(iterator_.CurrentVer());
2912 return essential && essential_;
2914 return version_ != current;
2918 - (BOOL) essential {
2923 return [database_ cache][iterator_].InstBroken();
2926 - (BOOL) unfiltered {
2927 _profile(Package$unfiltered$obsolete)
2928 if (_unlikely(obsolete_))
2932 _profile(Package$unfiltered$role)
2933 if (_unlikely(role_ > 3))
2941 if (![self unfiltered])
2946 _profile(Package$visible$section)
2947 section = [self section];
2950 _profile(Package$visible$isSectionVisible)
2951 if (!isSectionVisible(section))
2959 unsigned char current(iterator_->CurrentState);
2960 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2963 - (BOOL) halfConfigured {
2964 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2967 - (BOOL) halfInstalled {
2968 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2972 @synchronized (database_) {
2973 if ([database_ era] != era_ || iterator_.end())
2976 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2977 return state.Mode != pkgDepCache::ModeKeep;
2980 - (NSString *) mode {
2981 @synchronized (database_) {
2982 if ([database_ era] != era_ || iterator_.end())
2985 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2987 switch (state.Mode) {
2988 case pkgDepCache::ModeDelete:
2989 if ((state.iFlags & pkgDepCache::Purge) != 0)
2993 case pkgDepCache::ModeKeep:
2994 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2995 return @"REINSTALL";
2996 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
3000 case pkgDepCache::ModeInstall:
3001 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
3002 return @"REINSTALL";
3003 else*/ switch (state.Status) {
3005 return @"DOWNGRADE";
3011 return @"NEW_INSTALL";
3022 - (NSString *) name {
3023 return name_.empty() ? id_ : name_;
3026 - (UIImage *) icon {
3027 NSString *section = [self simpleSection];
3030 if (parsed_ != NULL)
3031 if (NSString *href = parsed_->icon_)
3032 if ([href hasPrefix:@"file:///"])
3033 icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
3034 if (icon == nil) if (section != nil)
3035 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]];
3036 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
3037 if ([dicon hasPrefix:@"file:///"])
3038 icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
3040 icon = [UIImage imageNamed:@"unknown.png"];
3044 - (NSString *) homepage {
3045 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
3048 - (NSString *) depiction {
3049 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
3052 - (MIMEAddress *) author {
3053 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
3056 - (NSString *) support {
3057 return parsed_ != NULL && !parsed_->support_.empty() ? parsed_->support_ : [[self source] supportForPackage:id_];
3060 - (NSArray *) files {
3061 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
3062 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
3065 fin.open([path UTF8String]);
3070 while (std::getline(fin, line))
3071 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
3076 - (NSString *) state {
3077 @synchronized (database_) {
3078 if ([database_ era] != era_ || file_.end())
3081 switch (iterator_->CurrentState) {
3082 case pkgCache::State::NotInstalled:
3083 return @"NotInstalled";
3084 case pkgCache::State::UnPacked:
3086 case pkgCache::State::HalfConfigured:
3087 return @"HalfConfigured";
3088 case pkgCache::State::HalfInstalled:
3089 return @"HalfInstalled";
3090 case pkgCache::State::ConfigFiles:
3091 return @"ConfigFiles";
3092 case pkgCache::State::Installed:
3093 return @"Installed";
3094 case pkgCache::State::TriggersAwaited:
3095 return @"TriggersAwaited";
3096 case pkgCache::State::TriggersPending:
3097 return @"TriggersPending";
3100 return (NSString *) [NSNull null];
3103 - (NSString *) selection {
3104 @synchronized (database_) {
3105 if ([database_ era] != era_ || file_.end())
3108 switch (iterator_->SelectedState) {
3109 case pkgCache::State::Unknown:
3111 case pkgCache::State::Install:
3113 case pkgCache::State::Hold:
3115 case pkgCache::State::DeInstall:
3116 return @"DeInstall";
3117 case pkgCache::State::Purge:
3121 return (NSString *) [NSNull null];
3124 - (NSArray *) warnings {
3125 @synchronized (database_) {
3126 if ([database_ era] != era_ || file_.end())
3129 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
3130 const char *name(iterator_.Name());
3132 size_t length(strlen(name));
3133 if (length < 2) invalid:
3134 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
3135 else for (size_t i(0); i != length; ++i)
3137 /* XXX: technically this is not allowed */
3138 (name[i] < 'A' || name[i] > 'Z') &&
3139 (name[i] < 'a' || name[i] > 'z') &&
3140 (name[i] < '0' || name[i] > '9') &&
3141 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
3144 if (strcmp(name, "cydia") != 0) {
3147 bool _private = false;
3149 bool dbstash = false;
3150 bool dsstore = false;
3152 bool repository = [[self section] isEqualToString:@"Repositories"];
3154 if (NSArray *files = [self files])
3155 for (NSString *file in files)
3156 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
3158 else if (!user && [file isEqualToString:@"/User"])
3160 else if (!_private && [file isEqualToString:@"/private"])
3162 else if (!stash && [file isEqualToString:@"/var/stash"])
3164 else if (!dbstash && [file isEqualToString:@"/var/db/stash"])
3166 else if (!dsstore && [file hasSuffix:@"/.DS_Store"])
3169 /* XXX: this is not sensitive enough. only some folders are valid. */
3170 if (cydia && !repository)
3171 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
3173 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
3175 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
3177 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
3179 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/db/stash"]];
3181 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @".DS_Store"]];
3184 return [warnings count] == 0 ? nil : warnings;
3187 - (NSArray *) applications {
3188 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
3190 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
3192 static RegEx application_r("/Applications/(.*)\\.app/Info.plist");
3193 if (NSArray *files = [self files])
3194 for (NSString *file in files)
3195 if (application_r(file)) {
3196 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
3199 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
3200 if (id == nil || [id isEqualToString:me])
3203 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
3205 display = application_r[1];
3207 NSString *bundle([file stringByDeletingLastPathComponent]);
3208 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
3209 // XXX: maybe this should check if this is really a string, not just for length
3210 if (icon == nil || ![icon respondsToSelector:@selector(length)] || [icon length] == 0)
3212 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
3214 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
3215 [applications addObject:application];
3217 [application addObject:id];
3218 [application addObject:display];
3219 [application addObject:url];
3222 return [applications count] == 0 ? nil : applications;
3225 - (Source *) source {
3226 if (source_ == nil) {
3227 @synchronized (database_) {
3228 if ([database_ era] != era_ || file_.end())
3229 source_ = (Source *) [NSNull null];
3231 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
3235 return source_ == (Source *) [NSNull null] ? nil : source_;
3238 - (time_t) upgraded {
3242 - (uint32_t) recent {
3243 return std::numeric_limits<uint32_t>::max() - upgraded_;
3250 - (BOOL) matches:(NSArray *)query {
3251 if (query == nil || [query count] == 0)
3260 string = [self name];
3261 length = [string length];
3264 for (NSString *term in query) {
3265 range = [string rangeOfString:term options:MatchCompareOptions_];
3266 if (range.location != NSNotFound)
3267 rank_ -= 6 * 1000000 / length;
3272 length = [string length];
3275 for (NSString *term in query) {
3276 range = [string rangeOfString:term options:MatchCompareOptions_];
3277 if (range.location != NSNotFound)
3278 rank_ -= 6 * 1000000 / length;
3282 string = [self shortDescription];
3283 length = [string length];
3284 NSUInteger stop(std::min<NSUInteger>(length, 200));
3287 for (NSString *term in query) {
3288 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
3289 if (range.location != NSNotFound)
3290 rank_ -= 2 * 100000;
3296 - (NSArray *) tags {
3300 - (BOOL) hasTag:(NSString *)tag {
3301 return tags_ == nil ? NO : [tags_ containsObject:tag];
3304 - (NSString *) primaryPurpose {
3305 for (NSString *tag in (NSArray *) tags_)
3306 if ([tag hasPrefix:@"purpose::"])
3307 return [tag substringFromIndex:9];
3311 - (NSArray *) purposes {
3312 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
3313 for (NSString *tag in (NSArray *) tags_)
3314 if ([tag hasPrefix:@"purpose::"])
3315 [purposes addObject:[tag substringFromIndex:9]];
3316 return [purposes count] == 0 ? nil : purposes;
3319 - (bool) isCommercial {
3320 return [self hasTag:@"cydia::commercial"];
3323 - (void) setIndex:(size_t)index {
3324 if (metadata_->index_ != index + 1)
3325 metadata_->index_ = index + 1;
3328 - (CYString &) cyname {
3329 return !transform_.empty() ? transform_ : !name_.empty() ? name_ : id_;
3332 - (uint32_t) compareBySection:(NSArray *)sections {
3333 NSString *section([self section]);
3334 for (size_t i(0), e([sections count]); i != e; ++i) {
3335 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3339 return _not(uint32_t);
3343 @synchronized (database_) {
3344 if ([database_ era] != era_ || file_.end())
3347 pkgProblemResolver *resolver = [database_ resolver];
3348 resolver->Clear(iterator_);
3350 pkgCacheFile &cache([database_ cache]);
3351 cache->SetReInstall(iterator_, false);
3352 cache->MarkKeep(iterator_, false);
3356 @synchronized (database_) {
3357 if ([database_ era] != era_ || file_.end())
3360 pkgProblemResolver *resolver = [database_ resolver];
3361 resolver->Clear(iterator_);
3362 resolver->Protect(iterator_);
3364 pkgCacheFile &cache([database_ cache]);
3365 cache->SetCandidateVersion(version_);
3366 cache->SetReInstall(iterator_, false);
3367 cache->MarkInstall(iterator_, false);
3369 pkgDepCache::StateCache &state((*cache)[iterator_]);
3370 if (!state.Install())
3371 cache->SetReInstall(iterator_, true);
3375 @synchronized (database_) {
3376 if ([database_ era] != era_ || file_.end())
3379 pkgProblemResolver *resolver = [database_ resolver];
3380 resolver->Clear(iterator_);
3381 resolver->Remove(iterator_);
3382 resolver->Protect(iterator_);
3384 pkgCacheFile &cache([database_ cache]);
3385 cache->SetReInstall(iterator_, false);
3386 cache->MarkDelete(iterator_, true);
3391 /* Section Class {{{ */
3392 @interface Section : NSObject {
3396 _H<NSString> localized_;
3399 - (NSComparisonResult) compareByLocalized:(Section *)section;
3400 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3401 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3402 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3404 - (NSString *) name;
3405 - (void) setName:(NSString *)name;
3411 - (void) addToCount;
3413 - (void) setCount:(size_t)count;
3414 - (NSString *) localized;
3418 @implementation Section
3420 - (NSComparisonResult) compareByLocalized:(Section *)section {
3421 NSString *lhs(localized_);
3422 NSString *rhs([section localized]);
3424 /*if ([lhs length] != 0 && [rhs length] != 0) {
3425 unichar lhc = [lhs characterAtIndex:0];
3426 unichar rhc = [rhs characterAtIndex:0];
3428 if (isalpha(lhc) && !isalpha(rhc))
3429 return NSOrderedAscending;
3430 else if (!isalpha(lhc) && isalpha(rhc))
3431 return NSOrderedDescending;
3434 return [lhs compare:rhs options:LaxCompareOptions_];
3437 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3438 if ((self = [self initWithName:name localize:NO]) != nil) {
3439 if (localized != nil)
3440 localized_ = localized;
3444 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3445 return [self initWithName:name row:0 localize:localize];
3448 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3449 if ((self = [super init]) != nil) {
3453 localized_ = LocalizeSection(name_);
3457 - (NSString *) name {
3461 - (void) setName:(NSString *)name {
3477 - (void) addToCount {
3481 - (void) setCount:(size_t)count {
3485 - (NSString *) localized {
3492 class CydiaLogCleaner :
3493 public pkgArchiveCleaner
3496 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3501 /* Database Implementation {{{ */
3502 @implementation Database
3504 + (Database *) sharedInstance {
3505 static _H<Database> instance;
3506 if (instance == nil)
3507 instance = [[[Database alloc] init] autorelease];
3515 - (void) releasePackages {
3519 - (bool) hasPackages {
3520 return [packages_ count] != 0;
3524 // XXX: actually implement this thing
3526 [self releasePackages];
3527 NSRecycleZone(zone_);
3531 - (void) _readCydia:(NSNumber *)fd {
3532 boost::fdistream is([fd intValue]);
3535 static RegEx finish_r("finish:([^:]*)");
3537 while (std::getline(is, line)) {
3538 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3540 const char *data(line.c_str());
3541 size_t size = line.size();
3542 lprintf("C:%s\n", data);
3544 if (finish_r(data, size)) {
3545 NSString *finish = finish_r[1];
3546 int index = [Finishes_ indexOfObject:finish];
3547 if (index != INT_MAX && index > Finish_)
3557 - (void) _readStatus:(NSNumber *)fd {
3558 boost::fdistream is([fd intValue]);
3561 static RegEx conffile_r("status: [^ ]* : conffile-prompt : (.*?) *");
3562 static RegEx pmstatus_r("([^:]*):([^:]*):([^:]*):(.*)");
3564 while (std::getline(is, line)) {
3565 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3567 const char *data(line.c_str());
3568 size_t size(line.size());
3569 lprintf("S:%s\n", data);
3571 if (conffile_r(data, size)) {
3572 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3573 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3574 } else if (strncmp(data, "status: ", 8) == 0) {
3575 // status: <package>: {unpacked,half-configured,installed}
3576 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3577 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3578 } else if (strncmp(data, "processing: ", 12) == 0) {
3579 // processing: configure: config-test
3580 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3581 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3582 } else if (pmstatus_r(data, size)) {
3583 std::string type([pmstatus_r[1] UTF8String]);
3585 NSString *package = pmstatus_r[2];
3586 if ([package isEqualToString:@"dpkg-exec"])
3589 float percent([pmstatus_r[3] floatValue]);
3590 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3592 NSString *string = pmstatus_r[4];
3594 if (type == "pmerror") {
3595 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3596 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3597 } else if (type == "pmstatus") {
3598 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3599 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3600 } else if (type == "pmconffile")
3601 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3603 lprintf("E:unknown pmstatus\n");
3605 lprintf("E:unknown status\n");
3613 - (void) _readOutput:(NSNumber *)fd {
3614 boost::fdistream is([fd intValue]);
3617 while (std::getline(is, line)) {
3618 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3620 lprintf("O:%s\n", line.c_str());
3622 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3623 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3635 - (Package *) packageWithName:(NSString *)name {
3638 @synchronized (self) {
3639 if (static_cast<pkgDepCache *>(cache_) == NULL)
3641 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]
3646 return iterator.end() ? nil : [[Package newPackageWithIterator:iterator withZone:NULL inPool:NULL database:self] autorelease];
3650 if ((self = [super init]) != nil) {
3657 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3659 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3663 _assert(pipe(fds) != -1);
3666 _config->Set("APT::Keep-Fds::", cydiafd_);
3667 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3670 detachNewThreadSelector:@selector(_readCydia:)
3672 withObject:[NSNumber numberWithInt:fds[0]]
3675 _assert(pipe(fds) != -1);
3679 detachNewThreadSelector:@selector(_readStatus:)
3681 withObject:[NSNumber numberWithInt:fds[0]]
3684 _assert(pipe(fds) != -1);
3685 _assert(dup2(fds[0], 0) != -1);
3686 _assert(close(fds[0]) != -1);
3688 input_ = fdopen(fds[1], "a");
3690 _assert(pipe(fds) != -1);
3691 _assert(dup2(fds[1], 1) != -1);
3692 _assert(close(fds[1]) != -1);
3695 detachNewThreadSelector:@selector(_readOutput:)
3697 withObject:[NSNumber numberWithInt:fds[0]]
3702 - (pkgCacheFile &) cache {
3706 - (pkgDepCache::Policy *) policy {
3710 - (pkgRecords *) records {
3714 - (pkgProblemResolver *) resolver {
3718 - (pkgAcquire &) fetcher {
3722 - (pkgSourceList &) list {
3726 - (NSArray *) packages {
3730 - (NSArray *) sources {
3734 - (Source *) sourceWithKey:(NSString *)key {
3735 for (Source *source in [self sources]) {
3736 if ([[source key] isEqualToString:key])
3741 - (bool) popErrorWithTitle:(NSString *)title {
3744 while (!_error->empty()) {
3746 bool warning(!_error->PopMessage(error));
3751 size_t size(error.size());
3752 if (size == 0 || error[size - 1] != '\n')
3754 error.resize(size - 1);
3757 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3759 static RegEx no_pubkey("GPG error:.* NO_PUBKEY .*");
3760 if (warning && no_pubkey(error.c_str()))
3763 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3769 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3770 return [self popErrorWithTitle:title] || !success;
3773 - (bool) popErrorWithTitle:(NSString *)title forReadList:(pkgSourceList &)list {
3774 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3782 if (access("/etc/apt/sources.list", F_OK) == 0)
3783 error |= [self popErrorWithTitle:title forOperation:list.ReadAppend("/etc/apt/sources.list")];
3785 std::string base("/etc/apt/sources.list.d");
3786 if (DIR *sources = opendir(base.c_str())) {
3787 while (dirent *source = readdir(sources))
3788 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)
3789 error |= [self popErrorWithTitle:title forOperation:list.ReadAppend((base + "/" + source->d_name).c_str())];
3793 error |= [self popErrorWithTitle:title forOperation:list.ReadAppend(SOURCES_LIST)];
3798 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3799 @synchronized (self) {
3802 [self releasePackages];
3805 [sourceList_ removeAllObjects];
3826 new (&pool_) CYPool();
3828 NSRecycleZone(zone_);
3829 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3831 int chk(creat("/tmp/cydia.chk", 0644));
3835 if (invocation != nil)
3836 [invocation invoke];
3838 NSString *title(UCLocalize("DATABASE"));
3840 list_ = new pkgSourceList();
3841 _profile(reloadDataWithInvocation$ReadMainList)
3842 if ([self popErrorWithTitle:title forReadList:*list_])
3846 _profile(reloadDataWithInvocation$Source$initWithMetaIndex)
3847 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3848 Source *object([[[Source alloc] initWithMetaIndex:*source forDatabase:self inPool:&pool_] autorelease]);
3849 [sourceList_ addObject:object];
3854 OpProgress progress;
3857 delock_ = GetStatusDate();
3858 _profile(reloadDataWithInvocation$pkgCacheFile)
3859 opened = cache_.Open(progress, false);
3862 // XXX: this block should probably be merged with popError: in some way
3863 while (!_error->empty()) {
3865 bool warning(!_error->PopMessage(error));
3867 lprintf("cache_.Open():[%s]\n", error.c_str());
3869 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3873 else if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3874 repair = @selector(configure);
3875 //else if (error == "The package lists or status file could not be parsed or opened.")
3876 // repair = @selector(update);
3877 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3878 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3879 // else if (error == "Malformed Status line")
3880 // else if (error == "The list of sources could not be read.")
3882 if (repair != NULL) {
3884 [delegate_ repairWithSelector:repair];
3890 } else if ([self popErrorWithTitle:title forOperation:true])
3894 unlink("/tmp/cydia.chk");
3896 now_ = [[NSDate date] timeIntervalSince1970];
3898 policy_ = new pkgDepCache::Policy();
3899 records_ = new pkgRecords(cache_);
3900 resolver_ = new pkgProblemResolver(cache_);
3901 fetcher_ = new pkgAcquire(&status_);
3904 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3905 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3909 _profile(reloadDataWithInvocation$pkgApplyStatus)
3910 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3914 if (cache_->BrokenCount() != 0) {
3915 _profile(pkgApplyStatus$pkgFixBroken)
3916 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3920 if (cache_->BrokenCount() != 0) {
3921 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3925 _profile(pkgApplyStatus$pkgMinimizeUpgrade)
3926 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3931 for (Source *object in (id) sourceList_) {
3932 metaIndex *source([object metaIndex]);
3933 std::vector<pkgIndexFile *> *indices = source->GetIndexFiles();
3934 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3935 // XXX: this could be more intelligent
3936 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3937 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3939 sourceMap_[cached->ID] = object;
3944 size_t capacity(MetaFile_->active_);
3946 capacity = 128*1024;
3950 std::vector<Package *> packages;
3951 packages.reserve(capacity);
3955 _profile(reloadDataWithInvocation$packageWithIterator)
3956 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3957 if (Package *package = [Package newPackageWithIterator:iterator withZone:zone_ inPool:&pool_ database:self]) {
3958 if (unsigned index = package.metadata->index_) {
3960 if (packages.size() == index) {
3961 packages.push_back(package);
3962 } else if (packages.size() <= index) {
3963 packages.resize(index + 1, nil);
3964 packages[index] = package;
3967 std::swap(package, packages[index]);
3975 if (last == packages.size()) {
3976 packages.push_back(package);
3979 packages[last] = package;
3984 for (; last != packages.size(); ++last)
3985 if (packages[last] == nil)
3990 for (size_t next(last + 1); last != packages.size(); ++last, ++next) {
3992 if (next == packages.size())
3994 if (packages[next] != nil)
3999 std::swap(packages[last], packages[next]);
4002 packages.resize(last);
4005 NSLog(@"lost = %zu", lost);
4007 _profile(reloadDataWithInvocation$radix$8)
4008 CYRadixSortUsingFunction(packages.data(), packages.size(), reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix), reinterpret_cast<void *>(8));
4011 _profile(reloadDataWithInvocation$radix$4)
4012 CYRadixSortUsingFunction(packages.data(), packages.size(), reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix), reinterpret_cast<void *>(4));
4015 _profile(reloadDataWithInvocation$radix$0)
4016 CYRadixSortUsingFunction(packages.data(), packages.size(), reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix), reinterpret_cast<void *>(0));
4020 _profile(reloadDataWithInvocation$insertion)
4021 CYArrayInsertionSortValues(packages.data(), packages.size(), &PackageNameCompare, NULL);
4024 packages_ = [[[NSArray alloc] initWithObjects:packages.data() count:packages.size()] autorelease];
4026 /*_profile(reloadDataWithInvocation$CFQSortArray)
4027 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);
4030 /*_profile(reloadDataWithInvocation$stdsort)
4031 std::sort(packages.begin(), packages.end(), PackageNameOrdering());
4034 /*_profile(reloadDataWithInvocation$CFArraySortValues)
4035 CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
4038 /*_profile(reloadDataWithInvocation$sortUsingFunction)
4039 [packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
4042 MetaFile_->active_ = packages.size();
4043 for (size_t index(0), count(packages.size()); index != count; ++index) {
4044 auto package(packages[index]);
4045 [package setIndex:index];
4052 @synchronized (self) {
4054 resolver_ = new pkgProblemResolver(cache_);
4056 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
4057 if (!cache_[iterator].Keep())
4058 cache_->MarkKeep(iterator, false);
4059 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
4060 cache_->SetReInstall(iterator, false);
4063 - (void) configure {
4064 NSString *dpkg = [NSString stringWithFormat:@"/usr/libexec/cydo --configure -a --status-fd %u", statusfd_];
4066 system([dpkg UTF8String]);
4071 @synchronized (self) {
4072 // XXX: I don't remember this condition
4077 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
4079 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
4081 if ([self popErrorWithTitle:title])
4085 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
4087 CydiaLogCleaner cleaner;
4088 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
4095 fetcher_->Shutdown();
4097 pkgRecords records(cache_);
4099 lock_ = new FileFd();
4100 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
4102 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
4104 if ([self popErrorWithTitle:title])
4108 if ([self popErrorWithTitle:title forReadList:list])
4111 manager_ = (_system->CreatePM(cache_));
4112 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
4119 bool substrate(RestartSubstrate_);
4120 RestartSubstrate_ = false;
4122 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
4124 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
4126 if ([self popErrorWithTitle:title forReadList:list])
4128 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
4129 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
4132 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4134 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
4136 [self popErrorWithTitle:title];
4140 bool failed = false;
4141 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
4142 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
4144 if ((*item)->Status == pkgAcquire::Item::StatIdle)
4147 std::string uri = (*item)->DescURI();
4148 std::string error = (*item)->ErrorText;
4150 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
4153 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError]);
4154 [delegate_ addProgressEventOnMainThread:event forTask:title];
4157 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4165 RestartSubstrate_ = true;
4167 if (![delock_ isEqual:GetStatusDate()]) {
4168 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("DPKG_LOCKED") ofType:kCydiaProgressEventTypeError] forTask:title];
4174 pkgPackageManager::OrderResult result(manager_->DoInstall(statusfd_));
4176 NSString *oextended(@"/var/lib/apt/extended_states");
4177 NSString *nextended(Cache("extended_states"));
4180 if (stat([nextended UTF8String], &info) != -1 && (info.st_mode & S_IFMT) == S_IFREG)
4181 system([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /bin/cp --remove-destination %@ %@", ShellEscape(nextended), ShellEscape(oextended)] UTF8String]);
4183 unlink([nextended UTF8String]);
4184 symlink([oextended UTF8String], [nextended UTF8String]);
4186 if ([self popErrorWithTitle:title])
4189 if (result == pkgPackageManager::Failed) {
4194 if (result != pkgPackageManager::Completed) {
4199 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
4201 if ([self popErrorWithTitle:title forReadList:list])
4203 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
4204 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
4207 if (![before isEqualToArray:after])
4212 return ![delock_ isEqual:GetStatusDate()];
4216 NSString *title(UCLocalize("UPGRADE"));
4217 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
4223 [self updateWithStatus:status_];
4226 - (void) updateWithStatus:(CancelStatus &)status {
4227 NSString *title(UCLocalize("REFRESHING_DATA"));
4230 if ([self popErrorWithTitle:title forReadList:list])
4234 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
4235 if ([self popErrorWithTitle:title])
4238 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4240 bool success(ListUpdate(status, list, PulseInterval_));
4241 if (status.WasCancelled())
4244 [self popErrorWithTitle:title forOperation:success];
4246 [[NSDictionary dictionaryWithObjectsAndKeys:
4247 [NSDate date], @"LastUpdate",
4248 nil] writeToFile:@ CacheState_ atomically:YES];
4251 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4254 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
4255 delegate_ = delegate;
4258 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
4259 progress_ = delegate;
4260 status_.setDelegate(delegate);
4263 - (NSObject<ProgressDelegate> *) progressDelegate {
4267 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
4268 SourceMap::const_iterator i(sourceMap_.find(file->ID));
4269 return i == sourceMap_.end() ? nil : i->second;
4272 - (void) setFetch:(bool)fetch forURI:(const char *)uri {
4273 for (Source *source in (id) sourceList_)
4274 [source setFetch:fetch forURI:uri];
4277 - (void) resetFetch {
4278 for (Source *source in (id) sourceList_)
4279 [source resetFetch];
4282 - (NSString *) mappedSectionForPointer:(const char *)section {
4283 _H<NSString> *mapped;
4285 _profile(Database$mappedSectionForPointer$Cache)
4286 mapped = §ions_[section];
4289 if (*mapped == NULL) {
4290 size_t length(strlen(section));
4291 char spaced[length + 1];
4293 _profile(Database$mappedSectionForPointer$Replace)
4294 for (size_t index(0); index != length; ++index)
4295 spaced[index] = section[index] == '_' ? ' ' : section[index];
4296 spaced[length] = '\0';
4301 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
4302 string = [NSString stringWithUTF8String:spaced];
4305 _profile(Database$mappedSectionForPointer$Map)
4306 string = [SectionMap_ objectForKey:string] ?: string;
4316 static _H<NSMutableSet> Diversions_;
4318 @interface Diversion : NSObject {
4321 _H<NSString> format_;
4326 @implementation Diversion
4328 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
4329 if ((self = [super init]) != nil) {
4330 pattern_ = [from UTF8String];
4336 - (NSString *) divert:(NSString *)url {
4337 return !pattern_(url) ? nil : pattern_->*format_;
4340 + (NSURL *) divertURL:(NSURL *)url {
4342 NSString *href([url absoluteString]);
4344 for (Diversion *diversion in (id) Diversions_)
4345 if (NSString *diverted = [diversion divert:href]) {
4347 NSLog(@"div: %@", diverted);
4349 url = [NSURL URLWithString:diverted];
4356 - (NSString *) key {
4360 - (NSUInteger) hash {
4364 - (BOOL) isEqual:(Diversion *)object {
4365 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
4370 @interface CydiaObject : NSObject {
4371 _H<CyteWebViewController> indirect_;
4372 _transient id delegate_;
4375 - (id) initWithDelegate:(CyteWebViewController *)indirect;
4381 @interface CydiaWebViewController : CyteWebViewController {
4382 _H<CydiaObject> cydia_;
4385 + (void) addDiversion:(Diversion *)diversion;
4386 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request;
4387 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia;
4388 - (void) setDelegate:(id)delegate;
4392 /* Web Scripting {{{ */
4393 @implementation CydiaObject
4395 - (id) initWithDelegate:(CyteWebViewController *)indirect {
4396 if ((self = [super init]) != nil) {
4397 indirect_ = indirect;
4401 - (void) setDelegate:(id)delegate {
4402 delegate_ = delegate;
4405 + (NSArray *) _attributeKeys {
4406 return [NSArray arrayWithObjects:
4411 @"coreFoundationVersionNumber",
4427 - (NSArray *) attributeKeys {
4428 return [[self class] _attributeKeys];
4431 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4432 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4435 - (NSString *) version {
4439 - (unsigned) bittage {
4441 #elif defined(__arm64__)
4443 #elif defined(__arm__)
4450 - (NSString *) build {
4454 - (NSString *) coreFoundationVersionNumber {
4455 return [NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber];
4458 - (NSString *) device {
4459 return UniqueIdentifier();
4462 - (NSString *) firmware {
4463 return [[UIDevice currentDevice] systemVersion];
4466 - (NSString *) hostname {
4467 return [[UIDevice currentDevice] name];
4470 - (NSString *) idiom {
4471 return (id) Idiom_ ?: [NSNull null];
4474 - (NSArray *) cells {
4475 auto *$_CTServerConnectionCreate(reinterpret_cast<id (*)(void *, void *, void *)>(dlsym(RTLD_DEFAULT, "_CTServerConnectionCreate")));
4476 if ($_CTServerConnectionCreate == NULL)
4479 struct CTResult { int flag; int error; };
4480 auto *$_CTServerConnectionCellMonitorCopyCellInfo(reinterpret_cast<CTResult (*)(CFTypeRef, void *, CFArrayRef *)>(dlsym(RTLD_DEFAULT, "_CTServerConnectionCellMonitorCopyCellInfo")));
4481 if ($_CTServerConnectionCellMonitorCopyCellInfo == NULL)
4484 _H<const void> connection($_CTServerConnectionCreate(NULL, NULL, NULL), true);
4485 if (connection == nil)
4489 CFArrayRef cells(NULL);
4490 auto result($_CTServerConnectionCellMonitorCopyCellInfo(connection, &count, &cells));
4491 if (result.flag != 0)
4494 return [(NSArray *) cells autorelease];
4497 - (NSString *) mcc {
4498 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode")))
4499 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault) autorelease];
4503 - (NSString *) mnc {
4504 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberNetworkCode")))
4505 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault) autorelease];
4509 - (NSString *) operator {
4510 if (CFStringRef (*$CTRegistrationCopyOperatorName)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTRegistrationCopyOperatorName")))
4511 return [(NSString *) (*$CTRegistrationCopyOperatorName)(kCFAllocatorDefault) autorelease];
4515 - (NSString *) bbsnum {
4516 return (id) BBSNum_ ?: [NSNull null];
4519 - (NSString *) ecid {
4520 return (id) ChipID_ ?: [NSNull null];
4523 - (NSString *) serial {
4524 return SerialNumber_;
4527 - (NSString *) role {
4528 return (id) [NSNull null];
4531 - (NSString *) model {
4532 return [NSString stringWithUTF8String:Machine_];
4535 + (NSString *) webScriptNameForSelector:(SEL)selector {
4537 else if (selector == @selector(addBridgedHost:))
4538 return @"addBridgedHost";
4539 else if (selector == @selector(addInsecureHost:))
4540 return @"addInsecureHost";
4541 else if (selector == @selector(addInternalRedirect::))
4542 return @"addInternalRedirect";
4543 else if (selector == @selector(addSource:::))
4544 return @"addSource";
4545 else if (selector == @selector(addTrivialSource:))
4546 return @"addTrivialSource";
4547 else if (selector == @selector(close))
4549 else if (selector == @selector(du:))
4551 else if (selector == @selector(stringWithFormat:arguments:))
4553 else if (selector == @selector(getAllSources))
4554 return @"getAllSources";
4555 else if (selector == @selector(getApplicationInfo:value:))
4556 return @"getApplicationInfoValue";
4557 else if (selector == @selector(getDisplayIdentifiers))
4558 return @"getDisplayIdentifiers";
4559 else if (selector == @selector(getLocalizedNameForDisplayIdentifier:))
4560 return @"getLocalizedNameForDisplayIdentifier";
4561 else if (selector == @selector(getKernelNumber:))
4562 return @"getKernelNumber";
4563 else if (selector == @selector(getKernelString:))
4564 return @"getKernelString";
4565 else if (selector == @selector(getInstalledPackages))
4566 return @"getInstalledPackages";
4567 else if (selector == @selector(getIORegistryEntry::))
4568 return @"getIORegistryEntry";
4569 else if (selector == @selector(getLocaleIdentifier))
4570 return @"getLocaleIdentifier";
4571 else if (selector == @selector(getPreferredLanguages))
4572 return @"getPreferredLanguages";
4573 else if (selector == @selector(getPackageById:))
4574 return @"getPackageById";
4575 else if (selector == @selector(getMetadataKeys))
4576 return @"getMetadataKeys";
4577 else if (selector == @selector(getMetadataValue:))
4578 return @"getMetadataValue";
4579 else if (selector == @selector(getSessionValue:))
4580 return @"getSessionValue";
4581 else if (selector == @selector(installPackages:))
4582 return @"installPackages";
4583 else if (selector == @selector(isReachable:))
4584 return @"isReachable";
4585 else if (selector == @selector(localizedStringForKey:value:table:))
4587 else if (selector == @selector(popViewController:))
4588 return @"popViewController";
4589 else if (selector == @selector(refreshSources))
4590 return @"refreshSources";
4591 else if (selector == @selector(registerFrame:))
4592 return @"registerFrame";
4593 else if (selector == @selector(removeButton))
4594 return @"removeButton";
4595 else if (selector == @selector(saveConfig))
4596 return @"saveConfig";
4597 else if (selector == @selector(setMetadataValue::))
4598 return @"setMetadataValue";
4599 else if (selector == @selector(setSessionValue::))
4600 return @"setSessionValue";
4601 else if (selector == @selector(substitutePackageNames:))
4602 return @"substitutePackageNames";
4603 else if (selector == @selector(scrollToBottom:))
4604 return @"scrollToBottom";
4605 else if (selector == @selector(setAllowsNavigationAction:))
4606 return @"setAllowsNavigationAction";
4607 else if (selector == @selector(setBadgeValue:))
4608 return @"setBadgeValue";
4609 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4610 return @"setButtonImage";
4611 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4612 return @"setButtonTitle";
4613 else if (selector == @selector(setHidesBackButton:))
4614 return @"setHidesBackButton";
4615 else if (selector == @selector(setHidesNavigationBar:))
4616 return @"setHidesNavigationBar";
4617 else if (selector == @selector(setNavigationBarStyle:))
4618 return @"setNavigationBarStyle";
4619 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4620 return @"setNavigationBarTintColor";
4621 else if (selector == @selector(setPasteboardString:))
4622 return @"setPasteboardString";
4623 else if (selector == @selector(setPasteboardURL:))
4624 return @"setPasteboardURL";
4625 else if (selector == @selector(setScrollAlwaysBounceVertical:))
4626 return @"setScrollAlwaysBounceVertical";
4627 else if (selector == @selector(setScrollIndicatorStyle:))
4628 return @"setScrollIndicatorStyle";
4629 else if (selector == @selector(setToken:))
4631 else if (selector == @selector(setViewportWidth:))
4632 return @"setViewportWidth";
4633 else if (selector == @selector(statfs:))
4635 else if (selector == @selector(supports:))
4637 else if (selector == @selector(unload))
4643 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4644 return [self webScriptNameForSelector:selector] == nil;
4647 - (BOOL) supports:(NSString *)feature {
4648 return [feature isEqualToString:@"window.open"];
4652 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4655 - (void) setScrollAlwaysBounceVertical:(NSNumber *)value {
4656 [indirect_ performSelectorOnMainThread:@selector(setScrollAlwaysBounceVerticalNumber:) withObject:value waitUntilDone:NO];
4659 - (void) setScrollIndicatorStyle:(NSString *)style {
4660 [indirect_ performSelectorOnMainThread:@selector(setScrollIndicatorStyleWithName:) withObject:style waitUntilDone:NO];
4663 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4664 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4667 - (NSDictionary *) getApplicationInfo:(NSString *)display value:(NSString *)key {
4669 if (SBBundlePathForDisplayIdentifier(SBSSpringBoardServerPort(), [display UTF8String], path) != 0)
4670 return (id) [NSNull null];
4671 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:[[NSString stringWithUTF8String:path] stringByAppendingString:@"/Info.plist"]]);
4673 return (id) [NSNull null];
4674 return [info objectForKey:key];
4677 - (NSArray *) getDisplayIdentifiers {
4678 return SBSCopyApplicationDisplayIdentifiers(false, false);
4681 - (NSString *) getLocalizedNameForDisplayIdentifier:(NSString *)identifier {
4682 return [SBSCopyLocalizedApplicationNameForDisplayIdentifier(identifier) autorelease] ?: (id) [NSNull null];
4685 - (NSNumber *) getKernelNumber:(NSString *)name {
4686 const char *string([name UTF8String]);
4689 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4690 return (id) [NSNull null];
4692 if (size != sizeof(int))
4693 return (id) [NSNull null];
4696 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4697 return (id) [NSNull null];
4699 return [NSNumber numberWithInt:value];
4702 - (NSString *) getKernelString:(NSString *)name {
4703 const char *string([name UTF8String]);
4706 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4707 return (id) [NSNull null];
4709 char value[size + 1];
4710 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4711 return (id) [NSNull null];
4713 // XXX: just in case you request something ludicrous
4716 return [NSString stringWithCString:value];
4719 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4720 NSObject *value(CYIOGetValue([path UTF8String], entry));
4723 if ([value isKindOfClass:[NSData class]])
4724 value = CYHex((NSData *) value);
4729 - (NSArray *) getMetadataKeys {
4730 @synchronized (Values_) {
4731 return [Values_ allKeys];
4734 - (void) registerFrame:(DOMHTMLIFrameElement *)iframe {
4735 WebFrame *frame([iframe contentFrame]);
4736 [indirect_ registerFrame:frame];
4739 - (id) getMetadataValue:(NSString *)key {
4740 @synchronized (Values_) {
4741 return [Values_ objectForKey:key];
4744 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4745 @synchronized (Values_) {
4746 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4747 [Values_ removeObjectForKey:key];
4749 [Values_ setObject:value forKey:key];
4752 - (id) getSessionValue:(NSString *)key {
4753 @synchronized (SessionData_) {
4754 return [SessionData_ objectForKey:key];
4757 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4758 @synchronized (SessionData_) {
4759 if (value == (id) [WebUndefined undefined])
4760 [SessionData_ removeObjectForKey:key];
4762 [SessionData_ setObject:value forKey:key];
4765 - (void) addBridgedHost:(NSString *)host {
4766 @synchronized (HostConfig_) {
4767 [BridgedHosts_ addObject:host];
4770 - (void) addInsecureHost:(NSString *)host {
4771 @synchronized (HostConfig_) {
4772 [InsecureHosts_ addObject:host];
4775 - (void) popViewController:(NSNumber *)value {
4776 if (value == (id) [WebUndefined undefined])
4777 value = [NSNumber numberWithBool:YES];
4778 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4781 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4782 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4784 for (NSString *section in sections)
4785 [array addObject:section];
4787 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4790 distribution, @"Distribution",
4792 nil] waitUntilDone:NO];
4795 - (BOOL) addTrivialSource:(NSString *)href {
4796 href = VerifySource(href);
4799 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4803 - (void) refreshSources {
4804 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4807 - (void) saveConfig {
4808 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4811 - (NSArray *) getAllSources {
4812 return [[Database sharedInstance] sources];
4815 - (NSArray *) getInstalledPackages {
4816 Database *database([Database sharedInstance]);
4817 @synchronized (database) {
4818 NSArray *packages([database packages]);
4819 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4820 for (Package *package in packages)
4821 if (![package uninstalled])
4822 [installed addObject:package];
4826 - (Package *) getPackageById:(NSString *)id {
4827 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4831 return (Package *) [NSNull null];
4834 - (NSString *) getLocaleIdentifier {
4835 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4838 - (NSArray *) getPreferredLanguages {
4842 - (NSArray *) statfs:(NSString *)path {
4845 if (path == nil || statfs([path UTF8String], &stat) == -1)
4848 return [NSArray arrayWithObjects:
4849 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4850 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4851 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4855 - (NSNumber *) du:(NSString *)path {
4856 NSNumber *value(nil);
4858 FILE *du(popen([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /usr/libexec/cydia/du -ks %@", ShellEscape(path)] UTF8String], "r"));
4861 while (fgets(line, sizeof(line), du) != NULL) {
4862 size_t length(strlen(line));
4863 while (length != 0 && line[length - 1] == '\n')
4864 line[--length] = '\0';
4865 if (char *tab = strchr(line, '\t')) {
4867 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4877 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4880 - (NSNumber *) isReachable:(NSString *)name {
4881 return [NSNumber numberWithBool:IsReachable([name UTF8String])];
4884 - (void) installPackages:(NSArray *)packages {
4885 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4888 - (NSString *) substitutePackageNames:(NSString *)message {
4889 auto database([Database sharedInstance]);
4891 // XXX: this check is less racy than you'd expect, but this entire concept is a little awkward
4892 if (![database hasPackages])
4895 NSMutableArray *words([[[message componentsSeparatedByString:@" "] mutableCopy] autorelease]);
4896 for (size_t i(0), e([words count]); i != e; ++i) {
4897 NSString *word([words objectAtIndex:i]);
4898 if (Package *package = [database packageWithName:word])
4899 [words replaceObjectAtIndex:i withObject:[package name]];
4902 return [words componentsJoinedByString:@" "];
4905 - (void) removeButton {
4906 [indirect_ removeButton];
4909 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4910 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4913 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4914 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4917 - (void) setBadgeValue:(id)value {
4918 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4921 - (void) setAllowsNavigationAction:(NSString *)value {
4922 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4925 - (void) setHidesBackButton:(NSString *)value {
4926 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4929 - (void) setHidesNavigationBar:(NSString *)value {
4930 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4933 - (void) setNavigationBarStyle:(NSString *)value {
4934 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4937 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4938 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4939 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4940 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4943 - (void) setPasteboardString:(NSString *)value {
4944 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4947 - (void) setPasteboardURL:(NSString *)value {
4948 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4951 - (void) setToken:(NSString *)token {
4952 // XXX: the website expects this :/
4955 - (void) scrollToBottom:(NSNumber *)animated {
4956 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4959 - (void) setViewportWidth:(float)width {
4960 [indirect_ setViewportWidthOnMainThread:width];
4963 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4964 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4965 unsigned count([arguments count]);
4967 for (unsigned i(0); i != count; ++i)
4968 values[i] = [arguments objectAtIndex:i];
4969 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4972 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4973 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4975 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4977 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4983 @interface NSURL (CydiaSecure)
4986 @implementation NSURL (CydiaSecure)
4988 - (bool) isCydiaSecure {
4989 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4992 @synchronized (HostConfig_) {
4993 if ([InsecureHosts_ containsObject:[self host]])
5002 /* Cydia Browser Controller {{{ */
5003 @implementation CydiaWebViewController
5005 - (NSURL *) navigationURL {
5006 if (NSURLRequest *request = self.request)
5007 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request URL] absoluteString]]];
5012 + (void) _initialize {
5013 [super _initialize];
5015 Diversions_ = [NSMutableSet setWithCapacity:0];
5018 + (void) addDiversion:(Diversion *)diversion {
5019 [Diversions_ addObject:diversion];
5022 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5023 [super webView:view didClearWindowObject:window forFrame:frame];
5024 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
5027 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia {
5028 WebDataSource *source([frame dataSource]);
5029 NSURLResponse *response([source response]);
5030 NSURL *url([response URL]);
5031 NSString *scheme([[url scheme] lowercaseString]);
5033 bool bridged(false);
5035 @synchronized (HostConfig_) {
5036 if ([scheme isEqualToString:@"file"])
5038 else if ([scheme isEqualToString:@"https"])
5039 if ([BridgedHosts_ containsObject:[url host]])
5044 [window setValue:cydia forKey:@"cydia"];
5047 - (void) _setupMail:(MFMailComposeViewController *)controller {
5048 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
5050 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
5051 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
5054 - (NSURL *) URLWithURL:(NSURL *)url {
5055 return [Diversion divertURL:url];
5058 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
5059 return [CydiaWebViewController requestWithHeaders:[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
5062 - (NSURLRequest *) webThreadWebView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
5063 return [CydiaWebViewController requestWithHeaders:[super webThreadWebView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
5066 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request {
5067 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
5069 NSURL *url([copy URL]);
5070 NSString *href([url absoluteString]);
5071 NSString *host([url host]);
5073 if ([href hasPrefix:@"https://cydia.saurik.com/TSS/"]) {
5074 if (NSString *agent = [copy valueForHTTPHeaderField:@"X-User-Agent"]) {
5075 [copy setValue:agent forHTTPHeaderField:@"User-Agent"];
5076 [copy setValue:nil forHTTPHeaderField:@"X-User-Agent"];
5079 [copy setValue:nil forHTTPHeaderField:@"Referer"];
5080 [copy setValue:nil forHTTPHeaderField:@"Origin"];
5082 [copy setURL:[NSURL URLWithString:[@"http://gs.apple.com/TSS/" stringByAppendingString:[href substringFromIndex:29]]]];
5086 if ([copy valueForHTTPHeaderField:@"X-Cydia-Cf"] == nil)
5087 [copy setValue:[NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber] forHTTPHeaderField:@"X-Cydia-Cf"];
5088 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
5089 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
5091 bool bridged; @synchronized (HostConfig_) {
5092 bridged = [BridgedHosts_ containsObject:host];
5095 if ([url isCydiaSecure] && bridged && UniqueID_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Id"] == nil)
5096 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
5101 - (void) setDelegate:(id)delegate {
5102 [super setDelegate:delegate];
5103 [cydia_ setDelegate:delegate];
5106 - (NSString *) applicationNameForUserAgent {
5111 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
5112 cydia_ = [[[CydiaObject alloc] initWithDelegate:self.indirect] autorelease];
5118 @interface AppCacheController : CydiaWebViewController {
5123 @implementation AppCacheController
5125 - (void) didReceiveMemoryWarning {
5126 // XXX: this doesn't work
5129 - (bool) retainsNetworkActivityIndicator {
5137 @interface NSObject (CydiaScript)
5138 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
5141 @implementation NSObject (CydiaScript)
5143 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5149 @implementation NSArray (CydiaScript)
5151 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5152 WebScriptObject *object([context evaluateWebScript:@"[]"]);
5153 for (size_t i(0), e([self count]); i != e; ++i)
5154 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
5160 @implementation NSDictionary (CydiaScript)
5162 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5163 WebScriptObject *object([context evaluateWebScript:@"({})"]);
5165 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
5172 /* Confirmation Controller {{{ */
5173 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
5174 if (!iterator.end())
5175 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
5176 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
5178 pkgCache::PkgIterator package(dep.TargetPkg());
5181 if (strcmp(package.Name(), "mobilesubstrate") == 0)
5188 @protocol ConfirmationControllerDelegate
5189 - (void) cancelAndClear:(bool)clear;
5190 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
5194 @interface ConfirmationController : CydiaWebViewController {
5195 _transient Database *database_;
5197 _H<UIAlertView> essential_;
5199 _H<NSDictionary> changes_;
5200 _H<NSMutableArray> issues_;
5201 _H<NSDictionary> sizes_;
5206 - (id) initWithDatabase:(Database *)database;
5210 @implementation ConfirmationController
5214 RestartSubstrate_ = true;
5215 [self.delegate confirmWithNavigationController:[self navigationController]];
5218 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
5219 NSString *context([alert context]);
5221 if ([context isEqualToString:@"remove"]) {
5222 if (button == [alert cancelButtonIndex])
5224 else if (button == [alert firstOtherButtonIndex]) {
5225 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
5228 [alert dismissWithClickedButtonIndex:-1 animated:YES];
5229 } else if ([context isEqualToString:@"unable"]) {
5230 [self dismissModalViewControllerAnimated:YES];
5231 [alert dismissWithClickedButtonIndex:-1 animated:YES];
5233 [super alertView:alert clickedButtonAtIndex:button];
5237 - (void) _doContinue {
5238 [self.delegate cancelAndClear:NO];
5239 [self dismissModalViewControllerAnimated:YES];
5242 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
5243 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
5247 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5248 [super webView:view didClearWindowObject:window forFrame:frame];
5250 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
5251 (id) changes_, @"changes",
5252 (id) issues_, @"issues",
5253 (id) sizes_, @"sizes",
5255 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
5258 - (id) initWithDatabase:(Database *)database {
5259 if ((self = [super init]) != nil) {
5260 database_ = database;
5262 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
5263 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
5264 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
5265 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
5266 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
5270 pkgCacheFile &cache([database_ cache]);
5271 NSArray *packages([database_ packages]);
5272 pkgDepCache::Policy *policy([database_ policy]);
5274 issues_ = [NSMutableArray arrayWithCapacity:4];
5276 for (Package *package in packages) {
5277 pkgCache::PkgIterator iterator([package iterator]);
5278 NSString *name([package id]);
5280 if ([package broken]) {
5281 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
5283 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5285 reasons, @"reasons",
5288 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
5292 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
5293 pkgCache::DepIterator start;
5294 pkgCache::DepIterator end;
5295 dep.GlobOr(start, end); // ++dep
5297 if (!cache->IsImportantDep(end))
5299 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
5302 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
5304 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5305 [NSString stringWithUTF8String:start.DepType()], @"relationship",
5306 clauses, @"clauses",
5310 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
5312 pkgCache::PkgIterator target(start.TargetPkg());
5313 if (target->ProvidesList != 0)
5314 reason = @"missing";
5316 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
5318 reason = @"installed";
5319 installed = [NSString stringWithUTF8String:ver.VerStr()];
5320 } else if (!cache[target].CandidateVerIter(cache).end())
5321 reason = @"uninstalled";
5322 else if (target->ProvidesList == 0)
5323 reason = @"uninstallable";
5325 reason = @"virtual";
5328 NSDictionary *version(start.TargetVer() == 0 ? (NSDictionary *) [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
5329 [NSString stringWithUTF8String:start.CompType()], @"operator",
5330 [NSString stringWithUTF8String:start.TargetVer()], @"value",
5333 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5334 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
5335 version, @"version",
5337 installed, @"installed",
5340 // yes, seriously. (wtf?)
5348 pkgDepCache::StateCache &state(cache[iterator]);
5350 static RegEx special_r("(firmware|gsc\\..*|cy\\+.*)");
5352 if (state.NewInstall())
5353 [installs addObject:name];
5354 // XXX: else if (state.Install())
5355 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
5356 [reinstalls addObject:name];
5357 // XXX: move before previous if
5358 else if (state.Upgrade())
5359 [upgrades addObject:name];
5360 else if (state.Downgrade())
5361 [downgrades addObject:name];
5362 else if (!state.Delete())
5363 // XXX: _assert(state.Keep());
5365 else if (special_r(name))
5366 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5367 [NSNull null], @"package",
5368 [NSArray arrayWithObjects:
5369 [NSDictionary dictionaryWithObjectsAndKeys:
5370 @"Conflicts", @"relationship",
5371 [NSArray arrayWithObjects:
5372 [NSDictionary dictionaryWithObjectsAndKeys:
5374 [NSNull null], @"version",
5375 @"installed", @"reason",
5382 if ([package essential])
5384 [removes addObject:name];
5387 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
5388 substrate_ |= DepSubstrate(iterator.CurrentVer());
5393 else if (Advanced_) {
5394 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
5396 essential_ = [[[UIAlertView alloc]
5397 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
5398 message:UCLocalize("REMOVING_ESSENTIALS_EX")
5400 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
5402 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
5406 [essential_ setContext:@"remove"];
5407 [essential_ setNumberOfRows:2];
5409 essential_ = [[[UIAlertView alloc]
5410 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
5411 message:UCLocalize("UNABLE_TO_COMPLY_EX")
5413 cancelButtonTitle:UCLocalize("OKAY")
5414 otherButtonTitles:nil
5417 [essential_ setContext:@"unable"];
5420 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5421 installs, @"installs",
5422 reinstalls, @"reinstalls",
5423 upgrades, @"upgrades",
5424 downgrades, @"downgrades",
5425 removes, @"removes",
5428 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5429 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
5430 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
5433 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
5437 - (UIBarButtonItem *) leftButton {
5438 return [[[UIBarButtonItem alloc]
5439 initWithTitle:UCLocalize("CANCEL")
5440 style:UIBarButtonItemStylePlain
5442 action:@selector(cancelButtonClicked)
5447 - (void) applyRightButton {
5448 if ([issues_ count] == 0 && ![self isLoading])
5449 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
5450 initWithTitle:UCLocalize("CONFIRM")
5451 style:UIBarButtonItemStyleDone
5453 action:@selector(confirmButtonClicked)
5456 [[self navigationItem] setRightBarButtonItem:nil];
5460 - (void) cancelButtonClicked {
5461 [self.delegate cancelAndClear:YES];
5462 [self dismissModalViewControllerAnimated:YES];
5466 - (void) confirmButtonClicked {
5467 if (essential_ != nil)
5477 /* Progress Data {{{ */
5478 @interface CydiaProgressData : NSObject {
5479 _transient id delegate_;
5488 _H<NSMutableArray> events_;
5489 _H<NSString> title_;
5491 _H<NSString> status_;
5492 _H<NSString> finish_;
5497 @implementation CydiaProgressData
5499 + (NSArray *) _attributeKeys {
5500 return [NSArray arrayWithObjects:
5512 - (NSArray *) attributeKeys {
5513 return [[self class] _attributeKeys];
5516 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5517 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5521 if ((self = [super init]) != nil) {
5522 events_ = [NSMutableArray arrayWithCapacity:32];
5530 - (void) setDelegate:(id)delegate {
5531 delegate_ = delegate;
5534 - (void) setPercent:(float)value {
5538 - (NSNumber *) percent {
5539 return [NSNumber numberWithFloat:percent_];
5542 - (void) setCurrent:(float)value {
5546 - (NSNumber *) current {
5547 return [NSNumber numberWithFloat:current_];
5550 - (void) setTotal:(float)value {
5554 - (NSNumber *) total {
5555 return [NSNumber numberWithFloat:total_];
5558 - (void) setSpeed:(float)value {
5562 - (NSNumber *) speed {
5563 return [NSNumber numberWithFloat:speed_];
5566 - (NSArray *) events {
5570 - (void) removeAllEvents {
5571 [events_ removeAllObjects];
5574 - (void) addEvent:(CydiaProgressEvent *)event {
5575 [events_ addObject:event];
5578 - (void) setTitle:(NSString *)text {
5582 - (NSString *) title {
5586 - (void) setFinish:(NSString *)text {
5590 - (NSString *) finish {
5591 return (id) finish_ ?: [NSNull null];
5594 - (void) setRunning:(bool)running {
5598 - (NSNumber *) running {
5599 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5604 /* Progress Controller {{{ */
5605 @interface ProgressController : CydiaWebViewController <
5608 _transient Database *database_;
5609 _H<CydiaProgressData, 1> progress_;
5613 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5615 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5617 - (void) setTitle:(NSString *)title;
5618 - (void) setCancellable:(bool)cancellable;
5622 @implementation ProgressController
5625 [database_ setProgressDelegate:nil];
5629 - (UIBarButtonItem *) leftButton {
5630 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5631 initWithTitle:UCLocalize("CANCEL")
5632 style:UIBarButtonItemStylePlain
5634 action:@selector(cancel)
5635 ] autorelease] : nil;
5638 - (void) updateCancel {
5639 [super applyLeftButton];
5642 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5643 if ((self = [super init]) != nil) {
5644 database_ = database;
5645 self.delegate = delegate;
5647 [database_ setProgressDelegate:self];
5649 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5650 [progress_ setDelegate:self];
5652 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5654 [self setPageColor:[UIColor blackColor]];
5656 [[self navigationItem] setHidesBackButton:YES];
5658 [self updateCancel];
5662 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5663 [super webView:view didClearWindowObject:window forFrame:frame];
5664 [window setValue:progress_ forKey:@"cydiaProgress"];
5667 - (void) updateProgress {
5668 [self dispatchEvent:@"CydiaProgressUpdate"];
5671 - (void) viewWillAppear:(BOOL)animated {
5672 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5673 [super viewWillAppear:animated];
5677 UpdateExternalStatus(0);
5680 [self.delegate saveState];
5684 [self.delegate returnToCydia];
5688 [self.delegate terminateWithSuccess];
5689 /*if ([self.delegate respondsToSelector:@selector(suspendWithAnimation:)])
5690 [self.delegate suspendWithAnimation:YES];
5692 [self.delegate suspend];*/
5704 UIProgressHUD *hud([self.delegate addProgressHUD]);
5705 [hud setText:UCLocalize("LOADING")];
5706 [self.delegate performSelector:@selector(reloadSpringBoard) withObject:nil afterDelay:0.5];
5712 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5713 SBReboot(SBSSpringBoardServerPort());
5715 reboot2(RB_AUTOBOOT);
5722 - (void) setTitle:(NSString *)title {
5723 [progress_ setTitle:title];
5724 [self updateProgress];
5727 - (UIBarButtonItem *) rightButton {
5728 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5729 initWithTitle:UCLocalize("CLOSE")
5730 style:UIBarButtonItemStylePlain
5732 action:@selector(close)
5736 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5737 UpdateExternalStatus(1);
5739 [progress_ setRunning:true];
5740 [self setTitle:title];
5741 // implicit updateProgress
5743 SHA1SumValue notifyconf; {
5745 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5748 MMap mmap(file, MMap::ReadOnly);
5750 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5751 notifyconf = sha1.Result();
5755 SHA1SumValue springlist; {
5757 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5760 MMap mmap(file, MMap::ReadOnly);
5762 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5763 springlist = sha1.Result();
5767 if (invocation != nil) {
5768 [invocation yieldToSelector:@selector(invoke)];
5769 [self setTitle:@"COMPLETE"];
5774 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5777 MMap mmap(file, MMap::ReadOnly);
5779 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5780 if (!(notifyconf == sha1.Result()))
5787 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5790 MMap mmap(file, MMap::ReadOnly);
5792 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5793 if (!(springlist == sha1.Result()))
5799 if (RestartSubstrate_)
5803 RestartSubstrate_ = false;
5806 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5807 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5808 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5809 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5810 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5813 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5815 [progress_ setRunning:false];
5816 [self updateProgress];
5818 [self applyRightButton];
5821 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5822 [progress_ addEvent:event];
5823 [self updateProgress];
5826 - (bool) isProgressCancelled {
5827 return cancel_ == 2;
5832 [self updateCancel];
5835 - (void) setCancellable:(bool)cancellable {
5836 unsigned cancel(cancel_);
5840 else if (cancel_ == 0)
5843 if (cancel != cancel_)
5844 [self updateCancel];
5847 - (void) setProgressCancellable:(NSNumber *)cancellable {
5848 [self setCancellable:[cancellable boolValue]];
5851 - (void) setProgressPercent:(NSNumber *)percent {
5852 [progress_ setPercent:[percent floatValue]];
5853 [self updateProgress];
5856 - (void) setProgressStatus:(NSDictionary *)status {
5857 if (status == nil) {
5858 [progress_ setCurrent:0];
5859 [progress_ setTotal:0];
5860 [progress_ setSpeed:0];
5862 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5864 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5865 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5866 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5869 [self updateProgress];
5875 /* Package Cell {{{ */
5876 @interface PackageCell : CyteTableViewCell <
5877 CyteTableViewCellDelegate
5881 _H<NSString> description_;
5883 _H<NSString> source_;
5885 _H<UIImage> placard_;
5889 - (PackageCell *) init;
5890 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5892 - (void) drawContentRect:(CGRect)rect;
5896 @implementation PackageCell
5898 - (PackageCell *) init {
5899 CGRect frame(CGRectMake(0, 0, 320, 74));
5900 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5901 UIView *content([self contentView]);
5902 CGRect bounds([content bounds]);
5904 self.content = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5905 [self.content setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5906 [content addSubview:self.content];
5908 [self.content setDelegate:self];
5909 [self.content setOpaque:YES];
5913 - (NSString *) accessibilityLabel {
5917 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5918 summarized_ = summary;
5928 [self.content setBackgroundColor:[UIColor whiteColor]];
5932 Source *source = [package source];
5934 icon_ = [package icon];
5936 if (NSString *name = [package name])
5937 name_ = [NSString stringWithString:name];
5939 if (NSString *description = [package shortDescription])
5940 description_ = [NSString stringWithString:description];
5942 commercial_ = [package isCommercial];
5944 NSString *label = nil;
5945 bool trusted = false;
5947 if (source != nil) {
5948 label = [source label];
5949 trusted = [source trusted];
5950 } else if ([[package id] isEqualToString:@"firmware"])
5951 label = UCLocalize("APPLE");
5953 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5955 NSString *from(label);
5957 NSString *section = [package simpleSection];
5958 if (section != nil && ![section isEqualToString:label]) {
5959 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5960 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5963 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5965 if (NSString *purpose = [package primaryPurpose])
5966 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5971 if (NSString *mode = [package mode]) {
5972 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5973 color = RemovingColor_;
5974 placard = @"removing";
5976 color = InstallingColor_;
5977 placard = @"installing";
5980 color = [UIColor whiteColor];
5982 if ([package installed] != nil)
5983 placard = @"installed";
5988 [self.content setBackgroundColor:color];
5991 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5994 [self setNeedsDisplay];
5995 [self.content setNeedsDisplay];
5998 - (void) drawSummaryContentRect:(CGRect)rect {
5999 bool highlighted(self.highlighted);
6000 float width([self bounds].size.width);
6004 rect.size = [(UIImage *) icon_ size];
6006 while (rect.size.width > 16 || rect.size.height > 16) {
6007 rect.size.width /= 2;
6008 rect.size.height /= 2;
6011 rect.origin.x = 19 - rect.size.width / 2;
6012 rect.origin.y = 19 - rect.size.height / 2;
6014 [icon_ drawInRect:Retina(rect)];
6017 if (badge_ != nil) {
6019 rect.size = [(UIImage *) badge_ size];
6021 rect.size.width /= 4;
6022 rect.size.height /= 4;
6024 rect.origin.x = 25 - rect.size.width / 2;
6025 rect.origin.y = 25 - rect.size.height / 2;
6027 [badge_ drawInRect:Retina(rect)];
6030 if (highlighted && kCFCoreFoundationVersionNumber < 800)
6034 UISetColor(commercial_ ? Purple_ : Black_);
6035 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
6037 if (placard_ != nil)
6038 [placard_ drawAtPoint:CGPointMake(width - 52, 11)];
6041 - (void) drawNormalContentRect:(CGRect)rect {
6042 bool highlighted(self.highlighted);
6043 float width([self bounds].size.width);
6047 rect.size = [(UIImage *) icon_ size];
6049 while (rect.size.width > 32 || rect.size.height > 32) {
6050 rect.size.width /= 2;
6051 rect.size.height /= 2;
6054 rect.origin.x = 25 - rect.size.width / 2;
6055 rect.origin.y = 25 - rect.size.height / 2;
6057 [icon_ drawInRect:Retina(rect)];
6060 if (badge_ != nil) {
6062 rect.size = [(UIImage *) badge_ size];
6064 rect.size.width /= 2;
6065 rect.size.height /= 2;
6067 rect.origin.x = 36 - rect.size.width / 2;
6068 rect.origin.y = 36 - rect.size.height / 2;
6070 [badge_ drawInRect:Retina(rect)];
6073 if (highlighted && kCFCoreFoundationVersionNumber < 800)
6077 UISetColor(commercial_ ? Purple_ : Black_);
6078 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
6079 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
6082 UISetColor(commercial_ ? Purplish_ : Gray_);
6083 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:NSLineBreakByTruncatingTail];
6085 if (placard_ != nil)
6086 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
6089 - (void) drawContentRect:(CGRect)rect {
6091 [self drawSummaryContentRect:rect];
6093 [self drawNormalContentRect:rect];
6098 /* Section Cell {{{ */
6099 @interface SectionCell : CyteTableViewCell <
6100 CyteTableViewCellDelegate
6102 _H<NSString> basic_;
6103 _H<NSString> section_;
6105 _H<NSString> count_;
6107 _H<UISwitch> switch_;
6111 - (void) setSection:(Section *)section editing:(BOOL)editing;
6115 @implementation SectionCell
6117 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
6118 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
6119 icon_ = [UIImage imageNamed:@"folder.png"];
6120 // XXX: this initial frame is wrong, but is fixed later
6121 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
6122 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
6124 UIView *content([self contentView]);
6125 CGRect bounds([content bounds]);
6127 self.content = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
6128 [self.content setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6129 [content addSubview:self.content];
6130 [self.content setBackgroundColor:[UIColor whiteColor]];
6132 [self.content setDelegate:self];
6136 - (void) onSwitch:(id)sender {
6137 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
6138 if (metadata == nil) {
6139 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
6140 [Sections_ setObject:metadata forKey:basic_];
6143 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
6146 - (void) setSection:(Section *)section editing:(BOOL)editing {
6147 if (editing != editing_) {
6149 [switch_ removeFromSuperview];
6151 [self addSubview:switch_];
6160 if (section == nil) {
6161 name_ = UCLocalize("ALL_PACKAGES");
6164 basic_ = [section name];
6165 section_ = [section localized];
6167 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
6168 count_ = [NSString stringWithFormat:@"%zd", [section count]];
6171 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
6174 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
6175 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
6177 [self.content setNeedsDisplay];
6180 - (void) setFrame:(CGRect)frame {
6181 [super setFrame:frame];
6183 CGRect rect([switch_ frame]);
6184 [switch_ setFrame:CGRectMake(frame.size.width - rect.size.width - 9, 9, rect.size.width, rect.size.height)];
6187 - (NSString *) accessibilityLabel {
6191 - (void) drawContentRect:(CGRect)rect {
6192 bool highlighted(self.highlighted && !editing_);
6194 [icon_ drawInRect:CGRectMake(7, 7, 32, 32)];
6196 if (highlighted && kCFCoreFoundationVersionNumber < 800)
6199 float width(rect.size.width);
6201 width -= 9 + [switch_ frame].size.width;
6205 [name_ drawAtPoint:CGPointMake(48, 12) forWidth:(width - 58) withFont:Font18_ lineBreakMode:NSLineBreakByTruncatingTail];
6207 CGSize size = [count_ sizeWithFont:Font14_];
6209 UISetColor(Folder_);
6211 [count_ drawAtPoint:CGPointMake(Retina(10 + (30 - size.width) / 2), 18) withFont:Font12Bold_];
6217 /* File Table {{{ */
6218 @interface FileTable : CyteViewController <
6219 UITableViewDataSource,
6222 _transient Database *database_;
6223 _H<Package> package_;
6225 _H<NSMutableArray> files_;
6226 _H<UITableView, 2> list_;
6229 - (id) initWithDatabase:(Database *)database;
6230 - (void) setPackage:(Package *)package;
6234 @implementation FileTable
6236 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6237 return files_ == nil ? 0 : [files_ count];
6240 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6244 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6245 static NSString *reuseIdentifier = @"Cell";
6247 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6249 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6250 [cell setFont:[UIFont systemFontOfSize:16]];
6252 [cell setText:[files_ objectAtIndex:indexPath.row]];
6253 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
6258 - (NSURL *) navigationURL {
6259 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
6263 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
6264 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6265 [list_ setRowHeight:24.0f];
6266 [(UITableView *) list_ setDataSource:self];
6267 [list_ setDelegate:self];
6268 [self setView:list_];
6271 - (void) viewDidLoad {
6272 [super viewDidLoad];
6274 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
6277 - (void) releaseSubviews {
6283 [super releaseSubviews];
6286 - (id) initWithDatabase:(Database *)database {
6287 if ((self = [super init]) != nil) {
6288 database_ = database;
6292 - (void) setPackage:(Package *)package {
6296 files_ = [NSMutableArray arrayWithCapacity:32];
6298 if (package != nil) {
6300 name_ = [package id];
6302 if (NSArray *files = [package files])
6303 [files_ addObjectsFromArray:files];
6305 if ([files_ count] != 0) {
6306 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
6307 [files_ removeObjectAtIndex:0];
6308 [files_ sortUsingSelector:@selector(compareByPath:)];
6310 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
6311 [stack addObject:@"/"];
6313 for (int i(0), e([files_ count]); i != e; ++i) {
6314 NSString *file = [files_ objectAtIndex:i];
6315 while (![file hasPrefix:[stack lastObject]])
6316 [stack removeLastObject];
6317 NSString *directory = [stack lastObject];
6318 [stack addObject:[file stringByAppendingString:@"/"]];
6319 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
6320 int(([stack count] - 2) * 3), "",
6321 [file substringFromIndex:[directory length]]
6330 - (void) reloadData {
6333 [self setPackage:[database_ packageWithName:name_]];
6338 /* Package Controller {{{ */
6339 @interface CYPackageController : CydiaWebViewController <
6340 UIActionSheetDelegate
6342 _transient Database *database_;
6343 _H<Package> package_;
6346 std::vector<std::pair<_H<NSString>, _H<NSString>>> buttons_;
6347 _H<UIActionSheet> sheet_;
6348 _H<UIBarButtonItem> button_;
6349 _H<NSArray> versions_;
6352 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer;
6356 @implementation CYPackageController
6358 - (NSURL *) navigationURL {
6359 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
6362 - (void) _clickButtonWithPackage:(Package *)package {
6363 [self.delegate installPackage:package];
6366 - (void) _clickButtonWithName:(NSString *)name {
6367 if ([name isEqualToString:@"CLEAR"])
6368 return [self.delegate clearPackage:package_];
6369 else if ([name isEqualToString:@"REMOVE"])
6370 return [self.delegate removePackage:package_];
6371 else if ([name isEqualToString:@"DOWNGRADE"]) {
6372 sheet_ = [[[UIActionSheet alloc]
6375 cancelButtonTitle:nil
6376 destructiveButtonTitle:nil
6377 otherButtonTitles:nil
6380 for (Package *version in (id) versions_)
6381 [sheet_ addButtonWithTitle:[version latest]];
6382 [sheet_ setContext:@"version"];
6384 [self.delegate showActionSheet:sheet_ fromItem:[[self navigationItem] rightBarButtonItem]];
6388 else if ([name isEqualToString:@"INSTALL"]);
6389 else if ([name isEqualToString:@"REINSTALL"]);
6390 else if ([name isEqualToString:@"UPGRADE"]);
6391 else _assert(false);
6393 [self.delegate installPackage:package_];
6396 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
6397 NSString *context([sheet context]);
6398 if (sheet_ == sheet)
6401 if ([context isEqualToString:@"modify"]) {
6402 if (button != [sheet cancelButtonIndex]) {
6404 [self performSelector:@selector(_clickButtonWithName:) withObject:buttons_[button].first afterDelay:0];
6406 [self _clickButtonWithName:buttons_[button].first];
6409 [sheet dismissWithClickedButtonIndex:button animated:YES];
6410 } else if ([context isEqualToString:@"version"]) {
6411 if (button != [sheet cancelButtonIndex]) {
6412 Package *version([versions_ objectAtIndex:button]);
6414 [self performSelector:@selector(_clickButtonWithPackage:) withObject:version afterDelay:0];
6416 [self _clickButtonWithPackage:version];
6419 [sheet dismissWithClickedButtonIndex:button animated:YES];
6423 - (bool) _allowJavaScriptPanel {
6428 - (void) _customButtonClicked {
6429 if (commercial_ && self.isLoading && [package_ uninstalled])
6430 return [self reloadURLWithCache:NO];
6432 size_t count(buttons_.size());
6437 [self _clickButtonWithName:buttons_[0].first];
6439 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
6440 for (const auto &button : buttons_)
6441 [buttons addObject:button.second];
6443 sheet_ = [[[UIActionSheet alloc]
6446 cancelButtonTitle:nil
6447 destructiveButtonTitle:nil
6448 otherButtonTitles:nil
6451 for (NSString *button in buttons)
6452 [sheet_ addButtonWithTitle:button];
6453 [sheet_ setContext:@"modify"];
6455 [self.delegate showActionSheet:sheet_ fromItem:[[self navigationItem] rightBarButtonItem]];
6459 - (void) applyLoadingTitle {
6460 // Don't show "Loading" as the title. Ever.
6463 - (UIBarButtonItem *) rightButton {
6468 - (void) setPageColor:(UIColor *)color {
6469 return [super setPageColor:nil];
6472 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer {
6473 if ((self = [super init]) != nil) {
6474 database_ = database;
6475 name_ = name == nil ? @"" : [NSString stringWithString:name];
6476 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]] withReferrer:referrer];
6480 - (void) reloadData {
6483 [sheet_ dismissWithClickedButtonIndex:[sheet_ cancelButtonIndex] animated:YES];
6486 package_ = [database_ packageWithName:name_];
6487 versions_ = [package_ downgrades];
6491 if (package_ != nil) {
6492 [(Package *) package_ parse];
6494 commercial_ = [package_ isCommercial];
6496 if ([package_ mode] != nil)
6497 buttons_.push_back(std::make_pair(@"CLEAR", UCLocalize("CLEAR")));
6498 if ([package_ source] == nil);
6499 else if ([package_ upgradableAndEssential:NO])
6500 buttons_.push_back(std::make_pair(@"UPGRADE", UCLocalize("UPGRADE")));
6501 else if ([package_ uninstalled])
6502 buttons_.push_back(std::make_pair(@"INSTALL", UCLocalize("INSTALL")));
6504 buttons_.push_back(std::make_pair(@"REINSTALL", UCLocalize("REINSTALL")));
6505 if (![package_ uninstalled])
6506 buttons_.push_back(std::make_pair(@"REMOVE", UCLocalize("REMOVE")));
6507 if ([versions_ count] != 0)
6508 buttons_.push_back(std::make_pair(@"DOWNGRADE", UCLocalize("DOWNGRADE")));
6512 switch (buttons_.size()) {
6513 case 0: title = nil; break;
6514 case 1: title = buttons_[0].second; break;
6515 default: title = UCLocalize("MODIFY"); break;
6518 button_ = [[[UIBarButtonItem alloc]
6520 style:UIBarButtonItemStylePlain
6522 action:@selector(customButtonClicked)
6526 - (bool) isLoading {
6527 return commercial_ ? [super isLoading] : false;
6533 /* Package List Controller {{{ */
6534 @interface PackageListController : CyteViewController <
6535 UITableViewDataSource,
6538 _transient Database *database_;
6540 _H<NSArray> packages_;
6541 _H<NSArray> sections_;
6542 _H<UITableView, 2> list_;
6544 _H<NSArray> thumbs_;
6545 std::vector<NSInteger> offset_;
6547 _H<NSString> title_;
6548 unsigned reloading_;
6551 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6552 - (void) resetCursor;
6555 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages;
6559 @implementation PackageListController
6561 - (NSURL *) referrerURL {
6562 return [self navigationURL];
6565 - (bool) isSummarized {
6569 - (bool) showsSections {
6573 - (void) deselectWithAnimation:(BOOL)animated {
6574 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6577 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6578 CGRect base = [[self view] bounds];
6579 base.size.height -= bounds.size.height;
6580 base.origin = [list_ frame].origin;
6582 [UIView beginAnimations:nil context:NULL];
6583 [UIView setAnimationBeginsFromCurrentState:YES];
6584 [UIView setAnimationCurve:curve];
6585 [UIView setAnimationDuration:duration];
6586 [list_ setFrame:base];
6587 [UIView commitAnimations];
6590 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6591 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6594 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6595 [self resizeForKeyboardBounds:bounds duration:0];
6598 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6599 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6600 *curve = UIViewAnimationCurveEaseInOut;
6602 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6604 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6607 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6610 - (void) keyboardWillShow:(NSNotification *)notification {
6613 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6614 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6616 NSTimeInterval duration;
6617 UIViewAnimationCurve curve;
6618 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6620 CGRect kbframe = CGRectMake(Retina(center.x - bounds.size.width / 2), Retina(center.y - bounds.size.height / 2), bounds.size.width, bounds.size.height);
6621 UIViewController *base = self;
6622 while ([base parentOrPresentingViewController] != nil)
6623 base = [base parentOrPresentingViewController];
6624 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6625 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6627 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6628 intersection.size.height += CYStatusBarHeight();
6630 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6633 - (void) keyboardWillHide:(NSNotification *)notification {
6634 NSTimeInterval duration;
6635 UIViewAnimationCurve curve;
6636 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6638 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6641 - (void) viewWillAppear:(BOOL)animated {
6642 [super viewWillAppear:animated];
6644 [self resizeForKeyboardBounds:CGRectZero];
6645 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6646 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6649 - (void) viewWillDisappear:(BOOL)animated {
6650 [super viewWillDisappear:animated];
6652 [self resizeForKeyboardBounds:CGRectZero];
6653 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6654 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6657 - (void) viewDidAppear:(BOOL)animated {
6658 [super viewDidAppear:animated];
6659 [self deselectWithAnimation:animated];
6662 - (void) didSelectPackage:(Package *)package {
6663 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[[self referrerURL] absoluteString]] autorelease]);
6664 [view setDelegate:self.delegate];
6665 [[self navigationController] pushViewController:view animated:YES];
6668 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6669 NSInteger count([sections_ count]);
6670 return count == 0 ? 1 : count;
6673 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6674 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6676 return [[sections_ objectAtIndex:section] name];
6679 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6680 if ([sections_ count] == 0)
6682 return [[sections_ objectAtIndex:section] count];
6685 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6686 @synchronized (database_) {
6687 if ([database_ era] != era_)
6690 Section *section([sections_ objectAtIndex:[path section]]);
6691 NSInteger row([path row]);
6692 Package *package([packages_ objectAtIndex:([section row] + row)]);
6693 return [[package retain] autorelease];
6696 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6697 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6699 cell = [[[PackageCell alloc] init] autorelease];
6701 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6702 [cell setPackage:package asSummary:[self isSummarized]];
6706 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6707 Package *package([self packageAtIndexPath:path]);
6708 package = [database_ packageWithName:[package id]];
6709 [self didSelectPackage:package];
6712 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6716 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6717 return offset_[index];
6720 - (void) updateHeight {
6721 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6724 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6725 if ((self = [super init]) != nil) {
6726 database_ = database;
6727 title_ = [title copy];
6728 [[self navigationItem] setTitle:title_];
6733 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
6734 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
6735 [self setView:view];
6737 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6738 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6739 [view addSubview:list_];
6741 // XXX: is 20 the most optimal number here?
6742 [list_ setSectionIndexMinimumDisplayRowCount:20];
6744 [(UITableView *) list_ setDataSource:self];
6745 [list_ setDelegate:self];
6747 [self updateHeight];
6750 - (void) releaseSubviews {
6759 [super releaseSubviews];
6762 - (bool) shouldYield {
6766 - (bool) shouldBlock {
6770 - (NSMutableArray *) _reloadPackages {
6771 @synchronized (database_) {
6772 era_ = [database_ era];
6773 NSArray *packages([database_ packages]);
6775 return [NSMutableArray arrayWithArray:packages];
6778 - (void) _reloadData {
6779 if (reloading_ != 0) {
6784 NSMutableArray *packages;
6787 if ([self shouldYield]) {
6791 if (![self shouldBlock])
6794 hud = [self.delegate addProgressHUD];
6795 [hud setText:UCLocalize("LOADING")];
6799 packages = [self yieldToSelector:@selector(_reloadPackages)];
6802 [self.delegate removeProgressHUD:hud];
6803 } while (reloading_ == 2);
6805 packages = [self _reloadPackages];
6808 @synchronized (database_) {
6809 if (era_ != [database_ era])
6816 packages_ = packages;
6818 if ([self showsSections])
6819 sections_ = [self sectionsForPackages:packages];
6821 Section *section([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6822 [section setCount:[packages_ count]];
6823 sections_ = [NSArray arrayWithObject:section];
6826 [self updateHeight];
6828 _profile(PackageTable$reloadData$List)
6829 [(UITableView *) list_ setDataSource:self];
6837 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
6838 Section *prefix([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6839 size_t end([packages count]);
6841 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
6842 Section *section(prefix);
6844 thumbs_ = CollationThumbs_;
6845 offset_ = CollationOffset_;
6848 size_t offsets([CollationStarts_ count]);
6850 NSString *start([CollationStarts_ objectAtIndex:offset]);
6851 size_t length([start length]);
6853 for (size_t index(0); index != end; ++index) {
6855 Package *package([packages objectAtIndex:index]);
6856 NSString *name(PackageName(package, @selector(cyname)));
6858 //while ([start compare:name options:NSNumericSearch range:NSMakeRange(0, length) locale:CollationLocale_] != NSOrderedDescending) {
6859 while (StringNameCompare(start, name, length) != kCFCompareGreaterThan) {
6860 NSString *title([CollationTitles_ objectAtIndex:offset]);
6861 section = [[[Section alloc] initWithName:title row:index localize:NO] autorelease];
6862 [sections addObject:section];
6864 start = ++offset == offsets ? nil : [CollationStarts_ objectAtIndex:offset];
6867 length = [start length];
6871 [section addToCount];
6874 for (; offset != offsets; ++offset) {
6875 NSString *title([CollationTitles_ objectAtIndex:offset]);
6876 Section *section([[[Section alloc] initWithName:title row:end localize:NO] autorelease]);
6877 [sections addObject:section];
6880 if ([prefix count] != 0) {
6881 Section *suffix([sections lastObject]);
6882 [prefix setName:[suffix name]];
6883 [suffix setName:nil];
6884 [sections insertObject:prefix atIndex:(offsets - 1)];
6890 - (void) reloadData {
6893 if ([self shouldYield])
6894 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6899 - (void) resetCursor {
6900 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6903 - (void) clearData {
6904 [self updateHeight];
6906 [list_ setDataSource:nil];
6914 /* Filtered Package List Controller {{{ */
6915 typedef Function<bool, Package *> PackageFilter;
6916 typedef Function<void, NSMutableArray *> PackageSorter;
6917 @interface FilteredPackageListController : PackageListController {
6918 PackageFilter filter_;
6919 PackageSorter sorter_;
6922 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter;
6924 - (void) setFilter:(PackageFilter)filter;
6925 - (void) setSorter:(PackageSorter)sorter;
6929 @implementation FilteredPackageListController
6931 - (void) setFilter:(PackageFilter)filter {
6932 @synchronized (self) {
6936 - (void) setSorter:(PackageSorter)sorter {
6937 @synchronized (self) {
6941 - (NSMutableArray *) _reloadPackages {
6942 @synchronized (database_) {
6943 era_ = [database_ era];
6945 NSArray *packages([database_ packages]);
6946 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6948 PackageFilter filter;
6949 PackageSorter sorter;
6951 @synchronized (self) {
6956 _profile(PackageTable$reloadData$Filter)
6957 for (Package *package in packages)
6958 if (filter(package))
6959 [filtered addObject:package];
6967 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter {
6968 if ((self = [super initWithDatabase:database title:title]) != nil) {
6969 [self setFilter:filter];
6976 /* Home Controller {{{ */
6977 @interface HomeController : CydiaWebViewController {
6978 CFRunLoopRef runloop_;
6979 SCNetworkReachabilityRef reachability_;
6984 @implementation HomeController
6986 static void HomeControllerReachabilityCallback(SCNetworkReachabilityRef reachability, SCNetworkReachabilityFlags flags, void *info) {
6987 [(HomeController *) info dispatchEvent:@"CydiaReachabilityCallback"];
6991 if ((self = [super init]) != nil) {
6992 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6995 reachability_ = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "cydia.saurik.com");
6996 if (reachability_ != NULL) {
6997 SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
6998 SCNetworkReachabilitySetCallback(reachability_, HomeControllerReachabilityCallback, &context);
7000 CFRunLoopRef runloop(CFRunLoopGetCurrent());
7001 if (SCNetworkReachabilityScheduleWithRunLoop(reachability_, runloop, kCFRunLoopDefaultMode))
7008 if (reachability_ != NULL && runloop_ != NULL)
7009 SCNetworkReachabilityUnscheduleFromRunLoop(reachability_, runloop_, kCFRunLoopDefaultMode);
7013 - (NSURL *) navigationURL {
7014 return [NSURL URLWithString:@"cydia://home"];
7017 - (void) aboutButtonClicked {
7018 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
7020 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
7021 [alert addButtonWithTitle:UCLocalize("CLOSE")];
7022 [alert setCancelButtonIndex:0];
7025 @"Copyright \u00a9 2008-2015\n"
7028 "Jay Freeman (saurik)\n"
7029 "saurik@saurik.com\n"
7030 "http://www.saurik.com/"
7036 - (UIBarButtonItem *) leftButton {
7037 return [[[UIBarButtonItem alloc]
7038 initWithTitle:UCLocalize("ABOUT")
7039 style:UIBarButtonItemStylePlain
7041 action:@selector(aboutButtonClicked)
7048 /* Cydia Tab Bar Controller {{{ */
7049 @interface CydiaTabBarController : CyteTabBarController <
7050 UITabBarControllerDelegate,
7053 _transient Database *database_;
7055 _H<UIActivityIndicatorView> indicator_;
7058 // XXX: ok, "updatedelegate_"?...
7059 _transient NSObject<CydiaDelegate> *updatedelegate_;
7062 - (void) beginUpdate;
7067 @implementation CydiaTabBarController
7069 - (id) initWithDatabase:(Database *)database {
7070 if ((self = [super init]) != nil) {
7071 database_ = database;
7072 [self setDelegate:self];
7074 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteTiny] autorelease];
7075 [indicator_ setOrigin:CGPointMake(kCFCoreFoundationVersionNumber >= 800 ? 2 : 4, 2)];
7077 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7081 - (void) beginUpdate {
7085 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
7086 UITabBarItem *item([controller tabBarItem]);
7088 [item setBadgeValue:@""];
7089 UIView *badge(MSHookIvar<UIView *>([item view], "_badge"));
7091 [indicator_ startAnimating];
7092 [badge addSubview:indicator_];
7094 [updatedelegate_ retainNetworkActivityIndicator];
7098 detachNewThreadSelector:@selector(performUpdate)
7104 - (void) performUpdate {
7105 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
7107 SourceStatus status(self, database_);
7108 [database_ updateWithStatus:status];
7111 performSelectorOnMainThread:@selector(completeUpdate)
7119 - (void) stopUpdateWithSelector:(SEL)selector {
7121 [updatedelegate_ releaseNetworkActivityIndicator];
7123 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
7124 [[controller tabBarItem] setBadgeValue:nil];
7126 [indicator_ removeFromSuperview];
7127 [indicator_ stopAnimating];
7129 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
7132 - (void) completeUpdate {
7135 [self stopUpdateWithSelector:@selector(reloadData)];
7138 - (void) cancelUpdate {
7139 [self stopUpdateWithSelector:@selector(updateDataAndLoad)];
7142 - (void) cancelPressed {
7143 [self cancelUpdate];
7150 - (bool) isSourceCancelled {
7154 - (void) startSourceFetch:(NSString *)uri {
7157 - (void) stopSourceFetch:(NSString *)uri {
7160 - (void) setUpdateDelegate:(id)delegate {
7161 updatedelegate_ = delegate;
7167 /* Cydia:// Protocol {{{ */
7168 @interface CydiaURLProtocol : NSURLProtocol {
7173 @implementation CydiaURLProtocol
7175 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7176 NSURL *url([request URL]);
7180 NSString *scheme([[url scheme] lowercaseString]);
7181 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7183 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7189 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7193 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7194 id<NSURLProtocolClient> client([self client]);
7196 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7198 NSData *data(UIImagePNGRepresentation(icon));
7200 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7201 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7202 [client URLProtocol:self didLoadData:data];
7203 [client URLProtocolDidFinishLoading:self];
7207 - (void) startLoading {
7208 id<NSURLProtocolClient> client([self client]);
7209 NSURLRequest *request([self request]);
7211 NSURL *url([request URL]);
7212 NSString *href([url absoluteString]);
7213 NSString *scheme([[url scheme] lowercaseString]);
7217 if ([scheme isEqualToString:@"cydia"])
7218 path = [href substringFromIndex:8];
7219 else if ([scheme isEqualToString:@"about"])
7220 path = [href substringFromIndex:12];
7221 else _assert(false);
7223 NSRange slash([path rangeOfString:@"/"]);
7226 if (slash.location == NSNotFound) {
7230 command = [path substringToIndex:slash.location];
7231 path = [path substringFromIndex:(slash.location + 1)];
7234 Database *database([Database sharedInstance]);
7237 else if ([command isEqualToString:@"application-icon"]) {
7240 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7244 if (icon == nil && $SBSCopyIconImagePNGDataForDisplayIdentifier != NULL) {
7245 NSData *data([$SBSCopyIconImagePNGDataForDisplayIdentifier(path) autorelease]);
7246 icon = [UIImage imageWithData:data];
7250 if (NSString *file = SBSCopyIconImagePathForDisplayIdentifier(path))
7251 icon = [UIImage imageAtPath:file];
7254 icon = [UIImage imageNamed:@"unknown.png"];
7256 [self _returnPNGWithImage:icon forRequest:request];
7257 } else if ([command isEqualToString:@"package-icon"]) {
7260 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7261 Package *package([database packageWithName:path]);
7265 UIImage *icon([package icon]);
7266 [self _returnPNGWithImage:icon forRequest:request];
7267 } else if ([command isEqualToString:@"uikit-image"]) {
7270 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7271 UIImage *icon(_UIImageWithName(path));
7272 [self _returnPNGWithImage:icon forRequest:request];
7273 } else if ([command isEqualToString:@"section-icon"]) {
7276 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7277 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7279 icon = [UIImage imageNamed:@"unknown.png"];
7280 [self _returnPNGWithImage:icon forRequest:request];
7282 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7286 - (void) stopLoading {
7292 /* Section Controller {{{ */
7293 @interface SectionController : FilteredPackageListController {
7295 _H<NSString> section_;
7298 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section;
7302 @implementation SectionController
7304 - (NSURL *) referrerURL {
7305 NSString *name(section_);
7306 name = name ?: @"*";
7307 NSString *key(key_);
7309 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sections/%@/%@", UI_, [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7312 - (NSURL *) navigationURL {
7313 NSString *name(section_);
7314 name = name ?: @"*";
7315 NSString *key(key_);
7317 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@/%@", [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7320 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section {
7323 title = UCLocalize("ALL_PACKAGES");
7324 else if (![section isEqual:@""])
7325 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(section) value:nil table:@"Sections"];
7327 title = UCLocalize("NO_SECTION");
7329 if ((self = [super initWithDatabase:database title:title]) != nil) {
7330 key_ = [source key];
7335 - (void) reloadData {
7336 Source *source([database_ sourceWithKey:key_]);
7337 _H<NSString> name(section_);
7339 [self setFilter:[=](Package *package) {
7340 NSString *section([package section]);
7344 section == nil && [name length] == 0 ||
7345 [name isEqualToString:section]
7348 [package source] == source
7349 ) && [package visible];
7357 /* Sections Controller {{{ */
7358 @interface SectionsController : CyteViewController <
7359 UITableViewDataSource,
7362 _transient Database *database_;
7364 _H<NSMutableArray> sections_;
7365 _H<NSMutableArray> filtered_;
7366 _H<UITableView, 2> list_;
7369 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7370 - (void) editButtonClicked;
7374 @implementation SectionsController
7376 - (NSURL *) navigationURL {
7377 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
7380 - (Source *) source {
7383 return [database_ sourceWithKey:key_];
7386 - (void) updateNavigationItem {
7387 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7388 if ([sections_ count] == 0) {
7389 [[self navigationItem] setRightBarButtonItem:nil];
7391 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7392 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7394 action:@selector(editButtonClicked)
7395 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7399 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7400 [super setEditing:editing animated:animated];
7405 [self.delegate updateData];
7407 [self updateNavigationItem];
7410 - (void) viewDidAppear:(BOOL)animated {
7411 [super viewDidAppear:animated];
7412 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7415 - (void) viewWillDisappear:(BOOL)animated {
7416 [super viewWillDisappear:animated];
7417 [self setEditing:NO];
7420 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7421 Section *section = nil;
7422 int index = [indexPath row];
7423 if (![self isEditing]) {
7426 section = [filtered_ objectAtIndex:index];
7428 section = [sections_ objectAtIndex:index];
7433 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7434 if ([self isEditing])
7435 return [sections_ count];
7437 return [filtered_ count] + 1;
7440 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7444 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7445 static NSString *reuseIdentifier = @"SectionCell";
7447 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7449 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7451 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7456 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7457 if ([self isEditing])
7460 Section *section = [self sectionAtIndexPath:indexPath];
7462 SectionController *controller = [[[SectionController alloc]
7463 initWithDatabase:database_
7464 source:[self source]
7465 section:[section name]
7467 [controller setDelegate:self.delegate];
7469 [[self navigationController] pushViewController:controller animated:YES];
7473 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
7474 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7475 [list_ setRowHeight:46];
7476 [(UITableView *) list_ setDataSource:self];
7477 [list_ setDelegate:self];
7478 [self setView:list_];
7481 - (void) viewDidLoad {
7482 [super viewDidLoad];
7484 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7487 - (void) releaseSubviews {
7493 [super releaseSubviews];
7496 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7497 if ((self = [super init]) != nil) {
7498 database_ = database;
7499 key_ = [source key];
7503 - (void) reloadData {
7506 NSArray *packages = [database_ packages];
7508 sections_ = [NSMutableArray arrayWithCapacity:16];
7509 filtered_ = [NSMutableArray arrayWithCapacity:16];
7511 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7513 Source *source([self source]);
7516 for (Package *package in packages) {
7517 if (source != nil && [package source] != source)
7520 NSString *name([package section]);
7521 NSString *key(name == nil ? @"" : name);
7525 _profile(SectionsView$reloadData$Section)
7526 section = [sections objectForKey:key];
7527 if (section == nil) {
7528 _profile(SectionsView$reloadData$Section$Allocate)
7529 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7530 [sections setObject:section forKey:key];
7535 [section addToCount];
7537 _profile(SectionsView$reloadData$Filter)
7538 if (![package visible])
7546 [sections_ addObjectsFromArray:[sections allValues]];
7548 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7550 for (Section *section in (id) sections_) {
7551 size_t count([section row]);
7555 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7556 [section setCount:count];
7557 [filtered_ addObject:section];
7560 [self updateNavigationItem];
7565 - (void) editButtonClicked {
7566 [self setEditing:![self isEditing] animated:YES];
7572 /* Changes Controller {{{ */
7573 @interface ChangesController : FilteredPackageListController {
7577 - (id) initWithDatabase:(Database *)database;
7581 @implementation ChangesController
7583 - (NSURL *) referrerURL {
7584 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/changes/", UI_]];
7587 - (NSURL *) navigationURL {
7588 return [NSURL URLWithString:@"cydia://changes"];
7591 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7592 @synchronized (database_) {
7593 if ([database_ era] != era_)
7596 NSUInteger sectionIndex([path section]);
7597 if (sectionIndex >= [sections_ count])
7599 Section *section([sections_ objectAtIndex:sectionIndex]);
7600 NSInteger row([path row]);
7601 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7604 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7605 NSString *context([alert context]);
7607 if ([context isEqualToString:@"norefresh"])
7608 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7611 - (void) setLeftBarButtonItem {
7612 if ([self.delegate updating])
7613 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7614 initWithTitle:UCLocalize("CANCEL")
7615 style:UIBarButtonItemStyleDone
7617 action:@selector(cancelButtonClicked)
7618 ] autorelease] animated:YES];
7620 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7621 initWithTitle:UCLocalize("REFRESH")
7622 style:UIBarButtonItemStylePlain
7624 action:@selector(refreshButtonClicked)
7625 ] autorelease] animated:YES];
7628 - (void) refreshButtonClicked {
7629 if ([self.delegate requestUpdate])
7630 [self setLeftBarButtonItem];
7633 - (void) cancelButtonClicked {
7634 [self.delegate cancelUpdate];
7637 - (void) upgradeButtonClicked {
7638 [self.delegate distUpgrade];
7639 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7642 - (bool) shouldYield {
7646 - (bool) shouldBlock {
7650 - (void) useFilter {
7651 @synchronized (self) {
7652 [self setFilter:[](Package *package) {
7653 return [package upgradableAndEssential:YES] || [package visible];
7656 [self setSorter:[](NSMutableArray *packages) {
7657 [packages radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7661 - (id) initWithDatabase:(Database *)database {
7662 if ((self = [super initWithDatabase:database title:UCLocalize("CHANGES")]) != nil) {
7667 - (void) viewDidLoad {
7668 [super viewDidLoad];
7669 [self setLeftBarButtonItem];
7672 - (void) viewWillAppear:(BOOL)animated {
7673 [super viewWillAppear:animated];
7674 [self setLeftBarButtonItem];
7677 - (void) reloadData {
7678 [self setLeftBarButtonItem];
7682 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
7683 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
7685 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7686 Section *ignored = nil;
7687 Section *section = nil;
7691 bool unseens = false;
7693 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7695 for (size_t offset = 0, count = [packages count]; offset != count; ++offset) {
7696 Package *package = [packages objectAtIndex:offset];
7698 BOOL uae = [package upgradableAndEssential:YES];
7702 time_t seen([package seen]);
7704 if (section == nil || last != seen) {
7708 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7711 _profile(ChangesController$reloadData$Allocate)
7712 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7713 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7714 [sections addObject:section];
7718 [section addToCount];
7719 } else if ([package ignored]) {
7720 if (ignored == nil) {
7721 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7723 [ignored addToCount];
7726 [upgradable addToCount];
7731 CFRelease(formatter);
7734 Section *last = [sections lastObject];
7735 size_t count = [last count];
7736 [packages removeObjectsInRange:NSMakeRange([packages count] - count, count)];
7737 [sections removeLastObject];
7740 if ([ignored count] != 0)
7741 [sections insertObject:ignored atIndex:0];
7743 [sections insertObject:upgradable atIndex:0];
7747 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7748 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7749 style:UIBarButtonItemStylePlain
7751 action:@selector(upgradeButtonClicked)
7752 ] autorelease]) animated:YES];
7759 /* Search Controller {{{ */
7760 @interface SearchController : FilteredPackageListController <
7763 _H<UISearchBar, 1> search_;
7768 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7769 - (void) reloadData;
7773 @implementation SearchController
7775 - (NSURL *) referrerURL {
7776 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/search?q=%@", UI_, [([search_ text] ?: @"") stringByAddingPercentEscapesIncludingReserved]]];
7779 - (NSURL *) navigationURL {
7780 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7781 return [NSURL URLWithString:@"cydia://search"];
7783 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [[search_ text] stringByAddingPercentEscapesIncludingReserved]]];
7786 - (NSArray *) termsForQuery:(NSString *)query {
7787 NSMutableArray *terms([NSMutableArray arrayWithCapacity:2]);
7788 for (NSString *component in [query componentsSeparatedByString:@" "])
7789 if ([component length] != 0)
7790 [terms addObject:component];
7795 - (void) useSearch {
7796 _H<NSArray> query([self termsForQuery:[search_ text]]);
7799 @synchronized (self) {
7800 [self setFilter:[=](Package *package) {
7801 if (![package unfiltered])
7803 if (![package matches:query])
7808 [self setSorter:[](NSMutableArray *packages) {
7809 [packages radixSortUsingSelector:@selector(rank)];
7817 - (void) usePrefix:(NSString *)prefix {
7818 _H<NSString> query(prefix);
7821 @synchronized (self) {
7822 [self setFilter:[=](Package *package) {
7823 if ([query length] == 0)
7825 if (![package unfiltered])
7827 if ([[package name] compare:query options:MatchCompareOptions_ range:NSMakeRange(0, [query length])] != NSOrderedSame)
7832 [self setSorter:nullptr];
7838 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7840 [self usePrefix:[search_ text]];
7843 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7844 [search_ resignFirstResponder];
7848 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7849 [search_ setText:@""];
7850 [self searchBarButtonClicked:searchBar];
7853 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7854 [self searchBarButtonClicked:searchBar];
7857 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7858 [self usePrefix:text];
7861 - (bool) shouldYield {
7865 - (bool) shouldBlock {
7869 - (bool) isSummarized {
7873 - (bool) showsSections {
7877 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7878 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH")])) {
7879 search_ = [[[UISearchBar alloc] init] autorelease];
7880 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7881 [search_ setDelegate:self];
7883 UITextField *textField;
7884 if ([search_ respondsToSelector:@selector(searchField)])
7885 textField = [search_ searchField];
7887 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7889 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7890 [textField setEnablesReturnKeyAutomatically:NO];
7891 [[self navigationItem] setTitleView:textField];
7894 [search_ setText:query];
7899 - (void) viewDidAppear:(BOOL)animated {
7900 [super viewDidAppear:animated];
7902 if (!searchloaded_) {
7903 searchloaded_ = YES;
7904 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7905 [search_ layoutSubviews];
7908 if ([self isSummarized])
7909 [search_ becomeFirstResponder];
7912 - (void) reloadData {
7917 - (void) didSelectPackage:(Package *)package {
7918 [search_ resignFirstResponder];
7919 [super didSelectPackage:package];
7924 /* Package Settings Controller {{{ */
7925 @interface PackageSettingsController : CyteViewController <
7926 UITableViewDataSource,
7929 _transient Database *database_;
7931 _H<Package> package_;
7932 _H<UITableView, 2> table_;
7933 _H<UISwitch> subscribedSwitch_;
7934 _H<UISwitch> ignoredSwitch_;
7935 _H<UITableViewCell> subscribedCell_;
7936 _H<UITableViewCell> ignoredCell_;
7939 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7943 @implementation PackageSettingsController
7945 - (NSURL *) navigationURL {
7946 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
7949 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7950 if (package_ == nil)
7953 if ([package_ installed] == nil)
7959 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7960 if (package_ == nil)
7963 // both sections contain just one item right now.
7967 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7971 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7973 return UCLocalize("SHOW_ALL_CHANGES_EX");
7975 return UCLocalize("IGNORE_UPGRADES_EX");
7978 - (void) onSubscribed:(id)control {
7979 bool value([control isOn]);
7980 if (package_ == nil)
7982 if ([package_ setSubscribed:value])
7983 [self.delegate updateData];
7986 - (void) _updateIgnored {
7987 const char *package([name_ UTF8String]);
7988 bool on([ignoredSwitch_ isOn]);
7990 FILE *dpkg(popen("/usr/libexec/cydia/cydo --set-selections", "w"));
7991 fwrite(package, strlen(package), 1, dpkg);
7994 fwrite(" hold\n", 6, 1, dpkg);
7996 fwrite(" install\n", 9, 1, dpkg);
8001 - (void) onIgnored:(id)control {
8002 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
8003 [invocation setTarget:self];
8004 [invocation setSelector:@selector(_updateIgnored)];
8006 [self.delegate reloadDataWithInvocation:invocation];
8009 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8010 if (package_ == nil)
8013 switch ([indexPath section]) {
8014 case 0: return subscribedCell_;
8015 case 1: return ignoredCell_;
8024 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8025 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8026 [self setView:view];
8028 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
8029 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8030 [(UITableView *) table_ setDataSource:self];
8031 [table_ setDelegate:self];
8032 [view addSubview:table_];
8034 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
8035 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
8036 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
8038 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
8039 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
8040 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
8042 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
8043 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
8044 [subscribedCell_ setAccessoryView:subscribedSwitch_];
8045 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
8047 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
8048 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
8049 [ignoredCell_ setAccessoryView:ignoredSwitch_];
8050 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
8053 - (void) viewDidLoad {
8054 [super viewDidLoad];
8056 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
8059 - (void) releaseSubviews {
8061 subscribedCell_ = nil;
8063 ignoredSwitch_ = nil;
8064 subscribedSwitch_ = nil;
8066 [super releaseSubviews];
8069 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
8070 if ((self = [super init]) != nil) {
8071 database_ = database;
8076 - (void) reloadData {
8079 package_ = [database_ packageWithName:name_];
8081 if (package_ != nil) {
8082 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
8083 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
8084 } // XXX: what now, G?
8086 [table_ reloadData];
8092 /* Installed Controller {{{ */
8093 @interface InstalledController : FilteredPackageListController {
8097 - (id) initWithDatabase:(Database *)database;
8098 - (void) queueStatusDidChange;
8102 @implementation InstalledController
8104 - (NSURL *) referrerURL {
8105 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/installed/", UI_]];
8108 - (NSURL *) navigationURL {
8109 return [NSURL URLWithString:@"cydia://installed"];
8112 - (void) useRecent {
8115 @synchronized (self) {
8116 [self setFilter:[](Package *package) {
8117 return ![package uninstalled] && package->role_ < 7;
8120 [self setSorter:[](NSMutableArray *packages) {
8121 [packages radixSortUsingSelector:@selector(recent)];
8125 - (void) useFilter:(UISegmentedControl *)segmented {
8126 NSInteger selected([segmented selectedSegmentIndex]);
8128 return [self useRecent];
8129 bool simple(selected == 0);
8132 @synchronized (self) {
8133 [self setFilter:[=](Package *package) {
8134 return ![package uninstalled] && package->role_ <= (simple ? 1 : 3);
8137 [self setSorter:nullptr];
8140 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
8142 return [super sectionsForPackages:packages];
8144 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterLongStyle, kCFDateFormatterNoStyle));
8146 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
8147 Section *section(nil);
8150 for (size_t offset(0), count([packages count]); offset != count; ++offset) {
8151 Package *package([packages objectAtIndex:offset]);
8153 time_t upgraded([package upgraded]);
8154 if (upgraded < 1168364520)
8157 upgraded -= upgraded % (60 * 60 * 24);
8159 if (section == nil || upgraded != last) {
8164 continue; // XXX: name = UCLocalize("...");
8166 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:upgraded]);
8170 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
8171 [sections addObject:section];
8174 [section addToCount];
8177 CFRelease(formatter);
8181 - (id) initWithDatabase:(Database *)database {
8182 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED")]) != nil) {
8183 UISegmentedControl *segmented([[[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:UCLocalize("USER"), UCLocalize("EXPERT"), UCLocalize("RECENT"), nil]] autorelease]);
8184 [segmented setSelectedSegmentIndex:0];
8185 [segmented setSegmentedControlStyle:UISegmentedControlStyleBar];
8186 [[self navigationItem] setTitleView:segmented];
8188 [segmented addTarget:self action:@selector(modeChanged:) forEvents:UIControlEventValueChanged];
8189 [self useFilter:segmented];
8191 [self queueStatusDidChange];
8196 - (void) queueButtonClicked {
8197 [self.delegate queue];
8201 - (void) queueStatusDidChange {
8204 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8205 initWithTitle:UCLocalize("QUEUE")
8206 style:UIBarButtonItemStyleDone
8208 action:@selector(queueButtonClicked)
8211 [[self navigationItem] setRightBarButtonItem:nil];
8216 - (void) modeChanged:(UISegmentedControl *)segmented {
8217 [self useFilter:segmented];
8224 /* Source Cell {{{ */
8225 @interface SourceCell : CyteTableViewCell <
8226 CyteTableViewCellDelegate,
8229 _H<Source, 1> source_;
8232 _H<NSString> origin_;
8233 _H<NSString> label_;
8234 _H<UIActivityIndicatorView> indicator_;
8237 - (void) setSource:(Source *)source;
8238 - (void) setFetch:(NSNumber *)fetch;
8242 @implementation SourceCell
8244 - (void) _setImage:(NSArray *)data {
8245 if ([url_ isEqual:[data objectAtIndex:0]]) {
8246 icon_ = [data objectAtIndex:1];
8247 [self.content setNeedsDisplay];
8251 - (void) _setSource:(NSURL *) url {
8252 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8254 if (NSData *data = [NSURLConnection
8255 sendSynchronousRequest:[NSURLRequest
8257 cachePolicy:NSURLRequestUseProtocolCachePolicy
8261 returningResponse:NULL
8264 if (UIImage *image = [UIImage imageWithData:data])
8265 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
8270 - (void) setSource:(Source *)source {
8272 [source_ setDelegate:self];
8274 [self setFetch:[NSNumber numberWithBool:[source_ fetch]]];
8276 icon_ = [UIImage imageNamed:@"unknown.png"];
8278 origin_ = [source name];
8279 label_ = [source rooturi];
8281 [self.content setNeedsDisplay];
8283 url_ = [source iconURL];
8284 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
8287 - (void) setAllSource {
8289 [indicator_ stopAnimating];
8291 icon_ = [UIImage imageNamed:@"folder.png"];
8292 origin_ = UCLocalize("ALL_SOURCES");
8293 label_ = UCLocalize("ALL_SOURCES_EX");
8294 [self.content setNeedsDisplay];
8297 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8298 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8299 UIView *content([self contentView]);
8300 CGRect bounds([content bounds]);
8302 self.content = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8303 [self.content setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8304 [self.content setBackgroundColor:[UIColor whiteColor]];
8305 [content addSubview:self.content];
8307 [self.content setDelegate:self];
8308 [self.content setOpaque:YES];
8310 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGraySmall] autorelease];
8311 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin];// | UIViewAutoresizingFlexibleBottomMargin];
8312 [content addSubview:indicator_];
8314 [[self.content layer] setContentsGravity:kCAGravityTopLeft];
8318 - (void) layoutSubviews {
8319 [super layoutSubviews];
8321 UIView *content([self contentView]);
8322 CGRect bounds([content bounds]);
8324 CGRect frame([indicator_ frame]);
8325 frame.origin.x = bounds.size.width - frame.size.width;
8326 frame.origin.y = Retina((bounds.size.height - frame.size.height) / 2);
8328 if (kCFCoreFoundationVersionNumber < 800)
8329 frame.origin.x -= 8;
8330 [indicator_ setFrame:frame];
8333 - (NSString *) accessibilityLabel {
8337 - (void) drawContentRect:(CGRect)rect {
8338 bool highlighted(self.highlighted);
8339 float width(rect.size.width);
8343 rect.size = [(UIImage *) icon_ size];
8345 while (rect.size.width > 32 || rect.size.height > 32) {
8346 rect.size.width /= 2;
8347 rect.size.height /= 2;
8350 rect.origin.x = 26 - rect.size.width / 2;
8351 rect.origin.y = 26 - rect.size.height / 2;
8353 [icon_ drawInRect:Retina(rect)];
8356 if (highlighted && kCFCoreFoundationVersionNumber < 800)
8361 [origin_ drawAtPoint:CGPointMake(52, 8) forWidth:(width - 49) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
8365 [label_ drawAtPoint:CGPointMake(52, 29) forWidth:(width - 49) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
8368 - (void) setFetch:(NSNumber *)fetch {
8369 if ([fetch boolValue])
8370 [indicator_ startAnimating];
8372 [indicator_ stopAnimating];
8377 /* Sources Controller {{{ */
8378 @interface SourcesController : CyteViewController <
8379 UITableViewDataSource,
8382 _transient Database *database_;
8385 _H<UITableView, 2> list_;
8386 _H<NSMutableArray> sources_;
8390 _H<UIProgressHUD> hud_;
8393 NSURLConnection *trivial_bz2_;
8394 NSURLConnection *trivial_gz_;
8399 - (id) initWithDatabase:(Database *)database;
8400 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated;
8404 @implementation SourcesController
8406 - (void) _releaseConnection:(NSURLConnection *)connection {
8407 if (connection != nil) {
8408 [connection cancel];
8409 //[connection setDelegate:nil];
8410 [connection release];
8415 [self _releaseConnection:trivial_gz_];
8416 [self _releaseConnection:trivial_bz2_];
8421 - (NSURL *) navigationURL {
8422 return [NSURL URLWithString:@"cydia://sources"];
8425 - (void) viewDidAppear:(BOOL)animated {
8426 [super viewDidAppear:animated];
8427 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8430 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8434 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8436 return UCLocalize("INDIVIDUAL_SOURCES");
8440 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8443 case 1: return [sources_ count];
8448 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8449 @synchronized (database_) {
8450 if ([database_ era] != era_)
8452 if ([indexPath section] != 1)
8454 NSUInteger index([indexPath row]);
8455 if (index >= [sources_ count])
8457 return [sources_ objectAtIndex:index];
8460 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8461 static NSString *cellIdentifier = @"SourceCell";
8463 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8464 if (cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8465 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8467 Source *source([self sourceAtIndexPath:indexPath]);
8469 [cell setAllSource];
8471 [cell setSource:source];
8476 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8477 SectionsController *controller([[[SectionsController alloc]
8478 initWithDatabase:database_
8479 source:[self sourceAtIndexPath:indexPath]
8482 [controller setDelegate:self.delegate];
8483 [[self navigationController] pushViewController:controller animated:YES];
8486 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8487 if ([indexPath section] != 1)
8489 Source *source = [self sourceAtIndexPath:indexPath];
8490 return [source record] != nil;
8493 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8494 _assert([indexPath section] == 1);
8495 if (editingStyle == UITableViewCellEditingStyleDelete) {
8496 Source *source = [self sourceAtIndexPath:indexPath];
8497 if (source == nil) return;
8499 [Sources_ removeObjectForKey:[source key]];
8501 [self.delegate syncData];
8505 - (void) tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath {
8506 [self updateButtonsForEditingStatusAnimated:YES];
8510 [self.delegate addTrivialSource:href_];
8513 [self.delegate syncData];
8516 - (NSString *) getWarning {
8517 NSString *href(href_);
8518 NSRange colon([href rangeOfString:@"://"]);
8519 if (colon.location != NSNotFound)
8520 href = [href substringFromIndex:(colon.location + 3)];
8521 href = [href stringByAddingPercentEscapes];
8522 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8524 NSURL *url([NSURL URLWithString:href]);
8526 NSStringEncoding encoding;
8527 NSError *error(nil);
8529 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8530 return [warning length] == 0 ? nil : warning;
8534 - (void) _endConnection:(NSURLConnection *)connection {
8535 // XXX: the memory management in this method is horribly awkward
8537 NSURLConnection **field = NULL;
8538 if (connection == trivial_bz2_)
8539 field = &trivial_bz2_;
8540 else if (connection == trivial_gz_)
8541 field = &trivial_gz_;
8542 _assert(field != NULL);
8543 [connection release];
8547 trivial_bz2_ == nil &&
8550 NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil);
8552 [self.delegate releaseNetworkActivityIndicator];
8554 [self.delegate removeProgressHUD:hud_];
8558 if (warning != nil) {
8559 UIAlertView *alert = [[[UIAlertView alloc]
8560 initWithTitle:UCLocalize("SOURCE_WARNING")
8563 cancelButtonTitle:UCLocalize("CANCEL")
8565 UCLocalize("ADD_ANYWAY"),
8569 [alert setContext:@"warning"];
8570 [alert setNumberOfRows:1];
8573 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
8579 } else if (error_ != nil) {
8580 UIAlertView *alert = [[[UIAlertView alloc]
8581 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8582 message:[error_ localizedDescription]
8584 cancelButtonTitle:UCLocalize("OK")
8585 otherButtonTitles:nil
8588 [alert setContext:@"urlerror"];
8593 UIAlertView *alert = [[[UIAlertView alloc]
8594 initWithTitle:UCLocalize("NOT_REPOSITORY")
8595 message:UCLocalize("NOT_REPOSITORY_EX")
8597 cancelButtonTitle:UCLocalize("OK")
8598 otherButtonTitles:nil
8601 [alert setContext:@"trivial"];
8611 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8612 switch ([response statusCode]) {
8618 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8619 lprintf("connection:\"%s\" didFailWithError:\"%s\"\n", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8621 [self _endConnection:connection];
8624 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8625 [self _endConnection:connection];
8628 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8629 NSURL *url([NSURL URLWithString:href]);
8631 NSMutableURLRequest *request = [NSMutableURLRequest
8633 cachePolicy:NSURLRequestUseProtocolCachePolicy
8637 [request setHTTPMethod:method];
8639 if (Machine_ != NULL)
8640 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8642 if (UniqueID_ != nil)
8643 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8645 if ([url isCydiaSecure]) {
8646 if (UniqueID_ != nil)
8647 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
8650 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8653 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8654 NSString *context([alert context]);
8656 if ([context isEqualToString:@"source"]) {
8659 NSString *href = [[alert textField] text];
8660 href = VerifySource(href);
8665 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8666 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8670 // XXX: this is stupid
8671 hud_ = [self.delegate addProgressHUD];
8672 [hud_ setText:UCLocalize("VERIFYING_URL")];
8673 [self.delegate retainNetworkActivityIndicator];
8682 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8683 } else if ([context isEqualToString:@"trivial"])
8684 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8685 else if ([context isEqualToString:@"urlerror"])
8686 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8687 else if ([context isEqualToString:@"warning"]) {
8690 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
8699 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8703 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated {
8704 BOOL editing([list_ isEditing]);
8707 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8708 initWithTitle:UCLocalize("ADD")
8709 style:UIBarButtonItemStylePlain
8711 action:@selector(addButtonClicked)
8712 ] autorelease] animated:animated];
8713 else if ([self.delegate updating])
8714 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8715 initWithTitle:UCLocalize("CANCEL")
8716 style:UIBarButtonItemStyleDone
8718 action:@selector(cancelButtonClicked)
8719 ] autorelease] animated:animated];
8721 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8722 initWithTitle:UCLocalize("REFRESH")
8723 style:UIBarButtonItemStylePlain
8725 action:@selector(refreshButtonClicked)
8726 ] autorelease] animated:animated];
8728 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8729 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8730 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8732 action:@selector(editButtonClicked)
8733 ] autorelease] animated:animated];
8737 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease];
8738 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8739 [list_ setRowHeight:53];
8740 [(UITableView *) list_ setDataSource:self];
8741 [list_ setDelegate:self];
8742 [self setView:list_];
8745 - (void) viewDidLoad {
8746 [super viewDidLoad];
8748 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8749 [self updateButtonsForEditingStatusAnimated:NO];
8752 - (void) viewWillAppear:(BOOL)animated {
8753 [super viewWillAppear:animated];
8755 [list_ setEditing:NO];
8756 [self updateButtonsForEditingStatusAnimated:NO];
8759 - (void) releaseSubviews {
8764 [super releaseSubviews];
8767 - (id) initWithDatabase:(Database *)database {
8768 if ((self = [super init]) != nil) {
8769 database_ = database;
8773 - (void) reloadData {
8775 [self updateButtonsForEditingStatusAnimated:YES];
8777 @synchronized (database_) {
8778 era_ = [database_ era];
8780 sources_ = [NSMutableArray arrayWithCapacity:16];
8781 [sources_ addObjectsFromArray:[database_ sources]];
8783 [sources_ sortUsingSelector:@selector(compareByName:)];
8786 int count([sources_ count]);
8788 for (int i = 0; i != count; i++) {
8789 if ([[sources_ objectAtIndex:i] record] == nil)
8797 - (void) showAddSourcePrompt {
8798 UIAlertView *alert = [[[UIAlertView alloc]
8799 initWithTitle:UCLocalize("ENTER_APT_URL")
8802 cancelButtonTitle:UCLocalize("CANCEL")
8804 UCLocalize("ADD_SOURCE"),
8808 [alert setContext:@"source"];
8810 [alert setNumberOfRows:1];
8811 [alert addTextFieldWithValue:@"http://" label:@""];
8813 NSObject<UITextInputTraits> *traits = [[alert textField] textInputTraits];
8814 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8815 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8816 [traits setKeyboardType:UIKeyboardTypeURL];
8817 // XXX: UIReturnKeyDone
8818 [traits setReturnKeyType:UIReturnKeyNext];
8823 - (void) addButtonClicked {
8824 [self showAddSourcePrompt];
8827 - (void) refreshButtonClicked {
8828 if ([self.delegate requestUpdate])
8829 [self updateButtonsForEditingStatusAnimated:YES];
8832 - (void) cancelButtonClicked {
8833 [self.delegate cancelUpdate];
8836 - (void) editButtonClicked {
8837 [list_ setEditing:![list_ isEditing] animated:YES];
8838 [self updateButtonsForEditingStatusAnimated:YES];
8844 /* Stash Controller {{{ */
8845 @interface StashController : CyteViewController {
8846 _H<UIActivityIndicatorView> spinner_;
8847 _H<UILabel> status_;
8848 _H<UILabel> caption_;
8853 @implementation StashController
8856 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8857 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8858 [self setView:view];
8860 [view setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8862 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8863 CGRect spinrect = [spinner_ frame];
8864 spinrect.origin.x = Retina([[self view] frame].size.width / 2 - spinrect.size.width / 2);
8865 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8866 [spinner_ setFrame:spinrect];
8867 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8868 [view addSubview:spinner_];
8869 [spinner_ startAnimating];
8872 captrect.size.width = [[self view] frame].size.width;
8873 captrect.size.height = 40.0f;
8874 captrect.origin.x = 0;
8875 captrect.origin.y = Retina([[self view] frame].size.height / 2 - captrect.size.height * 2);
8876 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8877 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8878 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8879 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8880 [caption_ setTextColor:[UIColor whiteColor]];
8881 [caption_ setBackgroundColor:[UIColor clearColor]];
8882 [caption_ setShadowColor:[UIColor blackColor]];
8883 [caption_ setTextAlignment:NSTextAlignmentCenter];
8884 [view addSubview:caption_];
8887 statusrect.size.width = [[self view] frame].size.width;
8888 statusrect.size.height = 30.0f;
8889 statusrect.origin.x = 0;
8890 statusrect.origin.y = Retina([[self view] frame].size.height / 2 - statusrect.size.height);
8891 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8892 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8893 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8894 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8895 [status_ setTextColor:[UIColor whiteColor]];
8896 [status_ setBackgroundColor:[UIColor clearColor]];
8897 [status_ setShadowColor:[UIColor blackColor]];
8898 [status_ setTextAlignment:NSTextAlignmentCenter];
8899 [view addSubview:status_];
8902 - (void) releaseSubviews {
8907 [super releaseSubviews];
8913 @interface CYURLCache : SDURLCache {
8918 @implementation CYURLCache
8920 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8923 else if ([event isEqualToString:@"no-cache"])
8925 else if ([event isEqualToString:@"store"])
8927 else if ([event isEqualToString:@"invalid"])
8929 else if ([event isEqualToString:@"memory"])
8931 else if ([event isEqualToString:@"disk"])
8933 else if ([event isEqualToString:@"miss"])
8936 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8940 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
8941 if (NSURLResponse *response = [cached response])
8942 if (NSString *mime = [response MIMEType])
8943 if ([mime isEqualToString:@"text/cache-manifest"]) {
8944 NSURL *url([response URL]);
8947 NSLog(@"###: %@", [url absoluteString]);
8950 @synchronized (HostConfig_) {
8951 [CachedURLs_ addObject:url];
8955 [super storeCachedResponse:cached forRequest:request];
8958 - (void) createDiskCachePath {
8959 [super createDiskCachePath];
8964 @interface Cydia : CyteApplication <
8965 ConfirmationControllerDelegate,
8969 _H<UIWindow> window_;
8970 _H<CydiaTabBarController> tabbar_;
8971 _H<CyteTabBarController> emulated_;
8972 _H<AppCacheController> appcache_;
8974 _H<NSMutableArray> essential_;
8975 _H<NSMutableArray> broken_;
8977 Database *database_;
8979 _H<NSURL> starturl_;
8984 _H<StashController> stash_;
8993 @implementation Cydia
8995 - (void) lockSuspend {
8996 if (locked_++ == 0) {
8997 if ($SBSSetInterceptsMenuButtonForever != NULL)
8998 (*$SBSSetInterceptsMenuButtonForever)(true);
9000 [self setIdleTimerDisabled:YES];
9004 - (void) unlockSuspend {
9005 if (--locked_ == 0) {
9006 [self setIdleTimerDisabled:NO];
9008 if ($SBSSetInterceptsMenuButtonForever != NULL)
9009 (*$SBSSetInterceptsMenuButtonForever)(false);
9013 - (void) beginUpdate {
9014 [tabbar_ beginUpdate];
9017 - (void) cancelUpdate {
9018 [tabbar_ cancelUpdate];
9021 - (bool) requestUpdate {
9022 if (IsReachable("cydia.saurik.com")) {
9026 UIAlertView *alert = [[[UIAlertView alloc]
9027 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("REFRESH")]
9028 message:@"Host Unreachable" // XXX: Localize
9030 cancelButtonTitle:UCLocalize("OK")
9031 otherButtonTitles:nil
9034 [alert setContext:@"norefresh"];
9042 return [tabbar_ updating];
9046 if ([broken_ count] != 0) {
9047 int count = [broken_ count];
9049 UIAlertView *alert = [[[UIAlertView alloc]
9050 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
9051 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
9053 cancelButtonTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("FORCIBLY_CLEAR"), UCLocalize("UNSAFE")]
9055 UCLocalize("TEMPORARY_IGNORE"),
9059 [alert setContext:@"fixhalf"];
9060 [alert setNumberOfRows:2];
9062 } else if (!Ignored_ && [essential_ count] != 0) {
9063 int count = [essential_ count];
9065 UIAlertView *alert = [[[UIAlertView alloc]
9066 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
9067 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
9069 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
9071 UCLocalize("UPGRADE_ESSENTIAL"),
9072 UCLocalize("COMPLETE_UPGRADE"),
9076 [alert setContext:@"upgrade"];
9081 - (void) returnToCydia {
9085 - (void) reloadSpringBoard {
9086 if (kCFCoreFoundationVersionNumber >= 700) // XXX: iOS 6.x
9087 system("/usr/libexec/cydia/cydo /bin/launchctl stop com.apple.backboardd");
9089 system("/usr/libexec/cydia/cydo /bin/launchctl stop com.apple.SpringBoard");
9091 system("/usr/bin/killall backboardd SpringBoard");
9094 - (void) _saveConfig {
9095 SaveConfig(database_);
9098 // Navigation controller for the queuing badge.
9099 - (UINavigationController *) queueNavigationController {
9100 NSArray *controllers = [tabbar_ viewControllers];
9101 return [controllers objectAtIndex:3];
9104 - (void) unloadData {
9105 [tabbar_ unloadData];
9108 - (void) _updateData {
9112 UINavigationController *navigation = [self queueNavigationController];
9114 id queuedelegate = nil;
9115 if ([[navigation viewControllers] count] > 0)
9116 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9118 [queuedelegate queueStatusDidChange];
9119 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9122 - (void) _refreshIfPossible {
9123 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9125 NSDate *update([[NSDictionary dictionaryWithContentsOfFile:@ CacheState_] objectForKey:@"LastUpdate"]);
9127 bool recently = false;
9128 if (update != nil) {
9129 NSTimeInterval interval([update timeIntervalSinceNow]);
9130 if (interval > -(15*60))
9134 // Don't automatic refresh if:
9135 // - We already refreshed recently.
9136 // - We already auto-refreshed this launch.
9137 // - Auto-refresh is disabled.
9138 // - Cydia's server is not reachable
9139 if (recently || loaded_ || ManualRefresh || !IsReachable("cydia.saurik.com")) {
9140 // If we are cancelling, we need to make sure it knows it's already loaded.
9143 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9145 // We are going to load, so remember that.
9148 [tabbar_ performSelectorOnMainThread:@selector(beginUpdate) withObject:nil waitUntilDone:NO];
9154 - (void) refreshIfPossible {
9155 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
9158 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9159 _profile(reloadDataWithInvocation)
9160 @synchronized (self) {
9161 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9163 [hud setText:UCLocalize("RELOADING_DATA")];
9165 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9169 [essential_ removeAllObjects];
9170 [broken_ removeAllObjects];
9172 _profile(reloadDataWithInvocation$Essential)
9173 NSArray *packages([database_ packages]);
9174 for (Package *package in packages) {
9176 [broken_ addObject:package];
9177 if ([package upgradableAndEssential:YES] && ![package ignored]) {
9178 if ([package essential] && [package installed] != nil)
9179 [essential_ addObject:package];
9185 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9188 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9189 [changesItem setBadgeValue:badge];
9190 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9191 [self setApplicationIconBadgeNumber:changes];
9194 [changesItem setBadgeValue:nil];
9195 [changesItem setAnimatedBadge:NO];
9196 [self setApplicationIconBadgeNumber:0];
9203 [self removeProgressHUD:hud];
9210 - (void) updateData {
9214 - (void) updateDataAndLoad {
9216 if ([database_ progressDelegate] == nil)
9222 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9225 - (void) disemulate {
9226 if (emulated_ == nil)
9229 if ([window_ respondsToSelector:@selector(setRootViewController:)])
9230 [window_ setRootViewController:tabbar_];
9232 [window_ addSubview:[tabbar_ view]];
9233 [[emulated_ view] removeFromSuperview];
9237 [window_ setUserInteractionEnabled:YES];
9240 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9241 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9243 UIViewController *parent;
9244 if (emulated_ == nil)
9254 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9255 [parent presentModalViewController:navigation animated:YES];
9258 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9259 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9261 if (navigation != nil)
9262 [navigation pushViewController:progress animated:YES];
9264 [self presentModalViewController:progress force:YES];
9266 [progress invoke:invocation withTitle:title];
9270 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9271 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9274 - (void) repairWithInvocation:(NSInvocation *)invocation {
9276 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9280 - (void) repairWithSelector:(SEL)selector {
9281 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9284 - (void) reloadData {
9285 [self reloadDataWithInvocation:nil];
9286 if ([database_ progressDelegate] == nil)
9292 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9295 - (void) addSource:(NSDictionary *) source {
9296 CydiaAddSource(source);
9299 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9300 CydiaAddSource(href, distribution, sections);
9303 // XXX: this method should not return anything
9304 - (BOOL) addTrivialSource:(NSString *)href {
9305 CydiaAddSource(href, @"./");
9310 pkgProblemResolver *resolver = [database_ resolver];
9312 resolver->InstallProtect();
9313 if (!resolver->Resolve(true))
9318 // XXX: this is a really crappy way of doing this.
9319 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9320 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9321 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9322 if ([tabbar_ updating])
9323 [tabbar_ cancelUpdate];
9325 if (![database_ prepare])
9328 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9329 [page setDelegate:self];
9330 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9333 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9334 [tabbar_ presentModalViewController:confirm_ animated:YES];
9340 @synchronized (self) {
9345 - (void) clearPackage:(Package *)package {
9346 @synchronized (self) {
9353 - (void) installPackages:(NSArray *)packages {
9354 @synchronized (self) {
9355 for (Package *package in packages)
9362 - (void) installPackage:(Package *)package {
9363 @synchronized (self) {
9370 - (void) removePackage:(Package *)package {
9371 @synchronized (self) {
9378 - (void) distUpgrade {
9379 @synchronized (self) {
9380 if (![database_ upgrade])
9388 system("/usr/bin/uicache");
9393 UIProgressHUD *hud([self addProgressHUD]);
9394 [hud setText:UCLocalize("LOADING")];
9395 [self yieldToSelector:@selector(_uicache)];
9396 [self removeProgressHUD:hud];
9400 [database_ perform];
9401 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9402 [self performSelectorOnMainThread:@selector(uicache) withObject:nil waitUntilDone:YES];
9405 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9408 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9409 [self unlockSuspend];
9412 - (void) retainNetworkActivityIndicator {
9413 if (activity_++ == 0)
9414 [self setNetworkActivityIndicatorVisible:YES];
9417 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9421 - (void) releaseNetworkActivityIndicator {
9422 if (--activity_ == 0)
9423 [self setNetworkActivityIndicatorVisible:NO];
9426 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9431 - (void) cancelAndClear:(bool)clear {
9432 @synchronized (self) {
9444 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9445 NSString *context([alert context]);
9447 if ([context isEqualToString:@"conffile"]) {
9448 FILE *input = [database_ input];
9449 if (button == [alert cancelButtonIndex])
9450 fprintf(input, "N\n");
9451 else if (button == [alert firstOtherButtonIndex])
9452 fprintf(input, "Y\n");
9455 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9456 } else if ([context isEqualToString:@"fixhalf"]) {
9457 if (button == [alert cancelButtonIndex]) {
9458 @synchronized (self) {
9459 for (Package *broken in (id) broken_) {
9461 NSString *id(ShellEscape([broken id]));
9462 system([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /bin/rm -f"
9463 " /var/lib/dpkg/info/%@.prerm"
9464 " /var/lib/dpkg/info/%@.postrm"
9465 " /var/lib/dpkg/info/%@.preinst"
9466 " /var/lib/dpkg/info/%@.postinst"
9467 " /var/lib/dpkg/info/%@.extrainst_"
9468 "", id, id, id, id, id] UTF8String]);
9474 } else if (button == [alert firstOtherButtonIndex]) {
9475 [broken_ removeAllObjects];
9479 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9480 } else if ([context isEqualToString:@"upgrade"]) {
9481 if (button == [alert firstOtherButtonIndex]) {
9482 @synchronized (self) {
9483 for (Package *essential in (id) essential_)
9484 [essential install];
9489 } else if (button == [alert firstOtherButtonIndex] + 1) {
9491 } else if (button == [alert cancelButtonIndex]) {
9495 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9499 - (void) system:(NSString *)command {
9500 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9503 system([command UTF8String]);
9509 - (void) applicationWillSuspend {
9511 [super applicationWillSuspend];
9514 - (BOOL) isSafeToSuspend {
9517 NSLog(@"isSafeToSuspend: locked_ != 0");
9522 if ([tabbar_ modalViewController] != nil)
9525 // Use external process status API internally.
9526 // This is probably a really bad idea.
9527 // XXX: what is the point of this? does this solve anything at all?
9528 uint64_t status = 0;
9530 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9531 notify_get_state(notify_token, &status);
9532 notify_cancel(notify_token);
9537 NSLog(@"isSafeToSuspend: status != 0");
9543 NSLog(@"isSafeToSuspend: -> true");
9548 - (void) suspendReturningToLastApp:(BOOL)returning {
9549 if ([self isSafeToSuspend])
9550 [super suspendReturningToLastApp:returning];
9554 if ([self isSafeToSuspend])
9558 - (void) applicationSuspend {
9559 if ([self isSafeToSuspend])
9560 [super applicationSuspend];
9563 - (void) applicationSuspend:(GSEventRef)event {
9564 if ([self isSafeToSuspend])
9565 [super applicationSuspend:event];
9568 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9569 if ([self isSafeToSuspend])
9570 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9573 - (void) _setSuspended:(BOOL)value {
9574 if ([self isSafeToSuspend])
9575 [super _setSuspended:value];
9578 - (UIProgressHUD *) addProgressHUD {
9579 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9580 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9582 [window_ setUserInteractionEnabled:NO];
9584 UIViewController *target(tabbar_);
9585 if (UIViewController *modal = [target modalViewController])
9588 [hud showInView:[target view]];
9594 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9595 [self unlockSuspend];
9597 [hud removeFromSuperview];
9598 [window_ setUserInteractionEnabled:YES];
9601 - (CyteViewController *) pageForPackage:(NSString *)name withReferrer:(NSString *)referrer {
9602 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name withReferrer:referrer] autorelease];
9605 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external withReferrer:(NSString *)referrer {
9606 NSString *scheme([[url scheme] lowercaseString]);
9607 if ([[url absoluteString] length] <= [scheme length] + 3)
9609 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9610 NSArray *components([path componentsSeparatedByString:@"/"]);
9612 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"]) {
9613 CyteViewController *controller([self pageForPackage:[components objectAtIndex:1] withReferrer:referrer]);
9614 if (controller != nil)
9615 [controller setDelegate:self];
9619 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9622 NSString *base([components objectAtIndex:0]);
9624 CyteViewController *controller = nil;
9626 if ([base isEqualToString:@"url"]) {
9627 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9628 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9629 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9630 } else if (!external && [components count] == 1) {
9631 if ([base isEqualToString:@"sources"]) {
9632 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9635 if ([base isEqualToString:@"home"]) {
9636 controller = [[[HomeController alloc] init] autorelease];
9639 if ([base isEqualToString:@"sections"]) {
9640 controller = [[[SectionsController alloc] initWithDatabase:database_ source:nil] autorelease];
9643 if ([base isEqualToString:@"search"]) {
9644 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9647 if ([base isEqualToString:@"changes"]) {
9648 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9651 if ([base isEqualToString:@"installed"]) {
9652 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9654 } else if ([components count] == 2) {
9655 NSString *argument = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9657 if ([base isEqualToString:@"package"]) {
9658 controller = [self pageForPackage:argument withReferrer:referrer];
9661 if (!external && [base isEqualToString:@"search"]) {
9662 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9665 if (!external && [base isEqualToString:@"sections"]) {
9666 if ([argument isEqualToString:@"all"] || [argument isEqualToString:@"*"])
9668 controller = [[[SectionController alloc] initWithDatabase:database_ source:nil section:argument] autorelease];
9671 if ([base isEqualToString:@"sources"]) {
9672 if ([argument isEqualToString:@"add"]) {
9673 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9674 [(SourcesController *)controller showAddSourcePrompt];
9676 Source *source([database_ sourceWithKey:argument]);
9677 controller = [[[SectionsController alloc] initWithDatabase:database_ source:source] autorelease];
9681 if (!external && [base isEqualToString:@"launch"]) {
9682 [self launchApplicationWithIdentifier:argument suspended:NO];
9685 } else if (!external && [components count] == 3) {
9686 NSString *arg1 = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9687 NSString *arg2 = [[components objectAtIndex:2] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9689 if ([base isEqualToString:@"package"]) {
9690 if ([arg2 isEqualToString:@"settings"]) {
9691 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9692 } else if ([arg2 isEqualToString:@"files"]) {
9693 if (Package *package = [database_ packageWithName:arg1]) {
9694 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9695 [(FileTable *)controller setPackage:package];
9700 if ([base isEqualToString:@"sections"]) {
9701 Source *source([arg1 isEqualToString:@"*"] ? nil : [database_ sourceWithKey:arg1]);
9702 NSString *section([arg2 isEqualToString:@"*"] ? nil : arg2);
9703 controller = [[[SectionController alloc] initWithDatabase:database_ source:source section:section] autorelease];
9707 [controller setDelegate:self];
9711 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9712 CyteViewController *page([self pageForURL:url forExternal:external withReferrer:nil]);
9715 [tabbar_ setUnselectedViewController:page];
9720 - (void) applicationOpenURL:(NSURL *)url {
9721 [super applicationOpenURL:url];
9726 [self openCydiaURL:url forExternal:YES];
9729 - (void) applicationWillResignActive:(UIApplication *)application {
9730 // Stop refreshing if you get a phone call or lock the device.
9731 if ([tabbar_ updating])
9732 [tabbar_ cancelUpdate];
9734 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9735 [super applicationWillResignActive:application];
9738 - (void) saveState {
9739 [[NSDictionary dictionaryWithObjectsAndKeys:
9740 @"InterfaceState", [tabbar_ navigationURLCollection],
9741 @"LastClosed", [NSDate date],
9742 @"InterfaceIndex", [NSNumber numberWithInt:[tabbar_ selectedIndex]],
9743 nil] writeToFile:@ SavedState_ atomically:YES];
9748 - (void) applicationWillTerminate:(UIApplication *)application {
9752 - (void) applicationDidEnterBackground:(UIApplication *)application {
9753 if (kCFCoreFoundationVersionNumber < 1000 && [self isSafeToSuspend])
9754 return [self terminateWithSuccess];
9755 Backgrounded_ = [NSDate date];
9759 - (void) applicationWillEnterForeground:(UIApplication *)application {
9760 if (Backgrounded_ == nil)
9763 NSTimeInterval interval([Backgrounded_ timeIntervalSinceNow]);
9765 if (interval <= -(30*60)) {
9766 [tabbar_ setSelectedIndex:0];
9767 [[[tabbar_ viewControllers] objectAtIndex:0] popToRootViewControllerAnimated:NO];
9770 if (interval <= -(15*60)) {
9771 if (IsReachable("cydia.saurik.com")) {
9772 [tabbar_ beginUpdate];
9773 [appcache_ reloadURLWithCache:YES];
9777 if ([database_ delocked])
9781 - (void) setConfigurationData:(NSString *)data {
9782 static RegEx conffile_r("'(.*)' '(.*)' ([01]) ([01])");
9784 if (!conffile_r(data)) {
9785 lprintf("E:invalid conffile\n");
9789 NSString *ofile = conffile_r[1];
9790 //NSString *nfile = conffile_r[2];
9792 UIAlertView *alert = [[[UIAlertView alloc]
9793 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9794 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9796 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9798 UCLocalize("ACCEPT_NEW_COPY"),
9799 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9803 [alert setContext:@"conffile"];
9804 [alert setNumberOfRows:2];
9808 - (void) addStashController {
9810 stash_ = [[[StashController alloc] init] autorelease];
9811 [window_ addSubview:[stash_ view]];
9814 - (void) removeStashController {
9815 [[stash_ view] removeFromSuperview];
9817 [self unlockSuspend];
9821 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9822 UpdateExternalStatus(1);
9823 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/cydo /usr/libexec/cydia/free.sh"];
9824 UpdateExternalStatus(0);
9826 [self removeStashController];
9827 [self reloadSpringBoard];
9830 - (void) setupViewControllers {
9831 tabbar_ = [[[CydiaTabBarController alloc] initWithDatabase:database_] autorelease];
9833 NSMutableArray *items;
9834 if (kCFCoreFoundationVersionNumber < 800) {
9835 items = [NSMutableArray arrayWithObjects:
9836 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage imageNamed:@"home.png"] tag:0] autorelease],
9837 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage imageNamed:@"install.png"] tag:0] autorelease],
9838 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage imageNamed:@"changes.png"] tag:0] autorelease],
9839 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage imageNamed:@"manage.png"] tag:0] autorelease],
9840 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage imageNamed:@"search.png"] tag:0] autorelease],
9843 items = [NSMutableArray arrayWithObjects:
9844 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage imageNamed:@"home7.png"] selectedImage:[UIImage imageNamed:@"home7s.png"]] autorelease],
9845 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage imageNamed:@"install7.png"] selectedImage:[UIImage imageNamed:@"install7s.png"]] autorelease],
9846 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage imageNamed:@"changes7.png"] selectedImage:[UIImage imageNamed:@"changes7s.png"]] autorelease],
9847 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage imageNamed:@"manage7.png"] selectedImage:[UIImage imageNamed:@"manage7s.png"]] autorelease],
9848 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage imageNamed:@"search7.png"] selectedImage:[UIImage imageNamed:@"search7s.png"]] autorelease],
9852 NSMutableArray *controllers([NSMutableArray array]);
9853 for (UITabBarItem *item in items) {
9854 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9855 [controller setTabBarItem:item];
9856 [controllers addObject:controller];
9858 [tabbar_ setViewControllers:controllers];
9860 [tabbar_ setUpdateDelegate:self];
9863 - (void) applicationDidFinishLaunching:(id)unused {
9864 [super applicationDidFinishLaunching:unused];
9867 @synchronized (HostConfig_) {
9868 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9871 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9872 initWithMemoryCapacity:524288
9873 diskCapacity:10485760
9874 diskPath:Cache("SDURLCache")
9877 [CydiaWebViewController _initialize];
9879 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9881 // this would disallow http{,s} URLs from accessing this data
9882 //[WebView registerURLSchemeAsLocal:@"cydia"];
9884 Font12_ = [UIFont systemFontOfSize:12];
9885 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9886 Font14_ = [UIFont systemFontOfSize:14];
9887 Font18_ = [UIFont systemFontOfSize:18];
9888 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9889 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9891 essential_ = [NSMutableArray arrayWithCapacity:4];
9892 broken_ = [NSMutableArray arrayWithCapacity:4];
9894 // XXX: I really need this thing... like, seriously... I'm sorry
9895 appcache_ = [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] autorelease];
9896 [appcache_ reloadData];
9898 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9899 [window_ orderFront:self];
9900 [window_ makeKey:self];
9901 [window_ setHidden:NO];
9903 if (access("/.cydia_no_stash", F_OK) == 0);
9907 [self addStashController];
9908 // XXX: this would be much cleaner as a yieldToSelector:
9909 // that way the removeStashController could happen right here inline
9910 // we also could no longer require the useless stash_ field anymore
9911 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9916 int error(stat("/", &root));
9917 _assert(error != -1);
9919 #define Stash_(path) do { \
9920 struct stat folder; \
9921 int error(lstat((path), &folder)); \
9922 if (error != -1 && ( \
9923 folder.st_dev == root.st_dev && \
9924 S_ISDIR(folder.st_mode) \
9925 ) || error == -1 && ( \
9926 errno == ENOENT || \
9931 Stash_("/Applications");
9932 Stash_("/Library/Ringtones");
9933 Stash_("/Library/Wallpaper");
9934 //Stash_("/usr/bin");
9935 Stash_("/usr/include");
9936 Stash_("/usr/share");
9937 //Stash_("/var/lib");
9941 database_ = [Database sharedInstance];
9942 [database_ setDelegate:self];
9944 [window_ setUserInteractionEnabled:NO];
9945 [self setupViewControllers];
9947 CydiaLoadingViewController *loading([[[CydiaLoadingViewController alloc] init] autorelease]);
9948 UINavigationController *navigation([[[UINavigationController alloc] init] autorelease]);
9949 [navigation setViewControllers:[NSArray arrayWithObject:loading]];
9951 emulated_ = [[[CyteTabBarController alloc] init] autorelease];
9952 [emulated_ setViewControllers:[NSArray arrayWithObject:navigation]];
9953 [emulated_ setSelectedIndex:0];
9955 if ([emulated_ respondsToSelector:@selector(concealTabBarSelection)])
9956 [emulated_ concealTabBarSelection];
9958 if ([window_ respondsToSelector:@selector(setRootViewController:)])
9959 [window_ setRootViewController:emulated_];
9961 [window_ addSubview:[emulated_ view]];
9963 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9967 - (NSArray *) defaultStartPages {
9968 NSMutableArray *standard = [NSMutableArray array];
9969 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9970 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9971 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9972 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9973 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9979 if ([emulated_ modalViewController] != nil)
9980 [emulated_ dismissModalViewControllerAnimated:YES];
9981 [window_ setUserInteractionEnabled:NO];
9983 [self reloadDataWithInvocation:nil];
9984 [self refreshIfPossible];
9987 NSDictionary *state([NSDictionary dictionaryWithContentsOfFile:@ SavedState_]);
9989 int savedIndex = [[state objectForKey:@"InterfaceIndex"] intValue];
9990 NSArray *saved = [[[state objectForKey:@"InterfaceState"] mutableCopy] autorelease];
9991 int standardIndex = 0;
9992 NSArray *standard = [self defaultStartPages];
9999 NSDate *closed = [state objectForKey:@"LastClosed"];
10000 if (valid && closed != nil) {
10001 NSTimeInterval interval([closed timeIntervalSinceNow]);
10002 if (interval <= -(30*60))
10006 if (valid && [saved count] != [standard count])
10010 for (unsigned int i = 0; i < [standard count]; i++) {
10011 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
10012 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
10013 // but it's good enough for now.
10014 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
10021 NSArray *items = nil;
10023 [tabbar_ setSelectedIndex:savedIndex];
10026 [tabbar_ setSelectedIndex:standardIndex];
10030 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
10031 NSArray *stack = [items objectAtIndex:tab];
10032 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
10033 NSMutableArray *current = [NSMutableArray array];
10035 for (unsigned int nav = 0; nav < [stack count]; nav++) {
10036 NSString *addr = [stack objectAtIndex:nav];
10037 NSURL *url = [NSURL URLWithString:addr];
10038 CyteViewController *page = [self pageForURL:url forExternal:NO withReferrer:nil];
10040 [current addObject:page];
10043 [navigation setViewControllers:current];
10046 // (Try to) show the startup URL.
10047 if (starturl_ != nil) {
10048 [self openCydiaURL:starturl_ forExternal:YES];
10053 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
10055 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
10056 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
10059 if (item != nil && IsWildcat_) {
10060 [sheet showFromBarButtonItem:item animated:YES];
10062 [sheet showInView:window_];
10066 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
10067 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
10068 [progress setTitle:task];
10069 [progress addProgressEvent:event];
10072 - (void) addProgressEventForTask:(NSArray *)data {
10073 CydiaProgressEvent *event([data objectAtIndex:0]);
10074 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
10075 [self addProgressEvent:event forTask:task];
10078 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
10079 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
10085 id Alloc_(id self, SEL selector) {
10086 id object = alloc_(self, selector);
10087 lprintf("[%s]A-%p\n", self->isa->name, object);
10092 id Dealloc_(id self, SEL selector) {
10093 id object = dealloc_(self, selector);
10094 lprintf("[%s]D-%p\n", self->isa->name, object);
10098 Class $NSURLConnection;
10100 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
10101 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
10103 NSURL *url([copy URL]);
10105 @synchronized (HostConfig_) {
10106 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
10107 if ([control isEqualToString:@"max-age=0"])
10108 if ([CachedURLs_ containsObject:url]) {
10110 NSLog(@"~~~: %@", url);
10113 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
10115 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
10116 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
10117 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
10121 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
10127 static CGSize $WAKWindow$screenSize(WAKWindow *self, SEL _cmd) {
10128 CGSize size([[UIScreen mainScreen] bounds].size);
10129 /*if ([$WAKWindow respondsToSelector:@selector(hasLandscapeOrientation)])
10130 if ([$WAKWindow hasLandscapeOrientation])
10131 std::swap(size.width, size.height);*/
10135 Class $NSUserDefaults;
10137 MSHook(id, NSUserDefaults$objectForKey$, NSUserDefaults *self, SEL _cmd, NSString *key) {
10138 if ([key respondsToSelector:@selector(isEqualToString:)] && [key isEqualToString:@"WebKitLocalStorageDatabasePathPreferenceKey"])
10139 return Cache("LocalStorage");
10140 return _NSUserDefaults$objectForKey$(self, _cmd, key);
10143 static NSMutableDictionary *AutoreleaseDeepMutableCopyOfDictionary(CFTypeRef type) {
10146 if (CFGetTypeID(type) != CFDictionaryGetTypeID())
10148 CFTypeRef copy(CFPropertyListCreateDeepCopy(kCFAllocatorDefault, type, kCFPropertyListMutableContainers));
10150 return [(NSMutableDictionary *) copy autorelease];
10153 int main_store(int, char *argv[]);
10155 int main(int argc, char *argv[]) {
10157 const char *argv0(argv[0]);
10158 if (const char *slash = strrchr(argv0, '/'))
10161 else if (!strcmp(argv0, "store"))
10162 return main_store(argc, argv);
10165 int fd(open("/tmp/cydia.log", O_WRONLY | O_APPEND | O_CREAT, 0644));
10169 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10173 UpdateExternalStatus(0);
10175 UIScreen *screen([UIScreen mainScreen]);
10176 if ([screen respondsToSelector:@selector(scale)])
10177 ScreenScale_ = [screen scale];
10181 UIDevice *device([UIDevice currentDevice]);
10182 if ([device respondsToSelector:@selector(userInterfaceIdiom)]) {
10183 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10184 if (idiom == UIUserInterfaceIdiomPad)
10188 Idiom_ = IsWildcat_ ? @"ipad" : @"iphone";
10190 RegEx pattern("([0-9]+\\.[0-9]+).*");
10192 if (pattern([device systemVersion]))
10193 Firmware_ = pattern[1];
10194 if (pattern(Cydia_))
10195 Major_ = pattern[1];
10197 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
10199 HostConfig_ = [[[NSObject alloc] init] autorelease];
10200 @synchronized (HostConfig_) {
10201 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10202 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
10203 CachedURLs_ = [NSMutableSet setWithCapacity:32];
10206 NSString *ui(@"ui/ios");
10208 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
10209 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"/%@", Major_]];
10210 UI_ = CydiaURL(ui);
10212 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10214 /* Library Hacks {{{ */
10215 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10217 $WAKWindow = objc_getClass("WAKWindow");
10218 if ($WAKWindow != NULL)
10219 if (Method method = class_getInstanceMethod($WAKWindow, @selector(screenSize)))
10220 method_setImplementation(method, (IMP) &$WAKWindow$screenSize);
10222 $NSURLConnection = objc_getClass("NSURLConnection");
10223 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10224 if (NSURLConnection$init$ != NULL) {
10225 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10226 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10229 $NSUserDefaults = objc_getClass("NSUserDefaults");
10230 Method NSUserDefaults$objectForKey$(class_getInstanceMethod($NSUserDefaults, @selector(objectForKey:)));
10231 if (NSUserDefaults$objectForKey$ != NULL) {
10232 _NSUserDefaults$objectForKey$ = reinterpret_cast<id (*)(NSUserDefaults *, SEL, NSString *)>(method_getImplementation(NSUserDefaults$objectForKey$));
10233 method_setImplementation(NSUserDefaults$objectForKey$, reinterpret_cast<IMP>(&$NSUserDefaults$objectForKey$));
10236 /* Set Locale {{{ */
10237 Locale_ = CFLocaleCopyCurrent();
10238 Languages_ = [NSLocale preferredLanguages];
10240 std::string languages;
10241 const char *translation(NULL);
10243 // XXX: this isn't really a language, but this is compatible with older Cydia builds
10244 if (Locale_ != NULL)
10245 if (const char *language = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String]) {
10246 RegEx pattern("([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?");
10247 if (pattern(language)) {
10248 translation = strdup([pattern->*@"%1$@%2$@" UTF8String]);
10249 languages += translation;
10254 if (Languages_ != nil)
10255 for (NSString *locale : Languages_) {
10256 auto components([NSLocale componentsFromLocaleIdentifier:locale]);
10257 NSString *language([components objectForKey:(id)kCFLocaleLanguageCode]);
10258 if (NSString *script = [components objectForKey:(id)kCFLocaleScriptCode])
10259 language = [NSString stringWithFormat:@"%@-%@", language, script];
10260 languages += [language UTF8String];
10265 NSLog(@"Setting Language: [%s] %s", translation, languages.c_str());
10267 /* Index Collation {{{ */
10268 if (Class $UILocalizedIndexedCollation = objc_getClass("UILocalizedIndexedCollation")) { @try {
10269 NSBundle *bundle([NSBundle bundleForClass:$UILocalizedIndexedCollation]);
10270 NSString *path([bundle pathForResource:@"UITableViewLocalizedSectionIndex" ofType:@"plist"]);
10271 //path = @"/System/Library/Frameworks/UIKit.framework/.lproj/UITableViewLocalizedSectionIndex.plist";
10272 NSDictionary *dictionary([NSDictionary dictionaryWithContentsOfFile:path]);
10273 _H<UILocalizedIndexedCollation> collation([[[$UILocalizedIndexedCollation alloc] initWithDictionary:dictionary] autorelease]);
10275 CollationLocale_ = MSHookIvar<NSLocale *>(collation, "_locale");
10277 if (kCFCoreFoundationVersionNumber >= 800 && [[CollationLocale_ localeIdentifier] isEqualToString:@"zh@collation=stroke"]) {
10278 CollationThumbs_ = [NSArray arrayWithObjects:@"1",@"•",@"4",@"•",@"7",@"•",@"10",@"•",@"13",@"•",@"16",@"•",@"19",@"A",@"•",@"E",@"•",@"I",@"•",@"M",@"•",@"R",@"•",@"V",@"•",@"Z",@"#",nil];
10279 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})
10280 CollationOffset_.push_back(offset);
10281 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];
10282 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];
10285 CollationThumbs_ = [collation sectionIndexTitles];
10286 for (size_t index(0), end([CollationThumbs_ count]); index != end; ++index)
10287 CollationOffset_.push_back([collation sectionForSectionIndexTitleAtIndex:index]);
10289 CollationTitles_ = [collation sectionTitles];
10290 CollationStarts_ = MSHookIvar<NSArray *>(collation, "_sectionStartStrings");
10292 NSString *&transform(MSHookIvar<NSString *>(collation, "_transform"));
10293 if (&transform != NULL && transform != nil) {
10294 /*if ([collation respondsToSelector:@selector(transformedCollationStringForString:)])
10295 CollationModify_ = [=](NSString *value) { return [collation transformedCollationStringForString:value]; };*/
10296 const UChar *uid(reinterpret_cast<const UChar *>([transform cStringUsingEncoding:NSUnicodeStringEncoding]));
10297 UErrorCode code(U_ZERO_ERROR);
10298 CollationTransl_ = utrans_openU(uid, -1, UTRANS_FORWARD, NULL, 0, NULL, &code);
10299 if (!U_SUCCESS(code))
10300 NSLog(@"%s", u_errorName(code));
10304 } @catch (NSException *e) {
10308 CollationLocale_ = [[[NSLocale alloc] initWithLocaleIdentifier:@"en@collation=dictionary"] autorelease];
10310 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];
10311 for (NSInteger offset(0); offset != 28; ++offset)
10312 CollationOffset_.push_back(offset);
10314 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];
10315 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];
10319 App_ = [[NSBundle mainBundle] bundlePath];
10322 Cache_ = [[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia", @"/var/mobile"] retain];
10323 mkdir([Cache_ UTF8String], 0755);
10325 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10326 alloc_ = alloc->method_imp;
10327 alloc->method_imp = (IMP) &Alloc_;*/
10329 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10330 dealloc_ = dealloc->method_imp;
10331 dealloc->method_imp = (IMP) &Dealloc_;*/
10333 void *gestalt(dlopen("/usr/lib/libMobileGestalt.dylib", RTLD_GLOBAL | RTLD_LAZY));
10334 $MGCopyAnswer = reinterpret_cast<CFStringRef (*)(CFStringRef)>(dlsym(gestalt, "MGCopyAnswer"));
10336 /* System Information {{{ */
10340 size = sizeof(maxproc);
10341 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10342 perror("sysctlbyname(\"kern.maxproc\", ?)");
10343 else if (maxproc < 64) {
10345 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10346 perror("sysctlbyname(\"kern.maxproc\", #)");
10349 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10350 char *osversion = new char[size];
10351 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10352 perror("sysctlbyname(\"kern.osversion\", ?)");
10354 System_ = [NSString stringWithUTF8String:osversion];
10356 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10357 char *machine = new char[size];
10358 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10359 perror("sysctlbyname(\"hw.machine\", ?)");
10361 Machine_ = machine;
10363 int64_t usermem(0);
10364 size = sizeof(usermem);
10365 if (sysctlbyname("hw.usermem", &usermem, &size, NULL, 0) == -1)
10368 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10369 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10370 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10372 UniqueID_ = UniqueIdentifier(device);
10374 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10375 Product_ = [info objectForKey:@"SafariProductVersion"];
10376 Safari_ = [info objectForKey:@"CFBundleVersion"];
10379 NSString *agent([NSString stringWithFormat:@"Cydia/%@ CyF/%.2f", Cydia_, kCFCoreFoundationVersionNumber]);
10381 if (RegEx match = RegEx("([0-9]+(\\.[0-9]+)+).*", Safari_))
10382 agent = [NSString stringWithFormat:@"Safari/%@ %@", match[1], agent];
10383 if (RegEx match = RegEx("([0-9]+[A-Z][0-9]+[a-z]?).*", System_))
10384 agent = [NSString stringWithFormat:@"Mobile/%@ %@", match[1], agent];
10385 if (RegEx match = RegEx("([0-9]+(\\.[0-9]+)+).*", Product_))
10386 agent = [NSString stringWithFormat:@"Version/%@ %@", match[1], agent];
10388 UserAgent_ = agent;
10390 /* Load Database {{{ */
10391 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10394 mkdir("/var/mobile/Library/Cydia", 0755);
10395 MetaFile_.Open("/var/mobile/Library/Cydia/metadata.cb0");
10398 Values_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaValues"), CFSTR("com.saurik.Cydia")));
10399 Sections_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaSections"), CFSTR("com.saurik.Cydia")));
10400 Sources_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaSources"), CFSTR("com.saurik.Cydia")));
10401 Version_ = [(NSNumber *) CFPreferencesCopyAppValue(CFSTR("CydiaVersion"), CFSTR("com.saurik.Cydia")) autorelease];
10404 NSDictionary *metadata([[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease]);
10406 if (Values_ == nil)
10407 Values_ = [metadata objectForKey:@"Values"];
10408 if (Values_ == nil)
10409 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10411 if (Sections_ == nil)
10412 Sections_ = [metadata objectForKey:@"Sections"];
10413 if (Sections_ == nil)
10414 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10416 if (Sources_ == nil)
10417 Sources_ = [metadata objectForKey:@"Sources"];
10418 if (Sources_ == nil)
10419 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10421 // XXX: this wrong, but in a way that doesn't matter :/
10422 if (Version_ == nil)
10423 Version_ = [metadata objectForKey:@"Version"];
10424 if (Version_ == nil)
10425 Version_ = [NSNumber numberWithUnsignedInt:0];
10427 if (NSDictionary *packages = [metadata objectForKey:@"Packages"]) {
10429 CFDictionaryApplyFunction((CFDictionaryRef) packages, &PackageImport, &fail);
10432 NSLog(@"unable to import package preferences... from 2010? oh well :/");
10435 if ([Version_ unsignedIntValue] == 0) {
10436 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10437 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10438 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10439 CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./");
10441 Version_ = [NSNumber numberWithUnsignedInt:1];
10443 if (NSMutableDictionary *cache = [NSMutableDictionary dictionaryWithContentsOfFile:@ CacheState_]) {
10444 [cache removeObjectForKey:@"LastUpdate"];
10445 [cache writeToFile:@ CacheState_ atomically:YES];
10449 _H<NSMutableArray> broken([NSMutableArray array]);
10450 for (NSString *key in (id) Sources_)
10451 if ([key rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"# "]].location != NSNotFound || ![([[Sources_ objectForKey:key] objectForKey:@"URI"] ?: @"/") hasSuffix:@"/"])
10452 [broken addObject:key];
10453 if ([broken count] != 0)
10454 for (NSString *key in (id) broken)
10455 [Sources_ removeObjectForKey:key];
10459 system("/usr/libexec/cydia/cydo /bin/rm -f /var/lib/cydia/metadata.plist");
10462 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10464 if (kCFCoreFoundationVersionNumber > 1000)
10465 system("/usr/libexec/cydia/cydo /usr/libexec/cydia/setnsfpn /var/lib");
10467 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10469 if (access("/User", F_OK) != 0 || version != 6) {
10471 system("/usr/libexec/cydia/cydo /usr/libexec/cydia/firmware.sh");
10475 if (access("/tmp/cydia.chk", F_OK) == 0) {
10476 if (unlink([Cache("pkgcache.bin") UTF8String]) == -1)
10477 _assert(errno == ENOENT);
10478 if (unlink([Cache("srcpkgcache.bin") UTF8String]) == -1)
10479 _assert(errno == ENOENT);
10482 system("/usr/libexec/cydia/cydo /bin/ln -sf /var/mobile/Library/Caches/com.saurik.Cydia/sources.list /etc/apt/sources.list.d/cydia.list");
10484 /* APT Initialization {{{ */
10485 _assert(pkgInitConfig(*_config));
10486 _assert(pkgInitSystem(*_config, _system));
10488 _config->Set("Acquire::AllowInsecureRepositories", true);
10489 _config->Set("Acquire::Check-Valid-Until", false);
10490 _config->Set("Dir::Bin::Methods::store", "/Applications/Cydia.app/store");
10492 _config->Set("pkgCacheGen::ForceEssential", "");
10494 if (translation != NULL)
10495 _config->Set("APT::Acquire::Translation", translation);
10496 _config->Set("Acquire::Languages", languages);
10498 // XXX: this timeout might be important :(
10499 //_config->Set("Acquire::http::Timeout", 15);
10501 _config->Set("Acquire::http::MaxParallel", usermem >= 384 * 1024 * 1024 ? 16 : 3);
10503 mkdir([Cache("archives") UTF8String], 0755);
10504 mkdir([Cache("archives/partial") UTF8String], 0755);
10505 _config->Set("Dir::Cache", [Cache_ UTF8String]);
10507 symlink("/var/lib/apt/extended_states", [Cache("extended_states") UTF8String]);
10508 _config->Set("Dir::State", [Cache_ UTF8String]);
10510 mkdir([Cache("lists") UTF8String], 0755);
10511 mkdir([Cache("lists/partial") UTF8String], 0755);
10512 mkdir([Cache("periodic") UTF8String], 0755);
10513 _config->Set("Dir::State::Lists", [Cache("lists") UTF8String]);
10515 std::string logs("/var/mobile/Library/Logs/Cydia");
10516 mkdir(logs.c_str(), 0755);
10517 _config->Set("Dir::Log", logs);
10519 _config->Set("Dir::Bin::dpkg", "/usr/libexec/cydia/cydo");
10521 /* Color Choices {{{ */
10522 space_ = CGColorSpaceCreateDeviceRGB();
10524 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10525 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10526 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10527 Folder_.Set(space_, 0x8e/255.f, 0x8e/255.f, 0x93/255.f, 1.0);
10528 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10529 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10530 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10531 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10532 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10533 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10535 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10536 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10538 /* UIKit Configuration {{{ */
10539 // XXX: I have a feeling this was important
10540 //UIKeyboardDisableAutomaticAppearance();
10543 $SBSSetInterceptsMenuButtonForever = reinterpret_cast<void (*)(bool)>(dlsym(RTLD_DEFAULT, "SBSSetInterceptsMenuButtonForever"));
10544 $SBSCopyIconImagePNGDataForDisplayIdentifier = reinterpret_cast<NSData *(*)(NSString *)>(dlsym(RTLD_DEFAULT, "SBSCopyIconImagePNGDataForDisplayIdentifier"));
10546 const char *symbol(kCFCoreFoundationVersionNumber >= 800 ? "MGGetBoolAnswer" : "GSSystemHasCapability");
10547 BOOL (*GSSystemHasCapability)(CFStringRef) = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, symbol));
10548 bool fast = GSSystemHasCapability != NULL && GSSystemHasCapability(CFSTR("armv7"));
10550 PulseInterval_ = fast ? 50000 : 500000;
10552 Colon_ = UCLocalize("COLON_DELIMITED");
10553 Elision_ = UCLocalize("ELISION");
10554 Error_ = UCLocalize("ERROR");
10555 Warning_ = UCLocalize("WARNING");
10558 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10560 CGColorSpaceRelease(space_);
10561 CFRelease(Locale_);