1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2015 Jay Freeman (saurik)
5 /* GNU General Public License, Version 3 {{{ */
7 * Cydia is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published
9 * by the Free Software Foundation, either version 3 of the License,
10 * or (at your option) any later version.
12 * Cydia is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Cydia. If not, see <http://www.gnu.org/licenses/>.
22 // XXX: wtf/FastMalloc.h... wtf?
23 #define USE_SYSTEM_MALLOC 1
25 /* #include Directives {{{ */
26 #include "CyteKit/UCPlatform.h"
27 #include "CyteKit/Localize.h"
29 #include <unicode/ustring.h>
30 #include <unicode/utrans.h>
32 #include <objc/objc.h>
33 #include <objc/runtime.h>
35 #include <CoreGraphics/CoreGraphics.h>
36 #include <Foundation/Foundation.h>
39 #define DEPLOYMENT_TARGET_MACOSX 1
40 #define CF_BUILDING_CF 1
41 #include <CoreFoundation/CFInternal.h>
44 #include <CoreFoundation/CFUniChar.h>
46 #include <SystemConfiguration/SystemConfiguration.h>
48 #include <UIKit/UIKit.h>
49 #include "iPhonePrivate.h"
51 #include <IOKit/IOKitLib.h>
53 #include <QuartzCore/CALayer.h>
55 #include <WebCore/WebCoreThread.h>
56 #include <WebKit/DOMHTMLIFrameElement.h>
64 #include <ext/stdio_filebuf.h>
68 #include <apt-pkg/acquire.h>
69 #include <apt-pkg/acquire-item.h>
70 #include <apt-pkg/algorithms.h>
71 #include <apt-pkg/cachefile.h>
72 #include <apt-pkg/clean.h>
73 #include <apt-pkg/configuration.h>
74 #include <apt-pkg/debindexfile.h>
75 #include <apt-pkg/debmetaindex.h>
76 #include <apt-pkg/error.h>
77 #include <apt-pkg/init.h>
78 #include <apt-pkg/mmap.h>
79 #include <apt-pkg/pkgrecords.h>
80 #include <apt-pkg/sha1.h>
81 #include <apt-pkg/sourcelist.h>
82 #include <apt-pkg/sptr.h>
83 #include <apt-pkg/strutl.h>
84 #include <apt-pkg/tagfile.h>
86 #include <sys/types.h>
88 #include <sys/sysctl.h>
89 #include <sys/param.h>
90 #include <sys/mount.h>
91 #include <sys/reboot.h>
99 #include <mach-o/nlist.h>
108 #include <Cytore.hpp>
111 #include "Substrate.hpp"
112 #include "Menes/Menes.h"
114 #include "CyteKit/IndirectDelegate.h"
115 #include "CyteKit/RegEx.hpp"
116 #include "CyteKit/TableViewCell.h"
117 #include "CyteKit/TabBarController.h"
118 #include "CyteKit/WebScriptObject-Cyte.h"
119 #include "CyteKit/WebViewController.h"
120 #include "CyteKit/WebViewTableViewCell.h"
121 #include "CyteKit/stringWithUTF8Bytes.h"
123 #include "Cydia/MIMEAddress.h"
124 #include "Cydia/LoadingViewController.h"
125 #include "Cydia/ProgressEvent.h"
127 #include "SDURLCache/SDURLCache.h"
134 #define _timestamp ({ \
136 gettimeofday(&tv, NULL); \
137 tv.tv_sec * 1000000 + tv.tv_usec; \
140 typedef std::vector<class ProfileTime *> TimeList;
150 ProfileTime(const char *name) :
154 times_.push_back(this);
157 void AddTime(uint64_t time) {
164 std::cerr << std::setw(7) << count_ << ", " << std::setw(8) << total_ << " : " << name_ << std::endl;
176 ProfileTimer(ProfileTime &time) :
183 time_.AddTime(_timestamp - start_);
188 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
190 std::cerr << "========" << std::endl;
193 #define _profile(name) { \
194 static ProfileTime name(#name); \
195 ProfileTimer _ ## name(name);
200 // XXX: I hate clang. Apple: please get over your petty hatred of GPL and fix your gcc fork
201 #define synchronized(lock) \
202 synchronized(static_cast<NSObject *>(lock))
204 extern NSString *Cydia_;
206 #define lprintf(args...) fprintf(stderr, args)
209 #define TraceLogging (1 && !ForRelease)
210 #define HistogramInsertionSort (0 && !ForRelease)
211 #define ProfileTimes (0 && !ForRelease)
212 #define ForSaurik (0 && !ForRelease)
213 #define LogBrowser (0 && !ForRelease)
214 #define TrackResize (0 && !ForRelease)
215 #define ManualRefresh (1 && !ForRelease)
216 #define ShowInternals (0 && !ForRelease)
217 #define AlwaysReload (0 && !ForRelease)
221 #define _trace(args...)
226 #define _profile(name) {
229 #define PrintTimes() do {} while (false)
232 // Hash Functions/Structures {{{
233 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
241 @implementation NSDictionary (Cydia)
242 - (id) invokeUndefinedMethodFromWebScript:(NSString *)name withArguments:(NSArray *)arguments {
244 else if ([name isEqualToString:@"get"])
245 return [self objectForKey:[arguments objectAtIndex:0]];
246 else if ([name isEqualToString:@"keys"])
247 return [self allKeys];
251 static NSString *Colon_;
253 static NSString *Error_;
254 static NSString *Warning_;
256 static NSString *Cache_;
257 #define Cache(file) \
258 [NSString stringWithFormat:@"%@/%s", Cache_, file]
260 static void (*$SBSSetInterceptsMenuButtonForever)(bool);
261 static NSData *(*$SBSCopyIconImagePNGDataForDisplayIdentifier)(NSString *);
263 static CFStringRef (*$MGCopyAnswer)(CFStringRef);
265 static NSString *UniqueIdentifier(UIDevice *device = nil) {
266 if (kCFCoreFoundationVersionNumber < 800) // iOS 7.x
267 return [device ?: [UIDevice currentDevice] uniqueIdentifier];
269 return [(id)$MGCopyAnswer(CFSTR("UniqueDeviceID")) autorelease];
272 static bool IsReachable(const char *name) {
273 SCNetworkReachabilityFlags flags; {
274 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, name));
275 SCNetworkReachabilityGetFlags(reachability, &flags);
276 CFRelease(reachability);
279 // XXX: this elaborate mess is what Apple is using to determine this? :(
280 // XXX: do we care if the user has to intervene? maybe that's ok?
282 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
283 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
284 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
285 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
286 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
287 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
292 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
294 static _finline NSString *CydiaURL(NSString *path) {
296 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
297 page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
298 page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
299 page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
300 page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
302 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
305 static NSString *ShellEscape(NSString *value) {
306 return [NSString stringWithFormat:@"'%@'", [value stringByReplacingOccurrencesOfString:@"'" withString:@"'\\''"]];
309 static _finline void UpdateExternalStatus(uint64_t newStatus) {
311 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
312 notify_set_state(notify_token, newStatus);
313 notify_cancel(notify_token);
315 notify_post("com.saurik.Cydia.status");
318 static CGFloat CYStatusBarHeight() {
319 CGSize size([[UIApplication sharedApplication] statusBarFrame].size);
320 return UIInterfaceOrientationIsPortrait([[UIApplication sharedApplication] statusBarOrientation]) ? size.height : size.width;
323 /* NSForcedOrderingSearch doesn't work on the iPhone */
324 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
325 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
326 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
328 /* Insertion Sort {{{ */
330 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
331 const char *ptr = (const char *)list;
333 CFIndex half = count / 2;
334 const char *probe = ptr + elementSize * half;
335 CFComparisonResult cr = comparator(element, probe, context);
336 if (0 == cr) return (probe - (const char *)list) / elementSize;
337 ptr = (cr < 0) ? ptr : probe + elementSize;
338 count = (cr < 0) ? half : (half + (count & 1) - 1);
340 return (ptr - (const char *)list) / elementSize;
343 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
344 const char *ptr = (const char *)list;
346 CFIndex half = count / 2;
347 const char *probe = ptr + elementSize * half;
348 CFComparisonResult cr = comparator(element, probe, context);
349 if (0 == cr) return (probe - (const char *)list) / elementSize;
350 ptr = (cr < 0) ? ptr : probe + elementSize;
351 count = (cr < 0) ? half : (half + (count & 1) - 1);
353 return (ptr - (const char *)list) / elementSize;
356 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
357 if (range.length == 0)
359 const void **values(new const void *[range.length]);
360 CFArrayGetValues(array, range, values);
362 #if HistogramInsertionSort > 0
363 uint32_t total(0), *offsets(new uint32_t[range.length]);
366 for (CFIndex index(1); index != range.length; ++index) {
367 const void *value(values[index]);
368 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
369 CFIndex correct(index);
370 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
371 #if HistogramInsertionSort > 1
372 NSLog(@"%@ < %@", value, values[correct - 1]);
377 if (correct != index) {
378 size_t offset(index - correct);
379 #if HistogramInsertionSort
383 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
385 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
386 values[correct] = value;
390 CFArrayReplaceValues(array, range, values, range.length);
393 #if HistogramInsertionSort > 0
394 for (CFIndex index(0); index != range.length; ++index)
395 if (offsets[index] != 0)
396 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
397 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
404 /* Apple Bug Fixes {{{ */
405 @implementation UIWebDocumentView (Cydia)
407 - (void) _setScrollerOffset:(CGPoint)offset {
408 UIScroller *scroller([self _scroller]);
410 CGSize size([scroller contentSize]);
411 CGSize bounds([scroller bounds].size);
414 max.x = size.width - bounds.width;
415 max.y = size.height - bounds.height;
423 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
424 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
426 [scroller setOffset:offset];
432 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
433 size_t length([self length] - state->state);
436 else if (length > count)
438 for (size_t i(0); i != length; ++i)
439 objects[i] = [self item:state->state++];
440 state->itemsPtr = objects;
441 state->mutationsPtr = (unsigned long *) self;
445 /* Cydia NSString Additions {{{ */
446 @interface NSString (Cydia)
447 - (NSComparisonResult) compareByPath:(NSString *)other;
448 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
451 @implementation NSString (Cydia)
453 - (NSComparisonResult) compareByPath:(NSString *)other {
454 NSString *prefix = [self commonPrefixWithString:other options:0];
455 size_t length = [prefix length];
457 NSRange lrange = NSMakeRange(length, [self length] - length);
458 NSRange rrange = NSMakeRange(length, [other length] - length);
460 lrange = [self rangeOfString:@"/" options:0 range:lrange];
461 rrange = [other rangeOfString:@"/" options:0 range:rrange];
463 NSComparisonResult value;
465 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
466 value = NSOrderedSame;
467 else if (lrange.location == NSNotFound)
468 value = NSOrderedAscending;
469 else if (rrange.location == NSNotFound)
470 value = NSOrderedDescending;
472 value = NSOrderedSame;
474 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
475 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
476 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
477 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
479 NSComparisonResult result = [lpath compare:rpath];
480 return result == NSOrderedSame ? value : result;
483 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
484 return [(id)CFURLCreateStringByAddingPercentEscapes(
489 kCFStringEncodingUTF8
496 /* C++ NSString Wrapper Cache {{{ */
497 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
498 return size == 0 ? NULL :
499 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
500 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
503 static _finline CFStringRef CYStringCreate(const char *data) {
504 return CYStringCreate(data, strlen(data));
513 _finline void clear_() {
514 if (cache_ != NULL) {
521 _finline bool empty() const {
525 _finline size_t size() const {
529 _finline char *data() const {
533 _finline void clear() {
538 _finline CYString() :
545 _finline ~CYString() {
549 void operator =(const CYString &rhs) {
553 if (rhs.cache_ == nil)
556 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
559 void copy(CYPool *pool) {
560 char *temp(pool->malloc<char>(size_ + 1));
561 memcpy(temp, data_, size_);
566 void set(CYPool *pool, const char *data, size_t size) {
572 data_ = const_cast<char *>(data);
580 _finline void set(CYPool *pool, const char *data) {
581 set(pool, data, data == NULL ? 0 : strlen(data));
584 _finline void set(CYPool *pool, const std::string &rhs) {
585 set(pool, rhs.data(), rhs.size());
588 bool operator ==(const CYString &rhs) const {
589 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
592 _finline operator CFStringRef() {
594 cache_ = CYStringCreate(data_, size_);
598 _finline operator id() {
599 return (NSString *) static_cast<CFStringRef>(*this);
602 _finline operator const char *() {
603 return reinterpret_cast<const char *>(data_);
607 /* C++ NSString Algorithm Adapters {{{ */
609 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
612 struct NSStringMapHash :
613 std::unary_function<NSString *, size_t>
615 _finline size_t operator ()(NSString *value) const {
616 return CFStringHashNSString((CFStringRef) value);
620 struct NSStringMapLess :
621 std::binary_function<NSString *, NSString *, bool>
623 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
624 return [lhs compare:rhs] == NSOrderedAscending;
628 struct NSStringMapEqual :
629 std::binary_function<NSString *, NSString *, bool>
631 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
632 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
633 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
634 //[lhs isEqualToString:rhs];
639 /* CoreGraphics Primitives {{{ */
644 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
645 CGFloat color[] = {red, green, blue, alpha};
646 return CGColorCreate(space, color);
655 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
656 color_(Create_(space, red, green, blue, alpha))
658 Set(space, red, green, blue, alpha);
663 CGColorRelease(color_);
670 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
672 color_ = Create_(space, red, green, blue, alpha);
675 operator CGColorRef() {
681 /* Random Global Variables {{{ */
682 static int PulseInterval_ = 500000;
684 static const NSString *UI_;
687 static bool RestartSubstrate_;
688 static NSArray *Finishes_;
690 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
691 #define NotifyConfig_ "/etc/notify.conf"
693 static bool Queuing_;
695 static CYColor Blue_;
696 static CYColor Blueish_;
697 static CYColor Black_;
698 static CYColor Folder_;
700 static CYColor White_;
701 static CYColor Gray_;
702 static CYColor Green_;
703 static CYColor Purple_;
704 static CYColor Purplish_;
706 static UIColor *InstallingColor_;
707 static UIColor *RemovingColor_;
709 static NSString *App_;
711 static BOOL Advanced_;
712 static BOOL Ignored_;
714 static _H<UIFont> Font12_;
715 static _H<UIFont> Font12Bold_;
716 static _H<UIFont> Font14_;
717 static _H<UIFont> Font18_;
718 static _H<UIFont> Font18Bold_;
719 static _H<UIFont> Font22Bold_;
721 static const char *Machine_ = NULL;
722 static _H<NSString> System_;
723 static NSString *SerialNumber_ = nil;
724 static NSString *ChipID_ = nil;
725 static NSString *BBSNum_ = nil;
726 static _H<NSString> UniqueID_;
727 static _H<NSString> UserAgent_;
728 static _H<NSString> Product_;
729 static _H<NSString> Safari_;
731 static _H<NSLocale> CollationLocale_;
732 static _H<NSArray> CollationThumbs_;
733 static std::vector<NSInteger> CollationOffset_;
734 static _H<NSArray> CollationTitles_;
735 static _H<NSArray> CollationStarts_;
736 static UTransliterator *CollationTransl_;
737 //static Function<NSString *, NSString *> CollationModify_;
739 typedef std::basic_string<UChar> ustring;
740 static ustring CollationString_;
742 #define CUC const ustring &str(*reinterpret_cast<const ustring *>(rep))
743 #define UC ustring &str(*reinterpret_cast<ustring *>(rep))
744 static struct UReplaceableCallbacks CollationUCalls_ = {
745 .length = [](const UReplaceable *rep) -> int32_t { CUC;
749 .charAt = [](const UReplaceable *rep, int32_t offset) -> UChar { CUC;
750 //fprintf(stderr, "charAt(%d) : %d\n", offset, str.size());
751 if (offset >= str.size())
756 .char32At = [](const UReplaceable *rep, int32_t offset) -> UChar32 { CUC;
757 //fprintf(stderr, "char32At(%d) : %d\n", offset, str.size());
758 if (offset >= str.size())
761 U16_GET(str.data(), 0, offset, str.size(), c);
765 .replace = [](UReplaceable *rep, int32_t start, int32_t limit, const UChar *text, int32_t length) -> void { UC;
766 //fprintf(stderr, "replace(%d, %d, %d) : %d\n", start, limit, length, str.size());
767 str.replace(start, limit - start, text, length);
770 .extract = [](UReplaceable *rep, int32_t start, int32_t limit, UChar *dst) -> void { UC;
771 //fprintf(stderr, "extract(%d, %d) : %d\n", start, limit, str.size());
772 str.copy(dst, limit - start, start);
775 .copy = [](UReplaceable *rep, int32_t start, int32_t limit, int32_t dest) -> void { UC;
776 //fprintf(stderr, "copy(%d, %d, %d) : %d\n", start, limit, dest, str.size());
777 str.replace(dest, 0, str, start, limit - start);
781 static CFLocaleRef Locale_;
782 static NSArray *Languages_;
783 static CGColorSpaceRef space_;
785 #define CacheState_ "/var/mobile/Library/Caches/com.saurik.Cydia/CacheState.plist"
786 #define SavedState_ "/var/mobile/Library/Caches/com.saurik.Cydia/SavedState.plist"
788 static NSDictionary *SectionMap_;
789 static _H<NSDate> Backgrounded_;
790 static _transient NSMutableDictionary *Values_;
791 static _transient NSMutableDictionary *Sections_;
792 _H<NSMutableDictionary> Sources_;
793 static _transient NSNumber *Version_;
797 CGFloat ScreenScale_;
798 static NSString *Idiom_;
799 static _H<NSString> Firmware_;
800 static NSString *Major_;
802 static _H<NSMutableDictionary> SessionData_;
803 static _H<NSObject> HostConfig_;
804 static _H<NSMutableSet> BridgedHosts_;
805 static _H<NSMutableSet> InsecureHosts_;
806 static _H<NSMutableSet> PipelinedHosts_;
807 static _H<NSMutableSet> CachedURLs_;
809 static NSString *kCydiaProgressEventTypeError = @"Error";
810 static NSString *kCydiaProgressEventTypeInformation = @"Information";
811 static NSString *kCydiaProgressEventTypeStatus = @"Status";
812 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
815 /* Display Helpers {{{ */
816 inline float Interpolate(float begin, float end, float fraction) {
817 return (end - begin) * fraction + begin;
820 static inline double Retina(double value) {
821 value *= ScreenScale_;
822 value = round(value);
823 value /= ScreenScale_;
827 static inline CGRect Retina(CGRect value) {
828 value.origin.x *= ScreenScale_;
829 value.origin.y *= ScreenScale_;
830 value.size.width *= ScreenScale_;
831 value.size.height *= ScreenScale_;
832 value = CGRectIntegral(value);
833 value.origin.x /= ScreenScale_;
834 value.origin.y /= ScreenScale_;
835 value.size.width /= ScreenScale_;
836 value.size.height /= ScreenScale_;
840 static _finline const char *StripVersion_(const char *version) {
841 const char *colon(strchr(version, ':'));
842 return colon == NULL ? version : colon + 1;
845 NSString *LocalizeSection(NSString *section) {
846 static RegEx title_r("(.*?) \\((.*)\\)");
847 if (title_r(section)) {
848 NSString *parent(title_r[1]);
849 NSString *child(title_r[2]);
851 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
852 LocalizeSection(parent),
853 LocalizeSection(child)
857 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
860 NSString *Simplify(NSString *title) {
861 const char *data = [title UTF8String];
862 size_t size = [title lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
864 static RegEx square_r("\\[(.*)\\]");
865 if (square_r(data, size))
866 return Simplify(square_r[1]);
868 static RegEx paren_r("\\((.*)\\)");
869 if (paren_r(data, size))
870 return Simplify(paren_r[1]);
872 static RegEx title_r("(.*?) \\((.*)\\)");
873 if (title_r(data, size))
874 return Simplify(title_r[1]);
880 bool isSectionVisible(NSString *section) {
881 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
882 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
883 return hidden == nil || ![hidden boolValue];
886 static NSObject *CYIOGetValue(const char *path, NSString *property) {
887 io_registry_entry_t entry(IORegistryEntryFromPath(kIOMasterPortDefault, path));
888 if (entry == MACH_PORT_NULL)
891 CFTypeRef value(IORegistryEntryCreateCFProperty(entry, (CFStringRef) property, kCFAllocatorDefault, 0));
892 IOObjectRelease(entry);
896 return [(id) value autorelease];
899 static NSString *CYHex(NSData *data, bool reverse = false) {
903 size_t length([data length]);
904 uint8_t bytes[length];
905 [data getBytes:bytes];
907 char string[length * 2 + 1];
908 for (size_t i(0); i != length; ++i)
909 sprintf(string + i * 2, "%.2x", bytes[reverse ? length - i - 1 : i]);
911 return [NSString stringWithUTF8String:string];
914 static NSString *VerifySource(NSString *href) {
915 static RegEx href_r("(http(s?)://|file:///)[^# ]*");
917 [[[[UIAlertView alloc]
918 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("INVALID_URL")]
919 message:UCLocalize("INVALID_URL_EX")
921 cancelButtonTitle:UCLocalize("OK")
922 otherButtonTitles:nil
923 ] autorelease] show];
928 if (![href hasSuffix:@"/"])
929 href = [href stringByAppendingString:@"/"];
935 /* Delegate Prototypes {{{ */
938 @class CydiaProgressEvent;
940 @protocol DatabaseDelegate
941 - (void) repairWithSelector:(SEL)selector;
942 - (void) setConfigurationData:(NSString *)data;
943 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
946 @class CYPackageController;
948 @protocol SourceDelegate
949 - (void) setFetch:(NSNumber *)fetch;
952 @protocol FetchDelegate
953 - (bool) isSourceCancelled;
954 - (void) startSourceFetch:(NSString *)uri;
955 - (void) stopSourceFetch:(NSString *)uri;
958 @protocol CydiaDelegate
959 - (void) returnToCydia;
961 - (void) retainNetworkActivityIndicator;
962 - (void) releaseNetworkActivityIndicator;
963 - (void) clearPackage:(Package *)package;
964 - (void) installPackage:(Package *)package;
965 - (void) installPackages:(NSArray *)packages;
966 - (void) removePackage:(Package *)package;
967 - (void) beginUpdate;
969 - (bool) requestUpdate;
970 - (void) distUpgrade;
973 - (void) _saveConfig;
975 - (void) addSource:(NSDictionary *)source;
976 - (BOOL) addTrivialSource:(NSString *)href;
977 - (UIProgressHUD *) addProgressHUD;
978 - (void) removeProgressHUD:(UIProgressHUD *)hud;
979 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
980 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
984 /* CancelStatus {{{ */
986 public pkgAcquireStatus
997 virtual bool MediaChange(std::string media, std::string drive) {
1001 virtual void IMSHit(pkgAcquire::ItemDesc &desc) {
1005 virtual bool Pulse_(pkgAcquire *Owner) = 0;
1007 virtual bool Pulse(pkgAcquire *Owner) {
1008 if (pkgAcquireStatus::Pulse(Owner) && Pulse_(Owner))
1016 _finline bool WasCancelled() const {
1021 /* DelegateStatus {{{ */
1026 _transient NSObject<ProgressDelegate> *delegate_;
1034 void setDelegate(NSObject<ProgressDelegate> *delegate) {
1035 delegate_ = delegate;
1038 virtual void Fetch(pkgAcquire::ItemDesc &desc) {
1039 NSString *name([NSString stringWithUTF8String:desc.ShortDesc.c_str()]);
1040 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItemDesc:desc]);
1041 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1044 virtual void Done(pkgAcquire::ItemDesc &desc) {
1045 NSString *name([NSString stringWithUTF8String:desc.ShortDesc.c_str()]);
1046 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:Colon_, UCLocalize("DONE"), name] ofType:kCydiaProgressEventTypeStatus forItemDesc:desc]);
1047 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1050 virtual void Fail(pkgAcquire::ItemDesc &desc) {
1052 desc.Owner->Status == pkgAcquire::Item::StatIdle ||
1053 desc.Owner->Status == pkgAcquire::Item::StatDone
1057 std::string &error(desc.Owner->ErrorText);
1061 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItemDesc:desc]);
1062 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1065 virtual bool Pulse_(pkgAcquire *Owner) {
1067 double(CurrentBytes + CurrentItems) /
1068 double(TotalBytes + TotalItems)
1071 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
1072 [NSNumber numberWithDouble:percent], @"Percent",
1074 [NSNumber numberWithDouble:CurrentBytes], @"Current",
1075 [NSNumber numberWithDouble:TotalBytes], @"Total",
1076 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
1077 nil] waitUntilDone:YES];
1079 return ![delegate_ isProgressCancelled];
1082 virtual void Start() {
1083 pkgAcquireStatus::Start();
1084 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
1087 virtual void Stop() {
1088 pkgAcquireStatus::Stop();
1089 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
1090 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
1094 /* Database Interface {{{ */
1095 typedef std::map< unsigned long, _H<Source> > SourceMap;
1097 @interface Database : NSObject {
1104 pkgCacheFile cache_;
1105 pkgDepCache::Policy *policy_;
1106 pkgRecords *records_;
1107 pkgProblemResolver *resolver_;
1108 pkgAcquire *fetcher_;
1110 SPtr<pkgPackageManager> manager_;
1111 pkgSourceList *list_;
1113 SourceMap sourceMap_;
1114 _H<NSMutableArray> sourceList_;
1116 CFMutableArrayRef packages_;
1118 _transient NSObject<DatabaseDelegate> *delegate_;
1119 _transient NSObject<ProgressDelegate> *progress_;
1121 CydiaStatus status_;
1127 std::map<const char *, _H<NSString> > sections_;
1130 + (Database *) sharedInstance;
1133 - (void) _readCydia:(NSNumber *)fd;
1134 - (void) _readStatus:(NSNumber *)fd;
1135 - (void) _readOutput:(NSNumber *)fd;
1139 - (Package *) packageWithName:(NSString *)name;
1141 - (pkgCacheFile &) cache;
1142 - (pkgDepCache::Policy *) policy;
1143 - (pkgRecords *) records;
1144 - (pkgProblemResolver *) resolver;
1145 - (pkgAcquire &) fetcher;
1146 - (pkgSourceList &) list;
1147 - (NSArray *) packages;
1148 - (NSArray *) sources;
1149 - (Source *) sourceWithKey:(NSString *)key;
1150 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1158 - (void) updateWithStatus:(CancelStatus &)status;
1160 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1162 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1163 - (NSObject<ProgressDelegate> *) progressDelegate;
1165 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1166 - (void) setFetch:(bool)fetch forURI:(const char *)uri;
1167 - (void) resetFetch;
1169 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1173 /* SourceStatus {{{ */
1174 class SourceStatus :
1178 _transient NSObject<FetchDelegate> *delegate_;
1179 _transient Database *database_;
1180 std::set<std::string> fetches_;
1183 SourceStatus(NSObject<FetchDelegate> *delegate, Database *database) :
1184 delegate_(delegate),
1189 void Set(bool fetch, const std::string &uri) {
1191 if (!fetches_.insert(uri).second)
1194 if (fetches_.erase(uri) == 0)
1198 //printf("Set(%s, %s)\n", fetch ? "true" : "false", uri.c_str());
1199 [database_ setFetch:fetch forURI:uri.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 files_.insert(file);
1665 if (file.length() < sizeof("Packages.bz2") || file.substr(file.length() - sizeof("Packages.bz2")) != "/Packages.bz2")
1667 file = file.substr(0, file.length() - 4);
1668 files_.insert(file);
1669 files_.insert(file + ".gz");
1670 files_.insert(file + "Index");
1675 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1678 pkgTagFile tags(&fd);
1680 pkgTagSection section;
1687 {"default-icon", &defaultIcon_},
1688 {"depiction", &depiction_},
1689 {"description", &description_},
1691 {"origin", &origin_},
1692 {"support", &support_},
1693 {"version", &version_},
1696 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1697 const char *start, *end;
1699 if (section.Find(names[i].name_, start, end)) {
1700 CYString &value(*names[i].value_);
1701 value.set(pool, start, end - start);
1707 record_ = [Sources_ objectForKey:[self key]];
1709 NSURL *url([NSURL URLWithString:uri_]);
1713 host_ = [host_ lowercaseString];
1718 authority_ = [url path];
1721 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(CYPool *)pool {
1722 if ((self = [super init]) != nil) {
1723 era_ = [database era];
1724 database_ = database;
1727 _profile(Source$initWithMetaIndex$setMetaIndex)
1728 [self setMetaIndex:index inPool:pool];
1733 - (NSString *) getField:(NSString *)name {
1734 @synchronized (database_) {
1735 if ([database_ era] != era_ || index_ == NULL)
1738 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index_));
1743 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly)) {
1748 pkgTagFile tags(&fd);
1750 pkgTagSection section;
1753 const char *start, *end;
1754 if (!section.Find([name UTF8String], start, end))
1755 return (NSString *) [NSNull null];
1757 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
1760 - (NSComparisonResult) compareByName:(Source *)source {
1761 NSString *lhs = [self name];
1762 NSString *rhs = [source name];
1764 if ([lhs length] != 0 && [rhs length] != 0) {
1765 unichar lhc = [lhs characterAtIndex:0];
1766 unichar rhc = [rhs characterAtIndex:0];
1768 if (isalpha(lhc) && !isalpha(rhc))
1769 return NSOrderedAscending;
1770 else if (!isalpha(lhc) && isalpha(rhc))
1771 return NSOrderedDescending;
1774 return [lhs compare:rhs options:LaxCompareOptions_];
1777 - (NSString *) depictionForPackage:(NSString *)package {
1778 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1781 - (NSString *) supportForPackage:(NSString *)package {
1782 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1785 - (NSArray *) sections {
1786 return record_ == nil ? (id) [NSNull null] : [record_ objectForKey:@"Sections"] ?: [NSArray array];
1789 - (void) _addSection:(NSString *)section {
1792 else if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) {
1793 if (![sections containsObject:section])
1794 [sections addObject:section];
1796 [record_ setObject:[NSMutableArray arrayWithObject:section] forKey:@"Sections"];
1799 - (bool) addSection:(NSString *)section {
1803 [self performSelectorOnMainThread:@selector(_addSection:) withObject:section waitUntilDone:NO];
1807 - (void) _removeSection:(NSString *)section {
1811 if (NSMutableArray *sections = [record_ objectForKey:@"Sections"])
1812 if ([sections containsObject:section])
1813 [sections removeObject:section];
1816 - (bool) removeSection:(NSString *)section {
1820 [self performSelectorOnMainThread:@selector(_removeSection:) withObject:section waitUntilDone:NO];
1825 [Sources_ removeObjectForKey:[self key]];
1829 bool value(record_ != nil);
1830 [self performSelectorOnMainThread:@selector(_remove) withObject:nil waitUntilDone:NO];
1834 - (NSDictionary *) record {
1842 - (NSString *) rooturi {
1846 - (NSString *) distribution {
1847 return distribution_;
1850 - (NSString *) type {
1854 - (NSString *) baseuri {
1855 return base_.empty() ? nil : (id) base_;
1858 - (NSString *) iconuri {
1859 if (NSString *base = [self baseuri])
1860 return [base stringByAppendingString:@"CydiaIcon.png"];
1865 - (NSURL *) iconURL {
1866 if (NSString *uri = [self iconuri])
1867 return [NSURL URLWithString:uri];
1871 - (NSString *) key {
1872 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1875 - (NSString *) host {
1879 - (NSString *) name {
1880 return origin_.empty() ? (id) authority_ : origin_;
1883 - (NSString *) shortDescription {
1884 return description_;
1887 - (NSString *) label {
1888 return label_.empty() ? (id) authority_ : label_;
1891 - (NSString *) origin {
1895 - (NSString *) version {
1899 - (NSString *) defaultIcon {
1900 return defaultIcon_;
1903 - (void) setDelegate:(NSObject<SourceDelegate> *)delegate {
1904 delegate_ = delegate;
1908 return !fetches_.empty();
1911 - (void) setFetch:(bool)fetch forURI:(const char *)uri {
1913 if (fetches_.erase(uri) == 0)
1915 } else if (files_.find(uri) == files_.end())
1917 else if (!fetches_.insert(uri).second)
1920 [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:[self fetch]] waitUntilDone:NO];
1923 - (void) resetFetch {
1925 [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:NO];
1930 /* CydiaOperation Class {{{ */
1931 @interface CydiaOperation : NSObject {
1932 _H<NSString> operator_;
1933 _H<NSString> value_;
1936 - (NSString *) operator;
1937 - (NSString *) value;
1941 @implementation CydiaOperation
1943 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1944 if ((self = [super init]) != nil) {
1945 operator_ = [NSString stringWithUTF8String:_operator];
1946 value_ = [NSString stringWithUTF8String:value];
1950 + (NSArray *) _attributeKeys {
1951 return [NSArray arrayWithObjects:
1957 - (NSArray *) attributeKeys {
1958 return [[self class] _attributeKeys];
1961 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1962 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1965 - (NSString *) operator {
1969 - (NSString *) value {
1975 /* CydiaClause Class {{{ */
1976 @interface CydiaClause : NSObject {
1977 _H<NSString> package_;
1978 _H<CydiaOperation> version_;
1981 - (NSString *) package;
1982 - (CydiaOperation *) version;
1986 @implementation CydiaClause
1988 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1989 if ((self = [super init]) != nil) {
1990 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1992 if (const char *version = dep.TargetVer())
1993 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1995 version_ = (id) [NSNull null];
1999 + (NSArray *) _attributeKeys {
2000 return [NSArray arrayWithObjects:
2006 - (NSArray *) attributeKeys {
2007 return [[self class] _attributeKeys];
2010 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2011 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2014 - (NSString *) package {
2018 - (CydiaOperation *) version {
2024 /* CydiaRelation Class {{{ */
2025 @interface CydiaRelation : NSObject {
2026 _H<NSString> relationship_;
2027 _H<NSMutableArray> clauses_;
2030 - (NSString *) relationship;
2031 - (NSArray *) clauses;
2035 @implementation CydiaRelation
2037 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
2038 if ((self = [super init]) != nil) {
2039 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
2040 clauses_ = [NSMutableArray arrayWithCapacity:8];
2042 pkgCache::DepIterator start;
2043 pkgCache::DepIterator end;
2044 dep.GlobOr(start, end); // ++dep
2047 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
2049 // yes, seriously. (wtf?)
2057 + (NSArray *) _attributeKeys {
2058 return [NSArray arrayWithObjects:
2064 - (NSArray *) attributeKeys {
2065 return [[self class] _attributeKeys];
2068 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2069 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2072 - (NSString *) relationship {
2073 return relationship_;
2076 - (NSArray *) clauses {
2080 - (void) addClause:(CydiaClause *)clause {
2081 [clauses_ addObject:clause];
2086 /* Package Class {{{ */
2087 struct ParsedPackage {
2091 CYString architecture_;
2094 CYString depiction_;
2101 @interface Package : NSObject {
2103 @public uint32_t role_ : 3;
2104 uint32_t essential_ : 1;
2105 uint32_t obsolete_ : 1;
2106 uint32_t ignored_ : 1;
2107 uint32_t pooled_ : 1;
2113 _transient Database *database_;
2115 pkgCache::VerIterator version_;
2116 pkgCache::PkgIterator iterator_;
2117 pkgCache::VerFileIterator file_;
2121 CYString transform_;
2124 CYString installed_;
2127 const char *section_;
2128 _transient NSString *section$_;
2132 PackageValue *metadata_;
2133 ParsedPackage *parsed_;
2135 _H<NSMutableArray> tags_;
2138 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database;
2139 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database;
2141 - (pkgCache::PkgIterator) iterator;
2144 - (NSString *) section;
2145 - (NSString *) simpleSection;
2147 - (NSString *) longSection;
2148 - (NSString *) shortSection;
2152 - (MIMEAddress *) maintainer;
2154 - (NSString *) longDescription;
2155 - (NSString *) shortDescription;
2158 - (PackageValue *) metadata;
2161 - (bool) subscribed;
2162 - (bool) setSubscribed:(bool)subscribed;
2166 - (NSString *) latest;
2167 - (NSString *) installed;
2168 - (BOOL) uninstalled;
2170 - (BOOL) upgradableAndEssential:(BOOL)essential;
2173 - (BOOL) unfiltered;
2177 - (BOOL) halfConfigured;
2178 - (BOOL) halfInstalled;
2180 - (NSString *) mode;
2183 - (NSString *) name;
2185 - (NSString *) homepage;
2186 - (NSString *) depiction;
2187 - (MIMEAddress *) author;
2189 - (NSString *) support;
2191 - (NSArray *) files;
2192 - (NSArray *) warnings;
2193 - (NSArray *) applications;
2195 - (Source *) source;
2198 - (BOOL) matches:(NSArray *)query;
2200 - (BOOL) hasTag:(NSString *)tag;
2201 - (NSString *) primaryPurpose;
2202 - (NSArray *) purposes;
2203 - (bool) isCommercial;
2205 - (void) setIndex:(size_t)index;
2207 - (CYString &) cyname;
2209 - (uint32_t) compareBySection:(NSArray *)sections;
2216 uint32_t PackageChangesRadix(Package *self, void *) {
2221 uint32_t timestamp : 30;
2222 uint32_t ignored : 1;
2223 uint32_t upgradable : 1;
2227 bool upgradable([self upgradableAndEssential:YES]);
2228 value.bits.upgradable = upgradable ? 1 : 0;
2231 value.bits.timestamp = 0;
2232 value.bits.ignored = [self ignored] ? 0 : 1;
2233 value.bits.upgradable = 1;
2235 value.bits.timestamp = [self seen] >> 2;
2236 value.bits.ignored = 0;
2237 value.bits.upgradable = 0;
2240 return _not(uint32_t) - value.key;
2243 CYString &(*PackageName)(Package *self, SEL sel);
2245 uint32_t PackagePrefixRadix(Package *self, void *context) {
2246 size_t offset(reinterpret_cast<size_t>(context));
2247 CYString &name(PackageName(self, @selector(cyname)));
2249 size_t size(name.size());
2252 char *text(name.data());
2255 if (!isdigit(text[0]))
2259 while (size != digits && isdigit(text[digits]))
2267 if (offset == 0 && zeros != 0) {
2268 memset(data, '0', zeros);
2269 memcpy(data + zeros, text, 4 - zeros);
2271 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2272 if (size <= offset - zeros)
2275 text += offset - zeros;
2276 size -= offset - zeros;
2279 memcpy(data, text, 4);
2281 memcpy(data, text, size);
2282 memset(data + size, 0, 4 - size);
2285 for (size_t i(0); i != 4; ++i)
2286 if (isalpha(data[i]))
2294 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2296 /* XXX: ntohl may be more honest */
2297 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2300 CFComparisonResult StringNameCompare(CFStringRef lhn, CFStringRef rhn, size_t length) {
2301 _profile(PackageNameCompare)
2303 return rhn == NULL ? kCFCompareEqualTo : kCFCompareLessThan;
2304 else if (rhn == NULL)
2305 return kCFCompareGreaterThan;
2307 CFIndex length(CFStringGetLength(lhn));
2309 _profile(PackageNameCompare$NumbersLast)
2310 if (length != 0 && CFStringGetLength(rhn) != 0) {
2311 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2312 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2313 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2314 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2315 return lha ? kCFCompareLessThan : kCFCompareGreaterThan;
2319 _profile(PackageNameCompare$Compare)
2320 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, (CFLocaleRef) (id) CollationLocale_);
2325 _finline CFComparisonResult StringNameCompare(NSString *lhn, NSString*rhn, size_t length) {
2326 return StringNameCompare((CFStringRef) lhn, (CFStringRef) rhn, length);
2329 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2330 CYString &lhn(PackageName(lhs, @selector(cyname)));
2331 NSString *rhn(PackageName(rhs, @selector(cyname)));
2332 return StringNameCompare(lhn, rhn, lhn.size());
2335 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *arg) {
2336 return PackageNameCompare(*lhs, *rhs, arg);
2339 struct PackageNameOrdering :
2340 std::binary_function<Package *, Package *, bool>
2342 _finline bool operator ()(Package *lhs, Package *rhs) const {
2343 return PackageNameCompare(lhs, rhs, NULL) == kCFCompareLessThan;
2347 @implementation Package
2349 - (NSString *) description {
2350 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2356 if (parsed_ != NULL)
2361 + (NSString *) webScriptNameForSelector:(SEL)selector {
2363 else if (selector == @selector(clear))
2365 else if (selector == @selector(getField:))
2367 else if (selector == @selector(getRecord))
2368 return @"getRecord";
2369 else if (selector == @selector(hasTag:))
2371 else if (selector == @selector(install))
2373 else if (selector == @selector(remove))
2379 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2380 return [self webScriptNameForSelector:selector] == nil;
2383 + (NSArray *) _attributeKeys {
2384 return [NSArray arrayWithObjects:
2405 @"shortDescription",
2418 - (NSArray *) attributeKeys {
2419 return [[self class] _attributeKeys];
2422 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2423 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2426 - (NSArray *) relations {
2427 @synchronized (database_) {
2428 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2429 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2430 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2434 - (NSString *) architecture {
2436 @synchronized (database_) {
2437 return parsed_->architecture_.empty() ? [NSNull null] : (id) parsed_->architecture_;
2440 - (NSString *) getField:(NSString *)name {
2441 @synchronized (database_) {
2442 if ([database_ era] != era_ || file_.end())
2445 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2447 const char *start, *end;
2448 if (!parser.Find([name UTF8String], start, end))
2449 return (NSString *) [NSNull null];
2451 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2454 - (NSString *) getRecord {
2455 @synchronized (database_) {
2456 if ([database_ era] != era_ || file_.end())
2459 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2461 const char *start, *end;
2462 parser.GetRec(start, end);
2464 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2468 if (parsed_ != NULL)
2470 @synchronized (database_) {
2471 if ([database_ era] != era_ || file_.end())
2474 ParsedPackage *parsed(new ParsedPackage);
2477 _profile(Package$parse)
2478 pkgRecords::Parser *parser;
2480 _profile(Package$parse$Lookup)
2481 parser = &[database_ records]->Lookup(file_);
2487 _profile(Package$parse$Find)
2492 {"architecture", &parsed->architecture_},
2493 {"icon", &parsed->icon_},
2494 {"depiction", &parsed->depiction_},
2495 {"homepage", &parsed->homepage_},
2496 {"website", &website},
2498 {"support", &parsed->support_},
2499 {"author", &parsed->author_},
2500 {"md5sum", &parsed->md5sum_},
2503 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2504 const char *start, *end;
2506 if (parser->Find(names[i].name_, start, end)) {
2507 CYString &value(*names[i].value_);
2508 _profile(Package$parse$Value)
2509 value.set(pool_, start, end - start);
2515 _profile(Package$parse$Tagline)
2516 const char *start, *end;
2517 if (parser->ShortDesc(start, end)) {
2518 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2521 while (stop != start && stop[-1] == '\r')
2523 parsed->tagline_.set(pool_, start, stop - start);
2527 _profile(Package$parse$Retain)
2528 if (parsed->homepage_.empty())
2529 parsed->homepage_ = website;
2530 if (parsed->homepage_ == parsed->depiction_)
2531 parsed->homepage_.clear();
2532 if (parsed->support_.empty())
2533 parsed->support_ = bugs;
2538 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database {
2539 if ((self = [super init]) != nil) {
2540 _profile(Package$initWithVersion)
2542 pool_ = new CYPool();
2548 database_ = database;
2549 era_ = [database era];
2553 pkgCache::PkgIterator iterator(version.ParentPkg());
2554 iterator_ = iterator;
2556 _profile(Package$initWithVersion$Version)
2557 file_ = version_.FileList();
2560 _profile(Package$initWithVersion$Cache)
2561 name_.set(NULL, iterator.Display());
2563 latest_.set(NULL, StripVersion_(version_.VerStr()));
2565 pkgCache::VerIterator current(iterator.CurrentVer());
2567 installed_.set(NULL, StripVersion_(current.VerStr()));
2570 _profile(Package$initWithVersion$Transliterate) do {
2571 if (CollationTransl_ == NULL)
2576 _profile(Package$initWithVersion$Transliterate$utf8)
2577 const uint8_t *data(reinterpret_cast<const uint8_t *>(name_.data()));
2578 for (size_t i(0), e(name_.size()); i != e; ++i)
2579 if (data[i] >= 0x80)
2584 UErrorCode code(U_ZERO_ERROR);
2587 _profile(Package$initWithVersion$Transliterate$u_strFromUTF8WithSub)
2588 CollationString_.resize(name_.size());
2589 u_strFromUTF8WithSub(&CollationString_[0], CollationString_.size(), &length, name_.data(), name_.size(), 0xfffd, NULL, &code);
2590 if (!U_SUCCESS(code))
2592 CollationString_.resize(length);
2595 _profile(Package$initWithVersion$Transliterate$utrans_trans)
2596 length = CollationString_.size();
2597 utrans_trans(CollationTransl_, reinterpret_cast<UReplaceable *>(&CollationString_), &CollationUCalls_, 0, &length, &code);
2598 if (!U_SUCCESS(code))
2600 _assert(CollationString_.size() == length);
2603 _profile(Package$initWithVersion$Transliterate$u_strToUTF8WithSub$preflight)
2604 u_strToUTF8WithSub(NULL, 0, &length, CollationString_.data(), CollationString_.size(), 0xfffd, NULL, &code);
2605 if (code == U_BUFFER_OVERFLOW_ERROR)
2606 code = U_ZERO_ERROR;
2607 else if (!U_SUCCESS(code))
2612 _profile(Package$initWithVersion$Transliterate$apr_palloc)
2613 transform = pool_->malloc<char>(length);
2615 _profile(Package$initWithVersion$Transliterate$u_strToUTF8WithSub$transform)
2616 u_strToUTF8WithSub(transform, length, NULL, CollationString_.data(), CollationString_.size(), 0xfffd, NULL, &code);
2617 if (!U_SUCCESS(code))
2621 transform_.set(NULL, transform, length);
2622 } while (false); _end
2624 _profile(Package$initWithVersion$Tags)
2625 pkgCache::TagIterator tag(iterator.TagList());
2627 tags_ = [NSMutableArray arrayWithCapacity:8];
2629 goto tag; for (; !tag.end(); ++tag) tag: {
2630 const char *name(tag.Name());
2631 NSString *string((NSString *) CYStringCreate(name));
2635 [tags_ addObject:[string autorelease]];
2637 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2638 if (strcmp(name + 6, "enduser") == 0)
2640 else if (strcmp(name + 6, "hacker") == 0)
2642 else if (strcmp(name + 6, "developer") == 0)
2644 else if (strcmp(name + 6, "cydia") == 0)
2650 if (strncmp(name, "cydia::", 7) == 0) {
2651 if (strcmp(name + 7, "essential") == 0)
2653 else if (strcmp(name + 7, "obsolete") == 0)
2660 _profile(Package$initWithVersion$Metadata)
2661 const char *mixed(iterator.Name());
2662 size_t size(strlen(mixed));
2663 static const size_t prefix(sizeof("/var/lib/dpkg/info/") - 1);
2664 char lower[prefix + size + 5 + 1];
2666 for (size_t i(0); i != size; ++i)
2667 lower[prefix + i] = mixed[i] | 0x20;
2669 if (!installed_.empty()) {
2670 memcpy(lower, "/var/lib/dpkg/info/", prefix);
2671 memcpy(lower + prefix + size, ".list", 6);
2673 if (stat(lower, &info) != -1)
2674 upgraded_ = info.st_birthtime;
2677 PackageValue *metadata(PackageFind(lower + prefix, size));
2678 metadata_ = metadata;
2680 id_.set(NULL, metadata->name_, size);
2682 const char *latest(version_.VerStr());
2683 size_t length(strlen(latest));
2685 uint16_t vhash(hashlittle(latest, length));
2687 size_t capped(std::min<size_t>(8, length));
2688 latest = latest + length - capped;
2690 if (metadata->first_ == 0)
2691 metadata->first_ = now_;
2693 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2694 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2695 metadata->vhash_ = vhash;
2696 metadata->last_ = now_;
2697 } else if (metadata->last_ == 0)
2698 metadata->last_ = metadata->first_;
2701 _profile(Package$initWithVersion$Section)
2702 section_ = version_.Section();
2705 _profile(Package$initWithVersion$Flags)
2706 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2707 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2712 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database {
2713 pkgCache::VerIterator version;
2715 _profile(Package$packageWithIterator$GetCandidateVer)
2716 version = [database policy]->GetCandidateVer(iterator);
2724 _profile(Package$packageWithIterator$Allocate)
2725 package = [Package allocWithZone:zone];
2728 _profile(Package$packageWithIterator$Initialize)
2730 initWithVersion:version
2737 _profile(Package$packageWithIterator$Autorelease)
2738 package = [package autorelease];
2744 - (pkgCache::PkgIterator) iterator {
2748 - (NSArray *) downgrades {
2749 NSMutableArray *versions([NSMutableArray arrayWithCapacity:4]);
2751 for (auto version(iterator_.VersionList()); !version.end(); ++version) {
2752 if (version == version_)
2754 Package *package([[[Package allocWithZone:NULL] initWithVersion:version withZone:NULL inPool:NULL database:database_] autorelease]);
2755 if ([package source] == nil)
2757 [versions addObject:package];
2763 - (NSString *) section {
2764 if (section$_ == nil) {
2765 if (section_ == NULL)
2768 _profile(Package$section$mappedSectionForPointer)
2769 section$_ = [database_ mappedSectionForPointer:section_];
2774 - (NSString *) simpleSection {
2775 if (NSString *section = [self section])
2776 return Simplify(section);
2781 - (NSString *) longSection {
2782 if (NSString *section = [self section])
2783 return LocalizeSection(section);
2788 - (NSString *) shortSection {
2789 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2792 - (NSString *) uri {
2795 pkgIndexFile *index;
2796 pkgCache::PkgFileIterator file(file_.File());
2797 if (![database_ list].FindIndex(file, index))
2799 return [NSString stringWithUTF8String:iterator_->Path];
2800 //return [NSString stringWithUTF8String:file.Site()];
2801 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2805 - (MIMEAddress *) maintainer {
2806 @synchronized (database_) {
2807 if ([database_ era] != era_ || file_.end())
2810 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2811 const std::string &maintainer(parser->Maintainer());
2812 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2815 - (NSString *) md5sum {
2816 return parsed_ == NULL ? nil : (id) parsed_->md5sum_;
2820 @synchronized (database_) {
2821 if ([database_ era] != era_ || version_.end())
2824 return version_->InstalledSize;
2827 - (NSString *) longDescription {
2828 @synchronized (database_) {
2829 if ([database_ era] != era_ || file_.end())
2832 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2833 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2835 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2836 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2837 if ([lines count] < 2)
2840 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2841 for (size_t i(1), e([lines count]); i != e; ++i) {
2842 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2843 [trimmed addObject:trim];
2846 return [trimmed componentsJoinedByString:@"\n"];
2849 - (NSString *) shortDescription {
2850 if (parsed_ != NULL)
2851 return static_cast<NSString *>(parsed_->tagline_);
2853 @synchronized (database_) {
2854 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2856 const char *start, *end;
2857 if (!parser.ShortDesc(start, end))
2860 if (end - start > 200)
2864 if (const char *stop = reinterpret_cast<const char *>(memchr(start, '\n', end - start)))
2867 while (end != start && end[-1] == '\r')
2871 return [(id) CYStringCreate(start, end - start) autorelease];
2875 _profile(Package$index)
2876 CFStringRef name((CFStringRef) [self name]);
2877 if (CFStringGetLength(name) == 0)
2879 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2880 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2882 return toupper(character);
2886 - (PackageValue *) metadata {
2891 PackageValue *metadata([self metadata]);
2892 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2895 - (bool) subscribed {
2896 return [self metadata]->subscribed_;
2899 - (bool) setSubscribed:(bool)subscribed {
2900 PackageValue *metadata([self metadata]);
2901 if (metadata->subscribed_ == subscribed)
2903 metadata->subscribed_ = subscribed;
2911 - (NSString *) latest {
2915 - (NSString *) installed {
2919 - (BOOL) uninstalled {
2920 return installed_.empty();
2923 - (BOOL) upgradableAndEssential:(BOOL)essential {
2924 _profile(Package$upgradableAndEssential)
2925 pkgCache::VerIterator current(iterator_.CurrentVer());
2927 return essential && essential_;
2929 return version_ != current;
2933 - (BOOL) essential {
2938 return [database_ cache][iterator_].InstBroken();
2941 - (BOOL) unfiltered {
2942 _profile(Package$unfiltered$obsolete)
2943 if (_unlikely(obsolete_))
2947 _profile(Package$unfiltered$role)
2948 if (_unlikely(role_ > 3))
2956 if (![self unfiltered])
2961 _profile(Package$visible$section)
2962 section = [self section];
2965 _profile(Package$visible$isSectionVisible)
2966 if (!isSectionVisible(section))
2974 unsigned char current(iterator_->CurrentState);
2975 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2978 - (BOOL) halfConfigured {
2979 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2982 - (BOOL) halfInstalled {
2983 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2987 @synchronized (database_) {
2988 if ([database_ era] != era_ || iterator_.end())
2991 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2992 return state.Mode != pkgDepCache::ModeKeep;
2995 - (NSString *) mode {
2996 @synchronized (database_) {
2997 if ([database_ era] != era_ || iterator_.end())
3000 pkgDepCache::StateCache &state([database_ cache][iterator_]);
3002 switch (state.Mode) {
3003 case pkgDepCache::ModeDelete:
3004 if ((state.iFlags & pkgDepCache::Purge) != 0)
3008 case pkgDepCache::ModeKeep:
3009 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
3010 return @"REINSTALL";
3011 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
3015 case pkgDepCache::ModeInstall:
3016 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
3017 return @"REINSTALL";
3018 else*/ switch (state.Status) {
3020 return @"DOWNGRADE";
3026 return @"NEW_INSTALL";
3037 - (NSString *) name {
3038 return name_.empty() ? id_ : name_;
3041 - (UIImage *) icon {
3042 NSString *section = [self simpleSection];
3045 if (parsed_ != NULL)
3046 if (NSString *href = parsed_->icon_)
3047 if ([href hasPrefix:@"file:///"])
3048 icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
3049 if (icon == nil) if (section != nil)
3050 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]];
3051 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
3052 if ([dicon hasPrefix:@"file:///"])
3053 icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
3055 icon = [UIImage imageNamed:@"unknown.png"];
3059 - (NSString *) homepage {
3060 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
3063 - (NSString *) depiction {
3064 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
3067 - (MIMEAddress *) author {
3068 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
3071 - (NSString *) support {
3072 return parsed_ != NULL && !parsed_->support_.empty() ? parsed_->support_ : [[self source] supportForPackage:id_];
3075 - (NSArray *) files {
3076 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
3077 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
3080 fin.open([path UTF8String]);
3085 while (std::getline(fin, line))
3086 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
3091 - (NSString *) state {
3092 @synchronized (database_) {
3093 if ([database_ era] != era_ || file_.end())
3096 switch (iterator_->CurrentState) {
3097 case pkgCache::State::NotInstalled:
3098 return @"NotInstalled";
3099 case pkgCache::State::UnPacked:
3101 case pkgCache::State::HalfConfigured:
3102 return @"HalfConfigured";
3103 case pkgCache::State::HalfInstalled:
3104 return @"HalfInstalled";
3105 case pkgCache::State::ConfigFiles:
3106 return @"ConfigFiles";
3107 case pkgCache::State::Installed:
3108 return @"Installed";
3109 case pkgCache::State::TriggersAwaited:
3110 return @"TriggersAwaited";
3111 case pkgCache::State::TriggersPending:
3112 return @"TriggersPending";
3115 return (NSString *) [NSNull null];
3118 - (NSString *) selection {
3119 @synchronized (database_) {
3120 if ([database_ era] != era_ || file_.end())
3123 switch (iterator_->SelectedState) {
3124 case pkgCache::State::Unknown:
3126 case pkgCache::State::Install:
3128 case pkgCache::State::Hold:
3130 case pkgCache::State::DeInstall:
3131 return @"DeInstall";
3132 case pkgCache::State::Purge:
3136 return (NSString *) [NSNull null];
3139 - (NSArray *) warnings {
3140 @synchronized (database_) {
3141 if ([database_ era] != era_ || file_.end())
3144 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
3145 const char *name(iterator_.Name());
3147 size_t length(strlen(name));
3148 if (length < 2) invalid:
3149 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
3150 else for (size_t i(0); i != length; ++i)
3152 /* XXX: technically this is not allowed */
3153 (name[i] < 'A' || name[i] > 'Z') &&
3154 (name[i] < 'a' || name[i] > 'z') &&
3155 (name[i] < '0' || name[i] > '9') &&
3156 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
3159 if (strcmp(name, "cydia") != 0) {
3162 bool _private = false;
3164 bool dbstash = false;
3165 bool dsstore = false;
3167 bool repository = [[self section] isEqualToString:@"Repositories"];
3169 if (NSArray *files = [self files])
3170 for (NSString *file in files)
3171 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
3173 else if (!user && [file isEqualToString:@"/User"])
3175 else if (!_private && [file isEqualToString:@"/private"])
3177 else if (!stash && [file isEqualToString:@"/var/stash"])
3179 else if (!dbstash && [file isEqualToString:@"/var/db/stash"])
3181 else if (!dsstore && [file hasSuffix:@"/.DS_Store"])
3184 /* XXX: this is not sensitive enough. only some folders are valid. */
3185 if (cydia && !repository)
3186 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
3188 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
3190 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
3192 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
3194 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/db/stash"]];
3196 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @".DS_Store"]];
3199 return [warnings count] == 0 ? nil : warnings;
3202 - (NSArray *) applications {
3203 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
3205 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
3207 static RegEx application_r("/Applications/(.*)\\.app/Info.plist");
3208 if (NSArray *files = [self files])
3209 for (NSString *file in files)
3210 if (application_r(file)) {
3211 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
3214 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
3215 if (id == nil || [id isEqualToString:me])
3218 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
3220 display = application_r[1];
3222 NSString *bundle([file stringByDeletingLastPathComponent]);
3223 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
3224 // XXX: maybe this should check if this is really a string, not just for length
3225 if (icon == nil || ![icon respondsToSelector:@selector(length)] || [icon length] == 0)
3227 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
3229 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
3230 [applications addObject:application];
3232 [application addObject:id];
3233 [application addObject:display];
3234 [application addObject:url];
3237 return [applications count] == 0 ? nil : applications;
3240 - (Source *) source {
3241 if (source_ == nil) {
3242 @synchronized (database_) {
3243 if ([database_ era] != era_ || file_.end())
3244 source_ = (Source *) [NSNull null];
3246 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
3250 return source_ == (Source *) [NSNull null] ? nil : source_;
3253 - (time_t) upgraded {
3257 - (uint32_t) recent {
3258 return std::numeric_limits<uint32_t>::max() - upgraded_;
3265 - (BOOL) matches:(NSArray *)query {
3266 if (query == nil || [query count] == 0)
3275 string = [self name];
3276 length = [string length];
3279 for (NSString *term in query) {
3280 range = [string rangeOfString:term options:MatchCompareOptions_];
3281 if (range.location != NSNotFound)
3282 rank_ -= 6 * 1000000 / length;
3287 length = [string length];
3290 for (NSString *term in query) {
3291 range = [string rangeOfString:term options:MatchCompareOptions_];
3292 if (range.location != NSNotFound)
3293 rank_ -= 6 * 1000000 / length;
3297 string = [self shortDescription];
3298 length = [string length];
3299 NSUInteger stop(std::min<NSUInteger>(length, 200));
3302 for (NSString *term in query) {
3303 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
3304 if (range.location != NSNotFound)
3305 rank_ -= 2 * 100000;
3311 - (NSArray *) tags {
3315 - (BOOL) hasTag:(NSString *)tag {
3316 return tags_ == nil ? NO : [tags_ containsObject:tag];
3319 - (NSString *) primaryPurpose {
3320 for (NSString *tag in (NSArray *) tags_)
3321 if ([tag hasPrefix:@"purpose::"])
3322 return [tag substringFromIndex:9];
3326 - (NSArray *) purposes {
3327 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
3328 for (NSString *tag in (NSArray *) tags_)
3329 if ([tag hasPrefix:@"purpose::"])
3330 [purposes addObject:[tag substringFromIndex:9]];
3331 return [purposes count] == 0 ? nil : purposes;
3334 - (bool) isCommercial {
3335 return [self hasTag:@"cydia::commercial"];
3338 - (void) setIndex:(size_t)index {
3339 if (metadata_->index_ != index)
3340 metadata_->index_ = index;
3343 - (CYString &) cyname {
3344 return !transform_.empty() ? transform_ : !name_.empty() ? name_ : id_;
3347 - (uint32_t) compareBySection:(NSArray *)sections {
3348 NSString *section([self section]);
3349 for (size_t i(0), e([sections count]); i != e; ++i) {
3350 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3354 return _not(uint32_t);
3358 @synchronized (database_) {
3359 if ([database_ era] != era_ || file_.end())
3362 pkgProblemResolver *resolver = [database_ resolver];
3363 resolver->Clear(iterator_);
3365 pkgCacheFile &cache([database_ cache]);
3366 cache->SetReInstall(iterator_, false);
3367 cache->MarkKeep(iterator_, false);
3371 @synchronized (database_) {
3372 if ([database_ era] != era_ || file_.end())
3375 pkgProblemResolver *resolver = [database_ resolver];
3376 resolver->Clear(iterator_);
3377 resolver->Protect(iterator_);
3379 pkgCacheFile &cache([database_ cache]);
3380 cache->SetCandidateVersion(version_);
3381 cache->SetReInstall(iterator_, false);
3382 cache->MarkInstall(iterator_, false);
3384 pkgDepCache::StateCache &state((*cache)[iterator_]);
3385 if (!state.Install())
3386 cache->SetReInstall(iterator_, true);
3390 @synchronized (database_) {
3391 if ([database_ era] != era_ || file_.end())
3394 pkgProblemResolver *resolver = [database_ resolver];
3395 resolver->Clear(iterator_);
3396 resolver->Remove(iterator_);
3397 resolver->Protect(iterator_);
3399 pkgCacheFile &cache([database_ cache]);
3400 cache->SetReInstall(iterator_, false);
3401 cache->MarkDelete(iterator_, true);
3406 /* Section Class {{{ */
3407 @interface Section : NSObject {
3411 _H<NSString> localized_;
3414 - (NSComparisonResult) compareByLocalized:(Section *)section;
3415 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3416 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3417 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3419 - (NSString *) name;
3420 - (void) setName:(NSString *)name;
3426 - (void) addToCount;
3428 - (void) setCount:(size_t)count;
3429 - (NSString *) localized;
3433 @implementation Section
3435 - (NSComparisonResult) compareByLocalized:(Section *)section {
3436 NSString *lhs(localized_);
3437 NSString *rhs([section localized]);
3439 /*if ([lhs length] != 0 && [rhs length] != 0) {
3440 unichar lhc = [lhs characterAtIndex:0];
3441 unichar rhc = [rhs characterAtIndex:0];
3443 if (isalpha(lhc) && !isalpha(rhc))
3444 return NSOrderedAscending;
3445 else if (!isalpha(lhc) && isalpha(rhc))
3446 return NSOrderedDescending;
3449 return [lhs compare:rhs options:LaxCompareOptions_];
3452 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3453 if ((self = [self initWithName:name localize:NO]) != nil) {
3454 if (localized != nil)
3455 localized_ = localized;
3459 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3460 return [self initWithName:name row:0 localize:localize];
3463 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3464 if ((self = [super init]) != nil) {
3468 localized_ = LocalizeSection(name_);
3472 - (NSString *) name {
3476 - (void) setName:(NSString *)name {
3492 - (void) addToCount {
3496 - (void) setCount:(size_t)count {
3500 - (NSString *) localized {
3507 class CydiaLogCleaner :
3508 public pkgArchiveCleaner
3511 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3516 /* Database Implementation {{{ */
3517 @implementation Database
3519 + (Database *) sharedInstance {
3520 static _H<Database> instance;
3521 if (instance == nil)
3522 instance = [[[Database alloc] init] autorelease];
3530 - (void) releasePackages {
3531 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3532 CFArrayRemoveAllValues(packages_);
3536 // XXX: actually implement this thing
3538 [self releasePackages];
3539 NSRecycleZone(zone_);
3543 - (void) _readCydia:(NSNumber *)fd {
3544 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3545 std::istream is(&ib);
3548 static RegEx finish_r("finish:([^:]*)");
3550 while (std::getline(is, line)) {
3551 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3553 const char *data(line.c_str());
3554 size_t size = line.size();
3555 lprintf("C:%s\n", data);
3557 if (finish_r(data, size)) {
3558 NSString *finish = finish_r[1];
3559 int index = [Finishes_ indexOfObject:finish];
3560 if (index != INT_MAX && index > Finish_)
3570 - (void) _readStatus:(NSNumber *)fd {
3571 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3572 std::istream is(&ib);
3575 static RegEx conffile_r("status: [^ ]* : conffile-prompt : (.*?) *");
3576 static RegEx pmstatus_r("([^:]*):([^:]*):([^:]*):(.*)");
3578 while (std::getline(is, line)) {
3579 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3581 const char *data(line.c_str());
3582 size_t size(line.size());
3583 lprintf("S:%s\n", data);
3585 if (conffile_r(data, size)) {
3586 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3587 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3588 } else if (strncmp(data, "status: ", 8) == 0) {
3589 // status: <package>: {unpacked,half-configured,installed}
3590 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3591 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3592 } else if (strncmp(data, "processing: ", 12) == 0) {
3593 // processing: configure: config-test
3594 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3595 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3596 } else if (pmstatus_r(data, size)) {
3597 std::string type([pmstatus_r[1] UTF8String]);
3599 NSString *package = pmstatus_r[2];
3600 if ([package isEqualToString:@"dpkg-exec"])
3603 float percent([pmstatus_r[3] floatValue]);
3604 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3606 NSString *string = pmstatus_r[4];
3608 if (type == "pmerror") {
3609 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3610 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3611 } else if (type == "pmstatus") {
3612 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3613 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3614 } else if (type == "pmconffile")
3615 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3617 lprintf("E:unknown pmstatus\n");
3619 lprintf("E:unknown status\n");
3627 - (void) _readOutput:(NSNumber *)fd {
3628 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3629 std::istream is(&ib);
3632 while (std::getline(is, line)) {
3633 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3635 lprintf("O:%s\n", line.c_str());
3637 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3638 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3650 - (Package *) packageWithName:(NSString *)name {
3653 @synchronized (self) {
3654 if (static_cast<pkgDepCache *>(cache_) == NULL)
3656 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3657 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:NULL database:self];
3661 if ((self = [super init]) != nil) {
3668 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3670 size_t capacity(MetaFile_->active_);
3676 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3677 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3681 _assert(pipe(fds) != -1);
3684 _config->Set("APT::Keep-Fds::", cydiafd_);
3685 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3688 detachNewThreadSelector:@selector(_readCydia:)
3690 withObject:[NSNumber numberWithInt:fds[0]]
3693 _assert(pipe(fds) != -1);
3697 detachNewThreadSelector:@selector(_readStatus:)
3699 withObject:[NSNumber numberWithInt:fds[0]]
3702 _assert(pipe(fds) != -1);
3703 _assert(dup2(fds[0], 0) != -1);
3704 _assert(close(fds[0]) != -1);
3706 input_ = fdopen(fds[1], "a");
3708 _assert(pipe(fds) != -1);
3709 _assert(dup2(fds[1], 1) != -1);
3710 _assert(close(fds[1]) != -1);
3713 detachNewThreadSelector:@selector(_readOutput:)
3715 withObject:[NSNumber numberWithInt:fds[0]]
3720 - (pkgCacheFile &) cache {
3724 - (pkgDepCache::Policy *) policy {
3728 - (pkgRecords *) records {
3732 - (pkgProblemResolver *) resolver {
3736 - (pkgAcquire &) fetcher {
3740 - (pkgSourceList &) list {
3744 - (NSArray *) packages {
3745 return (NSArray *) packages_;
3748 - (NSArray *) sources {
3752 - (Source *) sourceWithKey:(NSString *)key {
3753 for (Source *source in [self sources]) {
3754 if ([[source key] isEqualToString:key])
3759 - (bool) popErrorWithTitle:(NSString *)title {
3762 while (!_error->empty()) {
3764 bool warning(!_error->PopMessage(error));
3769 size_t size(error.size());
3770 if (size == 0 || error[size - 1] != '\n')
3772 error.resize(size - 1);
3775 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3777 static RegEx no_pubkey("GPG error:.* NO_PUBKEY .*");
3778 if (warning && no_pubkey(error.c_str()))
3781 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3787 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3788 return [self popErrorWithTitle:title] || !success;
3791 - (bool) popErrorWithTitle:(NSString *)title forReadList:(pkgSourceList &)list {
3792 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3800 if (access("/etc/apt/sources.list", F_OK) == 0)
3801 error |= [self popErrorWithTitle:title forOperation:list.ReadAppend("/etc/apt/sources.list")];
3803 std::string base("/etc/apt/sources.list.d");
3804 if (DIR *sources = opendir(base.c_str())) {
3805 while (dirent *source = readdir(sources))
3806 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)
3807 error |= [self popErrorWithTitle:title forOperation:list.ReadAppend((base + "/" + source->d_name).c_str())];
3811 error |= [self popErrorWithTitle:title forOperation:list.ReadAppend(SOURCES_LIST)];
3816 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3817 @synchronized (self) {
3820 [self releasePackages];
3823 [sourceList_ removeAllObjects];
3844 new (&pool_) CYPool();
3846 NSRecycleZone(zone_);
3847 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3849 int chk(creat("/tmp/cydia.chk", 0644));
3853 if (invocation != nil)
3854 [invocation invoke];
3856 NSString *title(UCLocalize("DATABASE"));
3858 list_ = new pkgSourceList();
3859 _profile(reloadDataWithInvocation$ReadMainList)
3860 if ([self popErrorWithTitle:title forReadList:*list_])
3864 _profile(reloadDataWithInvocation$Source$initWithMetaIndex)
3865 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3866 Source *object([[[Source alloc] initWithMetaIndex:*source forDatabase:self inPool:&pool_] autorelease]);
3867 [sourceList_ addObject:object];
3872 OpProgress progress;
3875 delock_ = GetStatusDate();
3876 _profile(reloadDataWithInvocation$pkgCacheFile)
3877 opened = cache_.Open(progress, false);
3880 // XXX: what if there are errors, but Open() == true? this should be merged with popError:
3881 while (!_error->empty()) {
3883 bool warning(!_error->PopMessage(error));
3885 lprintf("cache_.Open():[%s]\n", error.c_str());
3887 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3891 else if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3892 repair = @selector(configure);
3893 //else if (error == "The package lists or status file could not be parsed or opened.")
3894 // repair = @selector(update);
3895 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3896 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3897 // else if (error == "Malformed Status line")
3898 // else if (error == "The list of sources could not be read.")
3900 if (repair != NULL) {
3902 [delegate_ repairWithSelector:repair];
3911 unlink("/tmp/cydia.chk");
3913 now_ = [[NSDate date] timeIntervalSince1970];
3915 policy_ = new pkgDepCache::Policy();
3916 records_ = new pkgRecords(cache_);
3917 resolver_ = new pkgProblemResolver(cache_);
3918 fetcher_ = new pkgAcquire(&status_);
3921 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3922 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3926 _profile(reloadDataWithInvocation$pkgApplyStatus)
3927 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3931 if (cache_->BrokenCount() != 0) {
3932 _profile(pkgApplyStatus$pkgFixBroken)
3933 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3937 if (cache_->BrokenCount() != 0) {
3938 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3942 _profile(pkgApplyStatus$pkgMinimizeUpgrade)
3943 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3948 for (Source *object in (id) sourceList_) {
3949 metaIndex *source([object metaIndex]);
3950 std::vector<pkgIndexFile *> *indices = source->GetIndexFiles();
3951 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3952 // XXX: this could be more intelligent
3953 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3954 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3956 sourceMap_[cached->ID] = object;
3961 /*std::vector<Package *> packages;
3962 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3965 _profile(reloadDataWithInvocation$packageWithIterator)
3966 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3967 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:&pool_ database:self])
3968 //packages.push_back(package);
3969 CFArrayAppendValue(packages_, CFRetain(package));
3973 /*if (packages.empty())
3974 packages_ = [[NSArray alloc] init];
3976 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3979 _profile(reloadDataWithInvocation$radix$8)
3980 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(8)];
3983 _profile(reloadDataWithInvocation$radix$4)
3984 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3987 _profile(reloadDataWithInvocation$radix$0)
3988 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3991 _profile(reloadDataWithInvocation$insertion)
3992 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3995 /*_profile(reloadDataWithInvocation$CFQSortArray)
3996 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);
3999 /*_profile(reloadDataWithInvocation$stdsort)
4000 std::sort(packages.begin(), packages.end(), PackageNameOrdering());
4003 /*_profile(reloadDataWithInvocation$CFArraySortValues)
4004 CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
4007 /*_profile(reloadDataWithInvocation$sortUsingFunction)
4008 [packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
4012 size_t count(CFArrayGetCount(packages_));
4013 MetaFile_->active_ = count;
4014 for (size_t index(0); index != count; ++index)
4015 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
4020 @synchronized (self) {
4022 resolver_ = new pkgProblemResolver(cache_);
4024 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
4025 if (!cache_[iterator].Keep())
4026 cache_->MarkKeep(iterator, false);
4027 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
4028 cache_->SetReInstall(iterator, false);
4031 - (void) configure {
4032 NSString *dpkg = [NSString stringWithFormat:@"/usr/libexec/cydo --configure -a --status-fd %u", statusfd_];
4034 system([dpkg UTF8String]);
4039 @synchronized (self) {
4040 // XXX: I don't remember this condition
4045 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
4047 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
4049 if ([self popErrorWithTitle:title])
4053 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
4055 CydiaLogCleaner cleaner;
4056 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
4063 fetcher_->Shutdown();
4065 pkgRecords records(cache_);
4067 lock_ = new FileFd();
4068 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
4070 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
4072 if ([self popErrorWithTitle:title])
4076 if ([self popErrorWithTitle:title forReadList:list])
4079 manager_ = (_system->CreatePM(cache_));
4080 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
4087 bool substrate(RestartSubstrate_);
4088 RestartSubstrate_ = false;
4090 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
4092 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
4094 if ([self popErrorWithTitle:title forReadList:list])
4096 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
4097 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
4100 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4102 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
4104 [self popErrorWithTitle:title];
4108 bool failed = false;
4109 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
4110 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
4112 if ((*item)->Status == pkgAcquire::Item::StatIdle)
4115 std::string uri = (*item)->DescURI();
4116 std::string error = (*item)->ErrorText;
4118 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
4121 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError]);
4122 [delegate_ addProgressEventOnMainThread:event forTask:title];
4125 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4133 RestartSubstrate_ = true;
4135 if (![delock_ isEqual:GetStatusDate()]) {
4136 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("DPKG_LOCKED") ofType:kCydiaProgressEventTypeError] forTask:title];
4142 pkgPackageManager::OrderResult result(manager_->DoInstall(statusfd_));
4144 NSString *oextended(@"/var/lib/apt/extended_states");
4145 NSString *nextended(Cache("extended_states"));
4148 if (stat([nextended UTF8String], &info) != -1 && (info.st_mode & S_IFMT) == S_IFREG)
4149 system([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /bin/cp --remove-destination %@ %@", ShellEscape(nextended), ShellEscape(oextended)] UTF8String]);
4151 unlink([nextended UTF8String]);
4152 symlink([oextended UTF8String], [nextended UTF8String]);
4154 if ([self popErrorWithTitle:title])
4157 if (result == pkgPackageManager::Failed) {
4162 if (result != pkgPackageManager::Completed) {
4167 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
4169 if ([self popErrorWithTitle:title forReadList:list])
4171 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
4172 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
4175 if (![before isEqualToArray:after])
4180 return ![delock_ isEqual:GetStatusDate()];
4184 NSString *title(UCLocalize("UPGRADE"));
4185 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
4191 [self updateWithStatus:status_];
4194 - (void) updateWithStatus:(CancelStatus &)status {
4195 NSString *title(UCLocalize("REFRESHING_DATA"));
4198 if ([self popErrorWithTitle:title forReadList:list])
4202 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
4203 if ([self popErrorWithTitle:title])
4206 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4208 bool success(ListUpdate(status, list, PulseInterval_));
4209 if (status.WasCancelled())
4212 [self popErrorWithTitle:title forOperation:success];
4214 [[NSDictionary dictionaryWithObjectsAndKeys:
4215 [NSDate date], @"LastUpdate",
4216 nil] writeToFile:@ CacheState_ atomically:YES];
4219 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4222 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
4223 delegate_ = delegate;
4226 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
4227 progress_ = delegate;
4228 status_.setDelegate(delegate);
4231 - (NSObject<ProgressDelegate> *) progressDelegate {
4235 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
4236 SourceMap::const_iterator i(sourceMap_.find(file->ID));
4237 return i == sourceMap_.end() ? nil : i->second;
4240 - (void) setFetch:(bool)fetch forURI:(const char *)uri {
4241 for (Source *source in (id) sourceList_)
4242 [source setFetch:fetch forURI:uri];
4245 - (void) resetFetch {
4246 for (Source *source in (id) sourceList_)
4247 [source resetFetch];
4250 - (NSString *) mappedSectionForPointer:(const char *)section {
4251 _H<NSString> *mapped;
4253 _profile(Database$mappedSectionForPointer$Cache)
4254 mapped = §ions_[section];
4257 if (*mapped == NULL) {
4258 size_t length(strlen(section));
4259 char spaced[length + 1];
4261 _profile(Database$mappedSectionForPointer$Replace)
4262 for (size_t index(0); index != length; ++index)
4263 spaced[index] = section[index] == '_' ? ' ' : section[index];
4264 spaced[length] = '\0';
4269 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
4270 string = [NSString stringWithUTF8String:spaced];
4273 _profile(Database$mappedSectionForPointer$Map)
4274 string = [SectionMap_ objectForKey:string] ?: string;
4284 static _H<NSMutableSet> Diversions_;
4286 @interface Diversion : NSObject {
4289 _H<NSString> format_;
4294 @implementation Diversion
4296 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
4297 if ((self = [super init]) != nil) {
4298 pattern_ = [from UTF8String];
4304 - (NSString *) divert:(NSString *)url {
4305 return !pattern_(url) ? nil : pattern_->*format_;
4308 + (NSURL *) divertURL:(NSURL *)url {
4310 NSString *href([url absoluteString]);
4312 for (Diversion *diversion in (id) Diversions_)
4313 if (NSString *diverted = [diversion divert:href]) {
4315 NSLog(@"div: %@", diverted);
4317 url = [NSURL URLWithString:diverted];
4324 - (NSString *) key {
4328 - (NSUInteger) hash {
4332 - (BOOL) isEqual:(Diversion *)object {
4333 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
4338 @interface CydiaObject : NSObject {
4339 _H<CyteWebViewController> indirect_;
4340 _transient id delegate_;
4343 - (id) initWithDelegate:(IndirectDelegate *)indirect;
4349 @interface CydiaWebViewController : CyteWebViewController {
4350 _H<CydiaObject> cydia_;
4353 + (void) addDiversion:(Diversion *)diversion;
4354 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request;
4355 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia;
4356 - (void) setDelegate:(id)delegate;
4360 /* Web Scripting {{{ */
4361 @implementation CydiaObject
4363 - (id) initWithDelegate:(IndirectDelegate *)indirect {
4364 if ((self = [super init]) != nil) {
4365 indirect_ = (CyteWebViewController *) indirect;
4369 - (void) setDelegate:(id)delegate {
4370 delegate_ = delegate;
4373 + (NSArray *) _attributeKeys {
4374 return [NSArray arrayWithObjects:
4378 @"coreFoundationVersionNumber",
4394 - (NSArray *) attributeKeys {
4395 return [[self class] _attributeKeys];
4398 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4399 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4402 - (NSString *) version {
4406 - (NSString *) build {
4410 - (NSString *) coreFoundationVersionNumber {
4411 return [NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber];
4414 - (NSString *) device {
4415 return UniqueIdentifier();
4418 - (NSString *) firmware {
4419 return [[UIDevice currentDevice] systemVersion];
4422 - (NSString *) hostname {
4423 return [[UIDevice currentDevice] name];
4426 - (NSString *) idiom {
4427 return (id) Idiom_ ?: [NSNull null];
4430 - (NSArray *) cells {
4431 auto *$_CTServerConnectionCreate(reinterpret_cast<id (*)(void *, void *, void *)>(dlsym(RTLD_DEFAULT, "_CTServerConnectionCreate")));
4432 if ($_CTServerConnectionCreate == NULL)
4435 struct CTResult { int flag; int error; };
4436 auto *$_CTServerConnectionCellMonitorCopyCellInfo(reinterpret_cast<CTResult (*)(CFTypeRef, void *, CFArrayRef *)>(dlsym(RTLD_DEFAULT, "_CTServerConnectionCellMonitorCopyCellInfo")));
4437 if ($_CTServerConnectionCellMonitorCopyCellInfo == NULL)
4440 _H<const void> connection($_CTServerConnectionCreate(NULL, NULL, NULL), true);
4441 if (connection == nil)
4445 CFArrayRef cells(NULL);
4446 auto result($_CTServerConnectionCellMonitorCopyCellInfo(connection, &count, &cells));
4447 if (result.flag != 0)
4450 return [(NSArray *) cells autorelease];
4453 - (NSString *) mcc {
4454 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode")))
4455 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault) autorelease];
4459 - (NSString *) mnc {
4460 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberNetworkCode")))
4461 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault) autorelease];
4465 - (NSString *) operator {
4466 if (CFStringRef (*$CTRegistrationCopyOperatorName)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTRegistrationCopyOperatorName")))
4467 return [(NSString *) (*$CTRegistrationCopyOperatorName)(kCFAllocatorDefault) autorelease];
4471 - (NSString *) bbsnum {
4472 return (id) BBSNum_ ?: [NSNull null];
4475 - (NSString *) ecid {
4476 return (id) ChipID_ ?: [NSNull null];
4479 - (NSString *) serial {
4480 return SerialNumber_;
4483 - (NSString *) role {
4484 return (id) [NSNull null];
4487 - (NSString *) model {
4488 return [NSString stringWithUTF8String:Machine_];
4491 + (NSString *) webScriptNameForSelector:(SEL)selector {
4493 else if (selector == @selector(addBridgedHost:))
4494 return @"addBridgedHost";
4495 else if (selector == @selector(addInsecureHost:))
4496 return @"addInsecureHost";
4497 else if (selector == @selector(addInternalRedirect::))
4498 return @"addInternalRedirect";
4499 else if (selector == @selector(addPipelinedHost:scheme:))
4500 return @"addPipelinedHost";
4501 else if (selector == @selector(addSource:::))
4502 return @"addSource";
4503 else if (selector == @selector(addTrivialSource:))
4504 return @"addTrivialSource";
4505 else if (selector == @selector(close))
4507 else if (selector == @selector(du:))
4509 else if (selector == @selector(stringWithFormat:arguments:))
4511 else if (selector == @selector(getAllSources))
4512 return @"getAllSources";
4513 else if (selector == @selector(getApplicationInfo:value:))
4514 return @"getApplicationInfoValue";
4515 else if (selector == @selector(getDisplayIdentifiers))
4516 return @"getDisplayIdentifiers";
4517 else if (selector == @selector(getLocalizedNameForDisplayIdentifier:))
4518 return @"getLocalizedNameForDisplayIdentifier";
4519 else if (selector == @selector(getKernelNumber:))
4520 return @"getKernelNumber";
4521 else if (selector == @selector(getKernelString:))
4522 return @"getKernelString";
4523 else if (selector == @selector(getInstalledPackages))
4524 return @"getInstalledPackages";
4525 else if (selector == @selector(getIORegistryEntry::))
4526 return @"getIORegistryEntry";
4527 else if (selector == @selector(getLocaleIdentifier))
4528 return @"getLocaleIdentifier";
4529 else if (selector == @selector(getPreferredLanguages))
4530 return @"getPreferredLanguages";
4531 else if (selector == @selector(getPackageById:))
4532 return @"getPackageById";
4533 else if (selector == @selector(getMetadataKeys))
4534 return @"getMetadataKeys";
4535 else if (selector == @selector(getMetadataValue:))
4536 return @"getMetadataValue";
4537 else if (selector == @selector(getSessionValue:))
4538 return @"getSessionValue";
4539 else if (selector == @selector(installPackages:))
4540 return @"installPackages";
4541 else if (selector == @selector(isReachable:))
4542 return @"isReachable";
4543 else if (selector == @selector(localizedStringForKey:value:table:))
4545 else if (selector == @selector(popViewController:))
4546 return @"popViewController";
4547 else if (selector == @selector(refreshSources))
4548 return @"refreshSources";
4549 else if (selector == @selector(registerFrame:))
4550 return @"registerFrame";
4551 else if (selector == @selector(removeButton))
4552 return @"removeButton";
4553 else if (selector == @selector(saveConfig))
4554 return @"saveConfig";
4555 else if (selector == @selector(setMetadataValue::))
4556 return @"setMetadataValue";
4557 else if (selector == @selector(setSessionValue::))
4558 return @"setSessionValue";
4559 else if (selector == @selector(substitutePackageNames:))
4560 return @"substitutePackageNames";
4561 else if (selector == @selector(scrollToBottom:))
4562 return @"scrollToBottom";
4563 else if (selector == @selector(setAllowsNavigationAction:))
4564 return @"setAllowsNavigationAction";
4565 else if (selector == @selector(setBadgeValue:))
4566 return @"setBadgeValue";
4567 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4568 return @"setButtonImage";
4569 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4570 return @"setButtonTitle";
4571 else if (selector == @selector(setHidesBackButton:))
4572 return @"setHidesBackButton";
4573 else if (selector == @selector(setHidesNavigationBar:))
4574 return @"setHidesNavigationBar";
4575 else if (selector == @selector(setNavigationBarStyle:))
4576 return @"setNavigationBarStyle";
4577 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4578 return @"setNavigationBarTintColor";
4579 else if (selector == @selector(setPasteboardString:))
4580 return @"setPasteboardString";
4581 else if (selector == @selector(setPasteboardURL:))
4582 return @"setPasteboardURL";
4583 else if (selector == @selector(setScrollAlwaysBounceVertical:))
4584 return @"setScrollAlwaysBounceVertical";
4585 else if (selector == @selector(setScrollIndicatorStyle:))
4586 return @"setScrollIndicatorStyle";
4587 else if (selector == @selector(setToken:))
4589 else if (selector == @selector(setViewportWidth:))
4590 return @"setViewportWidth";
4591 else if (selector == @selector(statfs:))
4593 else if (selector == @selector(supports:))
4595 else if (selector == @selector(unload))
4601 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4602 return [self webScriptNameForSelector:selector] == nil;
4605 - (BOOL) supports:(NSString *)feature {
4606 return [feature isEqualToString:@"window.open"];
4610 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4613 - (void) setScrollAlwaysBounceVertical:(NSNumber *)value {
4614 [indirect_ performSelectorOnMainThread:@selector(setScrollAlwaysBounceVerticalNumber:) withObject:value waitUntilDone:NO];
4617 - (void) setScrollIndicatorStyle:(NSString *)style {
4618 [indirect_ performSelectorOnMainThread:@selector(setScrollIndicatorStyleWithName:) withObject:style waitUntilDone:NO];
4621 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4622 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4625 - (NSDictionary *) getApplicationInfo:(NSString *)display value:(NSString *)key {
4627 if (SBBundlePathForDisplayIdentifier(SBSSpringBoardServerPort(), [display UTF8String], path) != 0)
4628 return (id) [NSNull null];
4629 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:[[NSString stringWithUTF8String:path] stringByAppendingString:@"/Info.plist"]]);
4631 return (id) [NSNull null];
4632 return [info objectForKey:key];
4635 - (NSArray *) getDisplayIdentifiers {
4636 NSSet *set([SBSCopyApplicationDisplayIdentifiers() autorelease]);
4637 if (set == nil || ![set isKindOfClass:[NSSet class]])
4638 return [NSArray array];
4639 return [set allObjects];
4642 - (NSString *) getLocalizedNameForDisplayIdentifier:(NSString *)identifier {
4643 return [SBSCopyLocalizedApplicationNameForDisplayIdentifier(identifier) autorelease] ?: (id) [NSNull null];
4646 - (NSNumber *) getKernelNumber:(NSString *)name {
4647 const char *string([name UTF8String]);
4650 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4651 return (id) [NSNull null];
4653 if (size != sizeof(int))
4654 return (id) [NSNull null];
4657 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4658 return (id) [NSNull null];
4660 return [NSNumber numberWithInt:value];
4663 - (NSString *) getKernelString:(NSString *)name {
4664 const char *string([name UTF8String]);
4667 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4668 return (id) [NSNull null];
4670 char value[size + 1];
4671 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4672 return (id) [NSNull null];
4674 // XXX: just in case you request something ludicrous
4677 return [NSString stringWithCString:value];
4680 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4681 NSObject *value(CYIOGetValue([path UTF8String], entry));
4684 if ([value isKindOfClass:[NSData class]])
4685 value = CYHex((NSData *) value);
4690 - (NSArray *) getMetadataKeys {
4691 @synchronized (Values_) {
4692 return [Values_ allKeys];
4695 - (void) registerFrame:(DOMHTMLIFrameElement *)iframe {
4696 WebFrame *frame([iframe contentFrame]);
4697 [indirect_ registerFrame:frame];
4700 - (id) getMetadataValue:(NSString *)key {
4701 @synchronized (Values_) {
4702 return [Values_ objectForKey:key];
4705 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4706 @synchronized (Values_) {
4707 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4708 [Values_ removeObjectForKey:key];
4710 [Values_ setObject:value forKey:key];
4713 - (id) getSessionValue:(NSString *)key {
4714 @synchronized (SessionData_) {
4715 return [SessionData_ objectForKey:key];
4718 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4719 @synchronized (SessionData_) {
4720 if (value == (id) [WebUndefined undefined])
4721 [SessionData_ removeObjectForKey:key];
4723 [SessionData_ setObject:value forKey:key];
4726 - (void) addBridgedHost:(NSString *)host {
4727 @synchronized (HostConfig_) {
4728 [BridgedHosts_ addObject:host];
4731 - (void) addInsecureHost:(NSString *)host {
4732 @synchronized (HostConfig_) {
4733 [InsecureHosts_ addObject:host];
4736 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4737 @synchronized (HostConfig_) {
4738 if (scheme != (id) [WebUndefined undefined])
4739 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4741 [PipelinedHosts_ addObject:host];
4744 - (void) popViewController:(NSNumber *)value {
4745 if (value == (id) [WebUndefined undefined])
4746 value = [NSNumber numberWithBool:YES];
4747 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4750 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4751 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4753 for (NSString *section in sections)
4754 [array addObject:section];
4756 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4759 distribution, @"Distribution",
4761 nil] waitUntilDone:NO];
4764 - (BOOL) addTrivialSource:(NSString *)href {
4765 href = VerifySource(href);
4768 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4772 - (void) refreshSources {
4773 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4776 - (void) saveConfig {
4777 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4780 - (NSArray *) getAllSources {
4781 return [[Database sharedInstance] sources];
4784 - (NSArray *) getInstalledPackages {
4785 Database *database([Database sharedInstance]);
4786 @synchronized (database) {
4787 NSArray *packages([database packages]);
4788 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4789 for (Package *package in packages)
4790 if (![package uninstalled])
4791 [installed addObject:package];
4795 - (Package *) getPackageById:(NSString *)id {
4796 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4800 return (Package *) [NSNull null];
4803 - (NSString *) getLocaleIdentifier {
4804 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4807 - (NSArray *) getPreferredLanguages {
4811 - (NSArray *) statfs:(NSString *)path {
4814 if (path == nil || statfs([path UTF8String], &stat) == -1)
4817 return [NSArray arrayWithObjects:
4818 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4819 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4820 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4824 - (NSNumber *) du:(NSString *)path {
4825 NSNumber *value(nil);
4827 FILE *du(popen([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /usr/libexec/cydia/du -ks %@", ShellEscape(path)] UTF8String], "r"));
4830 while (fgets(line, sizeof(line), du) != NULL) {
4831 size_t length(strlen(line));
4832 while (length != 0 && line[length - 1] == '\n')
4833 line[--length] = '\0';
4834 if (char *tab = strchr(line, '\t')) {
4836 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4846 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4849 - (NSNumber *) isReachable:(NSString *)name {
4850 return [NSNumber numberWithBool:IsReachable([name UTF8String])];
4853 - (void) installPackages:(NSArray *)packages {
4854 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4857 - (NSString *) substitutePackageNames:(NSString *)message {
4858 NSMutableArray *words([[[message componentsSeparatedByString:@" "] mutableCopy] autorelease]);
4859 for (size_t i(0), e([words count]); i != e; ++i) {
4860 NSString *word([words objectAtIndex:i]);
4861 if (Package *package = [[Database sharedInstance] packageWithName:word])
4862 [words replaceObjectAtIndex:i withObject:[package name]];
4865 return [words componentsJoinedByString:@" "];
4868 - (void) removeButton {
4869 [indirect_ removeButton];
4872 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4873 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4876 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4877 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4880 - (void) setBadgeValue:(id)value {
4881 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4884 - (void) setAllowsNavigationAction:(NSString *)value {
4885 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4888 - (void) setHidesBackButton:(NSString *)value {
4889 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4892 - (void) setHidesNavigationBar:(NSString *)value {
4893 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4896 - (void) setNavigationBarStyle:(NSString *)value {
4897 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4900 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4901 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4902 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4903 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4906 - (void) setPasteboardString:(NSString *)value {
4907 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4910 - (void) setPasteboardURL:(NSString *)value {
4911 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4914 - (void) setToken:(NSString *)token {
4915 // XXX: the website expects this :/
4918 - (void) scrollToBottom:(NSNumber *)animated {
4919 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4922 - (void) setViewportWidth:(float)width {
4923 [indirect_ setViewportWidthOnMainThread:width];
4926 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4927 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4928 unsigned count([arguments count]);
4930 for (unsigned i(0); i != count; ++i)
4931 values[i] = [arguments objectAtIndex:i];
4932 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4935 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4936 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4938 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4940 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4946 @interface NSURL (CydiaSecure)
4949 @implementation NSURL (CydiaSecure)
4951 - (bool) isCydiaSecure {
4952 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4955 @synchronized (HostConfig_) {
4956 if ([InsecureHosts_ containsObject:[self host]])
4965 /* Cydia Browser Controller {{{ */
4966 @implementation CydiaWebViewController
4968 - (NSURL *) navigationURL {
4969 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4972 + (void) _initialize {
4973 [super _initialize];
4975 Diversions_ = [NSMutableSet setWithCapacity:0];
4978 + (void) addDiversion:(Diversion *)diversion {
4979 [Diversions_ addObject:diversion];
4982 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4983 [super webView:view didClearWindowObject:window forFrame:frame];
4984 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
4987 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia {
4988 WebDataSource *source([frame dataSource]);
4989 NSURLResponse *response([source response]);
4990 NSURL *url([response URL]);
4991 NSString *scheme([[url scheme] lowercaseString]);
4993 bool bridged(false);
4995 @synchronized (HostConfig_) {
4996 if ([scheme isEqualToString:@"file"])
4998 else if ([scheme isEqualToString:@"https"])
4999 if ([BridgedHosts_ containsObject:[url host]])
5004 [window setValue:cydia forKey:@"cydia"];
5007 - (void) _setupMail:(MFMailComposeViewController *)controller {
5008 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
5010 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
5011 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
5014 - (NSURL *) URLWithURL:(NSURL *)url {
5015 return [Diversion divertURL:url];
5018 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
5019 return [CydiaWebViewController requestWithHeaders:[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
5022 - (NSURLRequest *) webThreadWebView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
5023 return [CydiaWebViewController requestWithHeaders:[super webThreadWebView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
5026 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request {
5027 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
5029 NSURL *url([copy URL]);
5030 NSString *href([url absoluteString]);
5031 NSString *host([url host]);
5033 if ([href hasPrefix:@"https://cydia.saurik.com/TSS/"]) {
5034 if (NSString *agent = [copy valueForHTTPHeaderField:@"X-User-Agent"]) {
5035 [copy setValue:agent forHTTPHeaderField:@"User-Agent"];
5036 [copy setValue:nil forHTTPHeaderField:@"X-User-Agent"];
5039 [copy setValue:nil forHTTPHeaderField:@"Referer"];
5040 [copy setValue:nil forHTTPHeaderField:@"Origin"];
5042 [copy setURL:[NSURL URLWithString:[@"http://gs.apple.com/TSS/" stringByAppendingString:[href substringFromIndex:29]]]];
5046 if ([copy valueForHTTPHeaderField:@"X-Cydia-Cf"] == nil)
5047 [copy setValue:[NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber] forHTTPHeaderField:@"X-Cydia-Cf"];
5048 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
5049 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
5051 bool bridged; @synchronized (HostConfig_) {
5052 bridged = [BridgedHosts_ containsObject:host];
5055 if ([url isCydiaSecure] && bridged && UniqueID_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Id"] == nil)
5056 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
5061 - (void) setDelegate:(id)delegate {
5062 [super setDelegate:delegate];
5063 [cydia_ setDelegate:delegate];
5066 - (NSString *) applicationNameForUserAgent {
5071 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
5072 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
5078 @interface AppCacheController : CydiaWebViewController {
5083 @implementation AppCacheController
5085 - (void) didReceiveMemoryWarning {
5086 // XXX: this doesn't work
5089 - (bool) retainsNetworkActivityIndicator {
5097 @interface NSObject (CydiaScript)
5098 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
5101 @implementation NSObject (CydiaScript)
5103 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5109 @implementation NSArray (CydiaScript)
5111 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5112 WebScriptObject *object([context evaluateWebScript:@"[]"]);
5113 for (size_t i(0), e([self count]); i != e; ++i)
5114 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
5120 @implementation NSDictionary (CydiaScript)
5122 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5123 WebScriptObject *object([context evaluateWebScript:@"({})"]);
5125 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
5132 /* Confirmation Controller {{{ */
5133 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
5134 if (!iterator.end())
5135 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
5136 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
5138 pkgCache::PkgIterator package(dep.TargetPkg());
5141 if (strcmp(package.Name(), "mobilesubstrate") == 0)
5148 @protocol ConfirmationControllerDelegate
5149 - (void) cancelAndClear:(bool)clear;
5150 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
5154 @interface ConfirmationController : CydiaWebViewController {
5155 _transient Database *database_;
5157 _H<UIAlertView> essential_;
5159 _H<NSDictionary> changes_;
5160 _H<NSMutableArray> issues_;
5161 _H<NSDictionary> sizes_;
5166 - (id) initWithDatabase:(Database *)database;
5170 @implementation ConfirmationController
5174 RestartSubstrate_ = true;
5175 [delegate_ confirmWithNavigationController:[self navigationController]];
5178 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
5179 NSString *context([alert context]);
5181 if ([context isEqualToString:@"remove"]) {
5182 if (button == [alert cancelButtonIndex])
5184 else if (button == [alert firstOtherButtonIndex]) {
5185 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
5188 [alert dismissWithClickedButtonIndex:-1 animated:YES];
5189 } else if ([context isEqualToString:@"unable"]) {
5190 [self dismissModalViewControllerAnimated:YES];
5191 [alert dismissWithClickedButtonIndex:-1 animated:YES];
5193 [super alertView:alert clickedButtonAtIndex:button];
5197 - (void) _doContinue {
5198 [delegate_ cancelAndClear:NO];
5199 [self dismissModalViewControllerAnimated:YES];
5202 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
5203 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
5207 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5208 [super webView:view didClearWindowObject:window forFrame:frame];
5210 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
5211 (id) changes_, @"changes",
5212 (id) issues_, @"issues",
5213 (id) sizes_, @"sizes",
5215 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
5218 - (id) initWithDatabase:(Database *)database {
5219 if ((self = [super init]) != nil) {
5220 database_ = database;
5222 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
5223 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
5224 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
5225 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
5226 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
5230 pkgCacheFile &cache([database_ cache]);
5231 NSArray *packages([database_ packages]);
5232 pkgDepCache::Policy *policy([database_ policy]);
5234 issues_ = [NSMutableArray arrayWithCapacity:4];
5236 for (Package *package in packages) {
5237 pkgCache::PkgIterator iterator([package iterator]);
5238 NSString *name([package id]);
5240 if ([package broken]) {
5241 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
5243 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5245 reasons, @"reasons",
5248 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
5252 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
5253 pkgCache::DepIterator start;
5254 pkgCache::DepIterator end;
5255 dep.GlobOr(start, end); // ++dep
5257 if (!cache->IsImportantDep(end))
5259 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
5262 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
5264 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5265 [NSString stringWithUTF8String:start.DepType()], @"relationship",
5266 clauses, @"clauses",
5270 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
5272 pkgCache::PkgIterator target(start.TargetPkg());
5273 if (target->ProvidesList != 0)
5274 reason = @"missing";
5276 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
5278 reason = @"installed";
5279 installed = [NSString stringWithUTF8String:ver.VerStr()];
5280 } else if (!cache[target].CandidateVerIter(cache).end())
5281 reason = @"uninstalled";
5282 else if (target->ProvidesList == 0)
5283 reason = @"uninstallable";
5285 reason = @"virtual";
5288 NSDictionary *version(start.TargetVer() == 0 ? (NSDictionary *) [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
5289 [NSString stringWithUTF8String:start.CompType()], @"operator",
5290 [NSString stringWithUTF8String:start.TargetVer()], @"value",
5293 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5294 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
5295 version, @"version",
5297 installed, @"installed",
5300 // yes, seriously. (wtf?)
5308 pkgDepCache::StateCache &state(cache[iterator]);
5310 static RegEx special_r("(firmware|gsc\\..*|cy\\+.*)");
5312 if (state.NewInstall())
5313 [installs addObject:name];
5314 // XXX: else if (state.Install())
5315 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
5316 [reinstalls addObject:name];
5317 // XXX: move before previous if
5318 else if (state.Upgrade())
5319 [upgrades addObject:name];
5320 else if (state.Downgrade())
5321 [downgrades addObject:name];
5322 else if (!state.Delete())
5323 // XXX: _assert(state.Keep());
5325 else if (special_r(name))
5326 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5327 [NSNull null], @"package",
5328 [NSArray arrayWithObjects:
5329 [NSDictionary dictionaryWithObjectsAndKeys:
5330 @"Conflicts", @"relationship",
5331 [NSArray arrayWithObjects:
5332 [NSDictionary dictionaryWithObjectsAndKeys:
5334 [NSNull null], @"version",
5335 @"installed", @"reason",
5342 if ([package essential])
5344 [removes addObject:name];
5347 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
5348 substrate_ |= DepSubstrate(iterator.CurrentVer());
5353 else if (Advanced_) {
5354 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
5356 essential_ = [[[UIAlertView alloc]
5357 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
5358 message:UCLocalize("REMOVING_ESSENTIALS_EX")
5360 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
5362 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
5366 [essential_ setContext:@"remove"];
5367 [essential_ setNumberOfRows:2];
5369 essential_ = [[[UIAlertView alloc]
5370 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
5371 message:UCLocalize("UNABLE_TO_COMPLY_EX")
5373 cancelButtonTitle:UCLocalize("OKAY")
5374 otherButtonTitles:nil
5377 [essential_ setContext:@"unable"];
5380 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5381 installs, @"installs",
5382 reinstalls, @"reinstalls",
5383 upgrades, @"upgrades",
5384 downgrades, @"downgrades",
5385 removes, @"removes",
5388 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5389 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
5390 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
5393 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
5397 - (UIBarButtonItem *) leftButton {
5398 return [[[UIBarButtonItem alloc]
5399 initWithTitle:UCLocalize("CANCEL")
5400 style:UIBarButtonItemStylePlain
5402 action:@selector(cancelButtonClicked)
5407 - (void) applyRightButton {
5408 if ([issues_ count] == 0 && ![self isLoading])
5409 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
5410 initWithTitle:UCLocalize("CONFIRM")
5411 style:UIBarButtonItemStyleDone
5413 action:@selector(confirmButtonClicked)
5416 [[self navigationItem] setRightBarButtonItem:nil];
5420 - (void) cancelButtonClicked {
5421 [delegate_ cancelAndClear:YES];
5422 [self dismissModalViewControllerAnimated:YES];
5426 - (void) confirmButtonClicked {
5427 if (essential_ != nil)
5437 /* Progress Data {{{ */
5438 @interface CydiaProgressData : NSObject {
5439 _transient id delegate_;
5448 _H<NSMutableArray> events_;
5449 _H<NSString> title_;
5451 _H<NSString> status_;
5452 _H<NSString> finish_;
5457 @implementation CydiaProgressData
5459 + (NSArray *) _attributeKeys {
5460 return [NSArray arrayWithObjects:
5472 - (NSArray *) attributeKeys {
5473 return [[self class] _attributeKeys];
5476 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5477 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5481 if ((self = [super init]) != nil) {
5482 events_ = [NSMutableArray arrayWithCapacity:32];
5490 - (void) setDelegate:(id)delegate {
5491 delegate_ = delegate;
5494 - (void) setPercent:(float)value {
5498 - (NSNumber *) percent {
5499 return [NSNumber numberWithFloat:percent_];
5502 - (void) setCurrent:(float)value {
5506 - (NSNumber *) current {
5507 return [NSNumber numberWithFloat:current_];
5510 - (void) setTotal:(float)value {
5514 - (NSNumber *) total {
5515 return [NSNumber numberWithFloat:total_];
5518 - (void) setSpeed:(float)value {
5522 - (NSNumber *) speed {
5523 return [NSNumber numberWithFloat:speed_];
5526 - (NSArray *) events {
5530 - (void) removeAllEvents {
5531 [events_ removeAllObjects];
5534 - (void) addEvent:(CydiaProgressEvent *)event {
5535 [events_ addObject:event];
5538 - (void) setTitle:(NSString *)text {
5542 - (NSString *) title {
5546 - (void) setFinish:(NSString *)text {
5550 - (NSString *) finish {
5551 return (id) finish_ ?: [NSNull null];
5554 - (void) setRunning:(bool)running {
5558 - (NSNumber *) running {
5559 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5564 /* Progress Controller {{{ */
5565 @interface ProgressController : CydiaWebViewController <
5568 _transient Database *database_;
5569 _H<CydiaProgressData, 1> progress_;
5573 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5575 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5577 - (void) setTitle:(NSString *)title;
5578 - (void) setCancellable:(bool)cancellable;
5582 @implementation ProgressController
5585 [database_ setProgressDelegate:nil];
5589 - (UIBarButtonItem *) leftButton {
5590 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5591 initWithTitle:UCLocalize("CANCEL")
5592 style:UIBarButtonItemStylePlain
5594 action:@selector(cancel)
5595 ] autorelease] : nil;
5598 - (void) updateCancel {
5599 [super applyLeftButton];
5602 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5603 if ((self = [super init]) != nil) {
5604 database_ = database;
5605 delegate_ = delegate;
5607 [database_ setProgressDelegate:self];
5609 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5610 [progress_ setDelegate:self];
5612 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5614 [scroller_ setBackgroundColor:[UIColor blackColor]];
5616 [[self navigationItem] setHidesBackButton:YES];
5618 [self updateCancel];
5622 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5623 [super webView:view didClearWindowObject:window forFrame:frame];
5624 [window setValue:progress_ forKey:@"cydiaProgress"];
5627 - (void) updateProgress {
5628 [self dispatchEvent:@"CydiaProgressUpdate"];
5631 - (void) viewWillAppear:(BOOL)animated {
5632 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5633 [super viewWillAppear:animated];
5637 UpdateExternalStatus(0);
5640 [delegate_ saveState];
5644 [delegate_ returnToCydia];
5648 [delegate_ terminateWithSuccess];
5649 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5650 [delegate_ suspendWithAnimation:YES];
5652 [delegate_ suspend];*/
5664 UIProgressHUD *hud([delegate_ addProgressHUD]);
5665 [hud setText:UCLocalize("LOADING")];
5666 [delegate_ performSelector:@selector(reloadSpringBoard) withObject:nil afterDelay:0.5];
5672 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5673 SBReboot(SBSSpringBoardServerPort());
5675 reboot2(RB_AUTOBOOT);
5682 - (void) setTitle:(NSString *)title {
5683 [progress_ setTitle:title];
5684 [self updateProgress];
5687 - (UIBarButtonItem *) rightButton {
5688 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5689 initWithTitle:UCLocalize("CLOSE")
5690 style:UIBarButtonItemStylePlain
5692 action:@selector(close)
5696 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5697 UpdateExternalStatus(1);
5699 [progress_ setRunning:true];
5700 [self setTitle:title];
5701 // implicit updateProgress
5703 SHA1SumValue notifyconf; {
5705 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5708 MMap mmap(file, MMap::ReadOnly);
5710 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5711 notifyconf = sha1.Result();
5715 SHA1SumValue springlist; {
5717 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5720 MMap mmap(file, MMap::ReadOnly);
5722 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5723 springlist = sha1.Result();
5727 if (invocation != nil) {
5728 [invocation yieldToSelector:@selector(invoke)];
5729 [self setTitle:@"COMPLETE"];
5734 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5737 MMap mmap(file, MMap::ReadOnly);
5739 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5740 if (!(notifyconf == sha1.Result()))
5747 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5750 MMap mmap(file, MMap::ReadOnly);
5752 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5753 if (!(springlist == sha1.Result()))
5759 if (RestartSubstrate_)
5763 RestartSubstrate_ = false;
5766 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5767 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5768 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5769 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5770 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5773 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5775 [progress_ setRunning:false];
5776 [self updateProgress];
5778 [self applyRightButton];
5781 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5782 [progress_ addEvent:event];
5783 [self updateProgress];
5786 - (bool) isProgressCancelled {
5787 return cancel_ == 2;
5792 [self updateCancel];
5795 - (void) setCancellable:(bool)cancellable {
5796 unsigned cancel(cancel_);
5800 else if (cancel_ == 0)
5803 if (cancel != cancel_)
5804 [self updateCancel];
5807 - (void) setProgressCancellable:(NSNumber *)cancellable {
5808 [self setCancellable:[cancellable boolValue]];
5811 - (void) setProgressPercent:(NSNumber *)percent {
5812 [progress_ setPercent:[percent floatValue]];
5813 [self updateProgress];
5816 - (void) setProgressStatus:(NSDictionary *)status {
5817 if (status == nil) {
5818 [progress_ setCurrent:0];
5819 [progress_ setTotal:0];
5820 [progress_ setSpeed:0];
5822 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5824 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5825 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5826 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5829 [self updateProgress];
5835 /* Package Cell {{{ */
5836 @interface PackageCell : CyteTableViewCell <
5837 CyteTableViewCellDelegate
5841 _H<NSString> description_;
5843 _H<NSString> source_;
5845 _H<UIImage> placard_;
5849 - (PackageCell *) init;
5850 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5852 - (void) drawContentRect:(CGRect)rect;
5856 @implementation PackageCell
5858 - (PackageCell *) init {
5859 CGRect frame(CGRectMake(0, 0, 320, 74));
5860 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5861 UIView *content([self contentView]);
5862 CGRect bounds([content bounds]);
5864 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5865 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5866 [content addSubview:content_];
5868 [content_ setDelegate:self];
5869 [content_ setOpaque:YES];
5873 - (NSString *) accessibilityLabel {
5877 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5878 summarized_ = summary;
5888 [content_ setBackgroundColor:[UIColor whiteColor]];
5892 Source *source = [package source];
5894 icon_ = [package icon];
5896 if (NSString *name = [package name])
5897 name_ = [NSString stringWithString:name];
5899 if (NSString *description = [package shortDescription])
5900 description_ = [NSString stringWithString:description];
5902 commercial_ = [package isCommercial];
5904 NSString *label = nil;
5905 bool trusted = false;
5907 if (source != nil) {
5908 label = [source label];
5909 trusted = [source trusted];
5910 } else if ([[package id] isEqualToString:@"firmware"])
5911 label = UCLocalize("APPLE");
5913 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5915 NSString *from(label);
5917 NSString *section = [package simpleSection];
5918 if (section != nil && ![section isEqualToString:label]) {
5919 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5920 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5923 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5925 if (NSString *purpose = [package primaryPurpose])
5926 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5931 if (NSString *mode = [package mode]) {
5932 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5933 color = RemovingColor_;
5934 placard = @"removing";
5936 color = InstallingColor_;
5937 placard = @"installing";
5940 color = [UIColor whiteColor];
5942 if ([package installed] != nil)
5943 placard = @"installed";
5948 [content_ setBackgroundColor:color];
5951 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5954 [self setNeedsDisplay];
5955 [content_ setNeedsDisplay];
5958 - (void) drawSummaryContentRect:(CGRect)rect {
5959 bool highlighted(highlighted_);
5960 float width([self bounds].size.width);
5964 rect.size = [(UIImage *) icon_ size];
5966 while (rect.size.width > 16 || rect.size.height > 16) {
5967 rect.size.width /= 2;
5968 rect.size.height /= 2;
5971 rect.origin.x = 19 - rect.size.width / 2;
5972 rect.origin.y = 19 - rect.size.height / 2;
5974 [icon_ drawInRect:Retina(rect)];
5977 if (badge_ != nil) {
5979 rect.size = [(UIImage *) badge_ size];
5981 rect.size.width /= 4;
5982 rect.size.height /= 4;
5984 rect.origin.x = 25 - rect.size.width / 2;
5985 rect.origin.y = 25 - rect.size.height / 2;
5987 [badge_ drawInRect:Retina(rect)];
5990 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5994 UISetColor(commercial_ ? Purple_ : Black_);
5995 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
5997 if (placard_ != nil)
5998 [placard_ drawAtPoint:CGPointMake(width - 52, 11)];
6001 - (void) drawNormalContentRect:(CGRect)rect {
6002 bool highlighted(highlighted_);
6003 float width([self bounds].size.width);
6007 rect.size = [(UIImage *) icon_ size];
6009 while (rect.size.width > 32 || rect.size.height > 32) {
6010 rect.size.width /= 2;
6011 rect.size.height /= 2;
6014 rect.origin.x = 25 - rect.size.width / 2;
6015 rect.origin.y = 25 - rect.size.height / 2;
6017 [icon_ drawInRect:Retina(rect)];
6020 if (badge_ != nil) {
6022 rect.size = [(UIImage *) badge_ size];
6024 rect.size.width /= 2;
6025 rect.size.height /= 2;
6027 rect.origin.x = 36 - rect.size.width / 2;
6028 rect.origin.y = 36 - rect.size.height / 2;
6030 [badge_ drawInRect:Retina(rect)];
6033 if (highlighted && kCFCoreFoundationVersionNumber < 800)
6037 UISetColor(commercial_ ? Purple_ : Black_);
6038 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
6039 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
6042 UISetColor(commercial_ ? Purplish_ : Gray_);
6043 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:NSLineBreakByTruncatingTail];
6045 if (placard_ != nil)
6046 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
6049 - (void) drawContentRect:(CGRect)rect {
6051 [self drawSummaryContentRect:rect];
6053 [self drawNormalContentRect:rect];
6058 /* Section Cell {{{ */
6059 @interface SectionCell : CyteTableViewCell <
6060 CyteTableViewCellDelegate
6062 _H<NSString> basic_;
6063 _H<NSString> section_;
6065 _H<NSString> count_;
6067 _H<UISwitch> switch_;
6071 - (void) setSection:(Section *)section editing:(BOOL)editing;
6075 @implementation SectionCell
6077 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
6078 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
6079 icon_ = [UIImage imageNamed:@"folder.png"];
6080 // XXX: this initial frame is wrong, but is fixed later
6081 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
6082 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
6084 UIView *content([self contentView]);
6085 CGRect bounds([content bounds]);
6087 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
6088 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6089 [content addSubview:content_];
6090 [content_ setBackgroundColor:[UIColor whiteColor]];
6092 [content_ setDelegate:self];
6096 - (void) onSwitch:(id)sender {
6097 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
6098 if (metadata == nil) {
6099 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
6100 [Sections_ setObject:metadata forKey:basic_];
6103 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
6106 - (void) setSection:(Section *)section editing:(BOOL)editing {
6107 if (editing != editing_) {
6109 [switch_ removeFromSuperview];
6111 [self addSubview:switch_];
6120 if (section == nil) {
6121 name_ = UCLocalize("ALL_PACKAGES");
6124 basic_ = [section name];
6125 section_ = [section localized];
6127 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
6128 count_ = [NSString stringWithFormat:@"%zd", [section count]];
6131 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
6134 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
6135 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
6137 [content_ setNeedsDisplay];
6140 - (void) setFrame:(CGRect)frame {
6141 [super setFrame:frame];
6143 CGRect rect([switch_ frame]);
6144 [switch_ setFrame:CGRectMake(frame.size.width - rect.size.width - 9, 9, rect.size.width, rect.size.height)];
6147 - (NSString *) accessibilityLabel {
6151 - (void) drawContentRect:(CGRect)rect {
6152 bool highlighted(highlighted_ && !editing_);
6154 [icon_ drawInRect:CGRectMake(7, 7, 32, 32)];
6156 if (highlighted && kCFCoreFoundationVersionNumber < 800)
6159 float width(rect.size.width);
6161 width -= 9 + [switch_ frame].size.width;
6165 [name_ drawAtPoint:CGPointMake(48, 12) forWidth:(width - 58) withFont:Font18_ lineBreakMode:NSLineBreakByTruncatingTail];
6167 CGSize size = [count_ sizeWithFont:Font14_];
6169 UISetColor(Folder_);
6171 [count_ drawAtPoint:CGPointMake(Retina(10 + (30 - size.width) / 2), 18) withFont:Font12Bold_];
6177 /* File Table {{{ */
6178 @interface FileTable : CyteViewController <
6179 UITableViewDataSource,
6182 _transient Database *database_;
6183 _H<Package> package_;
6185 _H<NSMutableArray> files_;
6186 _H<UITableView, 2> list_;
6189 - (id) initWithDatabase:(Database *)database;
6190 - (void) setPackage:(Package *)package;
6194 @implementation FileTable
6196 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6197 return files_ == nil ? 0 : [files_ count];
6200 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6204 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6205 static NSString *reuseIdentifier = @"Cell";
6207 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6209 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6210 [cell setFont:[UIFont systemFontOfSize:16]];
6212 [cell setText:[files_ objectAtIndex:indexPath.row]];
6213 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
6218 - (NSURL *) navigationURL {
6219 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
6223 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
6224 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6225 [list_ setRowHeight:24.0f];
6226 [(UITableView *) list_ setDataSource:self];
6227 [list_ setDelegate:self];
6228 [self setView:list_];
6231 - (void) viewDidLoad {
6232 [super viewDidLoad];
6234 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
6237 - (void) releaseSubviews {
6243 [super releaseSubviews];
6246 - (id) initWithDatabase:(Database *)database {
6247 if ((self = [super init]) != nil) {
6248 database_ = database;
6252 - (void) setPackage:(Package *)package {
6256 files_ = [NSMutableArray arrayWithCapacity:32];
6258 if (package != nil) {
6260 name_ = [package id];
6262 if (NSArray *files = [package files])
6263 [files_ addObjectsFromArray:files];
6265 if ([files_ count] != 0) {
6266 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
6267 [files_ removeObjectAtIndex:0];
6268 [files_ sortUsingSelector:@selector(compareByPath:)];
6270 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
6271 [stack addObject:@"/"];
6273 for (int i(0), e([files_ count]); i != e; ++i) {
6274 NSString *file = [files_ objectAtIndex:i];
6275 while (![file hasPrefix:[stack lastObject]])
6276 [stack removeLastObject];
6277 NSString *directory = [stack lastObject];
6278 [stack addObject:[file stringByAppendingString:@"/"]];
6279 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
6280 ([stack count] - 2) * 3, "",
6281 [file substringFromIndex:[directory length]]
6290 - (void) reloadData {
6293 [self setPackage:[database_ packageWithName:name_]];
6298 /* Package Controller {{{ */
6299 @interface CYPackageController : CydiaWebViewController <
6300 UIActionSheetDelegate
6302 _transient Database *database_;
6303 _H<Package> package_;
6306 std::vector<std::pair<_H<NSString>, _H<NSString>>> buttons_;
6307 _H<UIActionSheet> sheet_;
6308 _H<UIBarButtonItem> button_;
6309 _H<NSArray> versions_;
6312 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer;
6316 @implementation CYPackageController
6318 - (NSURL *) navigationURL {
6319 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
6322 - (void) _clickButtonWithPackage:(Package *)package {
6323 [delegate_ installPackage:package];
6326 - (void) _clickButtonWithName:(NSString *)name {
6327 if ([name isEqualToString:@"CLEAR"])
6328 return [delegate_ clearPackage:package_];
6329 else if ([name isEqualToString:@"REMOVE"])
6330 return [delegate_ removePackage:package_];
6331 else if ([name isEqualToString:@"DOWNGRADE"]) {
6332 sheet_ = [[[UIActionSheet alloc]
6335 cancelButtonTitle:nil
6336 destructiveButtonTitle:nil
6337 otherButtonTitles:nil
6340 for (Package *version in (id) versions_)
6341 [sheet_ addButtonWithTitle:[version latest]];
6342 [sheet_ setContext:@"version"];
6344 [delegate_ showActionSheet:sheet_ fromItem:[[self navigationItem] rightBarButtonItem]];
6348 else if ([name isEqualToString:@"INSTALL"]);
6349 else if ([name isEqualToString:@"REINSTALL"]);
6350 else if ([name isEqualToString:@"UPGRADE"]);
6351 else _assert(false);
6353 [delegate_ installPackage:package_];
6356 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
6357 NSString *context([sheet context]);
6358 if (sheet_ == sheet)
6361 if ([context isEqualToString:@"modify"]) {
6362 if (button != [sheet cancelButtonIndex]) {
6364 [self performSelector:@selector(_clickButtonWithName:) withObject:buttons_[button].first afterDelay:0];
6366 [self _clickButtonWithName:buttons_[button].first];
6369 [sheet dismissWithClickedButtonIndex:button animated:YES];
6370 } else if ([context isEqualToString:@"version"]) {
6371 if (button != [sheet cancelButtonIndex]) {
6372 Package *version([versions_ objectAtIndex:button]);
6374 [self performSelector:@selector(_clickButtonWithPackage:) withObject:version afterDelay:0];
6376 [self _clickButtonWithPackage:version];
6379 [sheet dismissWithClickedButtonIndex:button animated:YES];
6383 - (bool) _allowJavaScriptPanel {
6388 - (void) _customButtonClicked {
6389 size_t count(buttons_.size());
6394 [self _clickButtonWithName:buttons_[0].first];
6396 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
6397 for (const auto &button : buttons_)
6398 [buttons addObject:button.second];
6400 sheet_ = [[[UIActionSheet alloc]
6403 cancelButtonTitle:nil
6404 destructiveButtonTitle:nil
6405 otherButtonTitles:nil
6408 for (NSString *button in buttons)
6409 [sheet_ addButtonWithTitle:button];
6410 [sheet_ setContext:@"modify"];
6412 [delegate_ showActionSheet:sheet_ fromItem:[[self navigationItem] rightBarButtonItem]];
6416 - (void) reloadButtonClicked {
6417 if (commercial_ && function_ == nil && [package_ uninstalled])
6419 [self customButtonClicked];
6422 - (void) applyLoadingTitle {
6423 // Don't show "Loading" as the title. Ever.
6426 - (UIBarButtonItem *) rightButton {
6431 - (void) setPageColor:(UIColor *)color {
6432 return [super setPageColor:nil];
6435 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer {
6436 if ((self = [super init]) != nil) {
6437 database_ = database;
6438 name_ = name == nil ? @"" : [NSString stringWithString:name];
6439 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]] withReferrer:referrer];
6443 - (void) reloadData {
6446 [sheet_ dismissWithClickedButtonIndex:[sheet_ cancelButtonIndex] animated:YES];
6449 package_ = [database_ packageWithName:name_];
6450 versions_ = [package_ downgrades];
6454 if (package_ != nil) {
6455 [(Package *) package_ parse];
6457 commercial_ = [package_ isCommercial];
6459 if ([package_ mode] != nil)
6460 buttons_.push_back(std::make_pair(@"CLEAR", UCLocalize("CLEAR")));
6461 if ([package_ source] == nil);
6462 else if ([package_ upgradableAndEssential:NO])
6463 buttons_.push_back(std::make_pair(@"UPGRADE", UCLocalize("UPGRADE")));
6464 else if ([package_ uninstalled])
6465 buttons_.push_back(std::make_pair(@"INSTALL", UCLocalize("INSTALL")));
6467 buttons_.push_back(std::make_pair(@"REINSTALL", UCLocalize("REINSTALL")));
6468 if (![package_ uninstalled])
6469 buttons_.push_back(std::make_pair(@"REMOVE", UCLocalize("REMOVE")));
6470 if ([versions_ count] != 0)
6471 buttons_.push_back(std::make_pair(@"DOWNGRADE", UCLocalize("DOWNGRADE")));
6475 switch (buttons_.size()) {
6476 case 0: title = nil; break;
6477 case 1: title = buttons_[0].second; break;
6478 default: title = UCLocalize("MODIFY"); break;
6481 button_ = [[[UIBarButtonItem alloc]
6483 style:UIBarButtonItemStylePlain
6485 action:@selector(customButtonClicked)
6489 - (bool) isLoading {
6490 return commercial_ ? [super isLoading] : false;
6496 /* Package List Controller {{{ */
6497 @interface PackageListController : CyteViewController <
6498 UITableViewDataSource,
6501 _transient Database *database_;
6503 _H<NSArray> packages_;
6504 _H<NSArray> sections_;
6505 _H<UITableView, 2> list_;
6507 _H<NSArray> thumbs_;
6508 std::vector<NSInteger> offset_;
6510 _H<NSString> title_;
6511 unsigned reloading_;
6514 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6515 - (void) setDelegate:(id)delegate;
6516 - (void) resetCursor;
6519 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages;
6523 @implementation PackageListController
6525 - (NSURL *) referrerURL {
6526 return [self navigationURL];
6529 - (bool) isSummarized {
6533 - (bool) showsSections {
6537 - (void) deselectWithAnimation:(BOOL)animated {
6538 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6541 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6542 CGRect base = [[self view] bounds];
6543 base.size.height -= bounds.size.height;
6544 base.origin = [list_ frame].origin;
6546 [UIView beginAnimations:nil context:NULL];
6547 [UIView setAnimationBeginsFromCurrentState:YES];
6548 [UIView setAnimationCurve:curve];
6549 [UIView setAnimationDuration:duration];
6550 [list_ setFrame:base];
6551 [UIView commitAnimations];
6554 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6555 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6558 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6559 [self resizeForKeyboardBounds:bounds duration:0];
6562 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6563 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6564 *curve = UIViewAnimationCurveEaseInOut;
6566 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6568 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6571 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6574 - (void) keyboardWillShow:(NSNotification *)notification {
6577 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6578 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6580 NSTimeInterval duration;
6581 UIViewAnimationCurve curve;
6582 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6584 CGRect kbframe = CGRectMake(Retina(center.x - bounds.size.width / 2), Retina(center.y - bounds.size.height / 2), bounds.size.width, bounds.size.height);
6585 UIViewController *base = self;
6586 while ([base parentOrPresentingViewController] != nil)
6587 base = [base parentOrPresentingViewController];
6588 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6589 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6591 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6592 intersection.size.height += CYStatusBarHeight();
6594 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6597 - (void) keyboardWillHide:(NSNotification *)notification {
6598 NSTimeInterval duration;
6599 UIViewAnimationCurve curve;
6600 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6602 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6605 - (void) viewWillAppear:(BOOL)animated {
6606 [super viewWillAppear:animated];
6608 [self resizeForKeyboardBounds:CGRectZero];
6609 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6610 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6613 - (void) viewWillDisappear:(BOOL)animated {
6614 [super viewWillDisappear:animated];
6616 [self resizeForKeyboardBounds:CGRectZero];
6617 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6618 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6621 - (void) viewDidAppear:(BOOL)animated {
6622 [super viewDidAppear:animated];
6623 [self deselectWithAnimation:animated];
6626 - (void) didSelectPackage:(Package *)package {
6627 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[[self referrerURL] absoluteString]] autorelease]);
6628 [view setDelegate:delegate_];
6629 [[self navigationController] pushViewController:view animated:YES];
6632 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6633 NSInteger count([sections_ count]);
6634 return count == 0 ? 1 : count;
6637 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6638 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6640 return [[sections_ objectAtIndex:section] name];
6643 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6644 if ([sections_ count] == 0)
6646 return [[sections_ objectAtIndex:section] count];
6649 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6650 @synchronized (database_) {
6651 if ([database_ era] != era_)
6654 Section *section([sections_ objectAtIndex:[path section]]);
6655 NSInteger row([path row]);
6656 Package *package([packages_ objectAtIndex:([section row] + row)]);
6657 return [[package retain] autorelease];
6660 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6661 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6663 cell = [[[PackageCell alloc] init] autorelease];
6665 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6666 [cell setPackage:package asSummary:[self isSummarized]];
6670 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6671 Package *package([self packageAtIndexPath:path]);
6672 package = [database_ packageWithName:[package id]];
6673 [self didSelectPackage:package];
6676 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6680 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6681 return offset_[index];
6684 - (void) updateHeight {
6685 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6688 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6689 if ((self = [super init]) != nil) {
6690 database_ = database;
6691 title_ = [title copy];
6692 [[self navigationItem] setTitle:title_];
6697 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
6698 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
6699 [self setView:view];
6701 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6702 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6703 [view addSubview:list_];
6705 // XXX: is 20 the most optimal number here?
6706 [list_ setSectionIndexMinimumDisplayRowCount:20];
6708 [(UITableView *) list_ setDataSource:self];
6709 [list_ setDelegate:self];
6711 [self updateHeight];
6714 - (void) releaseSubviews {
6723 [super releaseSubviews];
6726 - (void) setDelegate:(id)delegate {
6727 delegate_ = delegate;
6730 - (bool) shouldYield {
6734 - (bool) shouldBlock {
6738 - (NSMutableArray *) _reloadPackages {
6739 @synchronized (database_) {
6740 era_ = [database_ era];
6741 NSArray *packages([database_ packages]);
6743 return [NSMutableArray arrayWithArray:packages];
6746 - (void) _reloadData {
6747 if (reloading_ != 0) {
6752 NSMutableArray *packages;
6755 if ([self shouldYield]) {
6759 if (![self shouldBlock])
6762 hud = [delegate_ addProgressHUD];
6763 [hud setText:UCLocalize("LOADING")];
6767 packages = [self yieldToSelector:@selector(_reloadPackages)];
6770 [delegate_ removeProgressHUD:hud];
6771 } while (reloading_ == 2);
6773 packages = [self _reloadPackages];
6776 @synchronized (database_) {
6777 if (era_ != [database_ era])
6784 packages_ = packages;
6786 if ([self showsSections])
6787 sections_ = [self sectionsForPackages:packages];
6789 Section *section([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6790 [section setCount:[packages_ count]];
6791 sections_ = [NSArray arrayWithObject:section];
6794 [self updateHeight];
6796 _profile(PackageTable$reloadData$List)
6797 [(UITableView *) list_ setDataSource:self];
6805 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
6806 Section *prefix([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6807 size_t end([packages count]);
6809 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
6810 Section *section(prefix);
6812 thumbs_ = CollationThumbs_;
6813 offset_ = CollationOffset_;
6816 size_t offsets([CollationStarts_ count]);
6818 NSString *start([CollationStarts_ objectAtIndex:offset]);
6819 size_t length([start length]);
6821 for (size_t index(0); index != end; ++index) {
6823 Package *package([packages objectAtIndex:index]);
6824 NSString *name(PackageName(package, @selector(cyname)));
6826 //while ([start compare:name options:NSNumericSearch range:NSMakeRange(0, length) locale:CollationLocale_] != NSOrderedDescending) {
6827 while (StringNameCompare(start, name, length) != kCFCompareGreaterThan) {
6828 NSString *title([CollationTitles_ objectAtIndex:offset]);
6829 section = [[[Section alloc] initWithName:title row:index localize:NO] autorelease];
6830 [sections addObject:section];
6832 start = ++offset == offsets ? nil : [CollationStarts_ objectAtIndex:offset];
6835 length = [start length];
6839 [section addToCount];
6842 for (; offset != offsets; ++offset) {
6843 NSString *title([CollationTitles_ objectAtIndex:offset]);
6844 Section *section([[[Section alloc] initWithName:title row:end localize:NO] autorelease]);
6845 [sections addObject:section];
6848 if ([prefix count] != 0) {
6849 Section *suffix([sections lastObject]);
6850 [prefix setName:[suffix name]];
6851 [suffix setName:nil];
6852 [sections insertObject:prefix atIndex:(offsets - 1)];
6858 - (void) reloadData {
6861 if ([self shouldYield])
6862 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6867 - (void) resetCursor {
6868 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6871 - (void) clearData {
6872 [self updateHeight];
6874 [list_ setDataSource:nil];
6882 /* Filtered Package List Controller {{{ */
6883 typedef Function<bool, Package *> PackageFilter;
6884 typedef Function<void, NSMutableArray *> PackageSorter;
6885 @interface FilteredPackageListController : PackageListController {
6886 PackageFilter filter_;
6887 PackageSorter sorter_;
6890 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter;
6892 - (void) setFilter:(PackageFilter)filter;
6893 - (void) setSorter:(PackageSorter)sorter;
6897 @implementation FilteredPackageListController
6899 - (void) setFilter:(PackageFilter)filter {
6900 @synchronized (self) {
6904 - (void) setSorter:(PackageSorter)sorter {
6905 @synchronized (self) {
6909 - (NSMutableArray *) _reloadPackages {
6910 @synchronized (database_) {
6911 era_ = [database_ era];
6913 NSArray *packages([database_ packages]);
6914 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6916 PackageFilter filter;
6917 PackageSorter sorter;
6919 @synchronized (self) {
6924 _profile(PackageTable$reloadData$Filter)
6925 for (Package *package in packages)
6926 if (filter(package))
6927 [filtered addObject:package];
6935 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter {
6936 if ((self = [super initWithDatabase:database title:title]) != nil) {
6937 [self setFilter:filter];
6944 /* Home Controller {{{ */
6945 @interface HomeController : CydiaWebViewController {
6946 CFRunLoopRef runloop_;
6947 SCNetworkReachabilityRef reachability_;
6952 @implementation HomeController
6954 static void HomeControllerReachabilityCallback(SCNetworkReachabilityRef reachability, SCNetworkReachabilityFlags flags, void *info) {
6955 [(HomeController *) info dispatchEvent:@"CydiaReachabilityCallback"];
6959 if ((self = [super init]) != nil) {
6960 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6963 reachability_ = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "cydia.saurik.com");
6964 if (reachability_ != NULL) {
6965 SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
6966 SCNetworkReachabilitySetCallback(reachability_, HomeControllerReachabilityCallback, &context);
6968 CFRunLoopRef runloop(CFRunLoopGetCurrent());
6969 if (SCNetworkReachabilityScheduleWithRunLoop(reachability_, runloop, kCFRunLoopDefaultMode))
6976 if (reachability_ != NULL && runloop_ != NULL)
6977 SCNetworkReachabilityUnscheduleFromRunLoop(reachability_, runloop_, kCFRunLoopDefaultMode);
6981 - (NSURL *) navigationURL {
6982 return [NSURL URLWithString:@"cydia://home"];
6985 - (void) aboutButtonClicked {
6986 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6988 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6989 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6990 [alert setCancelButtonIndex:0];
6993 @"Copyright \u00a9 2008-2015\n"
6996 "Jay Freeman (saurik)\n"
6997 "saurik@saurik.com\n"
6998 "http://www.saurik.com/"
7004 - (UIBarButtonItem *) leftButton {
7005 return [[[UIBarButtonItem alloc]
7006 initWithTitle:UCLocalize("ABOUT")
7007 style:UIBarButtonItemStylePlain
7009 action:@selector(aboutButtonClicked)
7016 /* Cydia Navigation Controller Interface {{{ */
7017 @interface UINavigationController (Cydia)
7019 - (NSArray *) navigationURLCollection;
7020 - (void) unloadData;
7025 /* Cydia Tab Bar Controller {{{ */
7026 @interface CydiaTabBarController : CyteTabBarController <
7027 UITabBarControllerDelegate,
7030 _transient Database *database_;
7032 _H<UIActivityIndicatorView> indicator_;
7035 // XXX: ok, "updatedelegate_"?...
7036 _transient NSObject<CydiaDelegate> *updatedelegate_;
7039 - (NSArray *) navigationURLCollection;
7040 - (void) beginUpdate;
7045 @implementation CydiaTabBarController
7047 - (NSArray *) navigationURLCollection {
7048 NSMutableArray *items([NSMutableArray array]);
7050 // XXX: Should this deal with transient view controllers?
7051 for (id navigation in [self viewControllers]) {
7052 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
7054 [items addObject:stack];
7060 - (id) initWithDatabase:(Database *)database {
7061 if ((self = [super init]) != nil) {
7062 database_ = database;
7063 [self setDelegate:self];
7065 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteTiny] autorelease];
7066 [indicator_ setOrigin:CGPointMake(kCFCoreFoundationVersionNumber >= 800 ? 2 : 4, 2)];
7068 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7072 - (void) beginUpdate {
7076 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
7077 UITabBarItem *item([controller tabBarItem]);
7079 [item setBadgeValue:@""];
7080 UIView *badge(MSHookIvar<UIView *>([item view], "_badge"));
7082 [indicator_ startAnimating];
7083 [badge addSubview:indicator_];
7085 [updatedelegate_ retainNetworkActivityIndicator];
7089 detachNewThreadSelector:@selector(performUpdate)
7095 - (void) performUpdate {
7096 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
7098 SourceStatus status(self, database_);
7099 [database_ updateWithStatus:status];
7102 performSelectorOnMainThread:@selector(completeUpdate)
7110 - (void) stopUpdateWithSelector:(SEL)selector {
7112 [updatedelegate_ releaseNetworkActivityIndicator];
7114 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
7115 [[controller tabBarItem] setBadgeValue:nil];
7117 [indicator_ removeFromSuperview];
7118 [indicator_ stopAnimating];
7120 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
7123 - (void) completeUpdate {
7126 [self stopUpdateWithSelector:@selector(reloadData)];
7129 - (void) cancelUpdate {
7130 [self stopUpdateWithSelector:@selector(updateDataAndLoad)];
7133 - (void) cancelPressed {
7134 [self cancelUpdate];
7141 - (bool) isSourceCancelled {
7145 - (void) startSourceFetch:(NSString *)uri {
7148 - (void) stopSourceFetch:(NSString *)uri {
7151 - (void) setUpdateDelegate:(id)delegate {
7152 updatedelegate_ = delegate;
7158 /* Cydia Navigation Controller Implementation {{{ */
7159 @implementation UINavigationController (Cydia)
7161 - (NSArray *) navigationURLCollection {
7162 NSMutableArray *stack([NSMutableArray array]);
7164 for (CyteViewController *controller in [self viewControllers]) {
7165 NSString *url = [[controller navigationURL] absoluteString];
7167 [stack addObject:url];
7173 - (void) reloadData {
7176 UIViewController *visible([self visibleViewController]);
7178 [visible reloadData];
7180 // on the iPad, this view controller is ALSO visible. :(
7182 if (UIViewController *modal = [self modalViewController])
7183 if ([modal modalPresentationStyle] == UIModalPresentationFormSheet)
7184 if (UIViewController *top = [self topViewController])
7189 - (void) unloadData {
7190 for (CyteViewController *page in [self viewControllers])
7199 /* Cydia:// Protocol {{{ */
7200 @interface CydiaURLProtocol : NSURLProtocol {
7205 @implementation CydiaURLProtocol
7207 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7208 NSURL *url([request URL]);
7212 NSString *scheme([[url scheme] lowercaseString]);
7213 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7215 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7221 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7225 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7226 id<NSURLProtocolClient> client([self client]);
7228 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7230 NSData *data(UIImagePNGRepresentation(icon));
7232 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7233 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7234 [client URLProtocol:self didLoadData:data];
7235 [client URLProtocolDidFinishLoading:self];
7239 - (void) startLoading {
7240 id<NSURLProtocolClient> client([self client]);
7241 NSURLRequest *request([self request]);
7243 NSURL *url([request URL]);
7244 NSString *href([url absoluteString]);
7245 NSString *scheme([[url scheme] lowercaseString]);
7249 if ([scheme isEqualToString:@"cydia"])
7250 path = [href substringFromIndex:8];
7251 else if ([scheme isEqualToString:@"about"])
7252 path = [href substringFromIndex:12];
7253 else _assert(false);
7255 NSRange slash([path rangeOfString:@"/"]);
7258 if (slash.location == NSNotFound) {
7262 command = [path substringToIndex:slash.location];
7263 path = [path substringFromIndex:(slash.location + 1)];
7266 Database *database([Database sharedInstance]);
7269 else if ([command isEqualToString:@"application-icon"]) {
7272 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7276 if (icon == nil && $SBSCopyIconImagePNGDataForDisplayIdentifier != NULL) {
7277 NSData *data([$SBSCopyIconImagePNGDataForDisplayIdentifier(path) autorelease]);
7278 icon = [UIImage imageWithData:data];
7282 if (NSString *file = SBSCopyIconImagePathForDisplayIdentifier(path))
7283 icon = [UIImage imageAtPath:file];
7286 icon = [UIImage imageNamed:@"unknown.png"];
7288 [self _returnPNGWithImage:icon forRequest:request];
7289 } else if ([command isEqualToString:@"package-icon"]) {
7292 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7293 Package *package([database packageWithName:path]);
7297 UIImage *icon([package icon]);
7298 [self _returnPNGWithImage:icon forRequest:request];
7299 } else if ([command isEqualToString:@"uikit-image"]) {
7302 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7303 UIImage *icon(_UIImageWithName(path));
7304 [self _returnPNGWithImage:icon forRequest:request];
7305 } else if ([command isEqualToString:@"section-icon"]) {
7308 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7309 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7311 icon = [UIImage imageNamed:@"unknown.png"];
7312 [self _returnPNGWithImage:icon forRequest:request];
7314 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7318 - (void) stopLoading {
7324 /* Section Controller {{{ */
7325 @interface SectionController : FilteredPackageListController {
7327 _H<NSString> section_;
7330 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section;
7334 @implementation SectionController
7336 - (NSURL *) referrerURL {
7337 NSString *name(section_);
7338 name = name ?: @"*";
7339 NSString *key(key_);
7341 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sections/%@/%@", UI_, [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7344 - (NSURL *) navigationURL {
7345 NSString *name(section_);
7346 name = name ?: @"*";
7347 NSString *key(key_);
7349 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@/%@", [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7352 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section {
7355 title = UCLocalize("ALL_PACKAGES");
7356 else if (![section isEqual:@""])
7357 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(section) value:nil table:@"Sections"];
7359 title = UCLocalize("NO_SECTION");
7361 if ((self = [super initWithDatabase:database title:title]) != nil) {
7362 key_ = [source key];
7367 - (void) reloadData {
7368 Source *source([database_ sourceWithKey:key_]);
7369 _H<NSString> name(section_);
7371 [self setFilter:[=](Package *package) {
7372 NSString *section([package section]);
7376 section == nil && [name length] == 0 ||
7377 [name isEqualToString:section]
7380 [package source] == source
7381 ) && [package visible];
7389 /* Sections Controller {{{ */
7390 @interface SectionsController : CyteViewController <
7391 UITableViewDataSource,
7394 _transient Database *database_;
7396 _H<NSMutableArray> sections_;
7397 _H<NSMutableArray> filtered_;
7398 _H<UITableView, 2> list_;
7401 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7402 - (void) editButtonClicked;
7406 @implementation SectionsController
7408 - (NSURL *) navigationURL {
7409 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
7412 - (Source *) source {
7415 return [database_ sourceWithKey:key_];
7418 - (void) updateNavigationItem {
7419 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7420 if ([sections_ count] == 0) {
7421 [[self navigationItem] setRightBarButtonItem:nil];
7423 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7424 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7426 action:@selector(editButtonClicked)
7427 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7431 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7432 [super setEditing:editing animated:animated];
7437 [delegate_ updateData];
7439 [self updateNavigationItem];
7442 - (void) viewDidAppear:(BOOL)animated {
7443 [super viewDidAppear:animated];
7444 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7447 - (void) viewWillDisappear:(BOOL)animated {
7448 [super viewWillDisappear:animated];
7449 [self setEditing:NO];
7452 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7453 Section *section = nil;
7454 int index = [indexPath row];
7455 if (![self isEditing]) {
7458 section = [filtered_ objectAtIndex:index];
7460 section = [sections_ objectAtIndex:index];
7465 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7466 if ([self isEditing])
7467 return [sections_ count];
7469 return [filtered_ count] + 1;
7472 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7476 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7477 static NSString *reuseIdentifier = @"SectionCell";
7479 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7481 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7483 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7488 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7489 if ([self isEditing])
7492 Section *section = [self sectionAtIndexPath:indexPath];
7494 SectionController *controller = [[[SectionController alloc]
7495 initWithDatabase:database_
7496 source:[self source]
7497 section:[section name]
7499 [controller setDelegate:delegate_];
7501 [[self navigationController] pushViewController:controller animated:YES];
7505 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
7506 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7507 [list_ setRowHeight:46];
7508 [(UITableView *) list_ setDataSource:self];
7509 [list_ setDelegate:self];
7510 [self setView:list_];
7513 - (void) viewDidLoad {
7514 [super viewDidLoad];
7516 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7519 - (void) releaseSubviews {
7525 [super releaseSubviews];
7528 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7529 if ((self = [super init]) != nil) {
7530 database_ = database;
7531 key_ = [source key];
7535 - (void) reloadData {
7538 NSArray *packages = [database_ packages];
7540 sections_ = [NSMutableArray arrayWithCapacity:16];
7541 filtered_ = [NSMutableArray arrayWithCapacity:16];
7543 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7545 Source *source([self source]);
7548 for (Package *package in packages) {
7549 if (source != nil && [package source] != source)
7552 NSString *name([package section]);
7553 NSString *key(name == nil ? @"" : name);
7557 _profile(SectionsView$reloadData$Section)
7558 section = [sections objectForKey:key];
7559 if (section == nil) {
7560 _profile(SectionsView$reloadData$Section$Allocate)
7561 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7562 [sections setObject:section forKey:key];
7567 [section addToCount];
7569 _profile(SectionsView$reloadData$Filter)
7570 if (![package visible])
7578 [sections_ addObjectsFromArray:[sections allValues]];
7580 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7582 for (Section *section in (id) sections_) {
7583 size_t count([section row]);
7587 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7588 [section setCount:count];
7589 [filtered_ addObject:section];
7592 [self updateNavigationItem];
7597 - (void) editButtonClicked {
7598 [self setEditing:![self isEditing] animated:YES];
7604 /* Changes Controller {{{ */
7605 @interface ChangesController : FilteredPackageListController {
7609 - (id) initWithDatabase:(Database *)database;
7613 @implementation ChangesController
7615 - (NSURL *) referrerURL {
7616 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/changes/", UI_]];
7619 - (NSURL *) navigationURL {
7620 return [NSURL URLWithString:@"cydia://changes"];
7623 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7624 @synchronized (database_) {
7625 if ([database_ era] != era_)
7628 NSUInteger sectionIndex([path section]);
7629 if (sectionIndex >= [sections_ count])
7631 Section *section([sections_ objectAtIndex:sectionIndex]);
7632 NSInteger row([path row]);
7633 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7636 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7637 NSString *context([alert context]);
7639 if ([context isEqualToString:@"norefresh"])
7640 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7643 - (void) setLeftBarButtonItem {
7644 if ([delegate_ updating])
7645 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7646 initWithTitle:UCLocalize("CANCEL")
7647 style:UIBarButtonItemStyleDone
7649 action:@selector(cancelButtonClicked)
7650 ] autorelease] animated:YES];
7652 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7653 initWithTitle:UCLocalize("REFRESH")
7654 style:UIBarButtonItemStylePlain
7656 action:@selector(refreshButtonClicked)
7657 ] autorelease] animated:YES];
7660 - (void) refreshButtonClicked {
7661 if ([delegate_ requestUpdate])
7662 [self setLeftBarButtonItem];
7665 - (void) cancelButtonClicked {
7666 [delegate_ cancelUpdate];
7669 - (void) upgradeButtonClicked {
7670 [delegate_ distUpgrade];
7671 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7674 - (bool) shouldYield {
7678 - (bool) shouldBlock {
7682 - (void) useFilter {
7683 @synchronized (self) {
7684 [self setFilter:[](Package *package) {
7685 return [package upgradableAndEssential:YES] || [package visible];
7688 [self setSorter:[](NSMutableArray *packages) {
7689 [packages radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7693 - (id) initWithDatabase:(Database *)database {
7694 if ((self = [super initWithDatabase:database title:UCLocalize("CHANGES")]) != nil) {
7699 - (void) viewDidLoad {
7700 [super viewDidLoad];
7701 [self setLeftBarButtonItem];
7704 - (void) viewWillAppear:(BOOL)animated {
7705 [super viewWillAppear:animated];
7706 [self setLeftBarButtonItem];
7709 - (void) reloadData {
7710 [self setLeftBarButtonItem];
7714 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
7715 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
7717 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7718 Section *ignored = nil;
7719 Section *section = nil;
7723 bool unseens = false;
7725 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7727 for (size_t offset = 0, count = [packages count]; offset != count; ++offset) {
7728 Package *package = [packages objectAtIndex:offset];
7730 BOOL uae = [package upgradableAndEssential:YES];
7734 time_t seen([package seen]);
7736 if (section == nil || last != seen) {
7740 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7743 _profile(ChangesController$reloadData$Allocate)
7744 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7745 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7746 [sections addObject:section];
7750 [section addToCount];
7751 } else if ([package ignored]) {
7752 if (ignored == nil) {
7753 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7755 [ignored addToCount];
7758 [upgradable addToCount];
7763 CFRelease(formatter);
7766 Section *last = [sections lastObject];
7767 size_t count = [last count];
7768 [packages removeObjectsInRange:NSMakeRange([packages count] - count, count)];
7769 [sections removeLastObject];
7772 if ([ignored count] != 0)
7773 [sections insertObject:ignored atIndex:0];
7775 [sections insertObject:upgradable atIndex:0];
7779 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7780 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7781 style:UIBarButtonItemStylePlain
7783 action:@selector(upgradeButtonClicked)
7784 ] autorelease]) animated:YES];
7791 /* Search Controller {{{ */
7792 @interface SearchController : FilteredPackageListController <
7795 _H<UISearchBar, 1> search_;
7800 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7801 - (void) reloadData;
7805 @implementation SearchController
7807 - (NSURL *) referrerURL {
7808 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/search?q=%@", UI_, [([search_ text] ?: @"") stringByAddingPercentEscapesIncludingReserved]]];
7811 - (NSURL *) navigationURL {
7812 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7813 return [NSURL URLWithString:@"cydia://search"];
7815 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [[search_ text] stringByAddingPercentEscapesIncludingReserved]]];
7818 - (NSArray *) termsForQuery:(NSString *)query {
7819 NSMutableArray *terms([NSMutableArray arrayWithCapacity:2]);
7820 for (NSString *component in [query componentsSeparatedByString:@" "])
7821 if ([component length] != 0)
7822 [terms addObject:component];
7827 - (void) useSearch {
7828 _H<NSArray> query([self termsForQuery:[search_ text]]);
7831 @synchronized (self) {
7832 [self setFilter:[=](Package *package) {
7833 if (![package unfiltered])
7835 if (![package matches:query])
7840 [self setSorter:[](NSMutableArray *packages) {
7841 [packages radixSortUsingSelector:@selector(rank)];
7849 - (void) usePrefix:(NSString *)prefix {
7850 _H<NSString> query(prefix);
7853 @synchronized (self) {
7854 [self setFilter:[=](Package *package) {
7855 if ([query length] == 0)
7857 if (![package unfiltered])
7859 if ([[package name] compare:query options:MatchCompareOptions_ range:NSMakeRange(0, [query length])] != NSOrderedSame)
7864 [self setSorter:nullptr];
7870 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7872 [self usePrefix:[search_ text]];
7875 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7876 [search_ resignFirstResponder];
7880 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7881 [search_ setText:@""];
7882 [self searchBarButtonClicked:searchBar];
7885 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7886 [self searchBarButtonClicked:searchBar];
7889 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7890 [self usePrefix:text];
7893 - (bool) shouldYield {
7897 - (bool) shouldBlock {
7901 - (bool) isSummarized {
7905 - (bool) showsSections {
7909 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7910 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH")])) {
7911 search_ = [[[UISearchBar alloc] init] autorelease];
7912 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7913 [search_ setDelegate:self];
7915 UITextField *textField;
7916 if ([search_ respondsToSelector:@selector(searchField)])
7917 textField = [search_ searchField];
7919 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7921 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7922 [textField setEnablesReturnKeyAutomatically:NO];
7923 [[self navigationItem] setTitleView:textField];
7926 [search_ setText:query];
7931 - (void) viewDidAppear:(BOOL)animated {
7932 [super viewDidAppear:animated];
7934 if (!searchloaded_) {
7935 searchloaded_ = YES;
7936 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7937 [search_ layoutSubviews];
7940 if ([self isSummarized])
7941 [search_ becomeFirstResponder];
7944 - (void) reloadData {
7949 - (void) didSelectPackage:(Package *)package {
7950 [search_ resignFirstResponder];
7951 [super didSelectPackage:package];
7956 /* Package Settings Controller {{{ */
7957 @interface PackageSettingsController : CyteViewController <
7958 UITableViewDataSource,
7961 _transient Database *database_;
7963 _H<Package> package_;
7964 _H<UITableView, 2> table_;
7965 _H<UISwitch> subscribedSwitch_;
7966 _H<UISwitch> ignoredSwitch_;
7967 _H<UITableViewCell> subscribedCell_;
7968 _H<UITableViewCell> ignoredCell_;
7971 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7975 @implementation PackageSettingsController
7977 - (NSURL *) navigationURL {
7978 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
7981 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7982 if (package_ == nil)
7985 if ([package_ installed] == nil)
7991 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7992 if (package_ == nil)
7995 // both sections contain just one item right now.
7999 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8003 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8005 return UCLocalize("SHOW_ALL_CHANGES_EX");
8007 return UCLocalize("IGNORE_UPGRADES_EX");
8010 - (void) onSubscribed:(id)control {
8011 bool value([control isOn]);
8012 if (package_ == nil)
8014 if ([package_ setSubscribed:value])
8015 [delegate_ updateData];
8018 - (void) _updateIgnored {
8019 const char *package([name_ UTF8String]);
8020 bool on([ignoredSwitch_ isOn]);
8022 FILE *dpkg(popen("/usr/libexec/cydia/cydo --set-selections", "w"));
8023 fwrite(package, strlen(package), 1, dpkg);
8026 fwrite(" hold\n", 6, 1, dpkg);
8028 fwrite(" install\n", 9, 1, dpkg);
8033 - (void) onIgnored:(id)control {
8034 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
8035 [invocation setTarget:self];
8036 [invocation setSelector:@selector(_updateIgnored)];
8038 [delegate_ reloadDataWithInvocation:invocation];
8041 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8042 if (package_ == nil)
8045 switch ([indexPath section]) {
8046 case 0: return subscribedCell_;
8047 case 1: return ignoredCell_;
8056 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8057 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8058 [self setView:view];
8060 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
8061 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8062 [(UITableView *) table_ setDataSource:self];
8063 [table_ setDelegate:self];
8064 [view addSubview:table_];
8066 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
8067 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
8068 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
8070 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
8071 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
8072 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
8074 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
8075 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
8076 [subscribedCell_ setAccessoryView:subscribedSwitch_];
8077 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
8079 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
8080 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
8081 [ignoredCell_ setAccessoryView:ignoredSwitch_];
8082 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
8085 - (void) viewDidLoad {
8086 [super viewDidLoad];
8088 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
8091 - (void) releaseSubviews {
8093 subscribedCell_ = nil;
8095 ignoredSwitch_ = nil;
8096 subscribedSwitch_ = nil;
8098 [super releaseSubviews];
8101 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
8102 if ((self = [super init]) != nil) {
8103 database_ = database;
8108 - (void) reloadData {
8111 package_ = [database_ packageWithName:name_];
8113 if (package_ != nil) {
8114 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
8115 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
8116 } // XXX: what now, G?
8118 [table_ reloadData];
8124 /* Installed Controller {{{ */
8125 @interface InstalledController : FilteredPackageListController {
8129 - (id) initWithDatabase:(Database *)database;
8130 - (void) queueStatusDidChange;
8134 @implementation InstalledController
8136 - (NSURL *) referrerURL {
8137 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/installed/", UI_]];
8140 - (NSURL *) navigationURL {
8141 return [NSURL URLWithString:@"cydia://installed"];
8144 - (void) useRecent {
8147 @synchronized (self) {
8148 [self setFilter:[](Package *package) {
8149 return ![package uninstalled] && package->role_ < 7;
8152 [self setSorter:[](NSMutableArray *packages) {
8153 [packages radixSortUsingSelector:@selector(recent)];
8157 - (void) useFilter:(UISegmentedControl *)segmented {
8158 NSInteger selected([segmented selectedSegmentIndex]);
8160 return [self useRecent];
8161 bool simple(selected == 0);
8164 @synchronized (self) {
8165 [self setFilter:[=](Package *package) {
8166 return ![package uninstalled] && package->role_ <= (simple ? 1 : 3);
8169 [self setSorter:nullptr];
8172 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
8174 return [super sectionsForPackages:packages];
8176 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterLongStyle, kCFDateFormatterNoStyle));
8178 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
8179 Section *section(nil);
8182 for (size_t offset(0), count([packages count]); offset != count; ++offset) {
8183 Package *package([packages objectAtIndex:offset]);
8185 time_t upgraded([package upgraded]);
8186 if (upgraded < 1168364520)
8189 upgraded -= upgraded % (60 * 60 * 24);
8191 if (section == nil || upgraded != last) {
8196 continue; // XXX: name = UCLocalize("...");
8198 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:upgraded]);
8202 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
8203 [sections addObject:section];
8206 [section addToCount];
8209 CFRelease(formatter);
8213 - (id) initWithDatabase:(Database *)database {
8214 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED")]) != nil) {
8215 UISegmentedControl *segmented([[[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:UCLocalize("USER"), UCLocalize("EXPERT"), UCLocalize("RECENT"), nil]] autorelease]);
8216 [segmented setSelectedSegmentIndex:0];
8217 [segmented setSegmentedControlStyle:UISegmentedControlStyleBar];
8218 [[self navigationItem] setTitleView:segmented];
8220 [segmented addTarget:self action:@selector(modeChanged:) forEvents:UIControlEventValueChanged];
8221 [self useFilter:segmented];
8223 [self queueStatusDidChange];
8228 - (void) queueButtonClicked {
8233 - (void) queueStatusDidChange {
8236 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8237 initWithTitle:UCLocalize("QUEUE")
8238 style:UIBarButtonItemStyleDone
8240 action:@selector(queueButtonClicked)
8243 [[self navigationItem] setRightBarButtonItem:nil];
8248 - (void) modeChanged:(UISegmentedControl *)segmented {
8249 [self useFilter:segmented];
8256 /* Source Cell {{{ */
8257 @interface SourceCell : CyteTableViewCell <
8258 CyteTableViewCellDelegate,
8261 _H<Source, 1> source_;
8264 _H<NSString> origin_;
8265 _H<NSString> label_;
8266 _H<UIActivityIndicatorView> indicator_;
8269 - (void) setSource:(Source *)source;
8270 - (void) setFetch:(NSNumber *)fetch;
8274 @implementation SourceCell
8276 - (void) _setImage:(NSArray *)data {
8277 if ([url_ isEqual:[data objectAtIndex:0]]) {
8278 icon_ = [data objectAtIndex:1];
8279 [content_ setNeedsDisplay];
8283 - (void) _setSource:(NSURL *) url {
8284 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8286 if (NSData *data = [NSURLConnection
8287 sendSynchronousRequest:[NSURLRequest
8289 cachePolicy:NSURLRequestUseProtocolCachePolicy
8293 returningResponse:NULL
8296 if (UIImage *image = [UIImage imageWithData:data])
8297 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
8302 - (void) setSource:(Source *)source {
8304 [source_ setDelegate:self];
8306 [self setFetch:[NSNumber numberWithBool:[source_ fetch]]];
8308 icon_ = [UIImage imageNamed:@"unknown.png"];
8310 origin_ = [source name];
8311 label_ = [source rooturi];
8313 [content_ setNeedsDisplay];
8315 url_ = [source iconURL];
8316 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
8319 - (void) setAllSource {
8321 [indicator_ stopAnimating];
8323 icon_ = [UIImage imageNamed:@"folder.png"];
8324 origin_ = UCLocalize("ALL_SOURCES");
8325 label_ = UCLocalize("ALL_SOURCES_EX");
8326 [content_ setNeedsDisplay];
8329 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8330 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8331 UIView *content([self contentView]);
8332 CGRect bounds([content bounds]);
8334 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8335 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8336 [content_ setBackgroundColor:[UIColor whiteColor]];
8337 [content addSubview:content_];
8339 [content_ setDelegate:self];
8340 [content_ setOpaque:YES];
8342 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGraySmall] autorelease];
8343 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin];// | UIViewAutoresizingFlexibleBottomMargin];
8344 [content addSubview:indicator_];
8346 [[content_ layer] setContentsGravity:kCAGravityTopLeft];
8350 - (void) layoutSubviews {
8351 [super layoutSubviews];
8353 UIView *content([self contentView]);
8354 CGRect bounds([content bounds]);
8356 CGRect frame([indicator_ frame]);
8357 frame.origin.x = bounds.size.width - frame.size.width;
8358 frame.origin.y = Retina((bounds.size.height - frame.size.height) / 2);
8360 if (kCFCoreFoundationVersionNumber < 800)
8361 frame.origin.x -= 8;
8362 [indicator_ setFrame:frame];
8365 - (NSString *) accessibilityLabel {
8369 - (void) drawContentRect:(CGRect)rect {
8370 bool highlighted(highlighted_);
8371 float width(rect.size.width);
8375 rect.size = [(UIImage *) icon_ size];
8377 while (rect.size.width > 32 || rect.size.height > 32) {
8378 rect.size.width /= 2;
8379 rect.size.height /= 2;
8382 rect.origin.x = 26 - rect.size.width / 2;
8383 rect.origin.y = 26 - rect.size.height / 2;
8385 [icon_ drawInRect:Retina(rect)];
8388 if (highlighted && kCFCoreFoundationVersionNumber < 800)
8393 [origin_ drawAtPoint:CGPointMake(52, 8) forWidth:(width - 49) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
8397 [label_ drawAtPoint:CGPointMake(52, 29) forWidth:(width - 49) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
8400 - (void) setFetch:(NSNumber *)fetch {
8401 if ([fetch boolValue])
8402 [indicator_ startAnimating];
8404 [indicator_ stopAnimating];
8409 /* Sources Controller {{{ */
8410 @interface SourcesController : CyteViewController <
8411 UITableViewDataSource,
8414 _transient Database *database_;
8417 _H<UITableView, 2> list_;
8418 _H<NSMutableArray> sources_;
8422 _H<UIProgressHUD> hud_;
8425 NSURLConnection *trivial_bz2_;
8426 NSURLConnection *trivial_gz_;
8431 - (id) initWithDatabase:(Database *)database;
8432 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated;
8436 @implementation SourcesController
8438 - (void) _releaseConnection:(NSURLConnection *)connection {
8439 if (connection != nil) {
8440 [connection cancel];
8441 //[connection setDelegate:nil];
8442 [connection release];
8447 [self _releaseConnection:trivial_gz_];
8448 [self _releaseConnection:trivial_bz2_];
8453 - (NSURL *) navigationURL {
8454 return [NSURL URLWithString:@"cydia://sources"];
8457 - (void) viewDidAppear:(BOOL)animated {
8458 [super viewDidAppear:animated];
8459 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8462 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8466 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8468 return UCLocalize("INDIVIDUAL_SOURCES");
8472 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8475 case 1: return [sources_ count];
8480 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8481 @synchronized (database_) {
8482 if ([database_ era] != era_)
8484 if ([indexPath section] != 1)
8486 NSUInteger index([indexPath row]);
8487 if (index >= [sources_ count])
8489 return [sources_ objectAtIndex:index];
8492 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8493 static NSString *cellIdentifier = @"SourceCell";
8495 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8496 if (cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8497 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8499 Source *source([self sourceAtIndexPath:indexPath]);
8501 [cell setAllSource];
8503 [cell setSource:source];
8508 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8509 SectionsController *controller([[[SectionsController alloc]
8510 initWithDatabase:database_
8511 source:[self sourceAtIndexPath:indexPath]
8514 [controller setDelegate:delegate_];
8515 [[self navigationController] pushViewController:controller animated:YES];
8518 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8519 if ([indexPath section] != 1)
8521 Source *source = [self sourceAtIndexPath:indexPath];
8522 return [source record] != nil;
8525 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8526 _assert([indexPath section] == 1);
8527 if (editingStyle == UITableViewCellEditingStyleDelete) {
8528 Source *source = [self sourceAtIndexPath:indexPath];
8529 if (source == nil) return;
8531 [Sources_ removeObjectForKey:[source key]];
8533 [delegate_ _saveConfig];
8534 [delegate_ reloadDataWithInvocation:nil];
8538 - (void) tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath {
8539 [self updateButtonsForEditingStatusAnimated:YES];
8543 [delegate_ addTrivialSource:href_];
8546 [delegate_ syncData];
8549 - (NSString *) getWarning {
8550 NSString *href(href_);
8551 NSRange colon([href rangeOfString:@"://"]);
8552 if (colon.location != NSNotFound)
8553 href = [href substringFromIndex:(colon.location + 3)];
8554 href = [href stringByAddingPercentEscapes];
8555 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8557 NSURL *url([NSURL URLWithString:href]);
8559 NSStringEncoding encoding;
8560 NSError *error(nil);
8562 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8563 return [warning length] == 0 ? nil : warning;
8567 - (void) _endConnection:(NSURLConnection *)connection {
8568 // XXX: the memory management in this method is horribly awkward
8570 NSURLConnection **field = NULL;
8571 if (connection == trivial_bz2_)
8572 field = &trivial_bz2_;
8573 else if (connection == trivial_gz_)
8574 field = &trivial_gz_;
8575 _assert(field != NULL);
8576 [connection release];
8580 trivial_bz2_ == nil &&
8583 NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil);
8585 [delegate_ releaseNetworkActivityIndicator];
8587 [delegate_ removeProgressHUD:hud_];
8591 if (warning != nil) {
8592 UIAlertView *alert = [[[UIAlertView alloc]
8593 initWithTitle:UCLocalize("SOURCE_WARNING")
8596 cancelButtonTitle:UCLocalize("CANCEL")
8598 UCLocalize("ADD_ANYWAY"),
8602 [alert setContext:@"warning"];
8603 [alert setNumberOfRows:1];
8606 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
8612 } else if (error_ != nil) {
8613 UIAlertView *alert = [[[UIAlertView alloc]
8614 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8615 message:[error_ localizedDescription]
8617 cancelButtonTitle:UCLocalize("OK")
8618 otherButtonTitles:nil
8621 [alert setContext:@"urlerror"];
8626 UIAlertView *alert = [[[UIAlertView alloc]
8627 initWithTitle:UCLocalize("NOT_REPOSITORY")
8628 message:UCLocalize("NOT_REPOSITORY_EX")
8630 cancelButtonTitle:UCLocalize("OK")
8631 otherButtonTitles:nil
8634 [alert setContext:@"trivial"];
8644 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8645 switch ([response statusCode]) {
8651 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8652 lprintf("connection:\"%s\" didFailWithError:\"%s\"\n", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8654 [self _endConnection:connection];
8657 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8658 [self _endConnection:connection];
8661 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8662 NSURL *url([NSURL URLWithString:href]);
8664 NSMutableURLRequest *request = [NSMutableURLRequest
8666 cachePolicy:NSURLRequestUseProtocolCachePolicy
8670 [request setHTTPMethod:method];
8672 if (Machine_ != NULL)
8673 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8675 if (UniqueID_ != nil)
8676 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8678 if ([url isCydiaSecure]) {
8679 if (UniqueID_ != nil)
8680 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
8683 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8686 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8687 NSString *context([alert context]);
8689 if ([context isEqualToString:@"source"]) {
8692 NSString *href = [[alert textField] text];
8693 href = VerifySource(href);
8698 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8699 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8703 // XXX: this is stupid
8704 hud_ = [delegate_ addProgressHUD];
8705 [hud_ setText:UCLocalize("VERIFYING_URL")];
8706 [delegate_ retainNetworkActivityIndicator];
8715 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8716 } else if ([context isEqualToString:@"trivial"])
8717 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8718 else if ([context isEqualToString:@"urlerror"])
8719 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8720 else if ([context isEqualToString:@"warning"]) {
8723 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
8732 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8736 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated {
8737 BOOL editing([list_ isEditing]);
8740 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8741 initWithTitle:UCLocalize("ADD")
8742 style:UIBarButtonItemStylePlain
8744 action:@selector(addButtonClicked)
8745 ] autorelease] animated:animated];
8746 else if ([delegate_ updating])
8747 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8748 initWithTitle:UCLocalize("CANCEL")
8749 style:UIBarButtonItemStyleDone
8751 action:@selector(cancelButtonClicked)
8752 ] autorelease] animated:animated];
8754 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8755 initWithTitle:UCLocalize("REFRESH")
8756 style:UIBarButtonItemStylePlain
8758 action:@selector(refreshButtonClicked)
8759 ] autorelease] animated:animated];
8761 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8762 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8763 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8765 action:@selector(editButtonClicked)
8766 ] autorelease] animated:animated];
8770 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease];
8771 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8772 [list_ setRowHeight:53];
8773 [(UITableView *) list_ setDataSource:self];
8774 [list_ setDelegate:self];
8775 [self setView:list_];
8778 - (void) viewDidLoad {
8779 [super viewDidLoad];
8781 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8782 [self updateButtonsForEditingStatusAnimated:NO];
8785 - (void) viewWillAppear:(BOOL)animated {
8786 [super viewWillAppear:animated];
8788 [list_ setEditing:NO];
8789 [self updateButtonsForEditingStatusAnimated:NO];
8792 - (void) releaseSubviews {
8797 [super releaseSubviews];
8800 - (id) initWithDatabase:(Database *)database {
8801 if ((self = [super init]) != nil) {
8802 database_ = database;
8806 - (void) reloadData {
8808 [self updateButtonsForEditingStatusAnimated:YES];
8810 @synchronized (database_) {
8811 era_ = [database_ era];
8813 sources_ = [NSMutableArray arrayWithCapacity:16];
8814 [sources_ addObjectsFromArray:[database_ sources]];
8816 [sources_ sortUsingSelector:@selector(compareByName:)];
8819 int count([sources_ count]);
8821 for (int i = 0; i != count; i++) {
8822 if ([[sources_ objectAtIndex:i] record] == nil)
8830 - (void) showAddSourcePrompt {
8831 UIAlertView *alert = [[[UIAlertView alloc]
8832 initWithTitle:UCLocalize("ENTER_APT_URL")
8835 cancelButtonTitle:UCLocalize("CANCEL")
8837 UCLocalize("ADD_SOURCE"),
8841 [alert setContext:@"source"];
8843 [alert setNumberOfRows:1];
8844 [alert addTextFieldWithValue:@"http://" label:@""];
8846 UITextInputTraits *traits = [[alert textField] textInputTraits];
8847 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8848 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8849 [traits setKeyboardType:UIKeyboardTypeURL];
8850 // XXX: UIReturnKeyDone
8851 [traits setReturnKeyType:UIReturnKeyNext];
8856 - (void) addButtonClicked {
8857 [self showAddSourcePrompt];
8860 - (void) refreshButtonClicked {
8861 if ([delegate_ requestUpdate])
8862 [self updateButtonsForEditingStatusAnimated:YES];
8865 - (void) cancelButtonClicked {
8866 [delegate_ cancelUpdate];
8869 - (void) editButtonClicked {
8870 [list_ setEditing:![list_ isEditing] animated:YES];
8871 [self updateButtonsForEditingStatusAnimated:YES];
8877 /* Stash Controller {{{ */
8878 @interface StashController : CyteViewController {
8879 _H<UIActivityIndicatorView> spinner_;
8880 _H<UILabel> status_;
8881 _H<UILabel> caption_;
8886 @implementation StashController
8889 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8890 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8891 [self setView:view];
8893 [view setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8895 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8896 CGRect spinrect = [spinner_ frame];
8897 spinrect.origin.x = Retina([[self view] frame].size.width / 2 - spinrect.size.width / 2);
8898 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8899 [spinner_ setFrame:spinrect];
8900 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8901 [view addSubview:spinner_];
8902 [spinner_ startAnimating];
8905 captrect.size.width = [[self view] frame].size.width;
8906 captrect.size.height = 40.0f;
8907 captrect.origin.x = 0;
8908 captrect.origin.y = Retina([[self view] frame].size.height / 2 - captrect.size.height * 2);
8909 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8910 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8911 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8912 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8913 [caption_ setTextColor:[UIColor whiteColor]];
8914 [caption_ setBackgroundColor:[UIColor clearColor]];
8915 [caption_ setShadowColor:[UIColor blackColor]];
8916 [caption_ setTextAlignment:NSTextAlignmentCenter];
8917 [view addSubview:caption_];
8920 statusrect.size.width = [[self view] frame].size.width;
8921 statusrect.size.height = 30.0f;
8922 statusrect.origin.x = 0;
8923 statusrect.origin.y = Retina([[self view] frame].size.height / 2 - statusrect.size.height);
8924 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8925 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8926 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8927 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8928 [status_ setTextColor:[UIColor whiteColor]];
8929 [status_ setBackgroundColor:[UIColor clearColor]];
8930 [status_ setShadowColor:[UIColor blackColor]];
8931 [status_ setTextAlignment:NSTextAlignmentCenter];
8932 [view addSubview:status_];
8935 - (void) releaseSubviews {
8940 [super releaseSubviews];
8946 @interface CYURLCache : SDURLCache {
8951 @implementation CYURLCache
8953 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8956 else if ([event isEqualToString:@"no-cache"])
8958 else if ([event isEqualToString:@"store"])
8960 else if ([event isEqualToString:@"invalid"])
8962 else if ([event isEqualToString:@"memory"])
8964 else if ([event isEqualToString:@"disk"])
8966 else if ([event isEqualToString:@"miss"])
8969 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8973 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
8974 if (NSURLResponse *response = [cached response])
8975 if (NSString *mime = [response MIMEType])
8976 if ([mime isEqualToString:@"text/cache-manifest"]) {
8977 NSURL *url([response URL]);
8980 NSLog(@"###: %@", [url absoluteString]);
8983 @synchronized (HostConfig_) {
8984 [CachedURLs_ addObject:url];
8988 [super storeCachedResponse:cached forRequest:request];
8991 - (void) createDiskCachePath {
8992 [super createDiskCachePath];
8997 @interface Cydia : UIApplication <
8998 ConfirmationControllerDelegate,
9002 _H<UIWindow> window_;
9003 _H<CydiaTabBarController> tabbar_;
9004 _H<CyteTabBarController> emulated_;
9005 _H<AppCacheController> appcache_;
9007 _H<NSMutableArray> essential_;
9008 _H<NSMutableArray> broken_;
9010 Database *database_;
9012 _H<NSURL> starturl_;
9017 _H<StashController> stash_;
9026 @implementation Cydia
9028 - (void) lockSuspend {
9029 if (locked_++ == 0) {
9030 if ($SBSSetInterceptsMenuButtonForever != NULL)
9031 (*$SBSSetInterceptsMenuButtonForever)(true);
9033 [self setIdleTimerDisabled:YES];
9037 - (void) unlockSuspend {
9038 if (--locked_ == 0) {
9039 [self setIdleTimerDisabled:NO];
9041 if ($SBSSetInterceptsMenuButtonForever != NULL)
9042 (*$SBSSetInterceptsMenuButtonForever)(false);
9046 - (void) beginUpdate {
9047 [tabbar_ beginUpdate];
9050 - (void) cancelUpdate {
9051 [tabbar_ cancelUpdate];
9054 - (bool) requestUpdate {
9055 if (IsReachable("cydia.saurik.com")) {
9059 UIAlertView *alert = [[[UIAlertView alloc]
9060 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("REFRESH")]
9061 message:@"Host Unreachable" // XXX: Localize
9063 cancelButtonTitle:UCLocalize("OK")
9064 otherButtonTitles:nil
9067 [alert setContext:@"norefresh"];
9075 return [tabbar_ updating];
9079 if ([broken_ count] != 0) {
9080 int count = [broken_ count];
9082 UIAlertView *alert = [[[UIAlertView alloc]
9083 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
9084 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
9086 cancelButtonTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("FORCIBLY_CLEAR"), UCLocalize("UNSAFE")]
9088 UCLocalize("TEMPORARY_IGNORE"),
9092 [alert setContext:@"fixhalf"];
9093 [alert setNumberOfRows:2];
9095 } else if (!Ignored_ && [essential_ count] != 0) {
9096 int count = [essential_ count];
9098 UIAlertView *alert = [[[UIAlertView alloc]
9099 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
9100 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
9102 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
9104 UCLocalize("UPGRADE_ESSENTIAL"),
9105 UCLocalize("COMPLETE_UPGRADE"),
9109 [alert setContext:@"upgrade"];
9114 - (void) returnToCydia {
9118 - (void) reloadSpringBoard {
9119 if (kCFCoreFoundationVersionNumber >= 700) // XXX: iOS 6.x
9120 system("/bin/launchctl stop com.apple.backboardd");
9122 system("/bin/launchctl stop com.apple.SpringBoard");
9124 system("/usr/bin/killall backboardd SpringBoard");
9127 - (void) _saveConfig {
9128 SaveConfig(database_);
9131 // Navigation controller for the queuing badge.
9132 - (UINavigationController *) queueNavigationController {
9133 NSArray *controllers = [tabbar_ viewControllers];
9134 return [controllers objectAtIndex:3];
9137 - (void) unloadData {
9138 [tabbar_ unloadData];
9141 - (void) _updateData {
9145 UINavigationController *navigation = [self queueNavigationController];
9147 id queuedelegate = nil;
9148 if ([[navigation viewControllers] count] > 0)
9149 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9151 [queuedelegate queueStatusDidChange];
9152 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9155 - (void) _refreshIfPossible {
9156 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9158 NSDate *update([[NSDictionary dictionaryWithContentsOfFile:@ CacheState_] objectForKey:@"LastUpdate"]);
9160 bool recently = false;
9161 if (update != nil) {
9162 NSTimeInterval interval([update timeIntervalSinceNow]);
9163 if (interval > -(15*60))
9167 // Don't automatic refresh if:
9168 // - We already refreshed recently.
9169 // - We already auto-refreshed this launch.
9170 // - Auto-refresh is disabled.
9171 // - Cydia's server is not reachable
9172 if (recently || loaded_ || ManualRefresh || !IsReachable("cydia.saurik.com")) {
9173 // If we are cancelling, we need to make sure it knows it's already loaded.
9176 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9178 // We are going to load, so remember that.
9181 [tabbar_ performSelectorOnMainThread:@selector(beginUpdate) withObject:nil waitUntilDone:NO];
9187 - (void) refreshIfPossible {
9188 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
9191 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9192 _profile(reloadDataWithInvocation)
9193 @synchronized (self) {
9194 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9196 [hud setText:UCLocalize("RELOADING_DATA")];
9198 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9202 [essential_ removeAllObjects];
9203 [broken_ removeAllObjects];
9205 _profile(reloadDataWithInvocation$Essential)
9206 NSArray *packages([database_ packages]);
9207 for (Package *package in packages) {
9209 [broken_ addObject:package];
9210 if ([package upgradableAndEssential:YES] && ![package ignored]) {
9211 if ([package essential] && [package installed] != nil)
9212 [essential_ addObject:package];
9218 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9221 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9222 [changesItem setBadgeValue:badge];
9223 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9224 [self setApplicationIconBadgeNumber:changes];
9227 [changesItem setBadgeValue:nil];
9228 [changesItem setAnimatedBadge:NO];
9229 [self setApplicationIconBadgeNumber:0];
9236 [self removeProgressHUD:hud];
9243 - (void) updateData {
9247 - (void) updateDataAndLoad {
9249 if ([database_ progressDelegate] == nil)
9255 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9258 - (void) disemulate {
9259 if (emulated_ == nil)
9262 if ([window_ respondsToSelector:@selector(setRootViewController:)])
9263 [window_ setRootViewController:tabbar_];
9265 [window_ addSubview:[tabbar_ view]];
9266 [[emulated_ view] removeFromSuperview];
9270 [window_ setUserInteractionEnabled:YES];
9273 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9274 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9276 UIViewController *parent;
9277 if (emulated_ == nil)
9287 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9288 [parent presentModalViewController:navigation animated:YES];
9291 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9292 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9294 if (navigation != nil)
9295 [navigation pushViewController:progress animated:YES];
9297 [self presentModalViewController:progress force:YES];
9299 [progress invoke:invocation withTitle:title];
9303 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9304 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9307 - (void) repairWithInvocation:(NSInvocation *)invocation {
9309 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9313 - (void) repairWithSelector:(SEL)selector {
9314 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9317 - (void) reloadData {
9318 [self reloadDataWithInvocation:nil];
9319 if ([database_ progressDelegate] == nil)
9325 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9328 - (void) addSource:(NSDictionary *) source {
9329 CydiaAddSource(source);
9332 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9333 CydiaAddSource(href, distribution, sections);
9336 // XXX: this method should not return anything
9337 - (BOOL) addTrivialSource:(NSString *)href {
9338 CydiaAddSource(href, @"./");
9343 pkgProblemResolver *resolver = [database_ resolver];
9345 resolver->InstallProtect();
9346 if (!resolver->Resolve(true))
9351 // XXX: this is a really crappy way of doing this.
9352 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9353 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9354 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9355 if ([tabbar_ updating])
9356 [tabbar_ cancelUpdate];
9358 if (![database_ prepare])
9361 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9362 [page setDelegate:self];
9363 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9366 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9367 [tabbar_ presentModalViewController:confirm_ animated:YES];
9373 @synchronized (self) {
9378 - (void) clearPackage:(Package *)package {
9379 @synchronized (self) {
9386 - (void) installPackages:(NSArray *)packages {
9387 @synchronized (self) {
9388 for (Package *package in packages)
9395 - (void) installPackage:(Package *)package {
9396 @synchronized (self) {
9403 - (void) removePackage:(Package *)package {
9404 @synchronized (self) {
9411 - (void) distUpgrade {
9412 @synchronized (self) {
9413 if (![database_ upgrade])
9421 system("/usr/bin/uicache");
9426 UIProgressHUD *hud([self addProgressHUD]);
9427 [hud setText:UCLocalize("LOADING")];
9428 [self yieldToSelector:@selector(_uicache)];
9429 [self removeProgressHUD:hud];
9433 [database_ perform];
9434 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9435 [self performSelectorOnMainThread:@selector(uicache) withObject:nil waitUntilDone:YES];
9438 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9441 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9442 [self unlockSuspend];
9445 - (void) retainNetworkActivityIndicator {
9446 if (activity_++ == 0)
9447 [self setNetworkActivityIndicatorVisible:YES];
9450 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9454 - (void) releaseNetworkActivityIndicator {
9455 if (--activity_ == 0)
9456 [self setNetworkActivityIndicatorVisible:NO];
9459 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9464 - (void) cancelAndClear:(bool)clear {
9465 @synchronized (self) {
9477 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9478 NSString *context([alert context]);
9480 if ([context isEqualToString:@"conffile"]) {
9481 FILE *input = [database_ input];
9482 if (button == [alert cancelButtonIndex])
9483 fprintf(input, "N\n");
9484 else if (button == [alert firstOtherButtonIndex])
9485 fprintf(input, "Y\n");
9488 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9489 } else if ([context isEqualToString:@"fixhalf"]) {
9490 if (button == [alert cancelButtonIndex]) {
9491 @synchronized (self) {
9492 for (Package *broken in (id) broken_) {
9494 NSString *id(ShellEscape([broken id]));
9495 system([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /bin/rm -f"
9496 " /var/lib/dpkg/info/%@.prerm"
9497 " /var/lib/dpkg/info/%@.postrm"
9498 " /var/lib/dpkg/info/%@.preinst"
9499 " /var/lib/dpkg/info/%@.postinst"
9500 " /var/lib/dpkg/info/%@.extrainst_"
9501 "", id, id, id, id, id] UTF8String]);
9507 } else if (button == [alert firstOtherButtonIndex]) {
9508 [broken_ removeAllObjects];
9512 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9513 } else if ([context isEqualToString:@"upgrade"]) {
9514 if (button == [alert firstOtherButtonIndex]) {
9515 @synchronized (self) {
9516 for (Package *essential in (id) essential_)
9517 [essential install];
9522 } else if (button == [alert firstOtherButtonIndex] + 1) {
9524 } else if (button == [alert cancelButtonIndex]) {
9528 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9532 - (void) system:(NSString *)command {
9533 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9536 system([command UTF8String]);
9542 - (void) applicationWillSuspend {
9544 [super applicationWillSuspend];
9547 - (BOOL) isSafeToSuspend {
9550 NSLog(@"isSafeToSuspend: locked_ != 0");
9555 if ([tabbar_ modalViewController] != nil)
9558 // Use external process status API internally.
9559 // This is probably a really bad idea.
9560 // XXX: what is the point of this? does this solve anything at all?
9561 uint64_t status = 0;
9563 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9564 notify_get_state(notify_token, &status);
9565 notify_cancel(notify_token);
9570 NSLog(@"isSafeToSuspend: status != 0");
9576 NSLog(@"isSafeToSuspend: -> true");
9581 - (void) suspendReturningToLastApp:(BOOL)returning {
9582 if ([self isSafeToSuspend])
9583 [super suspendReturningToLastApp:returning];
9587 if ([self isSafeToSuspend])
9591 - (void) applicationSuspend {
9592 if ([self isSafeToSuspend])
9593 [super applicationSuspend];
9596 - (void) applicationSuspend:(__GSEvent *)event {
9597 if ([self isSafeToSuspend])
9598 [super applicationSuspend:event];
9601 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9602 if ([self isSafeToSuspend])
9603 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9606 - (void) _setSuspended:(BOOL)value {
9607 if ([self isSafeToSuspend])
9608 [super _setSuspended:value];
9611 - (UIProgressHUD *) addProgressHUD {
9612 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9613 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9615 [window_ setUserInteractionEnabled:NO];
9617 UIViewController *target(tabbar_);
9618 if (UIViewController *modal = [target modalViewController])
9621 [hud showInView:[target view]];
9627 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9628 [self unlockSuspend];
9630 [hud removeFromSuperview];
9631 [window_ setUserInteractionEnabled:YES];
9634 - (CyteViewController *) pageForPackage:(NSString *)name withReferrer:(NSString *)referrer {
9635 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name withReferrer:referrer] autorelease];
9638 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external withReferrer:(NSString *)referrer {
9639 NSString *scheme([[url scheme] lowercaseString]);
9640 if ([[url absoluteString] length] <= [scheme length] + 3)
9642 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9643 NSArray *components([path componentsSeparatedByString:@"/"]);
9645 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"]) {
9646 CyteViewController *controller([self pageForPackage:[components objectAtIndex:1] withReferrer:referrer]);
9647 if (controller != nil)
9648 [controller setDelegate:self];
9652 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9655 NSString *base([components objectAtIndex:0]);
9657 CyteViewController *controller = nil;
9659 if ([base isEqualToString:@"url"]) {
9660 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9661 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9662 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9663 } else if (!external && [components count] == 1) {
9664 if ([base isEqualToString:@"sources"]) {
9665 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9668 if ([base isEqualToString:@"home"]) {
9669 controller = [[[HomeController alloc] init] autorelease];
9672 if ([base isEqualToString:@"sections"]) {
9673 controller = [[[SectionsController alloc] initWithDatabase:database_ source:nil] autorelease];
9676 if ([base isEqualToString:@"search"]) {
9677 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9680 if ([base isEqualToString:@"changes"]) {
9681 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9684 if ([base isEqualToString:@"installed"]) {
9685 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9687 } else if ([components count] == 2) {
9688 NSString *argument = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9690 if ([base isEqualToString:@"package"]) {
9691 controller = [self pageForPackage:argument withReferrer:referrer];
9694 if (!external && [base isEqualToString:@"search"]) {
9695 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9698 if (!external && [base isEqualToString:@"sections"]) {
9699 if ([argument isEqualToString:@"all"] || [argument isEqualToString:@"*"])
9701 controller = [[[SectionController alloc] initWithDatabase:database_ source:nil section:argument] autorelease];
9704 if ([base isEqualToString:@"sources"]) {
9705 if ([argument isEqualToString:@"add"]) {
9706 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9707 [(SourcesController *)controller showAddSourcePrompt];
9709 Source *source([database_ sourceWithKey:argument]);
9710 controller = [[[SectionsController alloc] initWithDatabase:database_ source:source] autorelease];
9714 if (!external && [base isEqualToString:@"launch"]) {
9715 [self launchApplicationWithIdentifier:argument suspended:NO];
9718 } else if (!external && [components count] == 3) {
9719 NSString *arg1 = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9720 NSString *arg2 = [[components objectAtIndex:2] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9722 if ([base isEqualToString:@"package"]) {
9723 if ([arg2 isEqualToString:@"settings"]) {
9724 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9725 } else if ([arg2 isEqualToString:@"files"]) {
9726 if (Package *package = [database_ packageWithName:arg1]) {
9727 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9728 [(FileTable *)controller setPackage:package];
9733 if ([base isEqualToString:@"sections"]) {
9734 Source *source([arg1 isEqualToString:@"*"] ? nil : [database_ sourceWithKey:arg1]);
9735 NSString *section([arg2 isEqualToString:@"*"] ? nil : arg2);
9736 controller = [[[SectionController alloc] initWithDatabase:database_ source:source section:section] autorelease];
9740 [controller setDelegate:self];
9744 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9745 CyteViewController *page([self pageForURL:url forExternal:external withReferrer:nil]);
9748 [tabbar_ setUnselectedViewController:page];
9753 - (void) applicationOpenURL:(NSURL *)url {
9754 [super applicationOpenURL:url];
9759 [self openCydiaURL:url forExternal:YES];
9762 - (void) applicationWillResignActive:(UIApplication *)application {
9763 // Stop refreshing if you get a phone call or lock the device.
9764 if ([tabbar_ updating])
9765 [tabbar_ cancelUpdate];
9767 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9768 [super applicationWillResignActive:application];
9771 - (void) saveState {
9772 [[NSDictionary dictionaryWithObjectsAndKeys:
9773 @"InterfaceState", [tabbar_ navigationURLCollection],
9774 @"LastClosed", [NSDate date],
9775 @"InterfaceIndex", [NSNumber numberWithInt:[tabbar_ selectedIndex]],
9776 nil] writeToFile:@ SavedState_ atomically:YES];
9781 - (void) applicationWillTerminate:(UIApplication *)application {
9785 - (void) applicationDidEnterBackground:(UIApplication *)application {
9786 if (kCFCoreFoundationVersionNumber < 1000 && [self isSafeToSuspend])
9787 return [self terminateWithSuccess];
9788 Backgrounded_ = [NSDate date];
9792 - (void) applicationWillEnterForeground:(UIApplication *)application {
9793 if (Backgrounded_ == nil)
9796 NSTimeInterval interval([Backgrounded_ timeIntervalSinceNow]);
9798 if (interval <= -(30*60)) {
9799 [tabbar_ setSelectedIndex:0];
9800 [[[tabbar_ viewControllers] objectAtIndex:0] popToRootViewControllerAnimated:NO];
9803 if (interval <= -(15*60)) {
9804 if (IsReachable("cydia.saurik.com")) {
9805 [tabbar_ beginUpdate];
9806 [appcache_ reloadURLWithCache:YES];
9810 if ([database_ delocked])
9814 - (void) setConfigurationData:(NSString *)data {
9815 static RegEx conffile_r("'(.*)' '(.*)' ([01]) ([01])");
9817 if (!conffile_r(data)) {
9818 lprintf("E:invalid conffile\n");
9822 NSString *ofile = conffile_r[1];
9823 //NSString *nfile = conffile_r[2];
9825 UIAlertView *alert = [[[UIAlertView alloc]
9826 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9827 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9829 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9831 UCLocalize("ACCEPT_NEW_COPY"),
9832 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9836 [alert setContext:@"conffile"];
9837 [alert setNumberOfRows:2];
9841 - (void) addStashController {
9843 stash_ = [[[StashController alloc] init] autorelease];
9844 [window_ addSubview:[stash_ view]];
9847 - (void) removeStashController {
9848 [[stash_ view] removeFromSuperview];
9850 [self unlockSuspend];
9854 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9855 UpdateExternalStatus(1);
9856 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/cydo /usr/libexec/cydia/free.sh"];
9857 UpdateExternalStatus(0);
9859 [self removeStashController];
9860 [self reloadSpringBoard];
9863 - (void) setupViewControllers {
9864 tabbar_ = [[[CydiaTabBarController alloc] initWithDatabase:database_] autorelease];
9866 NSMutableArray *items;
9867 if (kCFCoreFoundationVersionNumber < 800) {
9868 items = [NSMutableArray arrayWithObjects:
9869 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage imageNamed:@"home.png"] tag:0] autorelease],
9870 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage imageNamed:@"install.png"] tag:0] autorelease],
9871 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage imageNamed:@"changes.png"] tag:0] autorelease],
9872 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage imageNamed:@"manage.png"] tag:0] autorelease],
9873 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage imageNamed:@"search.png"] tag:0] autorelease],
9876 items = [NSMutableArray arrayWithObjects:
9877 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage imageNamed:@"home7.png"] selectedImage:[UIImage imageNamed:@"home7s.png"]] autorelease],
9878 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage imageNamed:@"install7.png"] selectedImage:[UIImage imageNamed:@"install7s.png"]] autorelease],
9879 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage imageNamed:@"changes7.png"] selectedImage:[UIImage imageNamed:@"changes7s.png"]] autorelease],
9880 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage imageNamed:@"manage7.png"] selectedImage:[UIImage imageNamed:@"manage7s.png"]] autorelease],
9881 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage imageNamed:@"search7.png"] selectedImage:[UIImage imageNamed:@"search7s.png"]] autorelease],
9885 NSMutableArray *controllers([NSMutableArray array]);
9886 for (UITabBarItem *item in items) {
9887 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9888 [controller setTabBarItem:item];
9889 [controllers addObject:controller];
9891 [tabbar_ setViewControllers:controllers];
9893 [tabbar_ setUpdateDelegate:self];
9896 - (void) _sendMemoryWarningNotification {
9897 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: maybe 4_0?
9898 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationMemoryWarningNotification" object:[UIApplication sharedApplication]];
9900 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
9903 - (void) _sendMemoryWarningNotifications {
9905 [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO];
9911 - (void) applicationDidReceiveMemoryWarning:(UIApplication *)application {
9913 [[NSURLCache sharedURLCache] removeAllCachedResponses];
9916 - (void) applicationDidFinishLaunching:(id)unused {
9917 //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil];
9920 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9921 [self setApplicationSupportsShakeToEdit:NO];
9923 @synchronized (HostConfig_) {
9924 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9927 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9928 initWithMemoryCapacity:524288
9929 diskCapacity:10485760
9930 diskPath:Cache("SDURLCache")
9933 [CydiaWebViewController _initialize];
9935 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9937 // this would disallow http{,s} URLs from accessing this data
9938 //[WebView registerURLSchemeAsLocal:@"cydia"];
9940 Font12_ = [UIFont systemFontOfSize:12];
9941 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9942 Font14_ = [UIFont systemFontOfSize:14];
9943 Font18_ = [UIFont systemFontOfSize:18];
9944 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9945 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9947 essential_ = [NSMutableArray arrayWithCapacity:4];
9948 broken_ = [NSMutableArray arrayWithCapacity:4];
9950 // XXX: I really need this thing... like, seriously... I'm sorry
9951 appcache_ = [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] autorelease];
9952 [appcache_ reloadData];
9954 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9955 [window_ orderFront:self];
9956 [window_ makeKey:self];
9957 [window_ setHidden:NO];
9959 if (access("/.cydia_no_stash", F_OK) == 0);
9963 [self addStashController];
9964 // XXX: this would be much cleaner as a yieldToSelector:
9965 // that way the removeStashController could happen right here inline
9966 // we also could no longer require the useless stash_ field anymore
9967 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9972 int error(stat("/", &root));
9973 _assert(error != -1);
9975 #define Stash_(path) do { \
9976 struct stat folder; \
9977 int error(lstat((path), &folder)); \
9978 if (error != -1 && ( \
9979 folder.st_dev == root.st_dev && \
9980 S_ISDIR(folder.st_mode) \
9981 ) || error == -1 && ( \
9982 errno == ENOENT || \
9987 Stash_("/Applications");
9988 Stash_("/Library/Ringtones");
9989 Stash_("/Library/Wallpaper");
9990 //Stash_("/usr/bin");
9991 Stash_("/usr/include");
9992 Stash_("/usr/share");
9993 //Stash_("/var/lib");
9997 database_ = [Database sharedInstance];
9998 [database_ setDelegate:self];
10000 [window_ setUserInteractionEnabled:NO];
10001 [self setupViewControllers];
10003 CydiaLoadingViewController *loading([[[CydiaLoadingViewController alloc] init] autorelease]);
10004 UINavigationController *navigation([[[UINavigationController alloc] init] autorelease]);
10005 [navigation setViewControllers:[NSArray arrayWithObject:loading]];
10007 emulated_ = [[[CyteTabBarController alloc] init] autorelease];
10008 [emulated_ setViewControllers:[NSArray arrayWithObject:navigation]];
10009 [emulated_ setSelectedIndex:0];
10011 if ([emulated_ respondsToSelector:@selector(concealTabBarSelection)])
10012 [emulated_ concealTabBarSelection];
10014 if ([window_ respondsToSelector:@selector(setRootViewController:)])
10015 [window_ setRootViewController:emulated_];
10017 [window_ addSubview:[emulated_ view]];
10019 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
10023 - (NSArray *) defaultStartPages {
10024 NSMutableArray *standard = [NSMutableArray array];
10025 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
10026 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
10027 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
10028 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
10029 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
10033 - (void) loadData {
10035 if ([emulated_ modalViewController] != nil)
10036 [emulated_ dismissModalViewControllerAnimated:YES];
10037 [window_ setUserInteractionEnabled:NO];
10039 [self reloadDataWithInvocation:nil];
10040 [self refreshIfPossible];
10043 NSDictionary *state([NSDictionary dictionaryWithContentsOfFile:@ SavedState_]);
10045 int savedIndex = [[state objectForKey:@"InterfaceIndex"] intValue];
10046 NSArray *saved = [[[state objectForKey:@"InterfaceState"] mutableCopy] autorelease];
10047 int standardIndex = 0;
10048 NSArray *standard = [self defaultStartPages];
10055 NSDate *closed = [state objectForKey:@"LastClosed"];
10056 if (valid && closed != nil) {
10057 NSTimeInterval interval([closed timeIntervalSinceNow]);
10058 if (interval <= -(30*60))
10062 if (valid && [saved count] != [standard count])
10066 for (unsigned int i = 0; i < [standard count]; i++) {
10067 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
10068 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
10069 // but it's good enough for now.
10070 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
10077 NSArray *items = nil;
10079 [tabbar_ setSelectedIndex:savedIndex];
10082 [tabbar_ setSelectedIndex:standardIndex];
10086 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
10087 NSArray *stack = [items objectAtIndex:tab];
10088 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
10089 NSMutableArray *current = [NSMutableArray array];
10091 for (unsigned int nav = 0; nav < [stack count]; nav++) {
10092 NSString *addr = [stack objectAtIndex:nav];
10093 NSURL *url = [NSURL URLWithString:addr];
10094 CyteViewController *page = [self pageForURL:url forExternal:NO withReferrer:nil];
10096 [current addObject:page];
10099 [navigation setViewControllers:current];
10102 // (Try to) show the startup URL.
10103 if (starturl_ != nil) {
10104 [self openCydiaURL:starturl_ forExternal:YES];
10109 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
10111 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
10112 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
10115 if (item != nil && IsWildcat_) {
10116 [sheet showFromBarButtonItem:item animated:YES];
10118 [sheet showInView:window_];
10122 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
10123 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
10124 [progress setTitle:task];
10125 [progress addProgressEvent:event];
10128 - (void) addProgressEventForTask:(NSArray *)data {
10129 CydiaProgressEvent *event([data objectAtIndex:0]);
10130 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
10131 [self addProgressEvent:event forTask:task];
10134 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
10135 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
10141 id Alloc_(id self, SEL selector) {
10142 id object = alloc_(self, selector);
10143 lprintf("[%s]A-%p\n", self->isa->name, object);
10148 id Dealloc_(id self, SEL selector) {
10149 id object = dealloc_(self, selector);
10150 lprintf("[%s]D-%p\n", self->isa->name, object);
10154 Class $NSURLConnection;
10156 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
10157 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
10159 NSURL *url([copy URL]);
10161 NSString *host([url host]);
10162 NSString *scheme([[url scheme] lowercaseString]);
10164 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
10166 @synchronized (HostConfig_) {
10167 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
10168 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
10169 [copy setHTTPShouldUsePipelining:YES];
10171 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
10172 if ([control isEqualToString:@"max-age=0"])
10173 if ([CachedURLs_ containsObject:url]) {
10175 NSLog(@"~~~: %@", url);
10178 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
10180 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
10181 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
10182 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
10186 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
10192 static CGSize $WAKWindow$screenSize(WAKWindow *self, SEL _cmd) {
10193 CGSize size([[UIScreen mainScreen] bounds].size);
10194 /*if ([$WAKWindow respondsToSelector:@selector(hasLandscapeOrientation)])
10195 if ([$WAKWindow hasLandscapeOrientation])
10196 std::swap(size.width, size.height);*/
10200 Class $NSUserDefaults;
10202 MSHook(id, NSUserDefaults$objectForKey$, NSUserDefaults *self, SEL _cmd, NSString *key) {
10203 if ([key respondsToSelector:@selector(isEqualToString:)] && [key isEqualToString:@"WebKitLocalStorageDatabasePathPreferenceKey"])
10204 return Cache("LocalStorage");
10205 return _NSUserDefaults$objectForKey$(self, _cmd, key);
10208 static NSMutableDictionary *AutoreleaseDeepMutableCopyOfDictionary(CFTypeRef type) {
10211 if (CFGetTypeID(type) != CFDictionaryGetTypeID())
10213 CFTypeRef copy(CFPropertyListCreateDeepCopy(kCFAllocatorDefault, type, kCFPropertyListMutableContainers));
10215 return [(NSMutableDictionary *) copy autorelease];
10218 int main(int argc, char *argv[]) {
10219 int fd(open("/tmp/cydia.log", O_WRONLY | O_APPEND | O_CREAT, 0644));
10223 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10227 UpdateExternalStatus(0);
10229 UIScreen *screen([UIScreen mainScreen]);
10230 if ([screen respondsToSelector:@selector(scale)])
10231 ScreenScale_ = [screen scale];
10235 UIDevice *device([UIDevice currentDevice]);
10236 if ([device respondsToSelector:@selector(userInterfaceIdiom)]) {
10237 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10238 if (idiom == UIUserInterfaceIdiomPad)
10242 Idiom_ = IsWildcat_ ? @"ipad" : @"iphone";
10244 RegEx pattern("([0-9]+\\.[0-9]+).*");
10246 if (pattern([device systemVersion]))
10247 Firmware_ = pattern[1];
10248 if (pattern(Cydia_))
10249 Major_ = pattern[1];
10251 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
10253 HostConfig_ = [[[NSObject alloc] init] autorelease];
10254 @synchronized (HostConfig_) {
10255 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10256 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
10257 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
10258 CachedURLs_ = [NSMutableSet setWithCapacity:32];
10261 NSString *ui(@"ui/ios");
10263 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
10264 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"/%@", Major_]];
10265 UI_ = CydiaURL(ui);
10267 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10269 /* Library Hacks {{{ */
10270 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10272 $WAKWindow = objc_getClass("WAKWindow");
10273 if ($WAKWindow != NULL)
10274 if (Method method = class_getInstanceMethod($WAKWindow, @selector(screenSize)))
10275 method_setImplementation(method, (IMP) &$WAKWindow$screenSize);
10277 $NSURLConnection = objc_getClass("NSURLConnection");
10278 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10279 if (NSURLConnection$init$ != NULL) {
10280 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10281 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10284 $NSUserDefaults = objc_getClass("NSUserDefaults");
10285 Method NSUserDefaults$objectForKey$(class_getInstanceMethod($NSUserDefaults, @selector(objectForKey:)));
10286 if (NSUserDefaults$objectForKey$ != NULL) {
10287 _NSUserDefaults$objectForKey$ = reinterpret_cast<id (*)(NSUserDefaults *, SEL, NSString *)>(method_getImplementation(NSUserDefaults$objectForKey$));
10288 method_setImplementation(NSUserDefaults$objectForKey$, reinterpret_cast<IMP>(&$NSUserDefaults$objectForKey$));
10291 /* Set Locale {{{ */
10292 Locale_ = CFLocaleCopyCurrent();
10293 Languages_ = [NSLocale preferredLanguages];
10295 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10296 //NSLog(@"%@", [Languages_ description]);
10299 if (Locale_ != NULL)
10300 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10301 else if (Languages_ != nil && [Languages_ count] != 0)
10302 lang = [[Languages_ objectAtIndex:0] UTF8String];
10304 // XXX: consider just setting to C and then falling through?
10307 if (lang != NULL) {
10308 RegEx pattern("([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?");
10309 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10312 NSLog(@"Setting Language: %s", lang);
10314 if (lang != NULL) {
10315 setenv("LANG", lang, true);
10316 std::setlocale(LC_ALL, lang);
10319 /* Index Collation {{{ */
10320 if (Class $UILocalizedIndexedCollation = objc_getClass("UILocalizedIndexedCollation")) { @try {
10321 NSBundle *bundle([NSBundle bundleForClass:$UILocalizedIndexedCollation]);
10322 NSString *path([bundle pathForResource:@"UITableViewLocalizedSectionIndex" ofType:@"plist"]);
10323 //path = @"/System/Library/Frameworks/UIKit.framework/.lproj/UITableViewLocalizedSectionIndex.plist";
10324 NSDictionary *dictionary([NSDictionary dictionaryWithContentsOfFile:path]);
10325 _H<UILocalizedIndexedCollation> collation([[[$UILocalizedIndexedCollation alloc] initWithDictionary:dictionary] autorelease]);
10327 CollationLocale_ = MSHookIvar<NSLocale *>(collation, "_locale");
10329 if (kCFCoreFoundationVersionNumber >= 800 && [[CollationLocale_ localeIdentifier] isEqualToString:@"zh@collation=stroke"]) {
10330 CollationThumbs_ = [NSArray arrayWithObjects:@"1",@"•",@"4",@"•",@"7",@"•",@"10",@"•",@"13",@"•",@"16",@"•",@"19",@"A",@"•",@"E",@"•",@"I",@"•",@"M",@"•",@"R",@"•",@"V",@"•",@"Z",@"#",nil];
10331 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})
10332 CollationOffset_.push_back(offset);
10333 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];
10334 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];
10337 CollationThumbs_ = [collation sectionIndexTitles];
10338 for (size_t index(0), end([CollationThumbs_ count]); index != end; ++index)
10339 CollationOffset_.push_back([collation sectionForSectionIndexTitleAtIndex:index]);
10341 CollationTitles_ = [collation sectionTitles];
10342 CollationStarts_ = MSHookIvar<NSArray *>(collation, "_sectionStartStrings");
10344 NSString *&transform(MSHookIvar<NSString *>(collation, "_transform"));
10345 if (&transform != NULL && transform != nil) {
10346 /*if ([collation respondsToSelector:@selector(transformedCollationStringForString:)])
10347 CollationModify_ = [=](NSString *value) { return [collation transformedCollationStringForString:value]; };*/
10348 const UChar *uid(reinterpret_cast<const UChar *>([transform cStringUsingEncoding:NSUnicodeStringEncoding]));
10349 UErrorCode code(U_ZERO_ERROR);
10350 CollationTransl_ = utrans_openU(uid, -1, UTRANS_FORWARD, NULL, 0, NULL, &code);
10351 if (!U_SUCCESS(code))
10352 NSLog(@"%s", u_errorName(code));
10356 } @catch (NSException *e) {
10360 CollationLocale_ = [[[NSLocale alloc] initWithLocaleIdentifier:@"en@collation=dictionary"] autorelease];
10362 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];
10363 for (NSInteger offset(0); offset != 28; ++offset)
10364 CollationOffset_.push_back(offset);
10366 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];
10367 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];
10370 /* Parse Arguments {{{ */
10371 bool substrate(false);
10377 for (int argi(1); argi != argc; ++argi)
10378 if (strcmp(argv[argi], "--") == 0) {
10380 argv[argi] = argv[0];
10386 for (int argi(1); argi != arge; ++argi)
10387 if (strcmp(args[argi], "--substrate") == 0)
10390 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10394 App_ = [[NSBundle mainBundle] bundlePath];
10397 Cache_ = [[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia", @"/var/mobile"] retain];
10398 mkdir([Cache_ UTF8String], 0755);
10400 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10401 alloc_ = alloc->method_imp;
10402 alloc->method_imp = (IMP) &Alloc_;*/
10404 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10405 dealloc_ = dealloc->method_imp;
10406 dealloc->method_imp = (IMP) &Dealloc_;*/
10408 void *gestalt(dlopen("/usr/lib/libMobileGestalt.dylib", RTLD_GLOBAL | RTLD_LAZY));
10409 $MGCopyAnswer = reinterpret_cast<CFStringRef (*)(CFStringRef)>(dlsym(gestalt, "MGCopyAnswer"));
10411 /* System Information {{{ */
10415 size = sizeof(maxproc);
10416 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10417 perror("sysctlbyname(\"kern.maxproc\", ?)");
10418 else if (maxproc < 64) {
10420 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10421 perror("sysctlbyname(\"kern.maxproc\", #)");
10424 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10425 char *osversion = new char[size];
10426 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10427 perror("sysctlbyname(\"kern.osversion\", ?)");
10429 System_ = [NSString stringWithUTF8String:osversion];
10431 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10432 char *machine = new char[size];
10433 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10434 perror("sysctlbyname(\"hw.machine\", ?)");
10436 Machine_ = machine;
10438 int64_t usermem(0);
10439 size = sizeof(usermem);
10440 if (sysctlbyname("hw.usermem", &usermem, &size, NULL, 0) == -1)
10443 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10444 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10445 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10447 UniqueID_ = UniqueIdentifier(device);
10449 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10450 Product_ = [info objectForKey:@"SafariProductVersion"];
10451 Safari_ = [info objectForKey:@"CFBundleVersion"];
10454 NSString *agent([NSString stringWithFormat:@"Cydia/%@ CyF/%.2f", Cydia_, kCFCoreFoundationVersionNumber]);
10456 if (RegEx match = RegEx("([0-9]+(\\.[0-9]+)+).*", Safari_))
10457 agent = [NSString stringWithFormat:@"Safari/%@ %@", match[1], agent];
10458 if (RegEx match = RegEx("([0-9]+[A-Z][0-9]+[a-z]?).*", System_))
10459 agent = [NSString stringWithFormat:@"Mobile/%@ %@", match[1], agent];
10460 if (RegEx match = RegEx("([0-9]+(\\.[0-9]+)+).*", Product_))
10461 agent = [NSString stringWithFormat:@"Version/%@ %@", match[1], agent];
10463 UserAgent_ = agent;
10465 /* Load Database {{{ */
10466 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10469 mkdir("/var/mobile/Library/Cydia", 0755);
10470 MetaFile_.Open("/var/mobile/Library/Cydia/metadata.cb0");
10473 Values_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaValues"), CFSTR("com.saurik.Cydia")));
10474 Sections_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaSections"), CFSTR("com.saurik.Cydia")));
10475 Sources_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaSources"), CFSTR("com.saurik.Cydia")));
10476 Version_ = [(NSNumber *) CFPreferencesCopyAppValue(CFSTR("CydiaVersion"), CFSTR("com.saurik.Cydia")) autorelease];
10479 NSDictionary *metadata([[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease]);
10481 if (Values_ == nil)
10482 Values_ = [metadata objectForKey:@"Values"];
10483 if (Values_ == nil)
10484 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10486 if (Sections_ == nil)
10487 Sections_ = [metadata objectForKey:@"Sections"];
10488 if (Sections_ == nil)
10489 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10491 if (Sources_ == nil)
10492 Sources_ = [metadata objectForKey:@"Sources"];
10493 if (Sources_ == nil)
10494 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10496 // XXX: this wrong, but in a way that doesn't matter :/
10497 if (Version_ == nil)
10498 Version_ = [metadata objectForKey:@"Version"];
10499 if (Version_ == nil)
10500 Version_ = [NSNumber numberWithUnsignedInt:0];
10502 if (NSDictionary *packages = [metadata objectForKey:@"Packages"]) {
10504 CFDictionaryApplyFunction((CFDictionaryRef) packages, &PackageImport, &fail);
10507 NSLog(@"unable to import package preferences... from 2010? oh well :/");
10510 if ([Version_ unsignedIntValue] == 0) {
10511 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10512 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10513 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10514 CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./");
10516 Version_ = [NSNumber numberWithUnsignedInt:1];
10518 if (NSMutableDictionary *cache = [NSMutableDictionary dictionaryWithContentsOfFile:@ CacheState_]) {
10519 [cache removeObjectForKey:@"LastUpdate"];
10520 [cache writeToFile:@ CacheState_ atomically:YES];
10524 _H<NSMutableArray> broken([NSMutableArray array]);
10525 for (NSString *key in (id) Sources_)
10526 if ([key rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"# "]].location != NSNotFound || ![([[Sources_ objectForKey:key] objectForKey:@"URI"] ?: @"/") hasSuffix:@"/"])
10527 [broken addObject:key];
10528 if ([broken count] != 0)
10529 for (NSString *key in (id) broken)
10530 [Sources_ removeObjectForKey:key];
10534 system("/usr/libexec/cydia/cydo /bin/rm -f /var/lib/cydia/metadata.plist");
10537 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10539 if (kCFCoreFoundationVersionNumber > 1000)
10540 system("/usr/libexec/cydia/cydo /usr/libexec/cydia/setnsfpn /var/lib");
10542 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10544 if (access("/User", F_OK) != 0 || version != 6) {
10546 system("/usr/libexec/cydia/cydo /usr/libexec/cydia/firmware.sh");
10550 if (access("/tmp/cydia.chk", F_OK) == 0) {
10551 if (unlink([Cache("pkgcache.bin") UTF8String]) == -1)
10552 _assert(errno == ENOENT);
10553 if (unlink([Cache("srcpkgcache.bin") UTF8String]) == -1)
10554 _assert(errno == ENOENT);
10557 system("/usr/libexec/cydia/cydo /bin/ln -sf /var/mobile/Library/Caches/com.saurik.Cydia/sources.list /etc/apt/sources.list.d/cydia.list");
10559 /* APT Initialization {{{ */
10560 _assert(pkgInitConfig(*_config));
10561 _assert(pkgInitSystem(*_config, _system));
10564 _config->Set("APT::Acquire::Translation", lang);
10566 // XXX: this timeout might be important :(
10567 //_config->Set("Acquire::http::Timeout", 15);
10569 _config->Set("Acquire::http::MaxParallel", usermem >= 384 * 1024 * 1024 ? 16 : 3);
10571 mkdir([Cache("archives") UTF8String], 0755);
10572 mkdir([Cache("archives/partial") UTF8String], 0755);
10573 _config->Set("Dir::Cache", [Cache_ UTF8String]);
10575 symlink("/var/lib/apt/extended_states", [Cache("extended_states") UTF8String]);
10576 _config->Set("Dir::State", [Cache_ UTF8String]);
10578 mkdir([Cache("lists") UTF8String], 0755);
10579 mkdir([Cache("lists/partial") UTF8String], 0755);
10580 mkdir([Cache("periodic") UTF8String], 0755);
10581 _config->Set("Dir::State::Lists", [Cache("lists") UTF8String]);
10583 std::string logs("/var/mobile/Library/Logs/Cydia");
10584 mkdir(logs.c_str(), 0755);
10585 _config->Set("Dir::Log::Terminal", logs + "/apt.log");
10587 _config->Set("Dir::Bin::dpkg", "/usr/libexec/cydia/cydo");
10589 /* Color Choices {{{ */
10590 space_ = CGColorSpaceCreateDeviceRGB();
10592 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10593 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10594 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10595 Folder_.Set(space_, 0x8e/255.f, 0x8e/255.f, 0x93/255.f, 1.0);
10596 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10597 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10598 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10599 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10600 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10601 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10603 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10604 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10606 /* UIKit Configuration {{{ */
10607 // XXX: I have a feeling this was important
10608 //UIKeyboardDisableAutomaticAppearance();
10611 $SBSSetInterceptsMenuButtonForever = reinterpret_cast<void (*)(bool)>(dlsym(RTLD_DEFAULT, "SBSSetInterceptsMenuButtonForever"));
10612 $SBSCopyIconImagePNGDataForDisplayIdentifier = reinterpret_cast<NSData *(*)(NSString *)>(dlsym(RTLD_DEFAULT, "SBSCopyIconImagePNGDataForDisplayIdentifier"));
10614 const char *symbol(kCFCoreFoundationVersionNumber >= 800 ? "MGGetBoolAnswer" : "GSSystemHasCapability");
10615 BOOL (*GSSystemHasCapability)(CFStringRef) = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, symbol));
10616 bool fast = GSSystemHasCapability != NULL && GSSystemHasCapability(CFSTR("armv7"));
10618 PulseInterval_ = fast ? 50000 : 500000;
10620 Colon_ = UCLocalize("COLON_DELIMITED");
10621 Elision_ = UCLocalize("ELISION");
10622 Error_ = UCLocalize("ERROR");
10623 Warning_ = UCLocalize("WARNING");
10626 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10628 CGColorSpaceRelease(space_);
10629 CFRelease(Locale_);