1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2015 Jay Freeman (saurik)
5 /* GNU General Public License, Version 3 {{{ */
7 * Cydia is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published
9 * by the Free Software Foundation, either version 3 of the License,
10 * or (at your option) any later version.
12 * Cydia is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Cydia. If not, see <http://www.gnu.org/licenses/>.
22 // XXX: wtf/FastMalloc.h... wtf?
23 #define USE_SYSTEM_MALLOC 1
25 /* #include Directives {{{ */
26 #include "CyteKit/UCPlatform.h"
27 #include "CyteKit/Localize.h"
29 #include <unicode/ustring.h>
30 #include <unicode/utrans.h>
32 #include <objc/objc.h>
33 #include <objc/runtime.h>
35 #include <CoreGraphics/CoreGraphics.h>
36 #include <Foundation/Foundation.h>
39 #define DEPLOYMENT_TARGET_MACOSX 1
40 #define CF_BUILDING_CF 1
41 #include <CoreFoundation/CFInternal.h>
44 #include <CoreFoundation/CFUniChar.h>
46 #include <SystemConfiguration/SystemConfiguration.h>
48 #include <UIKit/UIKit.h>
49 #include "iPhonePrivate.h"
51 #include <IOKit/IOKitLib.h>
53 #include <QuartzCore/CALayer.h>
55 #include <WebCore/WebCoreThread.h>
56 #include <WebKit/DOMHTMLIFrameElement.h>
64 #include <ext/stdio_filebuf.h>
68 #include <apt-pkg/acquire.h>
69 #include <apt-pkg/acquire-item.h>
70 #include <apt-pkg/algorithms.h>
71 #include <apt-pkg/cachefile.h>
72 #include <apt-pkg/clean.h>
73 #include <apt-pkg/configuration.h>
74 #include <apt-pkg/debindexfile.h>
75 #include <apt-pkg/debmetaindex.h>
76 #include <apt-pkg/error.h>
77 #include <apt-pkg/init.h>
78 #include <apt-pkg/mmap.h>
79 #include <apt-pkg/pkgrecords.h>
80 #include <apt-pkg/sha1.h>
81 #include <apt-pkg/sourcelist.h>
82 #include <apt-pkg/sptr.h>
83 #include <apt-pkg/strutl.h>
84 #include <apt-pkg/tagfile.h>
86 #include <sys/types.h>
88 #include <sys/sysctl.h>
89 #include <sys/param.h>
90 #include <sys/mount.h>
91 #include <sys/reboot.h>
98 #include <mach-o/nlist.h>
107 #include <Cytore.hpp>
110 #include "Substrate.hpp"
111 #include "Menes/Menes.h"
113 #include "CyteKit/IndirectDelegate.h"
114 #include "CyteKit/RegEx.hpp"
115 #include "CyteKit/TableViewCell.h"
116 #include "CyteKit/TabBarController.h"
117 #include "CyteKit/WebScriptObject-Cyte.h"
118 #include "CyteKit/WebViewController.h"
119 #include "CyteKit/WebViewTableViewCell.h"
120 #include "CyteKit/stringWithUTF8Bytes.h"
122 #include "Cydia/MIMEAddress.h"
123 #include "Cydia/LoadingViewController.h"
124 #include "Cydia/ProgressEvent.h"
126 #include "SDURLCache/SDURLCache.h"
133 #define _timestamp ({ \
135 gettimeofday(&tv, NULL); \
136 tv.tv_sec * 1000000 + tv.tv_usec; \
139 typedef std::vector<class ProfileTime *> TimeList;
149 ProfileTime(const char *name) :
153 times_.push_back(this);
156 void AddTime(uint64_t time) {
163 std::cerr << std::setw(7) << count_ << ", " << std::setw(8) << total_ << " : " << name_ << std::endl;
175 ProfileTimer(ProfileTime &time) :
182 time_.AddTime(_timestamp - start_);
187 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
189 std::cerr << "========" << std::endl;
192 #define _profile(name) { \
193 static ProfileTime name(#name); \
194 ProfileTimer _ ## name(name);
199 // XXX: I hate clang. Apple: please get over your petty hatred of GPL and fix your gcc fork
200 #define synchronized(lock) \
201 synchronized(static_cast<NSObject *>(lock))
203 extern NSString *Cydia_;
205 #define lprintf(args...) fprintf(stderr, args)
208 #define TraceLogging (1 && !ForRelease)
209 #define HistogramInsertionSort (0 && !ForRelease)
210 #define ProfileTimes (0 && !ForRelease)
211 #define ForSaurik (0 && !ForRelease)
212 #define LogBrowser (0 && !ForRelease)
213 #define TrackResize (0 && !ForRelease)
214 #define ManualRefresh (1 && !ForRelease)
215 #define ShowInternals (0 && !ForRelease)
216 #define AlwaysReload (0 && !ForRelease)
220 #define _trace(args...)
225 #define _profile(name) {
228 #define PrintTimes() do {} while (false)
231 // Hash Functions/Structures {{{
232 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
240 static NSString *Colon_;
242 static NSString *Error_;
243 static NSString *Warning_;
245 static NSString *Cache_;
246 #define Cache(file) \
247 [NSString stringWithFormat:@"%@/%s", Cache_, file]
249 static void (*$SBSSetInterceptsMenuButtonForever)(bool);
251 static CFStringRef (*$MGCopyAnswer)(CFStringRef);
253 static NSString *UniqueIdentifier(UIDevice *device = nil) {
254 if (kCFCoreFoundationVersionNumber < 800) // iOS 7.x
255 return [device ?: [UIDevice currentDevice] uniqueIdentifier];
257 return [(id)$MGCopyAnswer(CFSTR("UniqueDeviceID")) autorelease];
260 static bool IsReachable(const char *name) {
261 SCNetworkReachabilityFlags flags; {
262 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, name));
263 SCNetworkReachabilityGetFlags(reachability, &flags);
264 CFRelease(reachability);
267 // XXX: this elaborate mess is what Apple is using to determine this? :(
268 // XXX: do we care if the user has to intervene? maybe that's ok?
270 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
271 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
272 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
273 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
274 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
275 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
280 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
282 static _finline NSString *CydiaURL(NSString *path) {
284 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
285 page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
286 page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
287 page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
288 page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
290 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
293 static void ReapZombie(pid_t pid) {
296 if (waitpid(pid, &status, 0) == -1)
302 static _finline void UpdateExternalStatus(uint64_t newStatus) {
304 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
305 notify_set_state(notify_token, newStatus);
306 notify_cancel(notify_token);
308 notify_post("com.saurik.Cydia.status");
311 static CGFloat CYStatusBarHeight() {
312 CGSize size([[UIApplication sharedApplication] statusBarFrame].size);
313 return UIInterfaceOrientationIsPortrait([[UIApplication sharedApplication] statusBarOrientation]) ? size.height : size.width;
316 /* NSForcedOrderingSearch doesn't work on the iPhone */
317 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
318 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
319 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
321 /* Insertion Sort {{{ */
323 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
324 const char *ptr = (const char *)list;
326 CFIndex half = count / 2;
327 const char *probe = ptr + elementSize * half;
328 CFComparisonResult cr = comparator(element, probe, context);
329 if (0 == cr) return (probe - (const char *)list) / elementSize;
330 ptr = (cr < 0) ? ptr : probe + elementSize;
331 count = (cr < 0) ? half : (half + (count & 1) - 1);
333 return (ptr - (const char *)list) / elementSize;
336 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
337 const char *ptr = (const char *)list;
339 CFIndex half = count / 2;
340 const char *probe = ptr + elementSize * half;
341 CFComparisonResult cr = comparator(element, probe, context);
342 if (0 == cr) return (probe - (const char *)list) / elementSize;
343 ptr = (cr < 0) ? ptr : probe + elementSize;
344 count = (cr < 0) ? half : (half + (count & 1) - 1);
346 return (ptr - (const char *)list) / elementSize;
349 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
350 if (range.length == 0)
352 const void **values(new const void *[range.length]);
353 CFArrayGetValues(array, range, values);
355 #if HistogramInsertionSort > 0
356 uint32_t total(0), *offsets(new uint32_t[range.length]);
359 for (CFIndex index(1); index != range.length; ++index) {
360 const void *value(values[index]);
361 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
362 CFIndex correct(index);
363 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
364 #if HistogramInsertionSort > 1
365 NSLog(@"%@ < %@", value, values[correct - 1]);
370 if (correct != index) {
371 size_t offset(index - correct);
372 #if HistogramInsertionSort
376 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
378 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
379 values[correct] = value;
383 CFArrayReplaceValues(array, range, values, range.length);
386 #if HistogramInsertionSort > 0
387 for (CFIndex index(0); index != range.length; ++index)
388 if (offsets[index] != 0)
389 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
390 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
397 /* Apple Bug Fixes {{{ */
398 @implementation UIWebDocumentView (Cydia)
400 - (void) _setScrollerOffset:(CGPoint)offset {
401 UIScroller *scroller([self _scroller]);
403 CGSize size([scroller contentSize]);
404 CGSize bounds([scroller bounds].size);
407 max.x = size.width - bounds.width;
408 max.y = size.height - bounds.height;
416 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
417 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
419 [scroller setOffset:offset];
425 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
426 size_t length([self length] - state->state);
429 else if (length > count)
431 for (size_t i(0); i != length; ++i)
432 objects[i] = [self item:state->state++];
433 state->itemsPtr = objects;
434 state->mutationsPtr = (unsigned long *) self;
438 /* Cydia NSString Additions {{{ */
439 @interface NSString (Cydia)
440 - (NSComparisonResult) compareByPath:(NSString *)other;
441 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
444 @implementation NSString (Cydia)
446 - (NSComparisonResult) compareByPath:(NSString *)other {
447 NSString *prefix = [self commonPrefixWithString:other options:0];
448 size_t length = [prefix length];
450 NSRange lrange = NSMakeRange(length, [self length] - length);
451 NSRange rrange = NSMakeRange(length, [other length] - length);
453 lrange = [self rangeOfString:@"/" options:0 range:lrange];
454 rrange = [other rangeOfString:@"/" options:0 range:rrange];
456 NSComparisonResult value;
458 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
459 value = NSOrderedSame;
460 else if (lrange.location == NSNotFound)
461 value = NSOrderedAscending;
462 else if (rrange.location == NSNotFound)
463 value = NSOrderedDescending;
465 value = NSOrderedSame;
467 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
468 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
469 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
470 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
472 NSComparisonResult result = [lpath compare:rpath];
473 return result == NSOrderedSame ? value : result;
476 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
477 return [(id)CFURLCreateStringByAddingPercentEscapes(
482 kCFStringEncodingUTF8
489 /* C++ NSString Wrapper Cache {{{ */
490 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
491 return size == 0 ? NULL :
492 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
493 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
496 static _finline CFStringRef CYStringCreate(const char *data) {
497 return CYStringCreate(data, strlen(data));
506 _finline void clear_() {
507 if (cache_ != NULL) {
514 _finline bool empty() const {
518 _finline size_t size() const {
522 _finline char *data() const {
526 _finline void clear() {
531 _finline CYString() :
538 _finline ~CYString() {
542 void operator =(const CYString &rhs) {
546 if (rhs.cache_ == nil)
549 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
552 void copy(CYPool *pool) {
553 char *temp(pool->malloc<char>(size_ + 1));
554 memcpy(temp, data_, size_);
559 void set(CYPool *pool, const char *data, size_t size) {
565 data_ = const_cast<char *>(data);
573 _finline void set(CYPool *pool, const char *data) {
574 set(pool, data, data == NULL ? 0 : strlen(data));
577 _finline void set(CYPool *pool, const std::string &rhs) {
578 set(pool, rhs.data(), rhs.size());
581 bool operator ==(const CYString &rhs) const {
582 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
585 _finline operator CFStringRef() {
587 cache_ = CYStringCreate(data_, size_);
591 _finline operator id() {
592 return (NSString *) static_cast<CFStringRef>(*this);
595 _finline operator const char *() {
596 return reinterpret_cast<const char *>(data_);
600 /* C++ NSString Algorithm Adapters {{{ */
602 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
605 struct NSStringMapHash :
606 std::unary_function<NSString *, size_t>
608 _finline size_t operator ()(NSString *value) const {
609 return CFStringHashNSString((CFStringRef) value);
613 struct NSStringMapLess :
614 std::binary_function<NSString *, NSString *, bool>
616 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
617 return [lhs compare:rhs] == NSOrderedAscending;
621 struct NSStringMapEqual :
622 std::binary_function<NSString *, NSString *, bool>
624 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
625 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
626 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
627 //[lhs isEqualToString:rhs];
632 /* CoreGraphics Primitives {{{ */
637 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
638 CGFloat color[] = {red, green, blue, alpha};
639 return CGColorCreate(space, color);
648 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
649 color_(Create_(space, red, green, blue, alpha))
651 Set(space, red, green, blue, alpha);
656 CGColorRelease(color_);
663 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
665 color_ = Create_(space, red, green, blue, alpha);
668 operator CGColorRef() {
674 /* Random Global Variables {{{ */
675 static int PulseInterval_ = 500000;
677 static const NSString *UI_;
680 static bool RestartSubstrate_;
681 static bool UpgradeCydia_;
682 static NSArray *Finishes_;
684 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
685 #define NotifyConfig_ "/etc/notify.conf"
687 static bool Queuing_;
689 static CYColor Blue_;
690 static CYColor Blueish_;
691 static CYColor Black_;
692 static CYColor Folder_;
694 static CYColor White_;
695 static CYColor Gray_;
696 static CYColor Green_;
697 static CYColor Purple_;
698 static CYColor Purplish_;
700 static UIColor *InstallingColor_;
701 static UIColor *RemovingColor_;
703 static NSString *App_;
705 static BOOL Advanced_;
706 static BOOL Ignored_;
708 static _H<UIFont> Font12_;
709 static _H<UIFont> Font12Bold_;
710 static _H<UIFont> Font14_;
711 static _H<UIFont> Font18_;
712 static _H<UIFont> Font18Bold_;
713 static _H<UIFont> Font22Bold_;
715 static const char *Machine_ = NULL;
716 static _H<NSString> System_;
717 static NSString *SerialNumber_ = nil;
718 static NSString *ChipID_ = nil;
719 static NSString *BBSNum_ = nil;
720 static _H<NSString> UniqueID_;
721 static _H<NSString> UserAgent_;
722 static _H<NSString> Product_;
723 static _H<NSString> Safari_;
725 static _H<NSLocale> CollationLocale_;
726 static _H<NSArray> CollationThumbs_;
727 static std::vector<NSInteger> CollationOffset_;
728 static _H<NSArray> CollationTitles_;
729 static _H<NSArray> CollationStarts_;
730 static UTransliterator *CollationTransl_;
731 //static Function<NSString *, NSString *> CollationModify_;
733 typedef std::basic_string<UChar> ustring;
734 static ustring CollationString_;
736 #define CUC const ustring &str(*reinterpret_cast<const ustring *>(rep))
737 #define UC ustring &str(*reinterpret_cast<ustring *>(rep))
738 static struct UReplaceableCallbacks CollationUCalls_ = {
739 .length = [](const UReplaceable *rep) -> int32_t { CUC;
743 .charAt = [](const UReplaceable *rep, int32_t offset) -> UChar { CUC;
744 //fprintf(stderr, "charAt(%d) : %d\n", offset, str.size());
745 if (offset >= str.size())
750 .char32At = [](const UReplaceable *rep, int32_t offset) -> UChar32 { CUC;
751 //fprintf(stderr, "char32At(%d) : %d\n", offset, str.size());
752 if (offset >= str.size())
755 U16_GET(str.data(), 0, offset, str.size(), c);
759 .replace = [](UReplaceable *rep, int32_t start, int32_t limit, const UChar *text, int32_t length) -> void { UC;
760 //fprintf(stderr, "replace(%d, %d, %d) : %d\n", start, limit, length, str.size());
761 str.replace(start, limit - start, text, length);
764 .extract = [](UReplaceable *rep, int32_t start, int32_t limit, UChar *dst) -> void { UC;
765 //fprintf(stderr, "extract(%d, %d) : %d\n", start, limit, str.size());
766 str.copy(dst, limit - start, start);
769 .copy = [](UReplaceable *rep, int32_t start, int32_t limit, int32_t dest) -> void { UC;
770 //fprintf(stderr, "copy(%d, %d, %d) : %d\n", start, limit, dest, str.size());
771 str.replace(dest, 0, str, start, limit - start);
775 static CFLocaleRef Locale_;
776 static NSArray *Languages_;
777 static CGColorSpaceRef space_;
779 #define CacheState_ "/var/mobile/Library/Caches/com.saurik.Cydia/CacheState.plist"
780 #define SavedState_ "/var/mobile/Library/Caches/com.saurik.Cydia/SavedState.plist"
782 static NSDictionary *SectionMap_;
783 static _H<NSDate> Backgrounded_;
784 static _transient NSMutableDictionary *Values_;
785 static _transient NSMutableDictionary *Sections_;
786 _H<NSMutableDictionary> Sources_;
787 static _transient NSNumber *Version_;
791 CGFloat ScreenScale_;
792 static NSString *Idiom_;
793 static _H<NSString> Firmware_;
794 static NSString *Major_;
796 static _H<NSMutableDictionary> SessionData_;
797 static _H<NSObject> HostConfig_;
798 static _H<NSMutableSet> BridgedHosts_;
799 static _H<NSMutableSet> InsecureHosts_;
800 static _H<NSMutableSet> PipelinedHosts_;
801 static _H<NSMutableSet> CachedURLs_;
803 static NSString *kCydiaProgressEventTypeError = @"Error";
804 static NSString *kCydiaProgressEventTypeInformation = @"Information";
805 static NSString *kCydiaProgressEventTypeStatus = @"Status";
806 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
809 /* Display Helpers {{{ */
810 inline float Interpolate(float begin, float end, float fraction) {
811 return (end - begin) * fraction + begin;
814 static inline double Retina(double value) {
815 value *= ScreenScale_;
816 value = round(value);
817 value /= ScreenScale_;
821 static inline CGRect Retina(CGRect value) {
822 value.origin.x *= ScreenScale_;
823 value.origin.y *= ScreenScale_;
824 value.size.width *= ScreenScale_;
825 value.size.height *= ScreenScale_;
826 value = CGRectIntegral(value);
827 value.origin.x /= ScreenScale_;
828 value.origin.y /= ScreenScale_;
829 value.size.width /= ScreenScale_;
830 value.size.height /= ScreenScale_;
834 static _finline const char *StripVersion_(const char *version) {
835 const char *colon(strchr(version, ':'));
836 return colon == NULL ? version : colon + 1;
839 NSString *LocalizeSection(NSString *section) {
840 static RegEx title_r("(.*?) \\((.*)\\)");
841 if (title_r(section)) {
842 NSString *parent(title_r[1]);
843 NSString *child(title_r[2]);
845 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
846 LocalizeSection(parent),
847 LocalizeSection(child)
851 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
854 NSString *Simplify(NSString *title) {
855 const char *data = [title UTF8String];
856 size_t size = [title lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
858 static RegEx square_r("\\[(.*)\\]");
859 if (square_r(data, size))
860 return Simplify(square_r[1]);
862 static RegEx paren_r("\\((.*)\\)");
863 if (paren_r(data, size))
864 return Simplify(paren_r[1]);
866 static RegEx title_r("(.*?) \\((.*)\\)");
867 if (title_r(data, size))
868 return Simplify(title_r[1]);
874 bool isSectionVisible(NSString *section) {
875 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
876 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
877 return hidden == nil || ![hidden boolValue];
880 static NSObject *CYIOGetValue(const char *path, NSString *property) {
881 io_registry_entry_t entry(IORegistryEntryFromPath(kIOMasterPortDefault, path));
882 if (entry == MACH_PORT_NULL)
885 CFTypeRef value(IORegistryEntryCreateCFProperty(entry, (CFStringRef) property, kCFAllocatorDefault, 0));
886 IOObjectRelease(entry);
890 return [(id) value autorelease];
893 static NSString *CYHex(NSData *data, bool reverse = false) {
897 size_t length([data length]);
898 uint8_t bytes[length];
899 [data getBytes:bytes];
901 char string[length * 2 + 1];
902 for (size_t i(0); i != length; ++i)
903 sprintf(string + i * 2, "%.2x", bytes[reverse ? length - i - 1 : i]);
905 return [NSString stringWithUTF8String:string];
910 /* Delegate Prototypes {{{ */
913 @class CydiaProgressEvent;
915 @protocol DatabaseDelegate
916 - (void) repairWithSelector:(SEL)selector;
917 - (void) setConfigurationData:(NSString *)data;
918 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
921 @class CYPackageController;
923 @protocol SourceDelegate
924 - (void) setFetch:(NSNumber *)fetch;
927 @protocol FetchDelegate
928 - (bool) isSourceCancelled;
929 - (void) startSourceFetch:(NSString *)uri;
930 - (void) stopSourceFetch:(NSString *)uri;
933 @protocol CydiaDelegate
934 - (void) returnToCydia;
936 - (void) retainNetworkActivityIndicator;
937 - (void) releaseNetworkActivityIndicator;
938 - (void) clearPackage:(Package *)package;
939 - (void) installPackage:(Package *)package;
940 - (void) installPackages:(NSArray *)packages;
941 - (void) removePackage:(Package *)package;
942 - (void) beginUpdate;
944 - (bool) requestUpdate;
945 - (void) distUpgrade;
948 - (void) _saveConfig;
950 - (void) addSource:(NSDictionary *)source;
951 - (void) addTrivialSource:(NSString *)href;
952 - (UIProgressHUD *) addProgressHUD;
953 - (void) removeProgressHUD:(UIProgressHUD *)hud;
954 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
955 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
959 /* CancelStatus {{{ */
961 public pkgAcquireStatus
972 virtual bool MediaChange(std::string media, std::string drive) {
976 virtual void IMSHit(pkgAcquire::ItemDesc &desc) {
980 virtual bool Pulse_(pkgAcquire *Owner) = 0;
982 virtual bool Pulse(pkgAcquire *Owner) {
983 if (pkgAcquireStatus::Pulse(Owner) && Pulse_(Owner))
991 _finline bool WasCancelled() const {
996 /* DelegateStatus {{{ */
1001 _transient NSObject<ProgressDelegate> *delegate_;
1009 void setDelegate(NSObject<ProgressDelegate> *delegate) {
1010 delegate_ = delegate;
1013 virtual void Fetch(pkgAcquire::ItemDesc &desc) {
1014 NSString *name([NSString stringWithUTF8String:desc.ShortDesc.c_str()]);
1015 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItemDesc:desc]);
1016 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1019 virtual void Done(pkgAcquire::ItemDesc &desc) {
1020 NSString *name([NSString stringWithUTF8String:desc.ShortDesc.c_str()]);
1021 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:Colon_, UCLocalize("DONE"), name] ofType:kCydiaProgressEventTypeStatus forItemDesc:desc]);
1022 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1025 virtual void Fail(pkgAcquire::ItemDesc &desc) {
1027 desc.Owner->Status == pkgAcquire::Item::StatIdle ||
1028 desc.Owner->Status == pkgAcquire::Item::StatDone
1032 std::string &error(desc.Owner->ErrorText);
1036 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItemDesc:desc]);
1037 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1040 virtual bool Pulse_(pkgAcquire *Owner) {
1042 double(CurrentBytes + CurrentItems) /
1043 double(TotalBytes + TotalItems)
1046 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
1047 [NSNumber numberWithDouble:percent], @"Percent",
1049 [NSNumber numberWithDouble:CurrentBytes], @"Current",
1050 [NSNumber numberWithDouble:TotalBytes], @"Total",
1051 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
1052 nil] waitUntilDone:YES];
1054 return ![delegate_ isProgressCancelled];
1057 virtual void Start() {
1058 pkgAcquireStatus::Start();
1059 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
1062 virtual void Stop() {
1063 pkgAcquireStatus::Stop();
1064 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
1065 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
1069 /* Database Interface {{{ */
1070 typedef std::map< unsigned long, _H<Source> > SourceMap;
1072 @interface Database : NSObject {
1079 pkgCacheFile cache_;
1080 pkgDepCache::Policy *policy_;
1081 pkgRecords *records_;
1082 pkgProblemResolver *resolver_;
1083 pkgAcquire *fetcher_;
1085 SPtr<pkgPackageManager> manager_;
1086 pkgSourceList *list_;
1088 SourceMap sourceMap_;
1089 _H<NSMutableArray> sourceList_;
1091 CFMutableArrayRef packages_;
1093 _transient NSObject<DatabaseDelegate> *delegate_;
1094 _transient NSObject<ProgressDelegate> *progress_;
1096 CydiaStatus status_;
1102 std::map<const char *, _H<NSString> > sections_;
1105 + (Database *) sharedInstance;
1108 - (void) _readCydia:(NSNumber *)fd;
1109 - (void) _readStatus:(NSNumber *)fd;
1110 - (void) _readOutput:(NSNumber *)fd;
1114 - (Package *) packageWithName:(NSString *)name;
1116 - (pkgCacheFile &) cache;
1117 - (pkgDepCache::Policy *) policy;
1118 - (pkgRecords *) records;
1119 - (pkgProblemResolver *) resolver;
1120 - (pkgAcquire &) fetcher;
1121 - (pkgSourceList &) list;
1122 - (NSArray *) packages;
1123 - (NSArray *) sources;
1124 - (Source *) sourceWithKey:(NSString *)key;
1125 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1133 - (void) updateWithStatus:(CancelStatus &)status;
1135 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1137 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1138 - (NSObject<ProgressDelegate> *) progressDelegate;
1140 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1141 - (void) setFetch:(bool)fetch forURI:(const char *)uri;
1142 - (void) resetFetch;
1144 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1148 /* SourceStatus {{{ */
1149 class SourceStatus :
1153 _transient NSObject<FetchDelegate> *delegate_;
1154 _transient Database *database_;
1155 std::set<std::string> fetches_;
1158 SourceStatus(NSObject<FetchDelegate> *delegate, Database *database) :
1159 delegate_(delegate),
1164 void Set(bool fetch, const std::string &uri) {
1166 if (!fetches_.insert(uri).second)
1169 if (fetches_.erase(uri) == 0)
1173 //printf("Set(%s, %s)\n", fetch ? "true" : "false", uri.c_str());
1174 [database_ setFetch:fetch forURI:uri.c_str()];
1177 _finline void Set(bool fetch, pkgAcquire::Item *item) {
1178 /*unsigned long ID(fetch ? 1 : 0);
1182 Set(fetch, item->DescURI());
1185 void Log(const char *tag, pkgAcquire::Item *item) {
1186 //printf("%s(%s) S:%u Q:%u\n", tag, item->DescURI().c_str(), item->Status, item->QueueCounter);
1189 virtual void Fetch(pkgAcquire::ItemDesc &desc) {
1190 Log("Fetch", desc.Owner);
1191 Set(true, desc.Owner);
1194 virtual void Done(pkgAcquire::ItemDesc &desc) {
1195 Log("Done", desc.Owner);
1196 Set(false, desc.Owner);
1199 virtual void Fail(pkgAcquire::ItemDesc &desc) {
1200 Log("Fail", desc.Owner);
1201 Set(false, desc.Owner);
1204 virtual bool Pulse_(pkgAcquire *Owner) {
1205 std::set<std::string> fetches;
1206 for (pkgAcquire::ItemCIterator item(Owner->ItemsBegin()); item != Owner->ItemsEnd(); ++item) {
1208 if ((*item)->QueueCounter == 0)
1210 else switch ((*item)->Status) {
1211 case pkgAcquire::Item::StatFetching:
1212 fetches.insert((*item)->DescURI());
1221 Log(fetch ? "Pulse<true>" : "Pulse<false>", *item);
1225 std::vector<std::string> stops;
1226 std::set_difference(fetches_.begin(), fetches_.end(), fetches.begin(), fetches.end(), std::back_insert_iterator<std::vector<std::string>>(stops));
1227 for (std::vector<std::string>::const_iterator stop(stops.begin()); stop != stops.end(); ++stop) {
1228 //printf("Stop(%s)\n", stop->c_str());
1232 return ![delegate_ isSourceCancelled];
1235 virtual void Stop() {
1236 pkgAcquireStatus::Stop();
1237 [database_ resetFetch];
1241 /* ProgressEvent Implementation {{{ */
1242 @implementation CydiaProgressEvent
1244 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1245 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1248 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1249 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1250 [event setPackage:package];
1254 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItemDesc:(pkgAcquire::ItemDesc &)desc {
1255 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1257 NSString *description([NSString stringWithUTF8String:desc.Description.c_str()]);
1258 NSArray *fields([description componentsSeparatedByString:@" "]);
1259 [event setItem:fields];
1261 if ([fields count] > 3) {
1262 [event setPackage:[fields objectAtIndex:2]];
1263 [event setVersion:[fields objectAtIndex:3]];
1266 [event setURL:[NSString stringWithUTF8String:desc.URI.c_str()]];
1271 + (NSArray *) _attributeKeys {
1272 return [NSArray arrayWithObjects:
1282 - (NSArray *) attributeKeys {
1283 return [[self class] _attributeKeys];
1286 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1287 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1290 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1291 if ((self = [super init]) != nil) {
1297 - (NSString *) message {
1301 - (NSString *) type {
1305 - (NSArray *) item {
1306 return (id) item_ ?: [NSNull null];
1309 - (void) setItem:(NSArray *)item {
1313 - (NSString *) package {
1314 return (id) package_ ?: [NSNull null];
1317 - (void) setPackage:(NSString *)package {
1321 - (NSString *) url {
1322 return (id) url_ ?: [NSNull null];
1325 - (void) setURL:(NSString *)url {
1329 - (void) setVersion:(NSString *)version {
1333 - (NSString *) version {
1334 return (id) version_ ?: [NSNull null];
1337 - (NSString *) compound:(NSString *)value {
1339 NSString *mode(nil); {
1340 NSString *type([self type]);
1341 if ([type isEqualToString:kCydiaProgressEventTypeError])
1342 mode = UCLocalize("ERROR");
1343 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1344 mode = UCLocalize("WARNING");
1348 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1354 - (NSString *) compoundMessage {
1355 return [self compound:[self message]];
1358 - (NSString *) compoundTitle {
1361 if (package_ == nil)
1363 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1364 title = [package name];
1368 return [self compound:title];
1374 // Cytore Definitions {{{
1375 struct PackageValue :
1378 Cytore::Offset<PackageValue> next_;
1380 uint32_t index_ : 23;
1381 uint32_t subscribed_ : 1;
1398 Cytore::Offset<PackageValue> packages_[1 << 16];
1401 static Cytore::File<MetaValue> MetaFile_;
1403 // Cytore Helper Functions {{{
1404 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1405 SplitHash nhash = { hashlittle(name, length) };
1407 PackageValue *metadata;
1409 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1410 for (;; offset = &metadata->next_) { if (offset->IsNull()) {
1411 *offset = MetaFile_.New<PackageValue>(length + 1);
1412 metadata = &MetaFile_.Get(*offset);
1414 if (metadata == NULL) {
1418 metadata = new PackageValue();
1419 memset(metadata, 0, sizeof(*metadata));
1422 memcpy(metadata->name_, name, length);
1423 metadata->name_[length] = '\0';
1424 metadata->nhash_ = nhash.u16[1];
1426 metadata = &MetaFile_.Get(*offset);
1427 if (metadata->nhash_ != nhash.u16[1])
1429 if (strncmp(metadata->name_, name, length) != 0)
1431 if (metadata->name_[length] != '\0')
1438 static void PackageImport(const void *key, const void *value, void *context) {
1439 bool &fail(*reinterpret_cast<bool *>(context));
1442 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1443 NSLog(@"failed to import package %@", key);
1447 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1448 NSDictionary *package((NSDictionary *) value);
1450 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1451 if ([subscribed boolValue] && !metadata->subscribed_)
1452 metadata->subscribed_ = true;
1454 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1455 time_t time([date timeIntervalSince1970]);
1456 if (metadata->first_ > time || metadata->first_ == 0)
1457 metadata->first_ = time;
1460 NSDate *date([package objectForKey:@"LastSeen"]);
1461 NSString *version([package objectForKey:@"LastVersion"]);
1463 if (date != nil && version != nil) {
1464 time_t time([date timeIntervalSince1970]);
1465 if (metadata->last_ < time || metadata->last_ == 0)
1466 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1467 size_t length(strlen(buffer));
1468 uint16_t vhash(hashlittle(buffer, length));
1470 size_t capped(std::min<size_t>(8, length));
1471 char *latest(buffer + length - capped);
1473 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1474 metadata->vhash_ = vhash;
1476 metadata->last_ = time;
1482 static NSDate *GetStatusDate() {
1483 return [[[NSFileManager defaultManager] attributesOfItemAtPath:@"/var/lib/dpkg/status" error:NULL] fileModificationDate];
1486 static void SaveConfig(NSObject *lock) {
1487 @synchronized (lock) {
1493 CFPreferencesSetMultiple((CFDictionaryRef) [NSDictionary dictionaryWithObjectsAndKeys:
1494 Values_, @"CydiaValues",
1495 Sections_, @"CydiaSections",
1496 (id) Sources_, @"CydiaSources",
1497 Version_, @"CydiaVersion",
1498 nil], NULL, CFSTR("com.saurik.Cydia"), kCFPreferencesCurrentUser, kCFPreferencesCurrentHost);
1500 if (!CFPreferencesAppSynchronize(CFSTR("com.saurik.Cydia")))
1501 NSLog(@"CFPreferencesAppSynchronize(com.saurik.Cydia) == false");
1503 CydiaWriteSources();
1506 /* Source Class {{{ */
1507 @interface Source : NSObject {
1509 Database *database_;
1512 CYString depiction_;
1513 CYString description_;
1519 CYString distribution_;
1525 _H<NSString> authority_;
1527 CYString defaultIcon_;
1529 _H<NSMutableDictionary> record_;
1532 std::set<std::string> fetches_;
1533 std::set<std::string> files_;
1534 _transient NSObject<SourceDelegate> *delegate_;
1537 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(CYPool *)pool;
1539 - (NSComparisonResult) compareByName:(Source *)source;
1541 - (NSString *) depictionForPackage:(NSString *)package;
1542 - (NSString *) supportForPackage:(NSString *)package;
1544 - (metaIndex *) metaIndex;
1545 - (NSDictionary *) record;
1548 - (NSString *) rooturi;
1549 - (NSString *) distribution;
1550 - (NSString *) type;
1553 - (NSString *) host;
1555 - (NSString *) name;
1556 - (NSString *) shortDescription;
1557 - (NSString *) label;
1558 - (NSString *) origin;
1559 - (NSString *) version;
1561 - (NSString *) defaultIcon;
1562 - (NSURL *) iconURL;
1564 - (void) setFetch:(bool)fetch forURI:(const char *)uri;
1565 - (void) resetFetch;
1569 @implementation Source
1571 + (NSString *) webScriptNameForSelector:(SEL)selector {
1573 else if (selector == @selector(addSection:))
1574 return @"addSection";
1575 else if (selector == @selector(getField:))
1577 else if (selector == @selector(removeSection:))
1578 return @"removeSection";
1579 else if (selector == @selector(remove))
1585 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1586 return [self webScriptNameForSelector:selector] == nil;
1589 + (NSArray *) _attributeKeys {
1590 return [NSArray arrayWithObjects:
1601 @"shortDescription",
1608 - (NSArray *) attributeKeys {
1609 return [[self class] _attributeKeys];
1612 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1613 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1616 - (metaIndex *) metaIndex {
1620 - (void) setMetaIndex:(metaIndex *)index inPool:(CYPool *)pool {
1621 trusted_ = index->IsTrusted();
1623 uri_.set(pool, index->GetURI());
1624 distribution_.set(pool, index->GetDist());
1625 type_.set(pool, index->GetType());
1627 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1628 if (dindex != NULL) {
1629 std::string file(dindex->MetaIndexURI(""));
1630 base_.set(pool, file);
1633 _profile(Source$setMetaIndex$GetIndexes)
1634 dindex->GetIndexes(&acquire, true);
1636 _profile(Source$setMetaIndex$DescURI)
1637 for (pkgAcquire::ItemIterator item(acquire.ItemsBegin()); item != acquire.ItemsEnd(); item++) {
1638 std::string file((*item)->DescURI());
1639 files_.insert(file);
1640 if (file.length() < sizeof("Packages.bz2") || file.substr(file.length() - sizeof("Packages.bz2")) != "/Packages.bz2")
1642 file = file.substr(0, file.length() - 4);
1643 files_.insert(file);
1644 files_.insert(file + ".gz");
1645 files_.insert(file + "Index");
1650 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1653 pkgTagFile tags(&fd);
1655 pkgTagSection section;
1662 {"default-icon", &defaultIcon_},
1663 {"depiction", &depiction_},
1664 {"description", &description_},
1666 {"origin", &origin_},
1667 {"support", &support_},
1668 {"version", &version_},
1671 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1672 const char *start, *end;
1674 if (section.Find(names[i].name_, start, end)) {
1675 CYString &value(*names[i].value_);
1676 value.set(pool, start, end - start);
1682 record_ = [Sources_ objectForKey:[self key]];
1684 NSURL *url([NSURL URLWithString:uri_]);
1688 host_ = [host_ lowercaseString];
1693 authority_ = [url path];
1696 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(CYPool *)pool {
1697 if ((self = [super init]) != nil) {
1698 era_ = [database era];
1699 database_ = database;
1702 _profile(Source$initWithMetaIndex$setMetaIndex)
1703 [self setMetaIndex:index inPool:pool];
1708 - (NSString *) getField:(NSString *)name {
1709 @synchronized (database_) {
1710 if ([database_ era] != era_ || index_ == NULL)
1713 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index_));
1718 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly)) {
1723 pkgTagFile tags(&fd);
1725 pkgTagSection section;
1728 const char *start, *end;
1729 if (!section.Find([name UTF8String], start, end))
1730 return (NSString *) [NSNull null];
1732 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
1735 - (NSComparisonResult) compareByName:(Source *)source {
1736 NSString *lhs = [self name];
1737 NSString *rhs = [source name];
1739 if ([lhs length] != 0 && [rhs length] != 0) {
1740 unichar lhc = [lhs characterAtIndex:0];
1741 unichar rhc = [rhs characterAtIndex:0];
1743 if (isalpha(lhc) && !isalpha(rhc))
1744 return NSOrderedAscending;
1745 else if (!isalpha(lhc) && isalpha(rhc))
1746 return NSOrderedDescending;
1749 return [lhs compare:rhs options:LaxCompareOptions_];
1752 - (NSString *) depictionForPackage:(NSString *)package {
1753 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1756 - (NSString *) supportForPackage:(NSString *)package {
1757 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1760 - (NSArray *) sections {
1761 return record_ == nil ? (id) [NSNull null] : [record_ objectForKey:@"Sections"] ?: [NSArray array];
1764 - (void) _addSection:(NSString *)section {
1767 else if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) {
1768 if (![sections containsObject:section])
1769 [sections addObject:section];
1771 [record_ setObject:[NSMutableArray arrayWithObject:section] forKey:@"Sections"];
1774 - (bool) addSection:(NSString *)section {
1778 [self performSelectorOnMainThread:@selector(_addSection:) withObject:section waitUntilDone:NO];
1782 - (void) _removeSection:(NSString *)section {
1786 if (NSMutableArray *sections = [record_ objectForKey:@"Sections"])
1787 if ([sections containsObject:section])
1788 [sections removeObject:section];
1791 - (bool) removeSection:(NSString *)section {
1795 [self performSelectorOnMainThread:@selector(_removeSection:) withObject:section waitUntilDone:NO];
1800 [Sources_ removeObjectForKey:[self key]];
1804 bool value(record_ != nil);
1805 [self performSelectorOnMainThread:@selector(_remove) withObject:nil waitUntilDone:NO];
1809 - (NSDictionary *) record {
1817 - (NSString *) rooturi {
1821 - (NSString *) distribution {
1822 return distribution_;
1825 - (NSString *) type {
1829 - (NSString *) baseuri {
1830 return base_.empty() ? nil : (id) base_;
1833 - (NSString *) iconuri {
1834 if (NSString *base = [self baseuri])
1835 return [base stringByAppendingString:@"CydiaIcon.png"];
1840 - (NSURL *) iconURL {
1841 if (NSString *uri = [self iconuri])
1842 return [NSURL URLWithString:uri];
1846 - (NSString *) key {
1847 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1850 - (NSString *) host {
1854 - (NSString *) name {
1855 return origin_.empty() ? (id) authority_ : origin_;
1858 - (NSString *) shortDescription {
1859 return description_;
1862 - (NSString *) label {
1863 return label_.empty() ? (id) authority_ : label_;
1866 - (NSString *) origin {
1870 - (NSString *) version {
1874 - (NSString *) defaultIcon {
1875 return defaultIcon_;
1878 - (void) setDelegate:(NSObject<SourceDelegate> *)delegate {
1879 delegate_ = delegate;
1883 return !fetches_.empty();
1886 - (void) setFetch:(bool)fetch forURI:(const char *)uri {
1888 if (fetches_.erase(uri) == 0)
1890 } else if (files_.find(uri) == files_.end())
1892 else if (!fetches_.insert(uri).second)
1895 [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:[self fetch]] waitUntilDone:NO];
1898 - (void) resetFetch {
1900 [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:NO];
1905 /* CydiaOperation Class {{{ */
1906 @interface CydiaOperation : NSObject {
1907 _H<NSString> operator_;
1908 _H<NSString> value_;
1911 - (NSString *) operator;
1912 - (NSString *) value;
1916 @implementation CydiaOperation
1918 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1919 if ((self = [super init]) != nil) {
1920 operator_ = [NSString stringWithUTF8String:_operator];
1921 value_ = [NSString stringWithUTF8String:value];
1925 + (NSArray *) _attributeKeys {
1926 return [NSArray arrayWithObjects:
1932 - (NSArray *) attributeKeys {
1933 return [[self class] _attributeKeys];
1936 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1937 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1940 - (NSString *) operator {
1944 - (NSString *) value {
1950 /* CydiaClause Class {{{ */
1951 @interface CydiaClause : NSObject {
1952 _H<NSString> package_;
1953 _H<CydiaOperation> version_;
1956 - (NSString *) package;
1957 - (CydiaOperation *) version;
1961 @implementation CydiaClause
1963 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1964 if ((self = [super init]) != nil) {
1965 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1967 if (const char *version = dep.TargetVer())
1968 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1970 version_ = (id) [NSNull null];
1974 + (NSArray *) _attributeKeys {
1975 return [NSArray arrayWithObjects:
1981 - (NSArray *) attributeKeys {
1982 return [[self class] _attributeKeys];
1985 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1986 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1989 - (NSString *) package {
1993 - (CydiaOperation *) version {
1999 /* CydiaRelation Class {{{ */
2000 @interface CydiaRelation : NSObject {
2001 _H<NSString> relationship_;
2002 _H<NSMutableArray> clauses_;
2005 - (NSString *) relationship;
2006 - (NSArray *) clauses;
2010 @implementation CydiaRelation
2012 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
2013 if ((self = [super init]) != nil) {
2014 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
2015 clauses_ = [NSMutableArray arrayWithCapacity:8];
2017 pkgCache::DepIterator start;
2018 pkgCache::DepIterator end;
2019 dep.GlobOr(start, end); // ++dep
2022 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
2024 // yes, seriously. (wtf?)
2032 + (NSArray *) _attributeKeys {
2033 return [NSArray arrayWithObjects:
2039 - (NSArray *) attributeKeys {
2040 return [[self class] _attributeKeys];
2043 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2044 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2047 - (NSString *) relationship {
2048 return relationship_;
2051 - (NSArray *) clauses {
2055 - (void) addClause:(CydiaClause *)clause {
2056 [clauses_ addObject:clause];
2061 /* Package Class {{{ */
2062 struct ParsedPackage {
2066 CYString architecture_;
2069 CYString depiction_;
2076 @interface Package : NSObject {
2078 @public uint32_t role_ : 3;
2079 uint32_t essential_ : 1;
2080 uint32_t obsolete_ : 1;
2081 uint32_t ignored_ : 1;
2082 uint32_t pooled_ : 1;
2088 _transient Database *database_;
2090 pkgCache::VerIterator version_;
2091 pkgCache::PkgIterator iterator_;
2092 pkgCache::VerFileIterator file_;
2096 CYString transform_;
2099 CYString installed_;
2102 const char *section_;
2103 _transient NSString *section$_;
2107 PackageValue *metadata_;
2108 ParsedPackage *parsed_;
2110 _H<NSMutableArray> tags_;
2113 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database;
2114 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database;
2116 - (pkgCache::PkgIterator) iterator;
2119 - (NSString *) section;
2120 - (NSString *) simpleSection;
2122 - (NSString *) longSection;
2123 - (NSString *) shortSection;
2127 - (MIMEAddress *) maintainer;
2129 - (NSString *) longDescription;
2130 - (NSString *) shortDescription;
2133 - (PackageValue *) metadata;
2136 - (bool) subscribed;
2137 - (bool) setSubscribed:(bool)subscribed;
2141 - (NSString *) latest;
2142 - (NSString *) installed;
2143 - (BOOL) uninstalled;
2146 - (BOOL) upgradableAndEssential:(BOOL)essential;
2149 - (BOOL) unfiltered;
2153 - (BOOL) halfConfigured;
2154 - (BOOL) halfInstalled;
2156 - (NSString *) mode;
2159 - (NSString *) name;
2161 - (NSString *) homepage;
2162 - (NSString *) depiction;
2163 - (MIMEAddress *) author;
2165 - (NSString *) support;
2167 - (NSArray *) files;
2168 - (NSArray *) warnings;
2169 - (NSArray *) applications;
2171 - (Source *) source;
2174 - (BOOL) matches:(NSArray *)query;
2176 - (BOOL) hasTag:(NSString *)tag;
2177 - (NSString *) primaryPurpose;
2178 - (NSArray *) purposes;
2179 - (bool) isCommercial;
2181 - (void) setIndex:(size_t)index;
2183 - (CYString &) cyname;
2185 - (uint32_t) compareBySection:(NSArray *)sections;
2192 uint32_t PackageChangesRadix(Package *self, void *) {
2197 uint32_t timestamp : 30;
2198 uint32_t ignored : 1;
2199 uint32_t upgradable : 1;
2203 bool upgradable([self upgradableAndEssential:YES]);
2204 value.bits.upgradable = upgradable ? 1 : 0;
2207 value.bits.timestamp = 0;
2208 value.bits.ignored = [self ignored] ? 0 : 1;
2209 value.bits.upgradable = 1;
2211 value.bits.timestamp = [self seen] >> 2;
2212 value.bits.ignored = 0;
2213 value.bits.upgradable = 0;
2216 return _not(uint32_t) - value.key;
2219 CYString &(*PackageName)(Package *self, SEL sel);
2221 uint32_t PackagePrefixRadix(Package *self, void *context) {
2222 size_t offset(reinterpret_cast<size_t>(context));
2223 CYString &name(PackageName(self, @selector(cyname)));
2225 size_t size(name.size());
2228 char *text(name.data());
2231 if (!isdigit(text[0]))
2235 while (size != digits && isdigit(text[digits]))
2243 if (offset == 0 && zeros != 0) {
2244 memset(data, '0', zeros);
2245 memcpy(data + zeros, text, 4 - zeros);
2247 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2248 if (size <= offset - zeros)
2251 text += offset - zeros;
2252 size -= offset - zeros;
2255 memcpy(data, text, 4);
2257 memcpy(data, text, size);
2258 memset(data + size, 0, 4 - size);
2261 for (size_t i(0); i != 4; ++i)
2262 if (isalpha(data[i]))
2270 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2272 /* XXX: ntohl may be more honest */
2273 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2276 CFComparisonResult StringNameCompare(CFStringRef lhn, CFStringRef rhn, size_t length) {
2277 _profile(PackageNameCompare)
2279 return rhn == NULL ? kCFCompareEqualTo : kCFCompareLessThan;
2280 else if (rhn == NULL)
2281 return kCFCompareGreaterThan;
2283 CFIndex length(CFStringGetLength(lhn));
2285 _profile(PackageNameCompare$NumbersLast)
2286 if (length != 0 && CFStringGetLength(rhn) != 0) {
2287 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2288 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2289 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2290 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2291 return lha ? kCFCompareLessThan : kCFCompareGreaterThan;
2295 _profile(PackageNameCompare$Compare)
2296 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, (CFLocaleRef) (id) CollationLocale_);
2301 _finline CFComparisonResult StringNameCompare(NSString *lhn, NSString*rhn, size_t length) {
2302 return StringNameCompare((CFStringRef) lhn, (CFStringRef) rhn, length);
2305 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2306 CYString &lhn(PackageName(lhs, @selector(cyname)));
2307 NSString *rhn(PackageName(rhs, @selector(cyname)));
2308 return StringNameCompare(lhn, rhn, lhn.size());
2311 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *arg) {
2312 return PackageNameCompare(*lhs, *rhs, arg);
2315 struct PackageNameOrdering :
2316 std::binary_function<Package *, Package *, bool>
2318 _finline bool operator ()(Package *lhs, Package *rhs) const {
2319 return PackageNameCompare(lhs, rhs, NULL) == kCFCompareLessThan;
2323 @implementation Package
2325 - (NSString *) description {
2326 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2332 if (parsed_ != NULL)
2337 + (NSString *) webScriptNameForSelector:(SEL)selector {
2339 else if (selector == @selector(clear))
2341 else if (selector == @selector(getField:))
2343 else if (selector == @selector(getRecord))
2344 return @"getRecord";
2345 else if (selector == @selector(hasTag:))
2347 else if (selector == @selector(install))
2349 else if (selector == @selector(remove))
2355 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2356 return [self webScriptNameForSelector:selector] == nil;
2359 + (NSArray *) _attributeKeys {
2360 return [NSArray arrayWithObjects:
2381 @"shortDescription",
2394 - (NSArray *) attributeKeys {
2395 return [[self class] _attributeKeys];
2398 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2399 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2402 - (NSArray *) relations {
2403 @synchronized (database_) {
2404 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2405 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2406 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2410 - (NSString *) architecture {
2412 @synchronized (database_) {
2413 return parsed_->architecture_.empty() ? [NSNull null] : (id) parsed_->architecture_;
2416 - (NSString *) getField:(NSString *)name {
2417 @synchronized (database_) {
2418 if ([database_ era] != era_ || file_.end())
2421 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2423 const char *start, *end;
2424 if (!parser.Find([name UTF8String], start, end))
2425 return (NSString *) [NSNull null];
2427 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2430 - (NSString *) getRecord {
2431 @synchronized (database_) {
2432 if ([database_ era] != era_ || file_.end())
2435 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2437 const char *start, *end;
2438 parser.GetRec(start, end);
2440 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2444 if (parsed_ != NULL)
2446 @synchronized (database_) {
2447 if ([database_ era] != era_ || file_.end())
2450 ParsedPackage *parsed(new ParsedPackage);
2453 _profile(Package$parse)
2454 pkgRecords::Parser *parser;
2456 _profile(Package$parse$Lookup)
2457 parser = &[database_ records]->Lookup(file_);
2463 _profile(Package$parse$Find)
2468 {"architecture", &parsed->architecture_},
2469 {"icon", &parsed->icon_},
2470 {"depiction", &parsed->depiction_},
2471 {"homepage", &parsed->homepage_},
2472 {"website", &website},
2474 {"support", &parsed->support_},
2475 {"author", &parsed->author_},
2476 {"md5sum", &parsed->md5sum_},
2479 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2480 const char *start, *end;
2482 if (parser->Find(names[i].name_, start, end)) {
2483 CYString &value(*names[i].value_);
2484 _profile(Package$parse$Value)
2485 value.set(pool_, start, end - start);
2491 _profile(Package$parse$Tagline)
2492 const char *start, *end;
2493 if (parser->ShortDesc(start, end)) {
2494 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2497 while (stop != start && stop[-1] == '\r')
2499 parsed->tagline_.set(pool_, start, stop - start);
2503 _profile(Package$parse$Retain)
2504 if (parsed->homepage_.empty())
2505 parsed->homepage_ = website;
2506 if (parsed->homepage_ == parsed->depiction_)
2507 parsed->homepage_.clear();
2508 if (parsed->support_.empty())
2509 parsed->support_ = bugs;
2514 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database {
2515 if ((self = [super init]) != nil) {
2516 _profile(Package$initWithVersion)
2518 pool_ = new CYPool();
2524 database_ = database;
2525 era_ = [database era];
2529 pkgCache::PkgIterator iterator(version.ParentPkg());
2530 iterator_ = iterator;
2532 _profile(Package$initWithVersion$Version)
2533 if (!version_.end())
2534 file_ = version_.FileList();
2536 pkgCache &cache([database_ cache]);
2537 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2541 _profile(Package$initWithVersion$Cache)
2542 name_.set(NULL, iterator.Display());
2544 latest_.set(NULL, StripVersion_(version_.VerStr()));
2546 pkgCache::VerIterator current(iterator.CurrentVer());
2548 installed_.set(NULL, StripVersion_(current.VerStr()));
2551 _profile(Package$initWithVersion$Transliterate) do {
2552 if (CollationTransl_ == NULL)
2557 _profile(Package$initWithVersion$Transliterate$utf8)
2558 const uint8_t *data(reinterpret_cast<const uint8_t *>(name_.data()));
2559 for (size_t i(0), e(name_.size()); i != e; ++i)
2560 if (data[i] >= 0x80)
2565 UErrorCode code(U_ZERO_ERROR);
2568 _profile(Package$initWithVersion$Transliterate$u_strFromUTF8WithSub)
2569 CollationString_.resize(name_.size());
2570 u_strFromUTF8WithSub(&CollationString_[0], CollationString_.size(), &length, name_.data(), name_.size(), 0xfffd, NULL, &code);
2571 if (!U_SUCCESS(code))
2573 CollationString_.resize(length);
2576 _profile(Package$initWithVersion$Transliterate$utrans_trans)
2577 length = CollationString_.size();
2578 utrans_trans(CollationTransl_, reinterpret_cast<UReplaceable *>(&CollationString_), &CollationUCalls_, 0, &length, &code);
2579 if (!U_SUCCESS(code))
2581 _assert(CollationString_.size() == length);
2584 _profile(Package$initWithVersion$Transliterate$u_strToUTF8WithSub$preflight)
2585 u_strToUTF8WithSub(NULL, 0, &length, CollationString_.data(), CollationString_.size(), 0xfffd, NULL, &code);
2586 if (code == U_BUFFER_OVERFLOW_ERROR)
2587 code = U_ZERO_ERROR;
2588 else if (!U_SUCCESS(code))
2593 _profile(Package$initWithVersion$Transliterate$apr_palloc)
2594 transform = pool_->malloc<char>(length);
2596 _profile(Package$initWithVersion$Transliterate$u_strToUTF8WithSub$transform)
2597 u_strToUTF8WithSub(transform, length, NULL, CollationString_.data(), CollationString_.size(), 0xfffd, NULL, &code);
2598 if (!U_SUCCESS(code))
2602 transform_.set(NULL, transform, length);
2603 } while (false); _end
2605 _profile(Package$initWithVersion$Tags)
2606 pkgCache::TagIterator tag(iterator.TagList());
2608 tags_ = [NSMutableArray arrayWithCapacity:8];
2610 goto tag; for (; !tag.end(); ++tag) tag: {
2611 const char *name(tag.Name());
2612 NSString *string((NSString *) CYStringCreate(name));
2616 [tags_ addObject:[string autorelease]];
2618 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2619 if (strcmp(name + 6, "enduser") == 0)
2621 else if (strcmp(name + 6, "hacker") == 0)
2623 else if (strcmp(name + 6, "developer") == 0)
2625 else if (strcmp(name + 6, "cydia") == 0)
2631 if (strncmp(name, "cydia::", 7) == 0) {
2632 if (strcmp(name + 7, "essential") == 0)
2634 else if (strcmp(name + 7, "obsolete") == 0)
2641 _profile(Package$initWithVersion$Metadata)
2642 const char *mixed(iterator.Name());
2643 size_t size(strlen(mixed));
2644 static const size_t prefix(sizeof("/var/lib/dpkg/info/") - 1);
2645 char lower[prefix + size + 5 + 1];
2647 for (size_t i(0); i != size; ++i)
2648 lower[prefix + i] = mixed[i] | 0x20;
2650 if (!installed_.empty()) {
2651 memcpy(lower, "/var/lib/dpkg/info/", prefix);
2652 memcpy(lower + prefix + size, ".list", 6);
2654 if (stat(lower, &info) != -1)
2655 upgraded_ = info.st_birthtime;
2658 PackageValue *metadata(PackageFind(lower + prefix, size));
2659 metadata_ = metadata;
2661 id_.set(NULL, metadata->name_, size);
2663 const char *latest(version_.VerStr());
2664 size_t length(strlen(latest));
2666 uint16_t vhash(hashlittle(latest, length));
2668 size_t capped(std::min<size_t>(8, length));
2669 latest = latest + length - capped;
2671 if (metadata->first_ == 0)
2672 metadata->first_ = now_;
2674 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2675 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2676 metadata->vhash_ = vhash;
2677 metadata->last_ = now_;
2678 } else if (metadata->last_ == 0)
2679 metadata->last_ = metadata->first_;
2682 _profile(Package$initWithVersion$Section)
2683 section_ = version_.Section();
2686 _profile(Package$initWithVersion$Flags)
2687 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2688 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2693 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database {
2694 pkgCache::VerIterator version;
2696 _profile(Package$packageWithIterator$GetCandidateVer)
2697 version = [database policy]->GetCandidateVer(iterator);
2705 _profile(Package$packageWithIterator$Allocate)
2706 package = [Package allocWithZone:zone];
2709 _profile(Package$packageWithIterator$Initialize)
2711 initWithVersion:version
2718 _profile(Package$packageWithIterator$Autorelease)
2719 package = [package autorelease];
2725 - (pkgCache::PkgIterator) iterator {
2729 - (NSString *) section {
2730 if (section$_ == nil) {
2731 if (section_ == NULL)
2734 _profile(Package$section$mappedSectionForPointer)
2735 section$_ = [database_ mappedSectionForPointer:section_];
2740 - (NSString *) simpleSection {
2741 if (NSString *section = [self section])
2742 return Simplify(section);
2747 - (NSString *) longSection {
2748 return LocalizeSection([self section]);
2751 - (NSString *) shortSection {
2752 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2755 - (NSString *) uri {
2758 pkgIndexFile *index;
2759 pkgCache::PkgFileIterator file(file_.File());
2760 if (![database_ list].FindIndex(file, index))
2762 return [NSString stringWithUTF8String:iterator_->Path];
2763 //return [NSString stringWithUTF8String:file.Site()];
2764 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2768 - (MIMEAddress *) maintainer {
2769 @synchronized (database_) {
2770 if ([database_ era] != era_ || file_.end())
2773 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2774 const std::string &maintainer(parser->Maintainer());
2775 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2778 - (NSString *) md5sum {
2779 return parsed_ == NULL ? nil : (id) parsed_->md5sum_;
2783 @synchronized (database_) {
2784 if ([database_ era] != era_ || version_.end())
2787 return version_->InstalledSize;
2790 - (NSString *) longDescription {
2791 @synchronized (database_) {
2792 if ([database_ era] != era_ || file_.end())
2795 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2796 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2798 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2799 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2800 if ([lines count] < 2)
2803 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2804 for (size_t i(1), e([lines count]); i != e; ++i) {
2805 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2806 [trimmed addObject:trim];
2809 return [trimmed componentsJoinedByString:@"\n"];
2812 - (NSString *) shortDescription {
2813 if (parsed_ != NULL)
2814 return static_cast<NSString *>(parsed_->tagline_);
2816 @synchronized (database_) {
2817 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2819 const char *start, *end;
2820 if (!parser.ShortDesc(start, end))
2823 if (end - start > 200)
2827 if (const char *stop = reinterpret_cast<const char *>(memchr(start, '\n', end - start)))
2830 while (end != start && end[-1] == '\r')
2834 return [(id) CYStringCreate(start, end - start) autorelease];
2838 _profile(Package$index)
2839 CFStringRef name((CFStringRef) [self name]);
2840 if (CFStringGetLength(name) == 0)
2842 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2843 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2845 return toupper(character);
2849 - (PackageValue *) metadata {
2854 PackageValue *metadata([self metadata]);
2855 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2858 - (bool) subscribed {
2859 return [self metadata]->subscribed_;
2862 - (bool) setSubscribed:(bool)subscribed {
2863 PackageValue *metadata([self metadata]);
2864 if (metadata->subscribed_ == subscribed)
2866 metadata->subscribed_ = subscribed;
2874 - (NSString *) latest {
2878 - (NSString *) installed {
2882 - (BOOL) uninstalled {
2883 return installed_.empty();
2887 return !version_.end();
2890 - (BOOL) upgradableAndEssential:(BOOL)essential {
2891 _profile(Package$upgradableAndEssential)
2892 pkgCache::VerIterator current(iterator_.CurrentVer());
2894 return essential && essential_;
2896 return !version_.end() && version_ != current;
2900 - (BOOL) essential {
2905 return [database_ cache][iterator_].InstBroken();
2908 - (BOOL) unfiltered {
2909 _profile(Package$unfiltered$obsolete)
2910 if (_unlikely(obsolete_))
2914 _profile(Package$unfiltered$role)
2915 if (_unlikely(role_ > 3))
2923 if (![self unfiltered])
2928 _profile(Package$visible$section)
2929 section = [self section];
2932 _profile(Package$visible$isSectionVisible)
2933 if (!isSectionVisible(section))
2941 unsigned char current(iterator_->CurrentState);
2942 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2945 - (BOOL) halfConfigured {
2946 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2949 - (BOOL) halfInstalled {
2950 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2954 @synchronized (database_) {
2955 if ([database_ era] != era_ || iterator_.end())
2958 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2959 return state.Mode != pkgDepCache::ModeKeep;
2962 - (NSString *) mode {
2963 @synchronized (database_) {
2964 if ([database_ era] != era_ || iterator_.end())
2967 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2969 switch (state.Mode) {
2970 case pkgDepCache::ModeDelete:
2971 if ((state.iFlags & pkgDepCache::Purge) != 0)
2975 case pkgDepCache::ModeKeep:
2976 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2977 return @"REINSTALL";
2978 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2982 case pkgDepCache::ModeInstall:
2983 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2984 return @"REINSTALL";
2985 else*/ switch (state.Status) {
2987 return @"DOWNGRADE";
2993 return @"NEW_INSTALL";
3004 - (NSString *) name {
3005 return name_.empty() ? id_ : name_;
3008 - (UIImage *) icon {
3009 NSString *section = [self simpleSection];
3012 if (parsed_ != NULL)
3013 if (NSString *href = parsed_->icon_)
3014 if ([href hasPrefix:@"file:///"])
3015 icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
3016 if (icon == nil) if (section != nil)
3017 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]];
3018 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
3019 if ([dicon hasPrefix:@"file:///"])
3020 icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
3022 icon = [UIImage imageNamed:@"unknown.png"];
3026 - (NSString *) homepage {
3027 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
3030 - (NSString *) depiction {
3031 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
3034 - (MIMEAddress *) author {
3035 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
3038 - (NSString *) support {
3039 return parsed_ != NULL && !parsed_->support_.empty() ? parsed_->support_ : [[self source] supportForPackage:id_];
3042 - (NSArray *) files {
3043 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
3044 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
3047 fin.open([path UTF8String]);
3052 while (std::getline(fin, line))
3053 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
3058 - (NSString *) state {
3059 @synchronized (database_) {
3060 if ([database_ era] != era_ || file_.end())
3063 switch (iterator_->CurrentState) {
3064 case pkgCache::State::NotInstalled:
3065 return @"NotInstalled";
3066 case pkgCache::State::UnPacked:
3068 case pkgCache::State::HalfConfigured:
3069 return @"HalfConfigured";
3070 case pkgCache::State::HalfInstalled:
3071 return @"HalfInstalled";
3072 case pkgCache::State::ConfigFiles:
3073 return @"ConfigFiles";
3074 case pkgCache::State::Installed:
3075 return @"Installed";
3076 case pkgCache::State::TriggersAwaited:
3077 return @"TriggersAwaited";
3078 case pkgCache::State::TriggersPending:
3079 return @"TriggersPending";
3082 return (NSString *) [NSNull null];
3085 - (NSString *) selection {
3086 @synchronized (database_) {
3087 if ([database_ era] != era_ || file_.end())
3090 switch (iterator_->SelectedState) {
3091 case pkgCache::State::Unknown:
3093 case pkgCache::State::Install:
3095 case pkgCache::State::Hold:
3097 case pkgCache::State::DeInstall:
3098 return @"DeInstall";
3099 case pkgCache::State::Purge:
3103 return (NSString *) [NSNull null];
3106 - (NSArray *) warnings {
3107 @synchronized (database_) {
3108 if ([database_ era] != era_ || file_.end())
3111 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
3112 const char *name(iterator_.Name());
3114 size_t length(strlen(name));
3115 if (length < 2) invalid:
3116 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
3117 else for (size_t i(0); i != length; ++i)
3119 /* XXX: technically this is not allowed */
3120 (name[i] < 'A' || name[i] > 'Z') &&
3121 (name[i] < 'a' || name[i] > 'z') &&
3122 (name[i] < '0' || name[i] > '9') &&
3123 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
3126 if (strcmp(name, "cydia") != 0) {
3129 bool _private = false;
3131 bool dbstash = false;
3132 bool dsstore = false;
3134 bool repository = [[self section] isEqualToString:@"Repositories"];
3136 if (NSArray *files = [self files])
3137 for (NSString *file in files)
3138 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
3140 else if (!user && [file isEqualToString:@"/User"])
3142 else if (!_private && [file isEqualToString:@"/private"])
3144 else if (!stash && [file isEqualToString:@"/var/stash"])
3146 else if (!dbstash && [file isEqualToString:@"/var/db/stash"])
3148 else if (!dsstore && [file hasSuffix:@"/.DS_Store"])
3151 /* XXX: this is not sensitive enough. only some folders are valid. */
3152 if (cydia && !repository)
3153 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
3155 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
3157 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
3159 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
3161 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/db/stash"]];
3163 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @".DS_Store"]];
3166 return [warnings count] == 0 ? nil : warnings;
3169 - (NSArray *) applications {
3170 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
3172 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
3174 static RegEx application_r("/Applications/(.*)\\.app/Info.plist");
3175 if (NSArray *files = [self files])
3176 for (NSString *file in files)
3177 if (application_r(file)) {
3178 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
3179 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
3180 if ([id isEqualToString:me])
3183 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
3185 display = application_r[1];
3187 NSString *bundle([file stringByDeletingLastPathComponent]);
3188 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
3189 // XXX: maybe this should check if this is really a string, not just for length
3190 if (icon == nil || ![icon respondsToSelector:@selector(length)] || [icon length] == 0)
3192 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
3194 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
3195 [applications addObject:application];
3197 [application addObject:id];
3198 [application addObject:display];
3199 [application addObject:url];
3202 return [applications count] == 0 ? nil : applications;
3205 - (Source *) source {
3206 if (source_ == nil) {
3207 @synchronized (database_) {
3208 if ([database_ era] != era_ || file_.end())
3209 source_ = (Source *) [NSNull null];
3211 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
3215 return source_ == (Source *) [NSNull null] ? nil : source_;
3218 - (time_t) upgraded {
3222 - (uint32_t) recent {
3223 return std::numeric_limits<uint32_t>::max() - upgraded_;
3230 - (BOOL) matches:(NSArray *)query {
3231 if (query == nil || [query count] == 0)
3240 string = [self name];
3241 length = [string length];
3244 for (NSString *term in query) {
3245 range = [string rangeOfString:term options:MatchCompareOptions_];
3246 if (range.location != NSNotFound)
3247 rank_ -= 6 * 1000000 / length;
3252 length = [string length];
3255 for (NSString *term in query) {
3256 range = [string rangeOfString:term options:MatchCompareOptions_];
3257 if (range.location != NSNotFound)
3258 rank_ -= 6 * 1000000 / length;
3262 string = [self shortDescription];
3263 length = [string length];
3264 NSUInteger stop(std::min<NSUInteger>(length, 200));
3267 for (NSString *term in query) {
3268 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
3269 if (range.location != NSNotFound)
3270 rank_ -= 2 * 100000;
3276 - (NSArray *) tags {
3280 - (BOOL) hasTag:(NSString *)tag {
3281 return tags_ == nil ? NO : [tags_ containsObject:tag];
3284 - (NSString *) primaryPurpose {
3285 for (NSString *tag in (NSArray *) tags_)
3286 if ([tag hasPrefix:@"purpose::"])
3287 return [tag substringFromIndex:9];
3291 - (NSArray *) purposes {
3292 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
3293 for (NSString *tag in (NSArray *) tags_)
3294 if ([tag hasPrefix:@"purpose::"])
3295 [purposes addObject:[tag substringFromIndex:9]];
3296 return [purposes count] == 0 ? nil : purposes;
3299 - (bool) isCommercial {
3300 return [self hasTag:@"cydia::commercial"];
3303 - (void) setIndex:(size_t)index {
3304 if (metadata_->index_ != index)
3305 metadata_->index_ = index;
3308 - (CYString &) cyname {
3309 return !transform_.empty() ? transform_ : !name_.empty() ? name_ : id_;
3312 - (uint32_t) compareBySection:(NSArray *)sections {
3313 NSString *section([self section]);
3314 for (size_t i(0), e([sections count]); i != e; ++i) {
3315 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3319 return _not(uint32_t);
3323 @synchronized (database_) {
3324 pkgProblemResolver *resolver = [database_ resolver];
3325 resolver->Clear(iterator_);
3327 pkgCacheFile &cache([database_ cache]);
3328 cache->SetReInstall(iterator_, false);
3329 cache->MarkKeep(iterator_, false);
3333 @synchronized (database_) {
3334 pkgProblemResolver *resolver = [database_ resolver];
3335 resolver->Clear(iterator_);
3336 resolver->Protect(iterator_);
3338 pkgCacheFile &cache([database_ cache]);
3339 cache->SetReInstall(iterator_, false);
3340 cache->MarkInstall(iterator_, false);
3342 pkgDepCache::StateCache &state((*cache)[iterator_]);
3343 if (!state.Install())
3344 cache->SetReInstall(iterator_, true);
3348 @synchronized (database_) {
3349 pkgProblemResolver *resolver = [database_ resolver];
3350 resolver->Clear(iterator_);
3351 resolver->Remove(iterator_);
3352 resolver->Protect(iterator_);
3354 pkgCacheFile &cache([database_ cache]);
3355 cache->SetReInstall(iterator_, false);
3356 cache->MarkDelete(iterator_, true);
3361 /* Section Class {{{ */
3362 @interface Section : NSObject {
3366 _H<NSString> localized_;
3369 - (NSComparisonResult) compareByLocalized:(Section *)section;
3370 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3371 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3372 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3374 - (NSString *) name;
3375 - (void) setName:(NSString *)name;
3381 - (void) addToCount;
3383 - (void) setCount:(size_t)count;
3384 - (NSString *) localized;
3388 @implementation Section
3390 - (NSComparisonResult) compareByLocalized:(Section *)section {
3391 NSString *lhs(localized_);
3392 NSString *rhs([section localized]);
3394 /*if ([lhs length] != 0 && [rhs length] != 0) {
3395 unichar lhc = [lhs characterAtIndex:0];
3396 unichar rhc = [rhs characterAtIndex:0];
3398 if (isalpha(lhc) && !isalpha(rhc))
3399 return NSOrderedAscending;
3400 else if (!isalpha(lhc) && isalpha(rhc))
3401 return NSOrderedDescending;
3404 return [lhs compare:rhs options:LaxCompareOptions_];
3407 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3408 if ((self = [self initWithName:name localize:NO]) != nil) {
3409 if (localized != nil)
3410 localized_ = localized;
3414 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3415 return [self initWithName:name row:0 localize:localize];
3418 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3419 if ((self = [super init]) != nil) {
3423 localized_ = LocalizeSection(name_);
3427 - (NSString *) name {
3431 - (void) setName:(NSString *)name {
3447 - (void) addToCount {
3451 - (void) setCount:(size_t)count {
3455 - (NSString *) localized {
3462 class CydiaLogCleaner :
3463 public pkgArchiveCleaner
3466 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3471 /* Database Implementation {{{ */
3472 @implementation Database
3474 + (Database *) sharedInstance {
3475 static _H<Database> instance;
3476 if (instance == nil)
3477 instance = [[[Database alloc] init] autorelease];
3485 - (void) releasePackages {
3486 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3487 CFArrayRemoveAllValues(packages_);
3491 // XXX: actually implement this thing
3493 [self releasePackages];
3494 NSRecycleZone(zone_);
3498 - (void) _readCydia:(NSNumber *)fd {
3499 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3500 std::istream is(&ib);
3503 static RegEx finish_r("finish:([^:]*)");
3505 while (std::getline(is, line)) {
3506 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3508 const char *data(line.c_str());
3509 size_t size = line.size();
3510 lprintf("C:%s\n", data);
3512 if (finish_r(data, size)) {
3513 NSString *finish = finish_r[1];
3514 int index = [Finishes_ indexOfObject:finish];
3515 if (index != INT_MAX && index > Finish_)
3525 - (void) _readStatus:(NSNumber *)fd {
3526 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3527 std::istream is(&ib);
3530 static RegEx conffile_r("status: [^ ]* : conffile-prompt : (.*?) *");
3531 static RegEx pmstatus_r("([^:]*):([^:]*):([^:]*):(.*)");
3533 while (std::getline(is, line)) {
3534 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3536 const char *data(line.c_str());
3537 size_t size(line.size());
3538 lprintf("S:%s\n", data);
3540 if (conffile_r(data, size)) {
3541 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3542 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3543 } else if (strncmp(data, "status: ", 8) == 0) {
3544 // status: <package>: {unpacked,half-configured,installed}
3545 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3546 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3547 } else if (strncmp(data, "processing: ", 12) == 0) {
3548 // processing: configure: config-test
3549 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3550 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3551 } else if (pmstatus_r(data, size)) {
3552 std::string type([pmstatus_r[1] UTF8String]);
3554 NSString *package = pmstatus_r[2];
3555 if ([package isEqualToString:@"dpkg-exec"])
3558 float percent([pmstatus_r[3] floatValue]);
3559 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3561 NSString *string = pmstatus_r[4];
3563 if (type == "pmerror") {
3564 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3565 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3566 } else if (type == "pmstatus") {
3567 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3568 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3569 } else if (type == "pmconffile")
3570 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3572 lprintf("E:unknown pmstatus\n");
3574 lprintf("E:unknown status\n");
3582 - (void) _readOutput:(NSNumber *)fd {
3583 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3584 std::istream is(&ib);
3587 while (std::getline(is, line)) {
3588 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3590 lprintf("O:%s\n", line.c_str());
3592 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3593 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3605 - (Package *) packageWithName:(NSString *)name {
3608 @synchronized (self) {
3609 if (static_cast<pkgDepCache *>(cache_) == NULL)
3611 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3612 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:NULL database:self];
3616 if ((self = [super init]) != nil) {
3623 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3625 size_t capacity(MetaFile_->active_);
3631 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3632 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3636 _assert(pipe(fds) != -1);
3639 _config->Set("APT::Keep-Fds::", cydiafd_);
3640 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3643 detachNewThreadSelector:@selector(_readCydia:)
3645 withObject:[NSNumber numberWithInt:fds[0]]
3648 _assert(pipe(fds) != -1);
3652 detachNewThreadSelector:@selector(_readStatus:)
3654 withObject:[NSNumber numberWithInt:fds[0]]
3657 _assert(pipe(fds) != -1);
3658 _assert(dup2(fds[0], 0) != -1);
3659 _assert(close(fds[0]) != -1);
3661 input_ = fdopen(fds[1], "a");
3663 _assert(pipe(fds) != -1);
3664 _assert(dup2(fds[1], 1) != -1);
3665 _assert(close(fds[1]) != -1);
3668 detachNewThreadSelector:@selector(_readOutput:)
3670 withObject:[NSNumber numberWithInt:fds[0]]
3675 - (pkgCacheFile &) cache {
3679 - (pkgDepCache::Policy *) policy {
3683 - (pkgRecords *) records {
3687 - (pkgProblemResolver *) resolver {
3691 - (pkgAcquire &) fetcher {
3695 - (pkgSourceList &) list {
3699 - (NSArray *) packages {
3700 return (NSArray *) packages_;
3703 - (NSArray *) sources {
3707 - (Source *) sourceWithKey:(NSString *)key {
3708 for (Source *source in [self sources]) {
3709 if ([[source key] isEqualToString:key])
3714 - (bool) popErrorWithTitle:(NSString *)title {
3717 while (!_error->empty()) {
3719 bool warning(!_error->PopMessage(error));
3724 size_t size(error.size());
3725 if (size == 0 || error[size - 1] != '\n')
3727 error.resize(size - 1);
3730 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3732 static RegEx no_pubkey("GPG error:.* NO_PUBKEY .*");
3733 if (warning && no_pubkey(error.c_str()))
3736 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3742 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3743 return [self popErrorWithTitle:title] || !success;
3746 - (bool) _isEtceteraAptSourcesListDirectoryCydiaListSymbolicallyLinkedToMobileCachesCydiaSourceList {
3748 ssize_t length(readlink("/etc/apt/sources.list.d/cydia.list", target, sizeof(target) - 1));
3751 if (length >= sizeof(target))
3753 target[length] = '\0';
3754 return strcmp(target, "/var/mobile/Library/Caches/com.saurik.Cydia/sources.list") == 0;
3757 - (bool) popErrorWithTitle:(NSString *)title forReadList:(pkgSourceList &)list {
3758 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3760 if (![self _isEtceteraAptSourcesListDirectoryCydiaListSymbolicallyLinkedToMobileCachesCydiaSourceList])
3761 if ([self popErrorWithTitle:title forOperation:list.Read(SOURCES_LIST)])
3766 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3767 @synchronized (self) {
3770 [self releasePackages];
3773 [sourceList_ removeAllObjects];
3794 new (&pool_) CYPool();
3796 NSRecycleZone(zone_);
3797 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3799 int chk(creat("/tmp/cydia.chk", 0644));
3803 if (invocation != nil)
3804 [invocation invoke];
3806 NSString *title(UCLocalize("DATABASE"));
3808 list_ = new pkgSourceList();
3809 _profile(reloadDataWithInvocation$ReadMainList)
3810 if ([self popErrorWithTitle:title forReadList:*list_])
3814 _profile(reloadDataWithInvocation$Source$initWithMetaIndex)
3815 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3816 Source *object([[[Source alloc] initWithMetaIndex:*source forDatabase:self inPool:&pool_] autorelease]);
3817 [sourceList_ addObject:object];
3821 delock_ = GetStatusDate();
3824 OpProgress progress;
3827 _profile(reloadDataWithInvocation$pkgCacheFile)
3828 opened = cache_.Open(progress, false);
3831 // XXX: what if there are errors, but Open() == true? this should be merged with popError:
3832 while (!_error->empty()) {
3834 bool warning(!_error->PopMessage(error));
3836 lprintf("cache_.Open():[%s]\n", error.c_str());
3838 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3842 else if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3843 repair = @selector(configure);
3844 //else if (error == "The package lists or status file could not be parsed or opened.")
3845 // repair = @selector(update);
3846 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3847 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3848 // else if (error == "Malformed Status line")
3849 // else if (error == "The list of sources could not be read.")
3851 if (repair != NULL) {
3853 [delegate_ repairWithSelector:repair];
3862 unlink("/tmp/cydia.chk");
3864 now_ = [[NSDate date] timeIntervalSince1970];
3866 policy_ = new pkgDepCache::Policy();
3867 records_ = new pkgRecords(cache_);
3868 resolver_ = new pkgProblemResolver(cache_);
3869 fetcher_ = new pkgAcquire(&status_);
3872 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3873 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3877 _profile(reloadDataWithInvocation$pkgApplyStatus)
3878 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3882 if (cache_->BrokenCount() != 0) {
3883 _profile(pkgApplyStatus$pkgFixBroken)
3884 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3888 if (cache_->BrokenCount() != 0) {
3889 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3893 _profile(pkgApplyStatus$pkgMinimizeUpgrade)
3894 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3899 for (Source *object in (id) sourceList_) {
3900 metaIndex *source([object metaIndex]);
3901 std::vector<pkgIndexFile *> *indices = source->GetIndexFiles();
3902 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3903 // XXX: this could be more intelligent
3904 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3905 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3907 sourceMap_[cached->ID] = object;
3912 /*std::vector<Package *> packages;
3913 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3916 _profile(reloadDataWithInvocation$packageWithIterator)
3917 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3918 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:&pool_ database:self])
3919 //packages.push_back(package);
3920 CFArrayAppendValue(packages_, CFRetain(package));
3924 /*if (packages.empty())
3925 packages_ = [[NSArray alloc] init];
3927 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3930 _profile(reloadDataWithInvocation$radix$8)
3931 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(8)];
3934 _profile(reloadDataWithInvocation$radix$4)
3935 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3938 _profile(reloadDataWithInvocation$radix$0)
3939 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3942 _profile(reloadDataWithInvocation$insertion)
3943 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3946 /*_profile(reloadDataWithInvocation$CFQSortArray)
3947 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);
3950 /*_profile(reloadDataWithInvocation$stdsort)
3951 std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3954 /*_profile(reloadDataWithInvocation$CFArraySortValues)
3955 CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3958 /*_profile(reloadDataWithInvocation$sortUsingFunction)
3959 [packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3963 size_t count(CFArrayGetCount(packages_));
3964 MetaFile_->active_ = count;
3965 for (size_t index(0); index != count; ++index)
3966 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3971 @synchronized (self) {
3973 resolver_ = new pkgProblemResolver(cache_);
3975 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3976 if (!cache_[iterator].Keep())
3977 cache_->MarkKeep(iterator, false);
3978 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3979 cache_->SetReInstall(iterator, false);
3982 - (void) configure {
3983 NSString *dpkg = [NSString stringWithFormat:@"/usr/libexec/cydo --configure -a --status-fd %u", statusfd_];
3985 system([dpkg UTF8String]);
3990 @synchronized (self) {
3991 // XXX: I don't remember this condition
3996 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3998 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
4000 if ([self popErrorWithTitle:title])
4004 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
4006 CydiaLogCleaner cleaner;
4007 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
4014 fetcher_->Shutdown();
4016 pkgRecords records(cache_);
4018 lock_ = new FileFd();
4019 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
4021 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
4023 if ([self popErrorWithTitle:title])
4027 if ([self popErrorWithTitle:title forReadList:list])
4030 manager_ = (_system->CreatePM(cache_));
4031 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
4038 bool substrate(RestartSubstrate_);
4039 RestartSubstrate_ = false;
4041 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
4043 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
4045 if ([self popErrorWithTitle:title forReadList:list])
4047 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
4048 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
4051 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4053 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
4055 [self popErrorWithTitle:title];
4059 bool failed = false;
4060 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
4061 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
4063 if ((*item)->Status == pkgAcquire::Item::StatIdle)
4066 std::string uri = (*item)->DescURI();
4067 std::string error = (*item)->ErrorText;
4069 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
4072 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError]);
4073 [delegate_ addProgressEventOnMainThread:event forTask:title];
4076 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4084 RestartSubstrate_ = true;
4086 if (![delock_ isEqual:GetStatusDate()]) {
4087 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("DPKG_LOCKED") ofType:kCydiaProgressEventTypeError] forTask:title];
4093 NSString *oextended(@"/var/lib/apt/extended_states");
4094 NSString *nextended(Cache("extended_states"));
4095 pkgPackageManager::OrderResult result(manager_->DoInstall(statusfd_));
4096 system([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /bin/mv -f %@ %@", nextended, oextended] UTF8String]);
4097 system([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /bin/chown 0:0 %@", oextended] UTF8String]);
4098 unlink([nextended UTF8String]);
4099 symlink([oextended UTF8String], [nextended UTF8String]);
4101 if ([self popErrorWithTitle:title])
4104 if (result == pkgPackageManager::Failed) {
4109 if (result != pkgPackageManager::Completed) {
4114 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
4116 if ([self popErrorWithTitle:title forReadList:list])
4118 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
4119 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
4122 if (![before isEqualToArray:after])
4127 return ![delock_ isEqual:GetStatusDate()];
4131 NSString *title(UCLocalize("UPGRADE"));
4132 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
4138 [self updateWithStatus:status_];
4141 - (void) updateWithStatus:(CancelStatus &)status {
4142 NSString *title(UCLocalize("REFRESHING_DATA"));
4145 if ([self popErrorWithTitle:title forReadList:list])
4149 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
4150 if ([self popErrorWithTitle:title])
4153 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4155 bool success(ListUpdate(status, list, PulseInterval_));
4156 if (status.WasCancelled())
4159 [self popErrorWithTitle:title forOperation:success];
4161 [[NSDictionary dictionaryWithObjectsAndKeys:
4162 [NSDate date], @"LastUpdate",
4163 nil] writeToFile:@ CacheState_ atomically:YES];
4166 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4169 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
4170 delegate_ = delegate;
4173 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
4174 progress_ = delegate;
4175 status_.setDelegate(delegate);
4178 - (NSObject<ProgressDelegate> *) progressDelegate {
4182 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
4183 SourceMap::const_iterator i(sourceMap_.find(file->ID));
4184 return i == sourceMap_.end() ? nil : i->second;
4187 - (void) setFetch:(bool)fetch forURI:(const char *)uri {
4188 for (Source *source in (id) sourceList_)
4189 [source setFetch:fetch forURI:uri];
4192 - (void) resetFetch {
4193 for (Source *source in (id) sourceList_)
4194 [source resetFetch];
4197 - (NSString *) mappedSectionForPointer:(const char *)section {
4198 _H<NSString> *mapped;
4200 _profile(Database$mappedSectionForPointer$Cache)
4201 mapped = §ions_[section];
4204 if (*mapped == NULL) {
4205 size_t length(strlen(section));
4206 char spaced[length + 1];
4208 _profile(Database$mappedSectionForPointer$Replace)
4209 for (size_t index(0); index != length; ++index)
4210 spaced[index] = section[index] == '_' ? ' ' : section[index];
4211 spaced[length] = '\0';
4216 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
4217 string = [NSString stringWithUTF8String:spaced];
4220 _profile(Database$mappedSectionForPointer$Map)
4221 string = [SectionMap_ objectForKey:string] ?: string;
4231 static _H<NSMutableSet> Diversions_;
4233 @interface Diversion : NSObject {
4236 _H<NSString> format_;
4241 @implementation Diversion
4243 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
4244 if ((self = [super init]) != nil) {
4245 pattern_ = [from UTF8String];
4251 - (NSString *) divert:(NSString *)url {
4252 return !pattern_(url) ? nil : pattern_->*format_;
4255 + (NSURL *) divertURL:(NSURL *)url {
4257 NSString *href([url absoluteString]);
4259 for (Diversion *diversion in (id) Diversions_)
4260 if (NSString *diverted = [diversion divert:href]) {
4262 NSLog(@"div: %@", diverted);
4264 url = [NSURL URLWithString:diverted];
4271 - (NSString *) key {
4275 - (NSUInteger) hash {
4279 - (BOOL) isEqual:(Diversion *)object {
4280 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
4285 @interface CydiaObject : NSObject {
4286 _H<CyteWebViewController> indirect_;
4287 _transient id delegate_;
4290 - (id) initWithDelegate:(IndirectDelegate *)indirect;
4296 @interface CydiaWebViewController : CyteWebViewController {
4297 _H<CydiaObject> cydia_;
4300 + (void) addDiversion:(Diversion *)diversion;
4301 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request;
4302 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia;
4303 - (void) setDelegate:(id)delegate;
4307 /* Web Scripting {{{ */
4308 @implementation CydiaObject
4310 - (id) initWithDelegate:(IndirectDelegate *)indirect {
4311 if ((self = [super init]) != nil) {
4312 indirect_ = (CyteWebViewController *) indirect;
4316 - (void) setDelegate:(id)delegate {
4317 delegate_ = delegate;
4320 + (NSArray *) _attributeKeys {
4321 return [NSArray arrayWithObjects:
4324 @"coreFoundationVersionNumber",
4340 - (NSArray *) attributeKeys {
4341 return [[self class] _attributeKeys];
4344 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4345 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4348 - (NSString *) version {
4352 - (NSString *) build {
4356 - (NSString *) coreFoundationVersionNumber {
4357 return [NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber];
4360 - (NSString *) device {
4361 return UniqueIdentifier();
4364 - (NSString *) firmware {
4365 return [[UIDevice currentDevice] systemVersion];
4368 - (NSString *) hostname {
4369 return [[UIDevice currentDevice] name];
4372 - (NSString *) idiom {
4373 return (id) Idiom_ ?: [NSNull null];
4376 - (NSString *) mcc {
4377 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode")))
4378 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault) autorelease];
4382 - (NSString *) mnc {
4383 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberNetworkCode")))
4384 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault) autorelease];
4388 - (NSString *) operator {
4389 if (CFStringRef (*$CTRegistrationCopyOperatorName)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTRegistrationCopyOperatorName")))
4390 return [(NSString *) (*$CTRegistrationCopyOperatorName)(kCFAllocatorDefault) autorelease];
4394 - (NSString *) bbsnum {
4395 return (id) BBSNum_ ?: [NSNull null];
4398 - (NSString *) ecid {
4399 return (id) ChipID_ ?: [NSNull null];
4402 - (NSString *) serial {
4403 return SerialNumber_;
4406 - (NSString *) role {
4407 return (id) [NSNull null];
4410 - (NSString *) model {
4411 return [NSString stringWithUTF8String:Machine_];
4414 + (NSString *) webScriptNameForSelector:(SEL)selector {
4416 else if (selector == @selector(addBridgedHost:))
4417 return @"addBridgedHost";
4418 else if (selector == @selector(addInsecureHost:))
4419 return @"addInsecureHost";
4420 else if (selector == @selector(addInternalRedirect::))
4421 return @"addInternalRedirect";
4422 else if (selector == @selector(addPipelinedHost:scheme:))
4423 return @"addPipelinedHost";
4424 else if (selector == @selector(addSource:::))
4425 return @"addSource";
4426 else if (selector == @selector(addTrivialSource:))
4427 return @"addTrivialSource";
4428 else if (selector == @selector(close))
4430 else if (selector == @selector(du:))
4432 else if (selector == @selector(stringWithFormat:arguments:))
4434 else if (selector == @selector(getAllSources))
4435 return @"getAllSources";
4436 else if (selector == @selector(getApplicationInfo:value:))
4437 return @"getApplicationInfoValue";
4438 else if (selector == @selector(getKernelNumber:))
4439 return @"getKernelNumber";
4440 else if (selector == @selector(getKernelString:))
4441 return @"getKernelString";
4442 else if (selector == @selector(getInstalledPackages))
4443 return @"getInstalledPackages";
4444 else if (selector == @selector(getIORegistryEntry::))
4445 return @"getIORegistryEntry";
4446 else if (selector == @selector(getLocaleIdentifier))
4447 return @"getLocaleIdentifier";
4448 else if (selector == @selector(getPreferredLanguages))
4449 return @"getPreferredLanguages";
4450 else if (selector == @selector(getPackageById:))
4451 return @"getPackageById";
4452 else if (selector == @selector(getMetadataKeys))
4453 return @"getMetadataKeys";
4454 else if (selector == @selector(getMetadataValue:))
4455 return @"getMetadataValue";
4456 else if (selector == @selector(getSessionValue:))
4457 return @"getSessionValue";
4458 else if (selector == @selector(installPackages:))
4459 return @"installPackages";
4460 else if (selector == @selector(isReachable:))
4461 return @"isReachable";
4462 else if (selector == @selector(localizedStringForKey:value:table:))
4464 else if (selector == @selector(popViewController:))
4465 return @"popViewController";
4466 else if (selector == @selector(refreshSources))
4467 return @"refreshSources";
4468 else if (selector == @selector(registerFrame:))
4469 return @"registerFrame";
4470 else if (selector == @selector(removeButton))
4471 return @"removeButton";
4472 else if (selector == @selector(saveConfig))
4473 return @"saveConfig";
4474 else if (selector == @selector(setMetadataValue::))
4475 return @"setMetadataValue";
4476 else if (selector == @selector(setSessionValue::))
4477 return @"setSessionValue";
4478 else if (selector == @selector(substitutePackageNames:))
4479 return @"substitutePackageNames";
4480 else if (selector == @selector(scrollToBottom:))
4481 return @"scrollToBottom";
4482 else if (selector == @selector(setAllowsNavigationAction:))
4483 return @"setAllowsNavigationAction";
4484 else if (selector == @selector(setBadgeValue:))
4485 return @"setBadgeValue";
4486 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4487 return @"setButtonImage";
4488 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4489 return @"setButtonTitle";
4490 else if (selector == @selector(setHidesBackButton:))
4491 return @"setHidesBackButton";
4492 else if (selector == @selector(setHidesNavigationBar:))
4493 return @"setHidesNavigationBar";
4494 else if (selector == @selector(setNavigationBarStyle:))
4495 return @"setNavigationBarStyle";
4496 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4497 return @"setNavigationBarTintColor";
4498 else if (selector == @selector(setPasteboardString:))
4499 return @"setPasteboardString";
4500 else if (selector == @selector(setPasteboardURL:))
4501 return @"setPasteboardURL";
4502 else if (selector == @selector(setScrollAlwaysBounceVertical:))
4503 return @"setScrollAlwaysBounceVertical";
4504 else if (selector == @selector(setScrollIndicatorStyle:))
4505 return @"setScrollIndicatorStyle";
4506 else if (selector == @selector(setToken:))
4508 else if (selector == @selector(setViewportWidth:))
4509 return @"setViewportWidth";
4510 else if (selector == @selector(statfs:))
4512 else if (selector == @selector(supports:))
4514 else if (selector == @selector(unload))
4520 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4521 return [self webScriptNameForSelector:selector] == nil;
4524 - (BOOL) supports:(NSString *)feature {
4525 return [feature isEqualToString:@"window.open"];
4529 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4532 - (void) setScrollAlwaysBounceVertical:(NSNumber *)value {
4533 [indirect_ performSelectorOnMainThread:@selector(setScrollAlwaysBounceVerticalNumber:) withObject:value waitUntilDone:NO];
4536 - (void) setScrollIndicatorStyle:(NSString *)style {
4537 [indirect_ performSelectorOnMainThread:@selector(setScrollIndicatorStyleWithName:) withObject:style waitUntilDone:NO];
4540 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4541 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4544 - (NSDictionary *) getApplicationInfo:(NSString *)display value:(NSString *)key {
4546 if (SBBundlePathForDisplayIdentifier(SBSSpringBoardServerPort(), [display UTF8String], path) != 0)
4547 return (id) [NSNull null];
4548 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:[[NSString stringWithUTF8String:path] stringByAppendingString:@"/Info.plist"]]);
4550 return (id) [NSNull null];
4551 return [info objectForKey:key];
4554 - (NSNumber *) getKernelNumber:(NSString *)name {
4555 const char *string([name UTF8String]);
4558 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4559 return (id) [NSNull null];
4561 if (size != sizeof(int))
4562 return (id) [NSNull null];
4565 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4566 return (id) [NSNull null];
4568 return [NSNumber numberWithInt:value];
4571 - (NSString *) getKernelString:(NSString *)name {
4572 const char *string([name UTF8String]);
4575 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4576 return (id) [NSNull null];
4578 char value[size + 1];
4579 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4580 return (id) [NSNull null];
4582 // XXX: just in case you request something ludicrous
4585 return [NSString stringWithCString:value];
4588 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4589 NSObject *value(CYIOGetValue([path UTF8String], entry));
4592 if ([value isKindOfClass:[NSData class]])
4593 value = CYHex((NSData *) value);
4598 - (NSArray *) getMetadataKeys {
4599 @synchronized (Values_) {
4600 return [Values_ allKeys];
4603 - (void) registerFrame:(DOMHTMLIFrameElement *)iframe {
4604 WebFrame *frame([iframe contentFrame]);
4605 [indirect_ registerFrame:frame];
4608 - (id) getMetadataValue:(NSString *)key {
4609 @synchronized (Values_) {
4610 return [Values_ objectForKey:key];
4613 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4614 @synchronized (Values_) {
4615 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4616 [Values_ removeObjectForKey:key];
4618 [Values_ setObject:value forKey:key];
4621 - (id) getSessionValue:(NSString *)key {
4622 @synchronized (SessionData_) {
4623 return [SessionData_ objectForKey:key];
4626 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4627 @synchronized (SessionData_) {
4628 if (value == (id) [WebUndefined undefined])
4629 [SessionData_ removeObjectForKey:key];
4631 [SessionData_ setObject:value forKey:key];
4634 - (void) addBridgedHost:(NSString *)host {
4635 @synchronized (HostConfig_) {
4636 [BridgedHosts_ addObject:host];
4639 - (void) addInsecureHost:(NSString *)host {
4640 @synchronized (HostConfig_) {
4641 [InsecureHosts_ addObject:host];
4644 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4645 @synchronized (HostConfig_) {
4646 if (scheme != (id) [WebUndefined undefined])
4647 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4649 [PipelinedHosts_ addObject:host];
4652 - (void) popViewController:(NSNumber *)value {
4653 if (value == (id) [WebUndefined undefined])
4654 value = [NSNumber numberWithBool:YES];
4655 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4658 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4659 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4661 for (NSString *section in sections)
4662 [array addObject:section];
4664 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4667 distribution, @"Distribution",
4669 nil] waitUntilDone:NO];
4672 - (void) addTrivialSource:(NSString *)href {
4673 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4676 - (void) refreshSources {
4677 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4680 - (void) saveConfig {
4681 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4684 - (NSArray *) getAllSources {
4685 return [[Database sharedInstance] sources];
4688 - (NSArray *) getInstalledPackages {
4689 Database *database([Database sharedInstance]);
4690 @synchronized (database) {
4691 NSArray *packages([database packages]);
4692 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4693 for (Package *package in packages)
4694 if (![package uninstalled])
4695 [installed addObject:package];
4699 - (Package *) getPackageById:(NSString *)id {
4700 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4704 return (Package *) [NSNull null];
4707 - (NSString *) getLocaleIdentifier {
4708 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4711 - (NSArray *) getPreferredLanguages {
4715 - (NSArray *) statfs:(NSString *)path {
4718 if (path == nil || statfs([path UTF8String], &stat) == -1)
4721 return [NSArray arrayWithObjects:
4722 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4723 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4724 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4728 ssize_t DiskUsage(const char *path);
4730 - (NSNumber *) du:(NSString *)path {
4731 ssize_t usage(DiskUsage([path UTF8String]));
4734 return [NSNumber numberWithUnsignedLong:usage];
4738 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4741 - (NSNumber *) isReachable:(NSString *)name {
4742 return [NSNumber numberWithBool:IsReachable([name UTF8String])];
4745 - (void) installPackages:(NSArray *)packages {
4746 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4749 - (NSString *) substitutePackageNames:(NSString *)message {
4750 NSMutableArray *words([[[message componentsSeparatedByString:@" "] mutableCopy] autorelease]);
4751 for (size_t i(0), e([words count]); i != e; ++i) {
4752 NSString *word([words objectAtIndex:i]);
4753 if (Package *package = [[Database sharedInstance] packageWithName:word])
4754 [words replaceObjectAtIndex:i withObject:[package name]];
4757 return [words componentsJoinedByString:@" "];
4760 - (void) removeButton {
4761 [indirect_ removeButton];
4764 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4765 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4768 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4769 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4772 - (void) setBadgeValue:(id)value {
4773 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4776 - (void) setAllowsNavigationAction:(NSString *)value {
4777 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4780 - (void) setHidesBackButton:(NSString *)value {
4781 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4784 - (void) setHidesNavigationBar:(NSString *)value {
4785 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4788 - (void) setNavigationBarStyle:(NSString *)value {
4789 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4792 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4793 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4794 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4795 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4798 - (void) setPasteboardString:(NSString *)value {
4799 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4802 - (void) setPasteboardURL:(NSString *)value {
4803 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4806 - (void) setToken:(NSString *)token {
4807 // XXX: the website expects this :/
4810 - (void) scrollToBottom:(NSNumber *)animated {
4811 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4814 - (void) setViewportWidth:(float)width {
4815 [indirect_ setViewportWidthOnMainThread:width];
4818 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4819 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4820 unsigned count([arguments count]);
4822 for (unsigned i(0); i != count; ++i)
4823 values[i] = [arguments objectAtIndex:i];
4824 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4827 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4828 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4830 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4832 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4838 @interface NSURL (CydiaSecure)
4841 @implementation NSURL (CydiaSecure)
4843 - (bool) isCydiaSecure {
4844 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4847 @synchronized (HostConfig_) {
4848 if ([InsecureHosts_ containsObject:[self host]])
4857 /* Cydia Browser Controller {{{ */
4858 @implementation CydiaWebViewController
4860 - (NSURL *) navigationURL {
4861 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4864 + (void) _initialize {
4865 [super _initialize];
4867 Diversions_ = [NSMutableSet setWithCapacity:0];
4870 + (void) addDiversion:(Diversion *)diversion {
4871 [Diversions_ addObject:diversion];
4874 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4875 [super webView:view didClearWindowObject:window forFrame:frame];
4876 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
4879 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia {
4880 WebDataSource *source([frame dataSource]);
4881 NSURLResponse *response([source response]);
4882 NSURL *url([response URL]);
4883 NSString *scheme([[url scheme] lowercaseString]);
4885 bool bridged(false);
4887 @synchronized (HostConfig_) {
4888 if ([scheme isEqualToString:@"file"])
4890 else if ([scheme isEqualToString:@"https"])
4891 if ([BridgedHosts_ containsObject:[url host]])
4896 [window setValue:cydia forKey:@"cydia"];
4899 - (void) _setupMail:(MFMailComposeViewController *)controller {
4900 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4902 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4903 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4906 - (NSURL *) URLWithURL:(NSURL *)url {
4907 return [Diversion divertURL:url];
4910 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4911 return [CydiaWebViewController requestWithHeaders:[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
4914 - (NSURLRequest *) webThreadWebView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4915 return [CydiaWebViewController requestWithHeaders:[super webThreadWebView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
4918 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request {
4919 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
4921 NSURL *url([copy URL]);
4922 NSString *href([url absoluteString]);
4923 NSString *host([url host]);
4925 if ([href hasPrefix:@"https://cydia.saurik.com/TSS/"]) {
4926 if (NSString *agent = [copy valueForHTTPHeaderField:@"X-User-Agent"]) {
4927 [copy setValue:agent forHTTPHeaderField:@"User-Agent"];
4928 [copy setValue:nil forHTTPHeaderField:@"X-User-Agent"];
4931 [copy setValue:nil forHTTPHeaderField:@"Referer"];
4932 [copy setValue:nil forHTTPHeaderField:@"Origin"];
4934 [copy setURL:[NSURL URLWithString:[@"http://gs.apple.com/TSS/" stringByAppendingString:[href substringFromIndex:29]]]];
4938 if ([copy valueForHTTPHeaderField:@"X-Cydia-Cf"] == nil)
4939 [copy setValue:[NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber] forHTTPHeaderField:@"X-Cydia-Cf"];
4940 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4941 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4943 bool bridged; @synchronized (HostConfig_) {
4944 bridged = [BridgedHosts_ containsObject:host];
4947 if ([url isCydiaSecure] && bridged && UniqueID_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Id"] == nil)
4948 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
4953 - (void) setDelegate:(id)delegate {
4954 [super setDelegate:delegate];
4955 [cydia_ setDelegate:delegate];
4958 - (NSString *) applicationNameForUserAgent {
4963 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4964 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
4970 @interface AppCacheController : CydiaWebViewController {
4975 @implementation AppCacheController
4977 - (void) didReceiveMemoryWarning {
4978 // XXX: this doesn't work
4981 - (bool) retainsNetworkActivityIndicator {
4989 @interface NSObject (CydiaScript)
4990 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4993 @implementation NSObject (CydiaScript)
4995 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5001 @implementation NSArray (CydiaScript)
5003 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5004 WebScriptObject *object([context evaluateWebScript:@"[]"]);
5005 for (size_t i(0), e([self count]); i != e; ++i)
5006 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
5012 @implementation NSDictionary (CydiaScript)
5014 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5015 WebScriptObject *object([context evaluateWebScript:@"({})"]);
5017 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
5024 /* Confirmation Controller {{{ */
5025 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
5026 if (!iterator.end())
5027 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
5028 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
5030 pkgCache::PkgIterator package(dep.TargetPkg());
5033 if (strcmp(package.Name(), "mobilesubstrate") == 0)
5040 @protocol ConfirmationControllerDelegate
5041 - (void) cancelAndClear:(bool)clear;
5042 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
5046 @interface ConfirmationController : CydiaWebViewController {
5047 _transient Database *database_;
5049 _H<UIAlertView> essential_;
5051 _H<NSDictionary> changes_;
5052 _H<NSMutableArray> issues_;
5053 _H<NSDictionary> sizes_;
5058 - (id) initWithDatabase:(Database *)database;
5062 @implementation ConfirmationController
5066 RestartSubstrate_ = true;
5067 [delegate_ confirmWithNavigationController:[self navigationController]];
5070 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
5071 NSString *context([alert context]);
5073 if ([context isEqualToString:@"remove"]) {
5074 if (button == [alert cancelButtonIndex])
5076 else if (button == [alert firstOtherButtonIndex]) {
5077 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
5080 [alert dismissWithClickedButtonIndex:-1 animated:YES];
5081 } else if ([context isEqualToString:@"unable"]) {
5082 [self dismissModalViewControllerAnimated:YES];
5083 [alert dismissWithClickedButtonIndex:-1 animated:YES];
5085 [super alertView:alert clickedButtonAtIndex:button];
5089 - (void) _doContinue {
5090 [delegate_ cancelAndClear:NO];
5091 [self dismissModalViewControllerAnimated:YES];
5094 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
5095 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
5099 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5100 [super webView:view didClearWindowObject:window forFrame:frame];
5102 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
5103 (id) changes_, @"changes",
5104 (id) issues_, @"issues",
5105 (id) sizes_, @"sizes",
5107 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
5110 - (id) initWithDatabase:(Database *)database {
5111 if ((self = [super init]) != nil) {
5112 database_ = database;
5114 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
5115 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
5116 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
5117 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
5118 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
5122 pkgCacheFile &cache([database_ cache]);
5123 NSArray *packages([database_ packages]);
5124 pkgDepCache::Policy *policy([database_ policy]);
5126 issues_ = [NSMutableArray arrayWithCapacity:4];
5128 UpgradeCydia_ = false;
5130 for (Package *package in packages) {
5131 pkgCache::PkgIterator iterator([package iterator]);
5132 NSString *name([package id]);
5134 if ([package broken]) {
5135 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
5137 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5139 reasons, @"reasons",
5142 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
5146 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
5147 pkgCache::DepIterator start;
5148 pkgCache::DepIterator end;
5149 dep.GlobOr(start, end); // ++dep
5151 if (!cache->IsImportantDep(end))
5153 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
5156 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
5158 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5159 [NSString stringWithUTF8String:start.DepType()], @"relationship",
5160 clauses, @"clauses",
5164 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
5166 pkgCache::PkgIterator target(start.TargetPkg());
5167 if (target->ProvidesList != 0)
5168 reason = @"missing";
5170 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
5172 reason = @"installed";
5173 installed = [NSString stringWithUTF8String:ver.VerStr()];
5174 } else if (!cache[target].CandidateVerIter(cache).end())
5175 reason = @"uninstalled";
5176 else if (target->ProvidesList == 0)
5177 reason = @"uninstallable";
5179 reason = @"virtual";
5182 NSDictionary *version(start.TargetVer() == 0 ? (NSDictionary *) [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
5183 [NSString stringWithUTF8String:start.CompType()], @"operator",
5184 [NSString stringWithUTF8String:start.TargetVer()], @"value",
5187 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5188 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
5189 version, @"version",
5191 installed, @"installed",
5194 // yes, seriously. (wtf?)
5202 pkgDepCache::StateCache &state(cache[iterator]);
5204 static RegEx special_r("(firmware|gsc\\..*|cy\\+.*)");
5206 if (state.NewInstall())
5207 [installs addObject:name];
5208 // XXX: else if (state.Install())
5209 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
5210 [reinstalls addObject:name];
5211 // XXX: move before previous if
5212 else if (state.Upgrade())
5213 [upgrades addObject:name];
5214 else if (state.Downgrade())
5215 [downgrades addObject:name];
5216 else if (!state.Delete())
5217 // XXX: _assert(state.Keep());
5219 else if (special_r(name))
5220 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5221 [NSNull null], @"package",
5222 [NSArray arrayWithObjects:
5223 [NSDictionary dictionaryWithObjectsAndKeys:
5224 @"Conflicts", @"relationship",
5225 [NSArray arrayWithObjects:
5226 [NSDictionary dictionaryWithObjectsAndKeys:
5228 [NSNull null], @"version",
5229 @"installed", @"reason",
5236 if ([package essential])
5238 [removes addObject:name];
5241 if ([name isEqualToString:@"cydia"])
5242 UpgradeCydia_ = true;
5244 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
5245 substrate_ |= DepSubstrate(iterator.CurrentVer());
5250 else if (Advanced_) {
5251 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
5253 essential_ = [[[UIAlertView alloc]
5254 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
5255 message:UCLocalize("REMOVING_ESSENTIALS_EX")
5257 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
5259 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
5263 [essential_ setContext:@"remove"];
5264 [essential_ setNumberOfRows:2];
5266 essential_ = [[[UIAlertView alloc]
5267 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
5268 message:UCLocalize("UNABLE_TO_COMPLY_EX")
5270 cancelButtonTitle:UCLocalize("OKAY")
5271 otherButtonTitles:nil
5274 [essential_ setContext:@"unable"];
5277 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5278 installs, @"installs",
5279 reinstalls, @"reinstalls",
5280 upgrades, @"upgrades",
5281 downgrades, @"downgrades",
5282 removes, @"removes",
5285 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5286 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
5287 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
5290 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
5294 - (UIBarButtonItem *) leftButton {
5295 return [[[UIBarButtonItem alloc]
5296 initWithTitle:UCLocalize("CANCEL")
5297 style:UIBarButtonItemStylePlain
5299 action:@selector(cancelButtonClicked)
5304 - (void) applyRightButton {
5305 if ([issues_ count] == 0 && ![self isLoading])
5306 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
5307 initWithTitle:UCLocalize("CONFIRM")
5308 style:UIBarButtonItemStyleDone
5310 action:@selector(confirmButtonClicked)
5313 [[self navigationItem] setRightBarButtonItem:nil];
5317 - (void) cancelButtonClicked {
5318 [delegate_ cancelAndClear:YES];
5319 [self dismissModalViewControllerAnimated:YES];
5323 - (void) confirmButtonClicked {
5324 if (essential_ != nil)
5334 /* Progress Data {{{ */
5335 @interface CydiaProgressData : NSObject {
5336 _transient id delegate_;
5345 _H<NSMutableArray> events_;
5346 _H<NSString> title_;
5348 _H<NSString> status_;
5349 _H<NSString> finish_;
5354 @implementation CydiaProgressData
5356 + (NSArray *) _attributeKeys {
5357 return [NSArray arrayWithObjects:
5369 - (NSArray *) attributeKeys {
5370 return [[self class] _attributeKeys];
5373 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5374 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5378 if ((self = [super init]) != nil) {
5379 events_ = [NSMutableArray arrayWithCapacity:32];
5387 - (void) setDelegate:(id)delegate {
5388 delegate_ = delegate;
5391 - (void) setPercent:(float)value {
5395 - (NSNumber *) percent {
5396 return [NSNumber numberWithFloat:percent_];
5399 - (void) setCurrent:(float)value {
5403 - (NSNumber *) current {
5404 return [NSNumber numberWithFloat:current_];
5407 - (void) setTotal:(float)value {
5411 - (NSNumber *) total {
5412 return [NSNumber numberWithFloat:total_];
5415 - (void) setSpeed:(float)value {
5419 - (NSNumber *) speed {
5420 return [NSNumber numberWithFloat:speed_];
5423 - (NSArray *) events {
5427 - (void) removeAllEvents {
5428 [events_ removeAllObjects];
5431 - (void) addEvent:(CydiaProgressEvent *)event {
5432 [events_ addObject:event];
5435 - (void) setTitle:(NSString *)text {
5439 - (NSString *) title {
5443 - (void) setFinish:(NSString *)text {
5447 - (NSString *) finish {
5448 return (id) finish_ ?: [NSNull null];
5451 - (void) setRunning:(bool)running {
5455 - (NSNumber *) running {
5456 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5461 /* Progress Controller {{{ */
5462 @interface ProgressController : CydiaWebViewController <
5465 _transient Database *database_;
5466 _H<CydiaProgressData, 1> progress_;
5470 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5472 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5474 - (void) setTitle:(NSString *)title;
5475 - (void) setCancellable:(bool)cancellable;
5479 @implementation ProgressController
5482 [database_ setProgressDelegate:nil];
5486 - (UIBarButtonItem *) leftButton {
5487 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5488 initWithTitle:UCLocalize("CANCEL")
5489 style:UIBarButtonItemStylePlain
5491 action:@selector(cancel)
5492 ] autorelease] : nil;
5495 - (void) updateCancel {
5496 [super applyLeftButton];
5499 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5500 if ((self = [super init]) != nil) {
5501 database_ = database;
5502 delegate_ = delegate;
5504 [database_ setProgressDelegate:self];
5506 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5507 [progress_ setDelegate:self];
5509 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5511 [scroller_ setBackgroundColor:[UIColor blackColor]];
5513 [[self navigationItem] setHidesBackButton:YES];
5515 [self updateCancel];
5519 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5520 [super webView:view didClearWindowObject:window forFrame:frame];
5521 [window setValue:progress_ forKey:@"cydiaProgress"];
5524 - (void) updateProgress {
5525 [self dispatchEvent:@"CydiaProgressUpdate"];
5528 - (void) viewWillAppear:(BOOL)animated {
5529 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5530 [super viewWillAppear:animated];
5533 - (void) reloadSpringBoard {
5534 if (kCFCoreFoundationVersionNumber >= 700) // XXX: iOS 6.x
5535 system("/bin/launchctl stop com.apple.backboardd");
5537 system("/bin/launchctl stop com.apple.SpringBoard");
5539 system("/usr/bin/killall backboardd SpringBoard");
5543 UpdateExternalStatus(0);
5546 [delegate_ saveState];
5550 [delegate_ returnToCydia];
5554 [delegate_ terminateWithSuccess];
5555 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5556 [delegate_ suspendWithAnimation:YES];
5558 [delegate_ suspend];*/
5570 UIProgressHUD *hud([delegate_ addProgressHUD]);
5571 [hud setText:UCLocalize("LOADING")];
5572 [self performSelector:@selector(reloadSpringBoard) withObject:nil afterDelay:0.5];
5578 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5579 SBReboot(SBSSpringBoardServerPort());
5581 reboot2(RB_AUTOBOOT);
5588 - (void) setTitle:(NSString *)title {
5589 [progress_ setTitle:title];
5590 [self updateProgress];
5593 - (UIBarButtonItem *) rightButton {
5594 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5595 initWithTitle:UCLocalize("CLOSE")
5596 style:UIBarButtonItemStylePlain
5598 action:@selector(close)
5602 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5603 UpdateExternalStatus(1);
5605 [progress_ setRunning:true];
5606 [self setTitle:title];
5607 // implicit updateProgress
5609 SHA1SumValue notifyconf; {
5611 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5614 MMap mmap(file, MMap::ReadOnly);
5616 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5617 notifyconf = sha1.Result();
5621 SHA1SumValue springlist; {
5623 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5626 MMap mmap(file, MMap::ReadOnly);
5628 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5629 springlist = sha1.Result();
5633 if (invocation != nil) {
5634 [invocation yieldToSelector:@selector(invoke)];
5635 [self setTitle:@"COMPLETE"];
5640 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5643 MMap mmap(file, MMap::ReadOnly);
5645 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5646 if (!(notifyconf == sha1.Result()))
5653 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5656 MMap mmap(file, MMap::ReadOnly);
5658 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5659 if (!(springlist == sha1.Result()))
5665 if (RestartSubstrate_)
5669 RestartSubstrate_ = false;
5672 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5673 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5674 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5675 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5676 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5679 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5681 [progress_ setRunning:false];
5682 [self updateProgress];
5684 [self applyRightButton];
5687 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5688 [progress_ addEvent:event];
5689 [self updateProgress];
5692 - (bool) isProgressCancelled {
5693 return cancel_ == 2;
5698 [self updateCancel];
5701 - (void) setCancellable:(bool)cancellable {
5702 unsigned cancel(cancel_);
5706 else if (cancel_ == 0)
5709 if (cancel != cancel_)
5710 [self updateCancel];
5713 - (void) setProgressCancellable:(NSNumber *)cancellable {
5714 [self setCancellable:[cancellable boolValue]];
5717 - (void) setProgressPercent:(NSNumber *)percent {
5718 [progress_ setPercent:[percent floatValue]];
5719 [self updateProgress];
5722 - (void) setProgressStatus:(NSDictionary *)status {
5723 if (status == nil) {
5724 [progress_ setCurrent:0];
5725 [progress_ setTotal:0];
5726 [progress_ setSpeed:0];
5728 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5730 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5731 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5732 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5735 [self updateProgress];
5741 /* Package Cell {{{ */
5742 @interface PackageCell : CyteTableViewCell <
5743 CyteTableViewCellDelegate
5747 _H<NSString> description_;
5749 _H<NSString> source_;
5751 _H<UIImage> placard_;
5755 - (PackageCell *) init;
5756 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5758 - (void) drawContentRect:(CGRect)rect;
5762 @implementation PackageCell
5764 - (PackageCell *) init {
5765 CGRect frame(CGRectMake(0, 0, 320, 74));
5766 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5767 UIView *content([self contentView]);
5768 CGRect bounds([content bounds]);
5770 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5771 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5772 [content addSubview:content_];
5774 [content_ setDelegate:self];
5775 [content_ setOpaque:YES];
5779 - (NSString *) accessibilityLabel {
5783 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5784 summarized_ = summary;
5794 [content_ setBackgroundColor:[UIColor whiteColor]];
5798 Source *source = [package source];
5800 icon_ = [package icon];
5802 if (NSString *name = [package name])
5803 name_ = [NSString stringWithString:name];
5805 if (NSString *description = [package shortDescription])
5806 description_ = [NSString stringWithString:description];
5808 commercial_ = [package isCommercial];
5810 NSString *label = nil;
5811 bool trusted = false;
5813 if (source != nil) {
5814 label = [source label];
5815 trusted = [source trusted];
5816 } else if ([[package id] isEqualToString:@"firmware"])
5817 label = UCLocalize("APPLE");
5819 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5821 NSString *from(label);
5823 NSString *section = [package simpleSection];
5824 if (section != nil && ![section isEqualToString:label]) {
5825 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5826 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5829 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5831 if (NSString *purpose = [package primaryPurpose])
5832 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5837 if (NSString *mode = [package mode]) {
5838 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5839 color = RemovingColor_;
5840 placard = @"removing";
5842 color = InstallingColor_;
5843 placard = @"installing";
5846 color = [UIColor whiteColor];
5848 if ([package installed] != nil)
5849 placard = @"installed";
5854 [content_ setBackgroundColor:color];
5857 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5860 [self setNeedsDisplay];
5861 [content_ setNeedsDisplay];
5864 - (void) drawSummaryContentRect:(CGRect)rect {
5865 bool highlighted(highlighted_);
5866 float width([self bounds].size.width);
5870 rect.size = [(UIImage *) icon_ size];
5872 while (rect.size.width > 16 || rect.size.height > 16) {
5873 rect.size.width /= 2;
5874 rect.size.height /= 2;
5877 rect.origin.x = 19 - rect.size.width / 2;
5878 rect.origin.y = 19 - rect.size.height / 2;
5880 [icon_ drawInRect:Retina(rect)];
5883 if (badge_ != nil) {
5885 rect.size = [(UIImage *) badge_ size];
5887 rect.size.width /= 4;
5888 rect.size.height /= 4;
5890 rect.origin.x = 25 - rect.size.width / 2;
5891 rect.origin.y = 25 - rect.size.height / 2;
5893 [badge_ drawInRect:Retina(rect)];
5896 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5900 UISetColor(commercial_ ? Purple_ : Black_);
5901 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
5903 if (placard_ != nil)
5904 [placard_ drawAtPoint:CGPointMake(width - 52, 11)];
5907 - (void) drawNormalContentRect:(CGRect)rect {
5908 bool highlighted(highlighted_);
5909 float width([self bounds].size.width);
5913 rect.size = [(UIImage *) icon_ size];
5915 while (rect.size.width > 32 || rect.size.height > 32) {
5916 rect.size.width /= 2;
5917 rect.size.height /= 2;
5920 rect.origin.x = 25 - rect.size.width / 2;
5921 rect.origin.y = 25 - rect.size.height / 2;
5923 [icon_ drawInRect:Retina(rect)];
5926 if (badge_ != nil) {
5928 rect.size = [(UIImage *) badge_ size];
5930 rect.size.width /= 2;
5931 rect.size.height /= 2;
5933 rect.origin.x = 36 - rect.size.width / 2;
5934 rect.origin.y = 36 - rect.size.height / 2;
5936 [badge_ drawInRect:Retina(rect)];
5939 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5943 UISetColor(commercial_ ? Purple_ : Black_);
5944 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
5945 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
5948 UISetColor(commercial_ ? Purplish_ : Gray_);
5949 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:NSLineBreakByTruncatingTail];
5951 if (placard_ != nil)
5952 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5955 - (void) drawContentRect:(CGRect)rect {
5957 [self drawSummaryContentRect:rect];
5959 [self drawNormalContentRect:rect];
5964 /* Section Cell {{{ */
5965 @interface SectionCell : CyteTableViewCell <
5966 CyteTableViewCellDelegate
5968 _H<NSString> basic_;
5969 _H<NSString> section_;
5971 _H<NSString> count_;
5973 _H<UISwitch> switch_;
5977 - (void) setSection:(Section *)section editing:(BOOL)editing;
5981 @implementation SectionCell
5983 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5984 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5985 icon_ = [UIImage imageNamed:@"folder.png"];
5986 // XXX: this initial frame is wrong, but is fixed later
5987 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5988 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5990 UIView *content([self contentView]);
5991 CGRect bounds([content bounds]);
5993 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5994 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5995 [content addSubview:content_];
5996 [content_ setBackgroundColor:[UIColor whiteColor]];
5998 [content_ setDelegate:self];
6002 - (void) onSwitch:(id)sender {
6003 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
6004 if (metadata == nil) {
6005 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
6006 [Sections_ setObject:metadata forKey:basic_];
6009 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
6012 - (void) setSection:(Section *)section editing:(BOOL)editing {
6013 if (editing != editing_) {
6015 [switch_ removeFromSuperview];
6017 [self addSubview:switch_];
6026 if (section == nil) {
6027 name_ = UCLocalize("ALL_PACKAGES");
6030 basic_ = [section name];
6031 section_ = [section localized];
6033 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
6034 count_ = [NSString stringWithFormat:@"%zd", [section count]];
6037 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
6040 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
6041 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
6043 [content_ setNeedsDisplay];
6046 - (void) setFrame:(CGRect)frame {
6047 [super setFrame:frame];
6049 CGRect rect([switch_ frame]);
6050 [switch_ setFrame:CGRectMake(frame.size.width - rect.size.width - 9, 9, rect.size.width, rect.size.height)];
6053 - (NSString *) accessibilityLabel {
6057 - (void) drawContentRect:(CGRect)rect {
6058 bool highlighted(highlighted_ && !editing_);
6060 [icon_ drawInRect:CGRectMake(7, 7, 32, 32)];
6062 if (highlighted && kCFCoreFoundationVersionNumber < 800)
6065 float width(rect.size.width);
6067 width -= 9 + [switch_ frame].size.width;
6071 [name_ drawAtPoint:CGPointMake(48, 12) forWidth:(width - 58) withFont:Font18_ lineBreakMode:NSLineBreakByTruncatingTail];
6073 CGSize size = [count_ sizeWithFont:Font14_];
6075 UISetColor(Folder_);
6077 [count_ drawAtPoint:CGPointMake(Retina(10 + (30 - size.width) / 2), 18) withFont:Font12Bold_];
6083 /* File Table {{{ */
6084 @interface FileTable : CyteViewController <
6085 UITableViewDataSource,
6088 _transient Database *database_;
6089 _H<Package> package_;
6091 _H<NSMutableArray> files_;
6092 _H<UITableView, 2> list_;
6095 - (id) initWithDatabase:(Database *)database;
6096 - (void) setPackage:(Package *)package;
6100 @implementation FileTable
6102 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6103 return files_ == nil ? 0 : [files_ count];
6106 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6110 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6111 static NSString *reuseIdentifier = @"Cell";
6113 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6115 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6116 [cell setFont:[UIFont systemFontOfSize:16]];
6118 [cell setText:[files_ objectAtIndex:indexPath.row]];
6119 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
6124 - (NSURL *) navigationURL {
6125 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
6129 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
6130 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6131 [list_ setRowHeight:24.0f];
6132 [(UITableView *) list_ setDataSource:self];
6133 [list_ setDelegate:self];
6134 [self setView:list_];
6137 - (void) viewDidLoad {
6138 [super viewDidLoad];
6140 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
6143 - (void) releaseSubviews {
6149 [super releaseSubviews];
6152 - (id) initWithDatabase:(Database *)database {
6153 if ((self = [super init]) != nil) {
6154 database_ = database;
6158 - (void) setPackage:(Package *)package {
6162 files_ = [NSMutableArray arrayWithCapacity:32];
6164 if (package != nil) {
6166 name_ = [package id];
6168 if (NSArray *files = [package files])
6169 [files_ addObjectsFromArray:files];
6171 if ([files_ count] != 0) {
6172 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
6173 [files_ removeObjectAtIndex:0];
6174 [files_ sortUsingSelector:@selector(compareByPath:)];
6176 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
6177 [stack addObject:@"/"];
6179 for (int i(0), e([files_ count]); i != e; ++i) {
6180 NSString *file = [files_ objectAtIndex:i];
6181 while (![file hasPrefix:[stack lastObject]])
6182 [stack removeLastObject];
6183 NSString *directory = [stack lastObject];
6184 [stack addObject:[file stringByAppendingString:@"/"]];
6185 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
6186 ([stack count] - 2) * 3, "",
6187 [file substringFromIndex:[directory length]]
6196 - (void) reloadData {
6199 [self setPackage:[database_ packageWithName:name_]];
6204 /* Package Controller {{{ */
6205 @interface CYPackageController : CydiaWebViewController <
6206 UIActionSheetDelegate
6208 _transient Database *database_;
6209 _H<Package> package_;
6212 std::vector<std::pair<_H<NSString>, _H<NSString>>> buttons_;
6213 _H<UIBarButtonItem> button_;
6216 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer;
6220 @implementation CYPackageController
6222 - (NSURL *) navigationURL {
6223 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
6226 - (void) _clickButtonWithName:(NSString *)name {
6227 if ([name isEqualToString:@"CLEAR"])
6228 [delegate_ clearPackage:package_];
6229 else if ([name isEqualToString:@"INSTALL"])
6230 [delegate_ installPackage:package_];
6231 else if ([name isEqualToString:@"REINSTALL"])
6232 [delegate_ installPackage:package_];
6233 else if ([name isEqualToString:@"REMOVE"])
6234 [delegate_ removePackage:package_];
6235 else if ([name isEqualToString:@"UPGRADE"])
6236 [delegate_ installPackage:package_];
6237 else _assert(false);
6240 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
6241 NSString *context([sheet context]);
6243 if ([context isEqualToString:@"modify"]) {
6244 if (button != [sheet cancelButtonIndex]) {
6246 [self performSelector:@selector(_clickButtonWithName:) withObject:buttons_[button].first afterDelay:0];
6248 [self _clickButtonWithName:buttons_[button].first];
6251 [sheet dismissWithClickedButtonIndex:button animated:YES];
6255 - (bool) _allowJavaScriptPanel {
6260 - (void) _customButtonClicked {
6261 size_t count(buttons_.size());
6266 [self _clickButtonWithName:buttons_[0].first];
6268 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
6269 for (const auto &button : buttons_)
6270 [buttons addObject:button.second];
6272 UIActionSheet *sheet = [[[UIActionSheet alloc]
6275 cancelButtonTitle:nil
6276 destructiveButtonTitle:nil
6277 otherButtonTitles:nil
6280 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
6282 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
6283 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
6285 [sheet setContext:@"modify"];
6287 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
6291 - (void) reloadButtonClicked {
6292 if (commercial_ && function_ == nil && [package_ uninstalled])
6294 [self customButtonClicked];
6297 - (void) applyLoadingTitle {
6298 // Don't show "Loading" as the title. Ever.
6301 - (UIBarButtonItem *) rightButton {
6306 - (void) setPageColor:(UIColor *)color {
6307 return [super setPageColor:nil];
6310 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer {
6311 if ((self = [super init]) != nil) {
6312 database_ = database;
6313 name_ = name == nil ? @"" : [NSString stringWithString:name];
6314 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]] withReferrer:referrer];
6318 - (void) reloadData {
6321 package_ = [database_ packageWithName:name_];
6325 if (package_ != nil) {
6326 [(Package *) package_ parse];
6328 commercial_ = [package_ isCommercial];
6330 if ([package_ mode] != nil)
6331 buttons_.push_back(std::make_pair(@"CLEAR", UCLocalize("CLEAR")));
6332 if ([package_ source] == nil);
6333 else if ([package_ upgradableAndEssential:NO])
6334 buttons_.push_back(std::make_pair(@"UPGRADE", UCLocalize("UPGRADE")));
6335 else if ([package_ uninstalled])
6336 buttons_.push_back(std::make_pair(@"INSTALL", UCLocalize("INSTALL")));
6338 buttons_.push_back(std::make_pair(@"REINSTALL", UCLocalize("REINSTALL")));
6339 if (![package_ uninstalled])
6340 buttons_.push_back(std::make_pair(@"REMOVE", UCLocalize("REMOVE")));
6344 switch (buttons_.size()) {
6345 case 0: title = nil; break;
6346 case 1: title = buttons_[0].second; break;
6347 default: title = UCLocalize("MODIFY"); break;
6350 button_ = [[[UIBarButtonItem alloc]
6352 style:UIBarButtonItemStylePlain
6354 action:@selector(customButtonClicked)
6358 - (bool) isLoading {
6359 return commercial_ ? [super isLoading] : false;
6365 /* Package List Controller {{{ */
6366 @interface PackageListController : CyteViewController <
6367 UITableViewDataSource,
6370 _transient Database *database_;
6372 _H<NSArray> packages_;
6373 _H<NSArray> sections_;
6374 _H<UITableView, 2> list_;
6376 _H<NSArray> thumbs_;
6377 std::vector<NSInteger> offset_;
6379 _H<NSString> title_;
6380 unsigned reloading_;
6383 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6384 - (void) setDelegate:(id)delegate;
6385 - (void) resetCursor;
6388 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages;
6392 @implementation PackageListController
6394 - (NSURL *) referrerURL {
6395 return [self navigationURL];
6398 - (bool) isSummarized {
6402 - (bool) showsSections {
6406 - (void) deselectWithAnimation:(BOOL)animated {
6407 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6410 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6411 CGRect base = [[self view] bounds];
6412 base.size.height -= bounds.size.height;
6413 base.origin = [list_ frame].origin;
6415 [UIView beginAnimations:nil context:NULL];
6416 [UIView setAnimationBeginsFromCurrentState:YES];
6417 [UIView setAnimationCurve:curve];
6418 [UIView setAnimationDuration:duration];
6419 [list_ setFrame:base];
6420 [UIView commitAnimations];
6423 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6424 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6427 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6428 [self resizeForKeyboardBounds:bounds duration:0];
6431 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6432 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6433 *curve = UIViewAnimationCurveEaseInOut;
6435 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6437 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6440 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6443 - (void) keyboardWillShow:(NSNotification *)notification {
6446 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6447 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6449 NSTimeInterval duration;
6450 UIViewAnimationCurve curve;
6451 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6453 CGRect kbframe = CGRectMake(Retina(center.x - bounds.size.width / 2), Retina(center.y - bounds.size.height / 2), bounds.size.width, bounds.size.height);
6454 UIViewController *base = self;
6455 while ([base parentOrPresentingViewController] != nil)
6456 base = [base parentOrPresentingViewController];
6457 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6458 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6460 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6461 intersection.size.height += CYStatusBarHeight();
6463 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6466 - (void) keyboardWillHide:(NSNotification *)notification {
6467 NSTimeInterval duration;
6468 UIViewAnimationCurve curve;
6469 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6471 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6474 - (void) viewWillAppear:(BOOL)animated {
6475 [super viewWillAppear:animated];
6477 [self resizeForKeyboardBounds:CGRectZero];
6478 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6479 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6482 - (void) viewWillDisappear:(BOOL)animated {
6483 [super viewWillDisappear:animated];
6485 [self resizeForKeyboardBounds:CGRectZero];
6486 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6487 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6490 - (void) viewDidAppear:(BOOL)animated {
6491 [super viewDidAppear:animated];
6492 [self deselectWithAnimation:animated];
6495 - (void) didSelectPackage:(Package *)package {
6496 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[[self referrerURL] absoluteString]] autorelease]);
6497 [view setDelegate:delegate_];
6498 [[self navigationController] pushViewController:view animated:YES];
6501 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6502 NSInteger count([sections_ count]);
6503 return count == 0 ? 1 : count;
6506 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6507 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6509 return [[sections_ objectAtIndex:section] name];
6512 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6513 if ([sections_ count] == 0)
6515 return [[sections_ objectAtIndex:section] count];
6518 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6519 @synchronized (database_) {
6520 if ([database_ era] != era_)
6523 Section *section([sections_ objectAtIndex:[path section]]);
6524 NSInteger row([path row]);
6525 Package *package([packages_ objectAtIndex:([section row] + row)]);
6526 return [[package retain] autorelease];
6529 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6530 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6532 cell = [[[PackageCell alloc] init] autorelease];
6534 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6535 [cell setPackage:package asSummary:[self isSummarized]];
6539 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6540 Package *package([self packageAtIndexPath:path]);
6541 package = [database_ packageWithName:[package id]];
6542 [self didSelectPackage:package];
6545 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6549 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6550 return offset_[index];
6553 - (void) updateHeight {
6554 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6557 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6558 if ((self = [super init]) != nil) {
6559 database_ = database;
6560 title_ = [title copy];
6561 [[self navigationItem] setTitle:title_];
6566 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
6567 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
6568 [self setView:view];
6570 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6571 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6572 [view addSubview:list_];
6574 // XXX: is 20 the most optimal number here?
6575 [list_ setSectionIndexMinimumDisplayRowCount:20];
6577 [(UITableView *) list_ setDataSource:self];
6578 [list_ setDelegate:self];
6580 [self updateHeight];
6583 - (void) releaseSubviews {
6592 [super releaseSubviews];
6595 - (void) setDelegate:(id)delegate {
6596 delegate_ = delegate;
6599 - (bool) shouldYield {
6603 - (bool) shouldBlock {
6607 - (NSMutableArray *) _reloadPackages {
6608 @synchronized (database_) {
6609 era_ = [database_ era];
6610 NSArray *packages([database_ packages]);
6612 return [NSMutableArray arrayWithArray:packages];
6615 - (void) _reloadData {
6616 if (reloading_ != 0) {
6621 NSMutableArray *packages;
6624 if ([self shouldYield]) {
6628 if (![self shouldBlock])
6631 hud = [delegate_ addProgressHUD];
6632 [hud setText:UCLocalize("LOADING")];
6636 packages = [self yieldToSelector:@selector(_reloadPackages)];
6639 [delegate_ removeProgressHUD:hud];
6640 } while (reloading_ == 2);
6642 packages = [self _reloadPackages];
6645 @synchronized (database_) {
6646 if (era_ != [database_ era])
6653 packages_ = packages;
6655 if ([self showsSections])
6656 sections_ = [self sectionsForPackages:packages];
6658 Section *section([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6659 [section setCount:[packages_ count]];
6660 sections_ = [NSArray arrayWithObject:section];
6663 [self updateHeight];
6665 _profile(PackageTable$reloadData$List)
6666 [(UITableView *) list_ setDataSource:self];
6674 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
6675 Section *prefix([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6676 size_t end([packages count]);
6678 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
6679 Section *section(prefix);
6681 thumbs_ = CollationThumbs_;
6682 offset_ = CollationOffset_;
6685 size_t offsets([CollationStarts_ count]);
6687 NSString *start([CollationStarts_ objectAtIndex:offset]);
6688 size_t length([start length]);
6690 for (size_t index(0); index != end; ++index) {
6692 Package *package([packages objectAtIndex:index]);
6693 NSString *name(PackageName(package, @selector(cyname)));
6695 //while ([start compare:name options:NSNumericSearch range:NSMakeRange(0, length) locale:CollationLocale_] != NSOrderedDescending) {
6696 while (StringNameCompare(start, name, length) != kCFCompareGreaterThan) {
6697 NSString *title([CollationTitles_ objectAtIndex:offset]);
6698 section = [[[Section alloc] initWithName:title row:index localize:NO] autorelease];
6699 [sections addObject:section];
6701 start = ++offset == offsets ? nil : [CollationStarts_ objectAtIndex:offset];
6704 length = [start length];
6708 [section addToCount];
6711 for (; offset != offsets; ++offset) {
6712 NSString *title([CollationTitles_ objectAtIndex:offset]);
6713 Section *section([[[Section alloc] initWithName:title row:end localize:NO] autorelease]);
6714 [sections addObject:section];
6717 if ([prefix count] != 0) {
6718 Section *suffix([sections lastObject]);
6719 [prefix setName:[suffix name]];
6720 [suffix setName:nil];
6721 [sections insertObject:prefix atIndex:(offsets - 1)];
6727 - (void) reloadData {
6730 if ([self shouldYield])
6731 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6736 - (void) resetCursor {
6737 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6740 - (void) clearData {
6741 [self updateHeight];
6743 [list_ setDataSource:nil];
6751 /* Filtered Package List Controller {{{ */
6752 typedef Function<bool, Package *> PackageFilter;
6753 typedef Function<void, NSMutableArray *> PackageSorter;
6754 @interface FilteredPackageListController : PackageListController {
6755 PackageFilter filter_;
6756 PackageSorter sorter_;
6759 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter;
6761 - (void) setFilter:(PackageFilter)filter;
6762 - (void) setSorter:(PackageSorter)sorter;
6766 @implementation FilteredPackageListController
6768 - (void) setFilter:(PackageFilter)filter {
6769 @synchronized (self) {
6773 - (void) setSorter:(PackageSorter)sorter {
6774 @synchronized (self) {
6778 - (NSMutableArray *) _reloadPackages {
6779 @synchronized (database_) {
6780 era_ = [database_ era];
6782 NSArray *packages([database_ packages]);
6783 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6785 PackageFilter filter;
6786 PackageSorter sorter;
6788 @synchronized (self) {
6793 _profile(PackageTable$reloadData$Filter)
6794 for (Package *package in packages)
6795 if ([package valid] && filter(package))
6796 [filtered addObject:package];
6804 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter {
6805 if ((self = [super initWithDatabase:database title:title]) != nil) {
6806 [self setFilter:filter];
6813 /* Home Controller {{{ */
6814 @interface HomeController : CydiaWebViewController {
6815 CFRunLoopRef runloop_;
6816 SCNetworkReachabilityRef reachability_;
6821 @implementation HomeController
6823 static void HomeControllerReachabilityCallback(SCNetworkReachabilityRef reachability, SCNetworkReachabilityFlags flags, void *info) {
6824 [(HomeController *) info dispatchEvent:@"CydiaReachabilityCallback"];
6828 if ((self = [super init]) != nil) {
6829 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6832 reachability_ = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "cydia.saurik.com");
6833 if (reachability_ != NULL) {
6834 SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
6835 SCNetworkReachabilitySetCallback(reachability_, HomeControllerReachabilityCallback, &context);
6837 CFRunLoopRef runloop(CFRunLoopGetCurrent());
6838 if (SCNetworkReachabilityScheduleWithRunLoop(reachability_, runloop, kCFRunLoopDefaultMode))
6845 if (reachability_ != NULL && runloop_ != NULL)
6846 SCNetworkReachabilityUnscheduleFromRunLoop(reachability_, runloop_, kCFRunLoopDefaultMode);
6850 - (NSURL *) navigationURL {
6851 return [NSURL URLWithString:@"cydia://home"];
6854 - (void) aboutButtonClicked {
6855 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6857 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6858 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6859 [alert setCancelButtonIndex:0];
6862 @"Copyright \u00a9 2008-2015\n"
6865 "Jay Freeman (saurik)\n"
6866 "saurik@saurik.com\n"
6867 "http://www.saurik.com/"
6873 - (UIBarButtonItem *) leftButton {
6874 return [[[UIBarButtonItem alloc]
6875 initWithTitle:UCLocalize("ABOUT")
6876 style:UIBarButtonItemStylePlain
6878 action:@selector(aboutButtonClicked)
6885 /* Cydia Navigation Controller Interface {{{ */
6886 @interface UINavigationController (Cydia)
6888 - (NSArray *) navigationURLCollection;
6889 - (void) unloadData;
6894 /* Cydia Tab Bar Controller {{{ */
6895 @interface CydiaTabBarController : CyteTabBarController <
6896 UITabBarControllerDelegate,
6899 _transient Database *database_;
6901 _H<UIActivityIndicatorView> indicator_;
6904 // XXX: ok, "updatedelegate_"?...
6905 _transient NSObject<CydiaDelegate> *updatedelegate_;
6908 - (NSArray *) navigationURLCollection;
6909 - (void) beginUpdate;
6914 @implementation CydiaTabBarController
6916 - (NSArray *) navigationURLCollection {
6917 NSMutableArray *items([NSMutableArray array]);
6919 // XXX: Should this deal with transient view controllers?
6920 for (id navigation in [self viewControllers]) {
6921 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6923 [items addObject:stack];
6929 - (id) initWithDatabase:(Database *)database {
6930 if ((self = [super init]) != nil) {
6931 database_ = database;
6932 [self setDelegate:self];
6934 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteTiny] autorelease];
6935 [indicator_ setOrigin:CGPointMake(kCFCoreFoundationVersionNumber >= 800 ? 2 : 4, 2)];
6937 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6941 - (void) beginUpdate {
6945 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
6946 UITabBarItem *item([controller tabBarItem]);
6948 [item setBadgeValue:@""];
6949 UIView *badge(MSHookIvar<UIView *>([item view], "_badge"));
6951 [indicator_ startAnimating];
6952 [badge addSubview:indicator_];
6954 [updatedelegate_ retainNetworkActivityIndicator];
6958 detachNewThreadSelector:@selector(performUpdate)
6964 - (void) performUpdate {
6965 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
6967 SourceStatus status(self, database_);
6968 [database_ updateWithStatus:status];
6971 performSelectorOnMainThread:@selector(completeUpdate)
6979 - (void) stopUpdateWithSelector:(SEL)selector {
6981 [updatedelegate_ releaseNetworkActivityIndicator];
6983 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
6984 [[controller tabBarItem] setBadgeValue:nil];
6986 [indicator_ removeFromSuperview];
6987 [indicator_ stopAnimating];
6989 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6992 - (void) completeUpdate {
6995 [self stopUpdateWithSelector:@selector(reloadData)];
6998 - (void) cancelUpdate {
6999 [self stopUpdateWithSelector:@selector(updateDataAndLoad)];
7002 - (void) cancelPressed {
7003 [self cancelUpdate];
7010 - (bool) isSourceCancelled {
7014 - (void) startSourceFetch:(NSString *)uri {
7017 - (void) stopSourceFetch:(NSString *)uri {
7020 - (void) setUpdateDelegate:(id)delegate {
7021 updatedelegate_ = delegate;
7027 /* Cydia Navigation Controller Implementation {{{ */
7028 @implementation UINavigationController (Cydia)
7030 - (NSArray *) navigationURLCollection {
7031 NSMutableArray *stack([NSMutableArray array]);
7033 for (CyteViewController *controller in [self viewControllers]) {
7034 NSString *url = [[controller navigationURL] absoluteString];
7036 [stack addObject:url];
7042 - (void) reloadData {
7045 UIViewController *visible([self visibleViewController]);
7047 [visible reloadData];
7049 // on the iPad, this view controller is ALSO visible. :(
7051 if (UIViewController *modal = [self modalViewController])
7052 if ([modal modalPresentationStyle] == UIModalPresentationFormSheet)
7053 if (UIViewController *top = [self topViewController])
7058 - (void) unloadData {
7059 for (CyteViewController *page in [self viewControllers])
7068 /* Cydia:// Protocol {{{ */
7069 @interface CydiaURLProtocol : NSURLProtocol {
7074 @implementation CydiaURLProtocol
7076 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7077 NSURL *url([request URL]);
7081 NSString *scheme([[url scheme] lowercaseString]);
7082 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7084 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7090 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7094 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7095 id<NSURLProtocolClient> client([self client]);
7097 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7099 NSData *data(UIImagePNGRepresentation(icon));
7101 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7102 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7103 [client URLProtocol:self didLoadData:data];
7104 [client URLProtocolDidFinishLoading:self];
7108 - (void) startLoading {
7109 id<NSURLProtocolClient> client([self client]);
7110 NSURLRequest *request([self request]);
7112 NSURL *url([request URL]);
7113 NSString *href([url absoluteString]);
7114 NSString *scheme([[url scheme] lowercaseString]);
7118 if ([scheme isEqualToString:@"cydia"])
7119 path = [href substringFromIndex:8];
7120 else if ([scheme isEqualToString:@"about"])
7121 path = [href substringFromIndex:12];
7122 else _assert(false);
7124 NSRange slash([path rangeOfString:@"/"]);
7127 if (slash.location == NSNotFound) {
7131 command = [path substringToIndex:slash.location];
7132 path = [path substringFromIndex:(slash.location + 1)];
7135 Database *database([Database sharedInstance]);
7137 if ([command isEqualToString:@"package-icon"]) {
7140 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7141 Package *package([database packageWithName:path]);
7145 UIImage *icon([package icon]);
7146 [self _returnPNGWithImage:icon forRequest:request];
7147 } else if ([command isEqualToString:@"uikit-image"]) {
7150 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7151 UIImage *icon(_UIImageWithName(path));
7152 [self _returnPNGWithImage:icon forRequest:request];
7153 } else if ([command isEqualToString:@"section-icon"]) {
7156 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7157 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7159 icon = [UIImage imageNamed:@"unknown.png"];
7160 [self _returnPNGWithImage:icon forRequest:request];
7162 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7166 - (void) stopLoading {
7172 /* Section Controller {{{ */
7173 @interface SectionController : FilteredPackageListController {
7175 _H<NSString> section_;
7178 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section;
7182 @implementation SectionController
7184 - (NSURL *) referrerURL {
7185 NSString *name(section_);
7186 name = name ?: @"*";
7187 NSString *key(key_);
7189 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sections/%@/%@", UI_, [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7192 - (NSURL *) navigationURL {
7193 NSString *name(section_);
7194 name = name ?: @"*";
7195 NSString *key(key_);
7197 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@/%@", [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7200 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section {
7203 title = UCLocalize("ALL_PACKAGES");
7204 else if (![section isEqual:@""])
7205 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(section) value:nil table:@"Sections"];
7207 title = UCLocalize("NO_SECTION");
7209 if ((self = [super initWithDatabase:database title:title]) != nil) {
7210 key_ = [source key];
7215 - (void) reloadData {
7216 Source *source([database_ sourceWithKey:key_]);
7217 _H<NSString> name(section_);
7219 [self setFilter:[=](Package *package) {
7220 NSString *section([package section]);
7224 section == nil && [name length] == 0 ||
7225 [name isEqualToString:section]
7228 [package source] == source
7229 ) && [package visible];
7237 /* Sections Controller {{{ */
7238 @interface SectionsController : CyteViewController <
7239 UITableViewDataSource,
7242 _transient Database *database_;
7244 _H<NSMutableArray> sections_;
7245 _H<NSMutableArray> filtered_;
7246 _H<UITableView, 2> list_;
7249 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7250 - (void) editButtonClicked;
7254 @implementation SectionsController
7256 - (NSURL *) navigationURL {
7257 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
7260 - (Source *) source {
7263 return [database_ sourceWithKey:key_];
7266 - (void) updateNavigationItem {
7267 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7268 if ([sections_ count] == 0) {
7269 [[self navigationItem] setRightBarButtonItem:nil];
7271 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7272 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7274 action:@selector(editButtonClicked)
7275 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7279 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7280 [super setEditing:editing animated:animated];
7285 [delegate_ updateData];
7287 [self updateNavigationItem];
7290 - (void) viewDidAppear:(BOOL)animated {
7291 [super viewDidAppear:animated];
7292 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7295 - (void) viewWillDisappear:(BOOL)animated {
7296 [super viewWillDisappear:animated];
7297 [self setEditing:NO];
7300 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7301 Section *section = nil;
7302 int index = [indexPath row];
7303 if (![self isEditing]) {
7306 section = [filtered_ objectAtIndex:index];
7308 section = [sections_ objectAtIndex:index];
7313 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7314 if ([self isEditing])
7315 return [sections_ count];
7317 return [filtered_ count] + 1;
7320 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7324 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7325 static NSString *reuseIdentifier = @"SectionCell";
7327 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7329 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7331 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7336 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7337 if ([self isEditing])
7340 Section *section = [self sectionAtIndexPath:indexPath];
7342 SectionController *controller = [[[SectionController alloc]
7343 initWithDatabase:database_
7344 source:[self source]
7345 section:[section name]
7347 [controller setDelegate:delegate_];
7349 [[self navigationController] pushViewController:controller animated:YES];
7353 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
7354 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7355 [list_ setRowHeight:46];
7356 [(UITableView *) list_ setDataSource:self];
7357 [list_ setDelegate:self];
7358 [self setView:list_];
7361 - (void) viewDidLoad {
7362 [super viewDidLoad];
7364 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7367 - (void) releaseSubviews {
7373 [super releaseSubviews];
7376 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7377 if ((self = [super init]) != nil) {
7378 database_ = database;
7379 key_ = [source key];
7383 - (void) reloadData {
7386 NSArray *packages = [database_ packages];
7388 sections_ = [NSMutableArray arrayWithCapacity:16];
7389 filtered_ = [NSMutableArray arrayWithCapacity:16];
7391 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7393 Source *source([self source]);
7396 for (Package *package in packages) {
7397 if (source != nil && [package source] != source)
7400 NSString *name([package section]);
7401 NSString *key(name == nil ? @"" : name);
7405 _profile(SectionsView$reloadData$Section)
7406 section = [sections objectForKey:key];
7407 if (section == nil) {
7408 _profile(SectionsView$reloadData$Section$Allocate)
7409 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7410 [sections setObject:section forKey:key];
7415 [section addToCount];
7417 _profile(SectionsView$reloadData$Filter)
7418 if (![package valid] || ![package visible])
7426 [sections_ addObjectsFromArray:[sections allValues]];
7428 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7430 for (Section *section in (id) sections_) {
7431 size_t count([section row]);
7435 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7436 [section setCount:count];
7437 [filtered_ addObject:section];
7440 [self updateNavigationItem];
7445 - (void) editButtonClicked {
7446 [self setEditing:![self isEditing] animated:YES];
7452 /* Changes Controller {{{ */
7453 @interface ChangesController : FilteredPackageListController {
7457 - (id) initWithDatabase:(Database *)database;
7461 @implementation ChangesController
7463 - (NSURL *) referrerURL {
7464 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/changes/", UI_]];
7467 - (NSURL *) navigationURL {
7468 return [NSURL URLWithString:@"cydia://changes"];
7471 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7472 @synchronized (database_) {
7473 if ([database_ era] != era_)
7476 NSUInteger sectionIndex([path section]);
7477 if (sectionIndex >= [sections_ count])
7479 Section *section([sections_ objectAtIndex:sectionIndex]);
7480 NSInteger row([path row]);
7481 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7484 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7485 NSString *context([alert context]);
7487 if ([context isEqualToString:@"norefresh"])
7488 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7491 - (void) setLeftBarButtonItem {
7492 if ([delegate_ updating])
7493 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7494 initWithTitle:UCLocalize("CANCEL")
7495 style:UIBarButtonItemStyleDone
7497 action:@selector(cancelButtonClicked)
7498 ] autorelease] animated:YES];
7500 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7501 initWithTitle:UCLocalize("REFRESH")
7502 style:UIBarButtonItemStylePlain
7504 action:@selector(refreshButtonClicked)
7505 ] autorelease] animated:YES];
7508 - (void) refreshButtonClicked {
7509 if ([delegate_ requestUpdate])
7510 [self setLeftBarButtonItem];
7513 - (void) cancelButtonClicked {
7514 [delegate_ cancelUpdate];
7517 - (void) upgradeButtonClicked {
7518 [delegate_ distUpgrade];
7519 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7522 - (bool) shouldYield {
7526 - (bool) shouldBlock {
7530 - (void) useFilter {
7531 @synchronized (self) {
7532 [self setFilter:[](Package *package) {
7533 return [package upgradableAndEssential:YES] || [package visible];
7536 [self setSorter:[](NSMutableArray *packages) {
7537 [packages radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7541 - (id) initWithDatabase:(Database *)database {
7542 if ((self = [super initWithDatabase:database title:UCLocalize("CHANGES")]) != nil) {
7547 - (void) viewDidLoad {
7548 [super viewDidLoad];
7549 [self setLeftBarButtonItem];
7552 - (void) viewWillAppear:(BOOL)animated {
7553 [super viewWillAppear:animated];
7554 [self setLeftBarButtonItem];
7557 - (void) reloadData {
7558 [self setLeftBarButtonItem];
7562 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
7563 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
7565 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7566 Section *ignored = nil;
7567 Section *section = nil;
7571 bool unseens = false;
7573 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7575 for (size_t offset = 0, count = [packages count]; offset != count; ++offset) {
7576 Package *package = [packages objectAtIndex:offset];
7578 BOOL uae = [package upgradableAndEssential:YES];
7582 time_t seen([package seen]);
7584 if (section == nil || last != seen) {
7588 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7591 _profile(ChangesController$reloadData$Allocate)
7592 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7593 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7594 [sections addObject:section];
7598 [section addToCount];
7599 } else if ([package ignored]) {
7600 if (ignored == nil) {
7601 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7603 [ignored addToCount];
7606 [upgradable addToCount];
7611 CFRelease(formatter);
7614 Section *last = [sections lastObject];
7615 size_t count = [last count];
7616 [packages removeObjectsInRange:NSMakeRange([packages count] - count, count)];
7617 [sections removeLastObject];
7620 if ([ignored count] != 0)
7621 [sections insertObject:ignored atIndex:0];
7623 [sections insertObject:upgradable atIndex:0];
7627 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7628 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7629 style:UIBarButtonItemStylePlain
7631 action:@selector(upgradeButtonClicked)
7632 ] autorelease]) animated:YES];
7639 /* Search Controller {{{ */
7640 @interface SearchController : FilteredPackageListController <
7643 _H<UISearchBar, 1> search_;
7648 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7649 - (void) reloadData;
7653 @implementation SearchController
7655 - (NSURL *) referrerURL {
7656 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/search?q=%@", UI_, [([search_ text] ?: @"") stringByAddingPercentEscapesIncludingReserved]]];
7659 - (NSURL *) navigationURL {
7660 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7661 return [NSURL URLWithString:@"cydia://search"];
7663 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [[search_ text] stringByAddingPercentEscapesIncludingReserved]]];
7666 - (NSArray *) termsForQuery:(NSString *)query {
7667 NSMutableArray *terms([NSMutableArray arrayWithCapacity:2]);
7668 for (NSString *component in [query componentsSeparatedByString:@" "])
7669 if ([component length] != 0)
7670 [terms addObject:component];
7675 - (void) useSearch {
7676 _H<NSArray> query([self termsForQuery:[search_ text]]);
7679 @synchronized (self) {
7680 [self setFilter:[=](Package *package) {
7681 if (![package unfiltered])
7683 if (![package matches:query])
7688 [self setSorter:[](NSMutableArray *packages) {
7689 [packages radixSortUsingSelector:@selector(rank)];
7697 - (void) usePrefix:(NSString *)prefix {
7698 _H<NSString> query(prefix);
7701 @synchronized (self) {
7702 [self setFilter:[=](Package *package) {
7703 if ([query length] == 0)
7705 if (![package unfiltered])
7707 if ([[package name] compare:query options:MatchCompareOptions_ range:NSMakeRange(0, [query length])] != NSOrderedSame)
7712 [self setSorter:nullptr];
7718 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7720 [self usePrefix:[search_ text]];
7723 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7724 [search_ resignFirstResponder];
7728 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7729 [search_ setText:@""];
7730 [self searchBarButtonClicked:searchBar];
7733 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7734 [self searchBarButtonClicked:searchBar];
7737 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7738 [self usePrefix:text];
7741 - (bool) shouldYield {
7745 - (bool) shouldBlock {
7749 - (bool) isSummarized {
7753 - (bool) showsSections {
7757 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7758 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH")])) {
7759 search_ = [[[UISearchBar alloc] init] autorelease];
7760 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7761 [search_ setDelegate:self];
7763 UITextField *textField;
7764 if ([search_ respondsToSelector:@selector(searchField)])
7765 textField = [search_ searchField];
7767 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7769 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7770 [textField setEnablesReturnKeyAutomatically:NO];
7771 [[self navigationItem] setTitleView:textField];
7774 [search_ setText:query];
7779 - (void) viewDidAppear:(BOOL)animated {
7780 [super viewDidAppear:animated];
7782 if (!searchloaded_) {
7783 searchloaded_ = YES;
7784 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7785 [search_ layoutSubviews];
7788 if ([self isSummarized])
7789 [search_ becomeFirstResponder];
7792 - (void) reloadData {
7797 - (void) didSelectPackage:(Package *)package {
7798 [search_ resignFirstResponder];
7799 [super didSelectPackage:package];
7804 /* Package Settings Controller {{{ */
7805 @interface PackageSettingsController : CyteViewController <
7806 UITableViewDataSource,
7809 _transient Database *database_;
7811 _H<Package> package_;
7812 _H<UITableView, 2> table_;
7813 _H<UISwitch> subscribedSwitch_;
7814 _H<UISwitch> ignoredSwitch_;
7815 _H<UITableViewCell> subscribedCell_;
7816 _H<UITableViewCell> ignoredCell_;
7819 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7823 @implementation PackageSettingsController
7825 - (NSURL *) navigationURL {
7826 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
7829 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7830 if (package_ == nil)
7833 if ([package_ installed] == nil)
7839 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7840 if (package_ == nil)
7843 // both sections contain just one item right now.
7847 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7851 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7853 return UCLocalize("SHOW_ALL_CHANGES_EX");
7855 return UCLocalize("IGNORE_UPGRADES_EX");
7858 - (void) onSubscribed:(id)control {
7859 bool value([control isOn]);
7860 if (package_ == nil)
7862 if ([package_ setSubscribed:value])
7863 [delegate_ updateData];
7866 - (void) _updateIgnored {
7867 const char *package([name_ UTF8String]);
7868 bool on([ignoredSwitch_ isOn]);
7870 pid_t pid(ExecFork());
7872 FILE *dpkg(popen("/usr/libexec/cydo --set-selections", "w"));
7873 fwrite(package, strlen(package), 1, dpkg);
7876 fwrite(" hold\n", 6, 1, dpkg);
7878 fwrite(" install\n", 9, 1, dpkg);
7886 - (void) onIgnored:(id)control {
7887 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7888 [invocation setTarget:self];
7889 [invocation setSelector:@selector(_updateIgnored)];
7891 [delegate_ reloadDataWithInvocation:invocation];
7894 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7895 if (package_ == nil)
7898 switch ([indexPath section]) {
7899 case 0: return subscribedCell_;
7900 case 1: return ignoredCell_;
7909 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
7910 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
7911 [self setView:view];
7913 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7914 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7915 [(UITableView *) table_ setDataSource:self];
7916 [table_ setDelegate:self];
7917 [view addSubview:table_];
7919 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7920 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7921 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7923 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7924 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7925 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7927 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7928 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7929 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7930 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7932 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7933 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7934 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7935 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7938 - (void) viewDidLoad {
7939 [super viewDidLoad];
7941 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7944 - (void) releaseSubviews {
7946 subscribedCell_ = nil;
7948 ignoredSwitch_ = nil;
7949 subscribedSwitch_ = nil;
7951 [super releaseSubviews];
7954 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7955 if ((self = [super init]) != nil) {
7956 database_ = database;
7961 - (void) reloadData {
7964 package_ = [database_ packageWithName:name_];
7966 if (package_ != nil) {
7967 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7968 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7969 } // XXX: what now, G?
7971 [table_ reloadData];
7977 /* Installed Controller {{{ */
7978 @interface InstalledController : FilteredPackageListController {
7982 - (id) initWithDatabase:(Database *)database;
7983 - (void) queueStatusDidChange;
7987 @implementation InstalledController
7989 - (NSURL *) referrerURL {
7990 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/installed/", UI_]];
7993 - (NSURL *) navigationURL {
7994 return [NSURL URLWithString:@"cydia://installed"];
7997 - (void) useRecent {
8000 @synchronized (self) {
8001 [self setFilter:[](Package *package) {
8002 return ![package uninstalled] && package->role_ < 7;
8005 [self setSorter:[](NSMutableArray *packages) {
8006 [packages radixSortUsingSelector:@selector(recent)];
8010 - (void) useFilter:(UISegmentedControl *)segmented {
8011 NSInteger selected([segmented selectedSegmentIndex]);
8013 return [self useRecent];
8014 bool simple(selected == 0);
8017 @synchronized (self) {
8018 [self setFilter:[=](Package *package) {
8019 return ![package uninstalled] && package->role_ <= (simple ? 1 : 3);
8022 [self setSorter:nullptr];
8025 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
8027 return [super sectionsForPackages:packages];
8029 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterLongStyle, kCFDateFormatterNoStyle));
8031 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
8032 Section *section(nil);
8035 for (size_t offset(0), count([packages count]); offset != count; ++offset) {
8036 Package *package([packages objectAtIndex:offset]);
8038 time_t upgraded([package upgraded]);
8039 if (upgraded < 1168364520)
8042 upgraded -= upgraded % (60 * 60 * 24);
8044 if (section == nil || upgraded != last) {
8049 continue; // XXX: name = UCLocalize("...");
8051 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:upgraded]);
8055 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
8056 [sections addObject:section];
8059 [section addToCount];
8062 CFRelease(formatter);
8066 - (id) initWithDatabase:(Database *)database {
8067 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED")]) != nil) {
8068 UISegmentedControl *segmented([[[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:UCLocalize("USER"), UCLocalize("EXPERT"), UCLocalize("RECENT"), nil]] autorelease]);
8069 [segmented setSelectedSegmentIndex:0];
8070 [segmented setSegmentedControlStyle:UISegmentedControlStyleBar];
8071 [[self navigationItem] setTitleView:segmented];
8073 [segmented addTarget:self action:@selector(modeChanged:) forEvents:UIControlEventValueChanged];
8074 [self useFilter:segmented];
8076 [self queueStatusDidChange];
8081 - (void) queueButtonClicked {
8086 - (void) queueStatusDidChange {
8089 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8090 initWithTitle:UCLocalize("QUEUE")
8091 style:UIBarButtonItemStyleDone
8093 action:@selector(queueButtonClicked)
8096 [[self navigationItem] setRightBarButtonItem:nil];
8101 - (void) modeChanged:(UISegmentedControl *)segmented {
8102 [self useFilter:segmented];
8109 /* Source Cell {{{ */
8110 @interface SourceCell : CyteTableViewCell <
8111 CyteTableViewCellDelegate,
8114 _H<Source, 1> source_;
8117 _H<NSString> origin_;
8118 _H<NSString> label_;
8119 _H<UIActivityIndicatorView> indicator_;
8122 - (void) setSource:(Source *)source;
8123 - (void) setFetch:(NSNumber *)fetch;
8127 @implementation SourceCell
8129 - (void) _setImage:(NSArray *)data {
8130 if ([url_ isEqual:[data objectAtIndex:0]]) {
8131 icon_ = [data objectAtIndex:1];
8132 [content_ setNeedsDisplay];
8136 - (void) _setSource:(NSURL *) url {
8137 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8139 if (NSData *data = [NSURLConnection
8140 sendSynchronousRequest:[NSURLRequest
8142 cachePolicy:NSURLRequestUseProtocolCachePolicy
8146 returningResponse:NULL
8149 if (UIImage *image = [UIImage imageWithData:data])
8150 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
8155 - (void) setSource:(Source *)source {
8157 [source_ setDelegate:self];
8159 [self setFetch:[NSNumber numberWithBool:[source_ fetch]]];
8161 icon_ = [UIImage imageNamed:@"unknown.png"];
8163 origin_ = [source name];
8164 label_ = [source rooturi];
8166 [content_ setNeedsDisplay];
8168 url_ = [source iconURL];
8169 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
8172 - (void) setAllSource {
8174 [indicator_ stopAnimating];
8176 icon_ = [UIImage imageNamed:@"folder.png"];
8177 origin_ = UCLocalize("ALL_SOURCES");
8178 label_ = UCLocalize("ALL_SOURCES_EX");
8179 [content_ setNeedsDisplay];
8182 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8183 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8184 UIView *content([self contentView]);
8185 CGRect bounds([content bounds]);
8187 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8188 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8189 [content_ setBackgroundColor:[UIColor whiteColor]];
8190 [content addSubview:content_];
8192 [content_ setDelegate:self];
8193 [content_ setOpaque:YES];
8195 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGraySmall] autorelease];
8196 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin];// | UIViewAutoresizingFlexibleBottomMargin];
8197 [content addSubview:indicator_];
8199 [[content_ layer] setContentsGravity:kCAGravityTopLeft];
8203 - (void) layoutSubviews {
8204 [super layoutSubviews];
8206 UIView *content([self contentView]);
8207 CGRect bounds([content bounds]);
8209 CGRect frame([indicator_ frame]);
8210 frame.origin.x = bounds.size.width - frame.size.width;
8211 frame.origin.y = Retina((bounds.size.height - frame.size.height) / 2);
8213 if (kCFCoreFoundationVersionNumber < 800)
8214 frame.origin.x -= 8;
8215 [indicator_ setFrame:frame];
8218 - (NSString *) accessibilityLabel {
8222 - (void) drawContentRect:(CGRect)rect {
8223 bool highlighted(highlighted_);
8224 float width(rect.size.width);
8228 rect.size = [(UIImage *) icon_ size];
8230 while (rect.size.width > 32 || rect.size.height > 32) {
8231 rect.size.width /= 2;
8232 rect.size.height /= 2;
8235 rect.origin.x = 26 - rect.size.width / 2;
8236 rect.origin.y = 26 - rect.size.height / 2;
8238 [icon_ drawInRect:Retina(rect)];
8241 if (highlighted && kCFCoreFoundationVersionNumber < 800)
8246 [origin_ drawAtPoint:CGPointMake(52, 8) forWidth:(width - 49) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
8250 [label_ drawAtPoint:CGPointMake(52, 29) forWidth:(width - 49) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
8253 - (void) setFetch:(NSNumber *)fetch {
8254 if ([fetch boolValue])
8255 [indicator_ startAnimating];
8257 [indicator_ stopAnimating];
8262 /* Sources Controller {{{ */
8263 @interface SourcesController : CyteViewController <
8264 UITableViewDataSource,
8267 _transient Database *database_;
8270 _H<UITableView, 2> list_;
8271 _H<NSMutableArray> sources_;
8275 _H<UIProgressHUD> hud_;
8278 NSURLConnection *trivial_bz2_;
8279 NSURLConnection *trivial_gz_;
8284 - (id) initWithDatabase:(Database *)database;
8285 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated;
8289 @implementation SourcesController
8291 - (void) _releaseConnection:(NSURLConnection *)connection {
8292 if (connection != nil) {
8293 [connection cancel];
8294 //[connection setDelegate:nil];
8295 [connection release];
8300 [self _releaseConnection:trivial_gz_];
8301 [self _releaseConnection:trivial_bz2_];
8306 - (NSURL *) navigationURL {
8307 return [NSURL URLWithString:@"cydia://sources"];
8310 - (void) viewDidAppear:(BOOL)animated {
8311 [super viewDidAppear:animated];
8312 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8315 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8319 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8321 return UCLocalize("INDIVIDUAL_SOURCES");
8325 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8328 case 1: return [sources_ count];
8333 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8334 @synchronized (database_) {
8335 if ([database_ era] != era_)
8337 if ([indexPath section] != 1)
8339 NSUInteger index([indexPath row]);
8340 if (index >= [sources_ count])
8342 return [sources_ objectAtIndex:index];
8345 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8346 static NSString *cellIdentifier = @"SourceCell";
8348 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8349 if (cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8350 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8352 Source *source([self sourceAtIndexPath:indexPath]);
8354 [cell setAllSource];
8356 [cell setSource:source];
8361 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8362 SectionsController *controller([[[SectionsController alloc]
8363 initWithDatabase:database_
8364 source:[self sourceAtIndexPath:indexPath]
8367 [controller setDelegate:delegate_];
8368 [[self navigationController] pushViewController:controller animated:YES];
8371 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8372 if ([indexPath section] != 1)
8374 Source *source = [self sourceAtIndexPath:indexPath];
8375 return [source record] != nil;
8378 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8379 _assert([indexPath section] == 1);
8380 if (editingStyle == UITableViewCellEditingStyleDelete) {
8381 Source *source = [self sourceAtIndexPath:indexPath];
8382 if (source == nil) return;
8384 [Sources_ removeObjectForKey:[source key]];
8386 [delegate_ _saveConfig];
8387 [delegate_ reloadDataWithInvocation:nil];
8391 - (void) tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath {
8392 [self updateButtonsForEditingStatusAnimated:YES];
8396 [delegate_ addTrivialSource:href_];
8399 [delegate_ syncData];
8402 - (NSString *) getWarning {
8403 NSString *href(href_);
8404 NSRange colon([href rangeOfString:@"://"]);
8405 if (colon.location != NSNotFound)
8406 href = [href substringFromIndex:(colon.location + 3)];
8407 href = [href stringByAddingPercentEscapes];
8408 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8410 NSURL *url([NSURL URLWithString:href]);
8412 NSStringEncoding encoding;
8413 NSError *error(nil);
8415 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8416 return [warning length] == 0 ? nil : warning;
8420 - (void) _endConnection:(NSURLConnection *)connection {
8421 // XXX: the memory management in this method is horribly awkward
8423 NSURLConnection **field = NULL;
8424 if (connection == trivial_bz2_)
8425 field = &trivial_bz2_;
8426 else if (connection == trivial_gz_)
8427 field = &trivial_gz_;
8428 _assert(field != NULL);
8429 [connection release];
8433 trivial_bz2_ == nil &&
8436 NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil);
8438 [delegate_ releaseNetworkActivityIndicator];
8440 [delegate_ removeProgressHUD:hud_];
8444 if (warning != nil) {
8445 UIAlertView *alert = [[[UIAlertView alloc]
8446 initWithTitle:UCLocalize("SOURCE_WARNING")
8449 cancelButtonTitle:UCLocalize("CANCEL")
8451 UCLocalize("ADD_ANYWAY"),
8455 [alert setContext:@"warning"];
8456 [alert setNumberOfRows:1];
8459 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
8465 } else if (error_ != nil) {
8466 UIAlertView *alert = [[[UIAlertView alloc]
8467 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8468 message:[error_ localizedDescription]
8470 cancelButtonTitle:UCLocalize("OK")
8471 otherButtonTitles:nil
8474 [alert setContext:@"urlerror"];
8479 UIAlertView *alert = [[[UIAlertView alloc]
8480 initWithTitle:UCLocalize("NOT_REPOSITORY")
8481 message:UCLocalize("NOT_REPOSITORY_EX")
8483 cancelButtonTitle:UCLocalize("OK")
8484 otherButtonTitles:nil
8487 [alert setContext:@"trivial"];
8497 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8498 switch ([response statusCode]) {
8504 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8505 lprintf("connection:\"%s\" didFailWithError:\"%s\"\n", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8507 [self _endConnection:connection];
8510 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8511 [self _endConnection:connection];
8514 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8515 NSURL *url([NSURL URLWithString:href]);
8517 NSMutableURLRequest *request = [NSMutableURLRequest
8519 cachePolicy:NSURLRequestUseProtocolCachePolicy
8523 [request setHTTPMethod:method];
8525 if (Machine_ != NULL)
8526 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8528 if (UniqueID_ != nil)
8529 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8531 if ([url isCydiaSecure]) {
8532 if (UniqueID_ != nil)
8533 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
8536 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8539 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8540 NSString *context([alert context]);
8542 if ([context isEqualToString:@"source"]) {
8545 NSString *href = [[alert textField] text];
8547 static RegEx href_r("(http(s?)://|file:///)[^# ]*");
8548 if (!href_r(href)) {
8549 UIAlertView *alert = [[[UIAlertView alloc]
8550 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("INVALID_URL")]
8551 message:UCLocalize("INVALID_URL_EX")
8553 cancelButtonTitle:UCLocalize("OK")
8554 otherButtonTitles:nil
8557 [alert setContext:@"badurl"];
8563 if (![href hasSuffix:@"/"])
8564 href_ = [href stringByAppendingString:@"/"];
8568 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8569 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8573 // XXX: this is stupid
8574 hud_ = [delegate_ addProgressHUD];
8575 [hud_ setText:UCLocalize("VERIFYING_URL")];
8576 [delegate_ retainNetworkActivityIndicator];
8585 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8586 } else if ([context isEqualToString:@"trivial"])
8587 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8588 else if ([context isEqualToString:@"urlerror"])
8589 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8590 else if ([context isEqualToString:@"warning"]) {
8593 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
8602 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8606 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated {
8607 BOOL editing([list_ isEditing]);
8610 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8611 initWithTitle:UCLocalize("ADD")
8612 style:UIBarButtonItemStylePlain
8614 action:@selector(addButtonClicked)
8615 ] autorelease] animated:animated];
8616 else if ([delegate_ updating])
8617 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8618 initWithTitle:UCLocalize("CANCEL")
8619 style:UIBarButtonItemStyleDone
8621 action:@selector(cancelButtonClicked)
8622 ] autorelease] animated:animated];
8624 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8625 initWithTitle:UCLocalize("REFRESH")
8626 style:UIBarButtonItemStylePlain
8628 action:@selector(refreshButtonClicked)
8629 ] autorelease] animated:animated];
8631 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8632 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8633 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8635 action:@selector(editButtonClicked)
8636 ] autorelease] animated:animated];
8640 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease];
8641 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8642 [list_ setRowHeight:53];
8643 [(UITableView *) list_ setDataSource:self];
8644 [list_ setDelegate:self];
8645 [self setView:list_];
8648 - (void) viewDidLoad {
8649 [super viewDidLoad];
8651 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8652 [self updateButtonsForEditingStatusAnimated:NO];
8655 - (void) viewWillAppear:(BOOL)animated {
8656 [super viewWillAppear:animated];
8658 [list_ setEditing:NO];
8659 [self updateButtonsForEditingStatusAnimated:NO];
8662 - (void) releaseSubviews {
8667 [super releaseSubviews];
8670 - (id) initWithDatabase:(Database *)database {
8671 if ((self = [super init]) != nil) {
8672 database_ = database;
8676 - (void) reloadData {
8678 [self updateButtonsForEditingStatusAnimated:YES];
8680 @synchronized (database_) {
8681 era_ = [database_ era];
8683 sources_ = [NSMutableArray arrayWithCapacity:16];
8684 [sources_ addObjectsFromArray:[database_ sources]];
8686 [sources_ sortUsingSelector:@selector(compareByName:)];
8689 int count([sources_ count]);
8691 for (int i = 0; i != count; i++) {
8692 if ([[sources_ objectAtIndex:i] record] == nil)
8700 - (void) showAddSourcePrompt {
8701 UIAlertView *alert = [[[UIAlertView alloc]
8702 initWithTitle:UCLocalize("ENTER_APT_URL")
8705 cancelButtonTitle:UCLocalize("CANCEL")
8707 UCLocalize("ADD_SOURCE"),
8711 [alert setContext:@"source"];
8713 [alert setNumberOfRows:1];
8714 [alert addTextFieldWithValue:@"http://" label:@""];
8716 UITextInputTraits *traits = [[alert textField] textInputTraits];
8717 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8718 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8719 [traits setKeyboardType:UIKeyboardTypeURL];
8720 // XXX: UIReturnKeyDone
8721 [traits setReturnKeyType:UIReturnKeyNext];
8726 - (void) addButtonClicked {
8727 [self showAddSourcePrompt];
8730 - (void) refreshButtonClicked {
8731 if ([delegate_ requestUpdate])
8732 [self updateButtonsForEditingStatusAnimated:YES];
8735 - (void) cancelButtonClicked {
8736 [delegate_ cancelUpdate];
8739 - (void) editButtonClicked {
8740 [list_ setEditing:![list_ isEditing] animated:YES];
8741 [self updateButtonsForEditingStatusAnimated:YES];
8747 /* Stash Controller {{{ */
8748 @interface StashController : CyteViewController {
8749 _H<UIActivityIndicatorView> spinner_;
8750 _H<UILabel> status_;
8751 _H<UILabel> caption_;
8756 @implementation StashController
8759 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8760 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8761 [self setView:view];
8763 [view setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8765 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8766 CGRect spinrect = [spinner_ frame];
8767 spinrect.origin.x = Retina([[self view] frame].size.width / 2 - spinrect.size.width / 2);
8768 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8769 [spinner_ setFrame:spinrect];
8770 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8771 [view addSubview:spinner_];
8772 [spinner_ startAnimating];
8775 captrect.size.width = [[self view] frame].size.width;
8776 captrect.size.height = 40.0f;
8777 captrect.origin.x = 0;
8778 captrect.origin.y = Retina([[self view] frame].size.height / 2 - captrect.size.height * 2);
8779 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8780 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8781 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8782 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8783 [caption_ setTextColor:[UIColor whiteColor]];
8784 [caption_ setBackgroundColor:[UIColor clearColor]];
8785 [caption_ setShadowColor:[UIColor blackColor]];
8786 [caption_ setTextAlignment:NSTextAlignmentCenter];
8787 [view addSubview:caption_];
8790 statusrect.size.width = [[self view] frame].size.width;
8791 statusrect.size.height = 30.0f;
8792 statusrect.origin.x = 0;
8793 statusrect.origin.y = Retina([[self view] frame].size.height / 2 - statusrect.size.height);
8794 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8795 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8796 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8797 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8798 [status_ setTextColor:[UIColor whiteColor]];
8799 [status_ setBackgroundColor:[UIColor clearColor]];
8800 [status_ setShadowColor:[UIColor blackColor]];
8801 [status_ setTextAlignment:NSTextAlignmentCenter];
8802 [view addSubview:status_];
8805 - (void) releaseSubviews {
8810 [super releaseSubviews];
8816 @interface CYURLCache : SDURLCache {
8821 @implementation CYURLCache
8823 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8826 else if ([event isEqualToString:@"no-cache"])
8828 else if ([event isEqualToString:@"store"])
8830 else if ([event isEqualToString:@"invalid"])
8832 else if ([event isEqualToString:@"memory"])
8834 else if ([event isEqualToString:@"disk"])
8836 else if ([event isEqualToString:@"miss"])
8839 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8843 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
8844 if (NSURLResponse *response = [cached response])
8845 if (NSString *mime = [response MIMEType])
8846 if ([mime isEqualToString:@"text/cache-manifest"]) {
8847 NSURL *url([response URL]);
8850 NSLog(@"###: %@", [url absoluteString]);
8853 @synchronized (HostConfig_) {
8854 [CachedURLs_ addObject:url];
8858 [super storeCachedResponse:cached forRequest:request];
8861 - (void) createDiskCachePath {
8862 [super createDiskCachePath];
8867 @interface Cydia : UIApplication <
8868 ConfirmationControllerDelegate,
8872 _H<UIWindow> window_;
8873 _H<CydiaTabBarController> tabbar_;
8874 _H<CyteTabBarController> emulated_;
8875 _H<AppCacheController> appcache_;
8877 _H<NSMutableArray> essential_;
8878 _H<NSMutableArray> broken_;
8880 Database *database_;
8882 _H<NSURL> starturl_;
8887 _H<StashController> stash_;
8896 @implementation Cydia
8898 - (void) lockSuspend {
8899 if (locked_++ == 0) {
8900 if ($SBSSetInterceptsMenuButtonForever != NULL)
8901 (*$SBSSetInterceptsMenuButtonForever)(true);
8903 [self setIdleTimerDisabled:YES];
8907 - (void) unlockSuspend {
8908 if (--locked_ == 0) {
8909 [self setIdleTimerDisabled:NO];
8911 if ($SBSSetInterceptsMenuButtonForever != NULL)
8912 (*$SBSSetInterceptsMenuButtonForever)(false);
8916 - (void) beginUpdate {
8917 [tabbar_ beginUpdate];
8920 - (void) cancelUpdate {
8921 [tabbar_ cancelUpdate];
8924 - (bool) requestUpdate {
8925 if (IsReachable("cydia.saurik.com")) {
8929 UIAlertView *alert = [[[UIAlertView alloc]
8930 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("REFRESH")]
8931 message:@"Host Unreachable" // XXX: Localize
8933 cancelButtonTitle:UCLocalize("OK")
8934 otherButtonTitles:nil
8937 [alert setContext:@"norefresh"];
8945 return [tabbar_ updating];
8949 if ([broken_ count] != 0) {
8950 int count = [broken_ count];
8952 UIAlertView *alert = [[[UIAlertView alloc]
8953 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8954 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8956 cancelButtonTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("FORCIBLY_CLEAR"), UCLocalize("UNSAFE")]
8958 UCLocalize("TEMPORARY_IGNORE"),
8962 [alert setContext:@"fixhalf"];
8963 [alert setNumberOfRows:2];
8965 } else if (!Ignored_ && [essential_ count] != 0) {
8966 int count = [essential_ count];
8968 UIAlertView *alert = [[[UIAlertView alloc]
8969 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8970 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8972 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8974 UCLocalize("UPGRADE_ESSENTIAL"),
8975 UCLocalize("COMPLETE_UPGRADE"),
8979 [alert setContext:@"upgrade"];
8984 - (void) returnToCydia {
8988 - (void) _saveConfig {
8989 SaveConfig(database_);
8992 // Navigation controller for the queuing badge.
8993 - (UINavigationController *) queueNavigationController {
8994 NSArray *controllers = [tabbar_ viewControllers];
8995 return [controllers objectAtIndex:3];
8998 - (void) unloadData {
8999 [tabbar_ unloadData];
9002 - (void) _updateData {
9006 UINavigationController *navigation = [self queueNavigationController];
9008 id queuedelegate = nil;
9009 if ([[navigation viewControllers] count] > 0)
9010 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9012 [queuedelegate queueStatusDidChange];
9013 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9016 - (void) _refreshIfPossible {
9017 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9019 NSDate *update([[NSDictionary dictionaryWithContentsOfFile:@ CacheState_] objectForKey:@"LastUpdate"]);
9021 bool recently = false;
9022 if (update != nil) {
9023 NSTimeInterval interval([update timeIntervalSinceNow]);
9024 if (interval > -(15*60))
9028 // Don't automatic refresh if:
9029 // - We already refreshed recently.
9030 // - We already auto-refreshed this launch.
9031 // - Auto-refresh is disabled.
9032 // - Cydia's server is not reachable
9033 if (recently || loaded_ || ManualRefresh || !IsReachable("cydia.saurik.com")) {
9034 // If we are cancelling, we need to make sure it knows it's already loaded.
9037 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9039 // We are going to load, so remember that.
9042 [tabbar_ performSelectorOnMainThread:@selector(beginUpdate) withObject:nil waitUntilDone:NO];
9048 - (void) refreshIfPossible {
9049 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
9052 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9053 _profile(reloadDataWithInvocation)
9054 @synchronized (self) {
9055 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9057 [hud setText:UCLocalize("RELOADING_DATA")];
9059 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9063 [essential_ removeAllObjects];
9064 [broken_ removeAllObjects];
9066 _profile(reloadDataWithInvocation$Essential)
9067 NSArray *packages([database_ packages]);
9068 for (Package *package in packages) {
9070 [broken_ addObject:package];
9071 if ([package upgradableAndEssential:YES] && ![package ignored]) {
9072 if ([package essential] && [package installed] != nil)
9073 [essential_ addObject:package];
9079 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9082 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9083 [changesItem setBadgeValue:badge];
9084 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9085 [self setApplicationIconBadgeNumber:changes];
9088 [changesItem setBadgeValue:nil];
9089 [changesItem setAnimatedBadge:NO];
9090 [self setApplicationIconBadgeNumber:0];
9097 [self removeProgressHUD:hud];
9104 - (void) updateData {
9108 - (void) updateDataAndLoad {
9110 if ([database_ progressDelegate] == nil)
9116 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9119 - (void) disemulate {
9120 if (emulated_ == nil)
9123 if ([window_ respondsToSelector:@selector(setRootViewController:)])
9124 [window_ setRootViewController:tabbar_];
9126 [window_ addSubview:[tabbar_ view]];
9127 [[emulated_ view] removeFromSuperview];
9131 [window_ setUserInteractionEnabled:YES];
9134 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9135 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9137 UIViewController *parent;
9138 if (emulated_ == nil)
9148 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9149 [parent presentModalViewController:navigation animated:YES];
9152 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9153 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9155 if (navigation != nil)
9156 [navigation pushViewController:progress animated:YES];
9158 [self presentModalViewController:progress force:YES];
9160 [progress invoke:invocation withTitle:title];
9164 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9165 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9168 - (void) repairWithInvocation:(NSInvocation *)invocation {
9170 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9174 - (void) repairWithSelector:(SEL)selector {
9175 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9178 - (void) reloadData {
9179 [self reloadDataWithInvocation:nil];
9180 if ([database_ progressDelegate] == nil)
9186 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9189 - (void) addSource:(NSDictionary *) source {
9190 CydiaAddSource(source);
9193 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9194 CydiaAddSource(href, distribution, sections);
9197 - (void) addTrivialSource:(NSString *)href {
9198 CydiaAddSource(href, @"./");
9202 pkgProblemResolver *resolver = [database_ resolver];
9204 resolver->InstallProtect();
9205 if (!resolver->Resolve(true))
9210 // XXX: this is a really crappy way of doing this.
9211 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9212 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9213 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9214 if ([tabbar_ updating])
9215 [tabbar_ cancelUpdate];
9217 if (![database_ prepare])
9220 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9221 [page setDelegate:self];
9222 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9225 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9226 [tabbar_ presentModalViewController:confirm_ animated:YES];
9232 @synchronized (self) {
9237 - (void) clearPackage:(Package *)package {
9238 @synchronized (self) {
9245 - (void) installPackages:(NSArray *)packages {
9246 @synchronized (self) {
9247 for (Package *package in packages)
9254 - (void) installPackage:(Package *)package {
9255 @synchronized (self) {
9262 - (void) removePackage:(Package *)package {
9263 @synchronized (self) {
9270 - (void) distUpgrade {
9271 @synchronized (self) {
9272 if (![database_ upgrade])
9281 if (UpgradeCydia_ && Finish_ > 0)
9282 system("/usr/libexec/cydia/cydo /bin/su -c /usr/bin/uicache mobile");
9284 system("/usr/bin/uicache");
9290 UIProgressHUD *hud([self addProgressHUD]);
9291 [hud setText:UCLocalize("LOADING")];
9292 [self yieldToSelector:@selector(_uicache)];
9293 [self removeProgressHUD:hud];
9297 [database_ perform];
9298 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9299 [self performSelectorOnMainThread:@selector(uicache) withObject:nil waitUntilDone:YES];
9302 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9305 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9306 [self unlockSuspend];
9309 - (void) retainNetworkActivityIndicator {
9310 if (activity_++ == 0)
9311 [self setNetworkActivityIndicatorVisible:YES];
9314 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9318 - (void) releaseNetworkActivityIndicator {
9319 if (--activity_ == 0)
9320 [self setNetworkActivityIndicatorVisible:NO];
9323 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9328 - (void) cancelAndClear:(bool)clear {
9329 @synchronized (self) {
9341 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9342 NSString *context([alert context]);
9344 if ([context isEqualToString:@"conffile"]) {
9345 FILE *input = [database_ input];
9346 if (button == [alert cancelButtonIndex])
9347 fprintf(input, "N\n");
9348 else if (button == [alert firstOtherButtonIndex])
9349 fprintf(input, "Y\n");
9352 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9353 } else if ([context isEqualToString:@"fixhalf"]) {
9354 if (button == [alert cancelButtonIndex]) {
9355 @synchronized (self) {
9356 for (Package *broken in (id) broken_) {
9358 NSString *id = [broken id];
9360 system([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /bin/rm -f"
9361 " /var/lib/dpkg/info/%@.prerm"
9362 " /var/lib/dpkg/info/%@.postrm"
9363 " /var/lib/dpkg/info/%@.preinst"
9364 " /var/lib/dpkg/info/%@.postinst"
9365 " /var/lib/dpkg/info/%@.extrainst_"
9366 , id, id, id, id, id] UTF8String]);
9372 } else if (button == [alert firstOtherButtonIndex]) {
9373 [broken_ removeAllObjects];
9377 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9378 } else if ([context isEqualToString:@"upgrade"]) {
9379 if (button == [alert firstOtherButtonIndex]) {
9380 @synchronized (self) {
9381 for (Package *essential in (id) essential_)
9382 [essential install];
9387 } else if (button == [alert firstOtherButtonIndex] + 1) {
9389 } else if (button == [alert cancelButtonIndex]) {
9393 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9397 - (void) system:(NSString *)command {
9398 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9401 system([command UTF8String]);
9407 - (void) applicationWillSuspend {
9409 [super applicationWillSuspend];
9412 - (BOOL) isSafeToSuspend {
9415 NSLog(@"isSafeToSuspend: locked_ != 0");
9420 if ([tabbar_ modalViewController] != nil)
9423 // Use external process status API internally.
9424 // This is probably a really bad idea.
9425 // XXX: what is the point of this? does this solve anything at all?
9426 uint64_t status = 0;
9428 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9429 notify_get_state(notify_token, &status);
9430 notify_cancel(notify_token);
9435 NSLog(@"isSafeToSuspend: status != 0");
9441 NSLog(@"isSafeToSuspend: -> true");
9446 - (void) suspendReturningToLastApp:(BOOL)returning {
9447 if ([self isSafeToSuspend])
9448 [super suspendReturningToLastApp:returning];
9452 if ([self isSafeToSuspend])
9456 - (void) applicationSuspend {
9457 if ([self isSafeToSuspend])
9458 [super applicationSuspend];
9461 - (void) applicationSuspend:(__GSEvent *)event {
9462 if ([self isSafeToSuspend])
9463 [super applicationSuspend:event];
9466 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9467 if ([self isSafeToSuspend])
9468 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9471 - (void) _setSuspended:(BOOL)value {
9472 if ([self isSafeToSuspend])
9473 [super _setSuspended:value];
9476 - (UIProgressHUD *) addProgressHUD {
9477 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9478 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9480 [window_ setUserInteractionEnabled:NO];
9482 UIViewController *target(tabbar_);
9483 if (UIViewController *modal = [target modalViewController])
9486 [hud showInView:[target view]];
9492 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9493 [self unlockSuspend];
9495 [hud removeFromSuperview];
9496 [window_ setUserInteractionEnabled:YES];
9499 - (CyteViewController *) pageForPackage:(NSString *)name withReferrer:(NSString *)referrer {
9500 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name withReferrer:referrer] autorelease];
9503 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external withReferrer:(NSString *)referrer {
9504 NSString *scheme([[url scheme] lowercaseString]);
9505 if ([[url absoluteString] length] <= [scheme length] + 3)
9507 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9508 NSArray *components([path componentsSeparatedByString:@"/"]);
9510 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"]) {
9511 CyteViewController *controller([self pageForPackage:[components objectAtIndex:1] withReferrer:referrer]);
9512 if (controller != nil)
9513 [controller setDelegate:self];
9517 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9520 NSString *base([components objectAtIndex:0]);
9522 CyteViewController *controller = nil;
9524 if ([base isEqualToString:@"url"]) {
9525 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9526 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9527 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9528 } else if (!external && [components count] == 1) {
9529 if ([base isEqualToString:@"sources"]) {
9530 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9533 if ([base isEqualToString:@"home"]) {
9534 controller = [[[HomeController alloc] init] autorelease];
9537 if ([base isEqualToString:@"sections"]) {
9538 controller = [[[SectionsController alloc] initWithDatabase:database_ source:nil] autorelease];
9541 if ([base isEqualToString:@"search"]) {
9542 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9545 if ([base isEqualToString:@"changes"]) {
9546 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9549 if ([base isEqualToString:@"installed"]) {
9550 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9552 } else if ([components count] == 2) {
9553 NSString *argument = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9555 if ([base isEqualToString:@"package"]) {
9556 controller = [self pageForPackage:argument withReferrer:referrer];
9559 if (!external && [base isEqualToString:@"search"]) {
9560 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9563 if (!external && [base isEqualToString:@"sections"]) {
9564 if ([argument isEqualToString:@"all"] || [argument isEqualToString:@"*"])
9566 controller = [[[SectionController alloc] initWithDatabase:database_ source:nil section:argument] autorelease];
9569 if (!external && [base isEqualToString:@"sources"]) {
9570 if ([argument isEqualToString:@"add"]) {
9571 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9572 [(SourcesController *)controller showAddSourcePrompt];
9574 Source *source([database_ sourceWithKey:argument]);
9575 controller = [[[SectionsController alloc] initWithDatabase:database_ source:source] autorelease];
9579 if (!external && [base isEqualToString:@"launch"]) {
9580 [self launchApplicationWithIdentifier:argument suspended:NO];
9583 } else if (!external && [components count] == 3) {
9584 NSString *arg1 = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9585 NSString *arg2 = [[components objectAtIndex:2] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9587 if ([base isEqualToString:@"package"]) {
9588 if ([arg2 isEqualToString:@"settings"]) {
9589 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9590 } else if ([arg2 isEqualToString:@"files"]) {
9591 if (Package *package = [database_ packageWithName:arg1]) {
9592 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9593 [(FileTable *)controller setPackage:package];
9598 if ([base isEqualToString:@"sections"]) {
9599 Source *source([arg1 isEqualToString:@"*"] ? nil : [database_ sourceWithKey:arg1]);
9600 NSString *section([arg2 isEqualToString:@"*"] ? nil : arg2);
9601 controller = [[[SectionController alloc] initWithDatabase:database_ source:source section:section] autorelease];
9605 [controller setDelegate:self];
9609 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9610 CyteViewController *page([self pageForURL:url forExternal:external withReferrer:nil]);
9613 [tabbar_ setUnselectedViewController:page];
9618 - (void) applicationOpenURL:(NSURL *)url {
9619 [super applicationOpenURL:url];
9624 [self openCydiaURL:url forExternal:YES];
9627 - (void) applicationWillResignActive:(UIApplication *)application {
9628 // Stop refreshing if you get a phone call or lock the device.
9629 if ([tabbar_ updating])
9630 [tabbar_ cancelUpdate];
9632 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9633 [super applicationWillResignActive:application];
9636 - (void) saveState {
9637 [[NSDictionary dictionaryWithObjectsAndKeys:
9638 @"InterfaceState", [tabbar_ navigationURLCollection],
9639 @"LastClosed", [NSDate date],
9640 @"InterfaceIndex", [NSNumber numberWithInt:[tabbar_ selectedIndex]],
9641 nil] writeToFile:@ SavedState_ atomically:YES];
9646 - (void) applicationWillTerminate:(UIApplication *)application {
9650 - (void) applicationDidEnterBackground:(UIApplication *)application {
9651 if (kCFCoreFoundationVersionNumber < 1000 && [self isSafeToSuspend])
9652 return [self terminateWithSuccess];
9653 Backgrounded_ = [NSDate date];
9657 - (void) applicationWillEnterForeground:(UIApplication *)application {
9658 if (Backgrounded_ == nil)
9661 NSTimeInterval interval([Backgrounded_ timeIntervalSinceNow]);
9663 if (interval <= -(30*60)) {
9664 [tabbar_ setSelectedIndex:0];
9665 [[[tabbar_ viewControllers] objectAtIndex:0] popToRootViewControllerAnimated:NO];
9668 if (interval <= -(15*60)) {
9669 if (IsReachable("cydia.saurik.com")) {
9670 [tabbar_ beginUpdate];
9671 [appcache_ reloadURLWithCache:YES];
9675 if ([database_ delocked])
9679 - (void) setConfigurationData:(NSString *)data {
9680 static RegEx conffile_r("'(.*)' '(.*)' ([01]) ([01])");
9682 if (!conffile_r(data)) {
9683 lprintf("E:invalid conffile\n");
9687 NSString *ofile = conffile_r[1];
9688 //NSString *nfile = conffile_r[2];
9690 UIAlertView *alert = [[[UIAlertView alloc]
9691 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9692 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9694 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9696 UCLocalize("ACCEPT_NEW_COPY"),
9697 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9701 [alert setContext:@"conffile"];
9702 [alert setNumberOfRows:2];
9706 - (void) addStashController {
9708 stash_ = [[[StashController alloc] init] autorelease];
9709 [window_ addSubview:[stash_ view]];
9712 - (void) removeStashController {
9713 [[stash_ view] removeFromSuperview];
9715 [self unlockSuspend];
9719 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9720 UpdateExternalStatus(1);
9721 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/cydo /usr/libexec/cydia/free.sh"];
9722 UpdateExternalStatus(0);
9724 [self removeStashController];
9726 pid_t pid(ExecFork());
9728 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9729 perror("launchctl stop");
9735 - (void) setupViewControllers {
9736 tabbar_ = [[[CydiaTabBarController alloc] initWithDatabase:database_] autorelease];
9738 NSMutableArray *items;
9739 if (kCFCoreFoundationVersionNumber < 800) {
9740 items = [NSMutableArray arrayWithObjects:
9741 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage imageNamed:@"home.png"] tag:0] autorelease],
9742 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage imageNamed:@"install.png"] tag:0] autorelease],
9743 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage imageNamed:@"changes.png"] tag:0] autorelease],
9744 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage imageNamed:@"manage.png"] tag:0] autorelease],
9745 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage imageNamed:@"search.png"] tag:0] autorelease],
9748 items = [NSMutableArray arrayWithObjects:
9749 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage imageNamed:@"home7.png"] selectedImage:[UIImage imageNamed:@"home7s.png"]] autorelease],
9750 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage imageNamed:@"install7.png"] selectedImage:[UIImage imageNamed:@"install7s.png"]] autorelease],
9751 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage imageNamed:@"changes7.png"] selectedImage:[UIImage imageNamed:@"changes7s.png"]] autorelease],
9752 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage imageNamed:@"manage7.png"] selectedImage:[UIImage imageNamed:@"manage7s.png"]] autorelease],
9753 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage imageNamed:@"search7.png"] selectedImage:[UIImage imageNamed:@"search7s.png"]] autorelease],
9757 NSMutableArray *controllers([NSMutableArray array]);
9758 for (UITabBarItem *item in items) {
9759 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9760 [controller setTabBarItem:item];
9761 [controllers addObject:controller];
9763 [tabbar_ setViewControllers:controllers];
9765 [tabbar_ setUpdateDelegate:self];
9768 - (void) _sendMemoryWarningNotification {
9769 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: maybe 4_0?
9770 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationMemoryWarningNotification" object:[UIApplication sharedApplication]];
9772 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
9775 - (void) _sendMemoryWarningNotifications {
9777 [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO];
9783 - (void) applicationDidReceiveMemoryWarning:(UIApplication *)application {
9785 [[NSURLCache sharedURLCache] removeAllCachedResponses];
9788 - (void) applicationDidFinishLaunching:(id)unused {
9789 //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil];
9792 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9793 [self setApplicationSupportsShakeToEdit:NO];
9795 @synchronized (HostConfig_) {
9796 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9799 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9800 initWithMemoryCapacity:524288
9801 diskCapacity:10485760
9802 diskPath:Cache("SDURLCache")
9805 [CydiaWebViewController _initialize];
9807 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9809 // this would disallow http{,s} URLs from accessing this data
9810 //[WebView registerURLSchemeAsLocal:@"cydia"];
9812 Font12_ = [UIFont systemFontOfSize:12];
9813 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9814 Font14_ = [UIFont systemFontOfSize:14];
9815 Font18_ = [UIFont systemFontOfSize:18];
9816 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9817 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9819 essential_ = [NSMutableArray arrayWithCapacity:4];
9820 broken_ = [NSMutableArray arrayWithCapacity:4];
9822 // XXX: I really need this thing... like, seriously... I'm sorry
9823 appcache_ = [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] autorelease];
9824 [appcache_ reloadData];
9826 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9827 [window_ orderFront:self];
9828 [window_ makeKey:self];
9829 [window_ setHidden:NO];
9832 [self addStashController];
9833 // XXX: this would be much cleaner as a yieldToSelector:
9834 // that way the removeStashController could happen right here inline
9835 // we also could no longer require the useless stash_ field anymore
9836 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9841 int error(stat("/", &root));
9842 _assert(error != -1);
9844 #define Stash_(path) do { \
9845 struct stat folder; \
9846 int error(lstat((path), &folder)); \
9847 if (error != -1 && ( \
9848 folder.st_dev == root.st_dev && \
9849 S_ISDIR(folder.st_mode) \
9850 ) || error == -1 && ( \
9851 errno == ENOENT || \
9856 Stash_("/Applications");
9857 Stash_("/Library/Ringtones");
9858 Stash_("/Library/Wallpaper");
9859 //Stash_("/usr/bin");
9860 Stash_("/usr/include");
9861 Stash_("/usr/share");
9862 //Stash_("/var/lib");
9864 database_ = [Database sharedInstance];
9865 [database_ setDelegate:self];
9867 [window_ setUserInteractionEnabled:NO];
9868 [self setupViewControllers];
9870 CydiaLoadingViewController *loading([[[CydiaLoadingViewController alloc] init] autorelease]);
9871 UINavigationController *navigation([[[UINavigationController alloc] init] autorelease]);
9872 [navigation setViewControllers:[NSArray arrayWithObject:loading]];
9874 emulated_ = [[[CyteTabBarController alloc] init] autorelease];
9875 [emulated_ setViewControllers:[NSArray arrayWithObject:navigation]];
9876 [emulated_ setSelectedIndex:0];
9878 if ([emulated_ respondsToSelector:@selector(concealTabBarSelection)])
9879 [emulated_ concealTabBarSelection];
9881 if ([window_ respondsToSelector:@selector(setRootViewController:)])
9882 [window_ setRootViewController:emulated_];
9884 [window_ addSubview:[emulated_ view]];
9886 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9890 - (NSArray *) defaultStartPages {
9891 NSMutableArray *standard = [NSMutableArray array];
9892 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9893 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9894 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9895 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9896 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9902 if ([emulated_ modalViewController] != nil)
9903 [emulated_ dismissModalViewControllerAnimated:YES];
9904 [window_ setUserInteractionEnabled:NO];
9906 [self reloadDataWithInvocation:nil];
9907 [self refreshIfPossible];
9910 NSDictionary *state([NSDictionary dictionaryWithContentsOfFile:@ SavedState_]);
9912 int savedIndex = [[state objectForKey:@"InterfaceIndex"] intValue];
9913 NSArray *saved = [[[state objectForKey:@"InterfaceState"] mutableCopy] autorelease];
9914 int standardIndex = 0;
9915 NSArray *standard = [self defaultStartPages];
9922 NSDate *closed = [state objectForKey:@"LastClosed"];
9923 if (valid && closed != nil) {
9924 NSTimeInterval interval([closed timeIntervalSinceNow]);
9925 if (interval <= -(30*60))
9929 if (valid && [saved count] != [standard count])
9933 for (unsigned int i = 0; i < [standard count]; i++) {
9934 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9935 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9936 // but it's good enough for now.
9937 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9944 NSArray *items = nil;
9946 [tabbar_ setSelectedIndex:savedIndex];
9949 [tabbar_ setSelectedIndex:standardIndex];
9953 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9954 NSArray *stack = [items objectAtIndex:tab];
9955 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9956 NSMutableArray *current = [NSMutableArray array];
9958 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9959 NSString *addr = [stack objectAtIndex:nav];
9960 NSURL *url = [NSURL URLWithString:addr];
9961 CyteViewController *page = [self pageForURL:url forExternal:NO withReferrer:nil];
9963 [current addObject:page];
9966 [navigation setViewControllers:current];
9969 // (Try to) show the startup URL.
9970 if (starturl_ != nil) {
9971 [self openCydiaURL:starturl_ forExternal:YES];
9976 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9977 if (item != nil && IsWildcat_) {
9978 [sheet showFromBarButtonItem:item animated:YES];
9980 [sheet showInView:window_];
9984 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9985 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9986 [progress setTitle:task];
9987 [progress addProgressEvent:event];
9990 - (void) addProgressEventForTask:(NSArray *)data {
9991 CydiaProgressEvent *event([data objectAtIndex:0]);
9992 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9993 [self addProgressEvent:event forTask:task];
9996 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9997 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
10003 id Alloc_(id self, SEL selector) {
10004 id object = alloc_(self, selector);
10005 lprintf("[%s]A-%p\n", self->isa->name, object);
10010 id Dealloc_(id self, SEL selector) {
10011 id object = dealloc_(self, selector);
10012 lprintf("[%s]D-%p\n", self->isa->name, object);
10016 Class $NSURLConnection;
10018 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
10019 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
10021 NSURL *url([copy URL]);
10023 NSString *host([url host]);
10024 NSString *scheme([[url scheme] lowercaseString]);
10026 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
10028 @synchronized (HostConfig_) {
10029 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
10030 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
10031 [copy setHTTPShouldUsePipelining:YES];
10033 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
10034 if ([control isEqualToString:@"max-age=0"])
10035 if ([CachedURLs_ containsObject:url]) {
10037 NSLog(@"~~~: %@", url);
10040 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
10042 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
10043 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
10044 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
10048 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
10054 static CGSize $WAKWindow$screenSize(WAKWindow *self, SEL _cmd) {
10055 CGSize size([[UIScreen mainScreen] bounds].size);
10056 /*if ([$WAKWindow respondsToSelector:@selector(hasLandscapeOrientation)])
10057 if ([$WAKWindow hasLandscapeOrientation])
10058 std::swap(size.width, size.height);*/
10062 Class $NSUserDefaults;
10064 MSHook(id, NSUserDefaults$objectForKey$, NSUserDefaults *self, SEL _cmd, NSString *key) {
10065 if ([key respondsToSelector:@selector(isEqualToString:)] && [key isEqualToString:@"WebKitLocalStorageDatabasePathPreferenceKey"])
10066 return Cache("LocalStorage");
10067 return _NSUserDefaults$objectForKey$(self, _cmd, key);
10070 int main(int argc, char *argv[]) {
10071 int fd(open("/tmp/cydia.log", O_WRONLY | O_APPEND | O_CREAT, 0644));
10075 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10079 UpdateExternalStatus(0);
10081 UIScreen *screen([UIScreen mainScreen]);
10082 if ([screen respondsToSelector:@selector(scale)])
10083 ScreenScale_ = [screen scale];
10087 UIDevice *device([UIDevice currentDevice]);
10088 if ([device respondsToSelector:@selector(userInterfaceIdiom)]) {
10089 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10090 if (idiom == UIUserInterfaceIdiomPad)
10094 Idiom_ = IsWildcat_ ? @"ipad" : @"iphone";
10096 RegEx pattern("([0-9]+\\.[0-9]+).*");
10098 if (pattern([device systemVersion]))
10099 Firmware_ = pattern[1];
10100 if (pattern(Cydia_))
10101 Major_ = pattern[1];
10103 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
10105 HostConfig_ = [[[NSObject alloc] init] autorelease];
10106 @synchronized (HostConfig_) {
10107 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10108 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
10109 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
10110 CachedURLs_ = [NSMutableSet setWithCapacity:32];
10113 NSString *ui(@"ui/ios");
10115 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
10116 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"/%@", Major_]];
10117 UI_ = CydiaURL(ui);
10119 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10121 /* Library Hacks {{{ */
10122 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10124 $WAKWindow = objc_getClass("WAKWindow");
10125 if ($WAKWindow != NULL)
10126 if (Method method = class_getInstanceMethod($WAKWindow, @selector(screenSize)))
10127 method_setImplementation(method, (IMP) &$WAKWindow$screenSize);
10129 $NSURLConnection = objc_getClass("NSURLConnection");
10130 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10131 if (NSURLConnection$init$ != NULL) {
10132 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10133 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10136 $NSUserDefaults = objc_getClass("NSUserDefaults");
10137 Method NSUserDefaults$objectForKey$(class_getInstanceMethod($NSUserDefaults, @selector(objectForKey:)));
10138 if (NSUserDefaults$objectForKey$ != NULL) {
10139 _NSUserDefaults$objectForKey$ = reinterpret_cast<id (*)(NSUserDefaults *, SEL, NSString *)>(method_getImplementation(NSUserDefaults$objectForKey$));
10140 method_setImplementation(NSUserDefaults$objectForKey$, reinterpret_cast<IMP>(&$NSUserDefaults$objectForKey$));
10143 /* Set Locale {{{ */
10144 Locale_ = CFLocaleCopyCurrent();
10145 Languages_ = [NSLocale preferredLanguages];
10147 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10148 //NSLog(@"%@", [Languages_ description]);
10151 if (Locale_ != NULL)
10152 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10153 else if (Languages_ != nil && [Languages_ count] != 0)
10154 lang = [[Languages_ objectAtIndex:0] UTF8String];
10156 // XXX: consider just setting to C and then falling through?
10159 if (lang != NULL) {
10160 RegEx pattern("([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?");
10161 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10164 NSLog(@"Setting Language: %s", lang);
10166 if (lang != NULL) {
10167 setenv("LANG", lang, true);
10168 std::setlocale(LC_ALL, lang);
10171 /* Index Collation {{{ */
10172 if (Class $UILocalizedIndexedCollation = objc_getClass("UILocalizedIndexedCollation")) { @try {
10173 NSBundle *bundle([NSBundle bundleForClass:$UILocalizedIndexedCollation]);
10174 NSString *path([bundle pathForResource:@"UITableViewLocalizedSectionIndex" ofType:@"plist"]);
10175 //path = @"/System/Library/Frameworks/UIKit.framework/.lproj/UITableViewLocalizedSectionIndex.plist";
10176 NSDictionary *dictionary([NSDictionary dictionaryWithContentsOfFile:path]);
10177 _H<UILocalizedIndexedCollation> collation([[[$UILocalizedIndexedCollation alloc] initWithDictionary:dictionary] autorelease]);
10179 CollationLocale_ = MSHookIvar<NSLocale *>(collation, "_locale");
10181 if (kCFCoreFoundationVersionNumber >= 800 && [[CollationLocale_ localeIdentifier] isEqualToString:@"zh@collation=stroke"]) {
10182 CollationThumbs_ = [NSArray arrayWithObjects:@"1",@"•",@"4",@"•",@"7",@"•",@"10",@"•",@"13",@"•",@"16",@"•",@"19",@"A",@"•",@"E",@"•",@"I",@"•",@"M",@"•",@"R",@"•",@"V",@"•",@"Z",@"#",nil];
10183 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})
10184 CollationOffset_.push_back(offset);
10185 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];
10186 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];
10189 CollationThumbs_ = [collation sectionIndexTitles];
10190 for (size_t index(0), end([CollationThumbs_ count]); index != end; ++index)
10191 CollationOffset_.push_back([collation sectionForSectionIndexTitleAtIndex:index]);
10193 CollationTitles_ = [collation sectionTitles];
10194 CollationStarts_ = MSHookIvar<NSArray *>(collation, "_sectionStartStrings");
10196 NSString *&transform(MSHookIvar<NSString *>(collation, "_transform"));
10197 if (&transform != NULL && transform != nil) {
10198 /*if ([collation respondsToSelector:@selector(transformedCollationStringForString:)])
10199 CollationModify_ = [=](NSString *value) { return [collation transformedCollationStringForString:value]; };*/
10200 const UChar *uid(reinterpret_cast<const UChar *>([transform cStringUsingEncoding:NSUnicodeStringEncoding]));
10201 UErrorCode code(U_ZERO_ERROR);
10202 CollationTransl_ = utrans_openU(uid, -1, UTRANS_FORWARD, NULL, 0, NULL, &code);
10203 if (!U_SUCCESS(code))
10204 NSLog(@"%s", u_errorName(code));
10208 } @catch (NSException *e) {
10212 CollationLocale_ = [[[NSLocale alloc] initWithLocaleIdentifier:@"en@collation=dictionary"] autorelease];
10214 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];
10215 for (NSInteger offset(0); offset != 28; ++offset)
10216 CollationOffset_.push_back(offset);
10218 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];
10219 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];
10222 /* Parse Arguments {{{ */
10223 bool substrate(false);
10229 for (int argi(1); argi != argc; ++argi)
10230 if (strcmp(argv[argi], "--") == 0) {
10232 argv[argi] = argv[0];
10238 for (int argi(1); argi != arge; ++argi)
10239 if (strcmp(args[argi], "--substrate") == 0)
10242 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10246 App_ = [[NSBundle mainBundle] bundlePath];
10249 Cache_ = [[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia", @"/var/mobile"] retain];
10251 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10252 alloc_ = alloc->method_imp;
10253 alloc->method_imp = (IMP) &Alloc_;*/
10255 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10256 dealloc_ = dealloc->method_imp;
10257 dealloc->method_imp = (IMP) &Dealloc_;*/
10259 void *gestalt(dlopen("/usr/lib/libMobileGestalt.dylib", RTLD_GLOBAL | RTLD_LAZY));
10260 $MGCopyAnswer = reinterpret_cast<CFStringRef (*)(CFStringRef)>(dlsym(gestalt, "MGCopyAnswer"));
10262 /* System Information {{{ */
10266 size = sizeof(maxproc);
10267 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10268 perror("sysctlbyname(\"kern.maxproc\", ?)");
10269 else if (maxproc < 64) {
10271 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10272 perror("sysctlbyname(\"kern.maxproc\", #)");
10275 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10276 char *osversion = new char[size];
10277 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10278 perror("sysctlbyname(\"kern.osversion\", ?)");
10280 System_ = [NSString stringWithUTF8String:osversion];
10282 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10283 char *machine = new char[size];
10284 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10285 perror("sysctlbyname(\"hw.machine\", ?)");
10287 Machine_ = machine;
10289 int64_t usermem(0);
10290 size = sizeof(usermem);
10291 if (sysctlbyname("hw.usermem", &usermem, &size, NULL, 0) == -1)
10294 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10295 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10296 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10298 UniqueID_ = UniqueIdentifier(device);
10300 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10301 Product_ = [info objectForKey:@"SafariProductVersion"];
10302 Safari_ = [info objectForKey:@"CFBundleVersion"];
10305 NSString *agent([NSString stringWithFormat:@"Cydia/%@ CyF/%.2f", Cydia_, kCFCoreFoundationVersionNumber]);
10307 if (RegEx match = RegEx("([0-9]+(\\.[0-9]+)+).*", Safari_))
10308 agent = [NSString stringWithFormat:@"Safari/%@ %@", match[1], agent];
10309 if (RegEx match = RegEx("([0-9]+[A-Z][0-9]+[a-z]?).*", System_))
10310 agent = [NSString stringWithFormat:@"Mobile/%@ %@", match[1], agent];
10311 if (RegEx match = RegEx("([0-9]+(\\.[0-9]+)+).*", Product_))
10312 agent = [NSString stringWithFormat:@"Version/%@ %@", match[1], agent];
10314 UserAgent_ = agent;
10316 /* Load Database {{{ */
10317 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10320 mkdir("/var/mobile/Library/Cydia", 0755);
10321 MetaFile_.Open("/var/mobile/Library/Cydia/metadata.cb0");
10324 // XXX: port this to NSUserDefaults when you aren't in such a rush
10325 Values_ = [[[(NSDictionary *) CFPreferencesCopyAppValue(CFSTR("CydiaValues"), CFSTR("com.saurik.Cydia")) autorelease] mutableCopy] autorelease];
10326 Sections_ = [[[(NSDictionary *) CFPreferencesCopyAppValue(CFSTR("CydiaSections"), CFSTR("com.saurik.Cydia")) autorelease] mutableCopy] autorelease];
10327 Sources_ = [[[(NSDictionary *) CFPreferencesCopyAppValue(CFSTR("CydiaSources"), CFSTR("com.saurik.Cydia")) autorelease] mutableCopy] autorelease];
10328 Version_ = [(NSNumber *) CFPreferencesCopyAppValue(CFSTR("CydiaVersion"), CFSTR("com.saurik.Cydia")) autorelease];
10331 NSDictionary *metadata([[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease]);
10333 if (Values_ == nil)
10334 Values_ = [metadata objectForKey:@"Values"];
10335 if (Values_ == nil)
10336 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10338 if (Sections_ == nil)
10339 Sections_ = [metadata objectForKey:@"Sections"];
10340 if (Sections_ == nil)
10341 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10343 if (Sources_ == nil)
10344 Sources_ = [metadata objectForKey:@"Sources"];
10345 if (Sources_ == nil)
10346 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10348 // XXX: this wrong, but in a way that doesn't matter :/
10349 if (Version_ == nil)
10350 Version_ = [metadata objectForKey:@"Version"];
10351 if (Version_ == nil)
10352 Version_ = [NSNumber numberWithUnsignedInt:0];
10354 if (NSDictionary *packages = [metadata objectForKey:@"Packages"]) {
10356 CFDictionaryApplyFunction((CFDictionaryRef) packages, &PackageImport, &fail);
10359 NSLog(@"unable to import package preferences... from 2010? oh well :/");
10362 if ([Version_ unsignedIntValue] == 0) {
10363 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10364 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10365 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10366 CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./");
10368 Version_ = [NSNumber numberWithUnsignedInt:1];
10370 if (NSMutableDictionary *cache = [NSMutableDictionary dictionaryWithContentsOfFile:@ CacheState_]) {
10371 [cache removeObjectForKey:@"LastUpdate"];
10372 [cache writeToFile:@ CacheState_ atomically:YES];
10376 _H<NSMutableArray> broken([NSMutableArray array]);
10377 for (NSString *key in (id) Sources_)
10378 if ([key rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"# "]].location != NSNotFound)
10379 [broken addObject:key];
10380 if ([broken count] != 0)
10381 for (NSString *key in (id) broken)
10382 [Sources_ removeObjectForKey:key];
10386 system("/usr/libexec/cydia/cydo /bin/rm -f /var/lib/cydia/metadata.plist");
10389 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10391 if (kCFCoreFoundationVersionNumber > 1000)
10392 system("/usr/libexec/cydia/cydo /usr/libexec/cydia/setnsfpn /var/lib");
10394 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10396 if (access("/User", F_OK) != 0 || version != 6) {
10398 system("/usr/libexec/cydia/cydo /usr/libexec/cydia/firmware.sh");
10402 if (access("/tmp/cydia.chk", F_OK) == 0) {
10403 if (unlink([Cache("pkgcache.bin") UTF8String]) == -1)
10404 _assert(errno == ENOENT);
10405 if (unlink([Cache("srcpkgcache.bin") UTF8String]) == -1)
10406 _assert(errno == ENOENT);
10409 /* APT Initialization {{{ */
10410 _assert(pkgInitConfig(*_config));
10411 _assert(pkgInitSystem(*_config, _system));
10414 _config->Set("APT::Acquire::Translation", lang);
10416 // XXX: this timeout might be important :(
10417 //_config->Set("Acquire::http::Timeout", 15);
10419 _config->Set("Acquire::http::MaxParallel", usermem >= 384 * 1024 * 1024 ? 16 : 3);
10421 mkdir([Cache_ UTF8String], 0755);
10422 mkdir([Cache("archives") UTF8String], 0755);
10423 mkdir([Cache("archives/partial") UTF8String], 0755);
10424 _config->Set("Dir::Cache", [Cache_ UTF8String]);
10426 symlink("/var/lib/apt/extended_states", [Cache("extended_states") UTF8String]);
10427 _config->Set("Dir::State", [Cache_ UTF8String]);
10429 mkdir([Cache("lists") UTF8String], 0755);
10430 mkdir([Cache("lists/partial") UTF8String], 0755);
10431 mkdir([Cache("periodic") UTF8String], 0755);
10432 _config->Set("Dir::State::Lists", [Cache("lists") UTF8String]);
10434 std::string logs("/var/mobile/Library/Logs/Cydia");
10435 mkdir(logs.c_str(), 0755);
10436 _config->Set("Dir::Log::Terminal", logs + "/apt.log");
10438 _config->Set("Dir::Bin::dpkg", "/usr/libexec/cydia/cydo");
10440 /* Color Choices {{{ */
10441 space_ = CGColorSpaceCreateDeviceRGB();
10443 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10444 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10445 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10446 Folder_.Set(space_, 0x8e/255.f, 0x8e/255.f, 0x93/255.f, 1.0);
10447 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10448 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10449 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10450 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10451 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10452 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10454 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10455 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10457 /* UIKit Configuration {{{ */
10458 // XXX: I have a feeling this was important
10459 //UIKeyboardDisableAutomaticAppearance();
10462 $SBSSetInterceptsMenuButtonForever = reinterpret_cast<void (*)(bool)>(dlsym(RTLD_DEFAULT, "SBSSetInterceptsMenuButtonForever"));
10464 const char *symbol(kCFCoreFoundationVersionNumber >= 800 ? "MGGetBoolAnswer" : "GSSystemHasCapability");
10465 BOOL (*GSSystemHasCapability)(CFStringRef) = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, symbol));
10466 bool fast = GSSystemHasCapability != NULL && GSSystemHasCapability(CFSTR("armv7"));
10468 PulseInterval_ = fast ? 50000 : 500000;
10470 Colon_ = UCLocalize("COLON_DELIMITED");
10471 Elision_ = UCLocalize("ELISION");
10472 Error_ = UCLocalize("ERROR");
10473 Warning_ = UCLocalize("WARNING");
10476 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10478 CGColorSpaceRelease(space_);
10479 CFRelease(Locale_);