1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2014 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 <apr-1/apr_pools.h>
88 #include <sys/types.h>
90 #include <sys/sysctl.h>
91 #include <sys/param.h>
92 #include <sys/mount.h>
93 #include <sys/reboot.h>
100 #include <mach-o/nlist.h>
109 #include <Cytore.hpp>
112 #include <CydiaSubstrate/CydiaSubstrate.h>
113 #include "Menes/Menes.h"
115 #include "CyteKit/IndirectDelegate.h"
116 #include "CyteKit/PerlCompatibleRegEx.hpp"
117 #include "CyteKit/TableViewCell.h"
118 #include "CyteKit/TabBarController.h"
119 #include "CyteKit/WebScriptObject-Cyte.h"
120 #include "CyteKit/WebViewController.h"
121 #include "CyteKit/WebViewTableViewCell.h"
122 #include "CyteKit/stringWithUTF8Bytes.h"
124 #include "Cydia/MIMEAddress.h"
125 #include "Cydia/LoadingViewController.h"
126 #include "Cydia/ProgressEvent.h"
128 #include "SDURLCache/SDURLCache.h"
135 #define _timestamp ({ \
137 gettimeofday(&tv, NULL); \
138 tv.tv_sec * 1000000 + tv.tv_usec; \
141 typedef std::vector<class ProfileTime *> TimeList;
151 ProfileTime(const char *name) :
155 times_.push_back(this);
158 void AddTime(uint64_t time) {
165 std::cerr << std::setw(7) << count_ << ", " << std::setw(8) << total_ << " : " << name_ << std::endl;
177 ProfileTimer(ProfileTime &time) :
184 time_.AddTime(_timestamp - start_);
189 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
191 std::cerr << "========" << std::endl;
194 #define _profile(name) { \
195 static ProfileTime name(#name); \
196 ProfileTimer _ ## name(name);
201 // XXX: I hate clang. Apple: please get over your petty hatred of GPL and fix your gcc fork
202 #define synchronized(lock) \
203 synchronized(static_cast<NSObject *>(lock))
205 extern NSString *Cydia_;
207 #define lprintf(args...) fprintf(stderr, args)
210 #define TraceLogging (1 && !ForRelease)
211 #define HistogramInsertionSort (0 && !ForRelease)
212 #define ProfileTimes (0 && !ForRelease)
213 #define ForSaurik (0 && !ForRelease)
214 #define LogBrowser (0 && !ForRelease)
215 #define TrackResize (0 && !ForRelease)
216 #define ManualRefresh (1 && !ForRelease)
217 #define ShowInternals (0 && !ForRelease)
218 #define AlwaysReload (0 && !ForRelease)
222 #define _trace(args...)
227 #define _profile(name) {
230 #define PrintTimes() do {} while (false)
233 // Hash Functions/Structures {{{
234 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
242 static void setreugid(uid_t uid, gid_t gid) {
243 _assert(setreuid(uid, uid) != -1);
244 _assert(setregid(gid, gid) != -1);
247 static void setreguid(gid_t gid, uid_t uid) {
248 _assert(setregid(gid, gid) != -1);
249 _assert(setreuid(uid, uid) != -1);
256 _assert(pthread_setugid_np(0, 0) != -1);
263 _assert(pthread_setugid_np(KAUTH_UID_NONE, KAUTH_GID_NONE) != -1);
268 #define _root(code) \
269 ({ Root _root; code; })
271 static NSString *Colon_;
273 static NSString *Error_;
274 static NSString *Warning_;
276 static NSString *Cache_;
277 #define Cache(file) \
278 [NSString stringWithFormat:@"%@/%s", Cache_, file]
280 static void (*$SBSSetInterceptsMenuButtonForever)(bool);
282 static CFStringRef (*$MGCopyAnswer)(CFStringRef);
284 static NSString *UniqueIdentifier(UIDevice *device = nil) {
285 if (kCFCoreFoundationVersionNumber < 800) // iOS 7.x
286 return [device ?: [UIDevice currentDevice] uniqueIdentifier];
288 return [(id)$MGCopyAnswer(CFSTR("UniqueDeviceID")) autorelease];
291 static bool IsReachable(const char *name) {
292 SCNetworkReachabilityFlags flags; {
293 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, name));
294 SCNetworkReachabilityGetFlags(reachability, &flags);
295 CFRelease(reachability);
298 // XXX: this elaborate mess is what Apple is using to determine this? :(
299 // XXX: do we care if the user has to intervene? maybe that's ok?
301 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
302 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
303 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
304 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
305 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
306 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
311 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
313 static _finline NSString *CydiaURL(NSString *path) {
315 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
316 page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
317 page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
318 page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
319 page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
321 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
324 static void ReapZombie(pid_t pid) {
327 if (waitpid(pid, &status, 0) == -1)
333 static _finline void UpdateExternalStatus(uint64_t newStatus) {
335 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
336 notify_set_state(notify_token, newStatus);
337 notify_cancel(notify_token);
339 notify_post("com.saurik.Cydia.status");
342 static CGFloat CYStatusBarHeight() {
343 CGSize size([[UIApplication sharedApplication] statusBarFrame].size);
344 return UIInterfaceOrientationIsPortrait([[UIApplication sharedApplication] statusBarOrientation]) ? size.height : size.width;
347 /* NSForcedOrderingSearch doesn't work on the iPhone */
348 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
349 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
350 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
352 /* Insertion Sort {{{ */
354 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
355 const char *ptr = (const char *)list;
357 CFIndex half = count / 2;
358 const char *probe = ptr + elementSize * half;
359 CFComparisonResult cr = comparator(element, probe, context);
360 if (0 == cr) return (probe - (const char *)list) / elementSize;
361 ptr = (cr < 0) ? ptr : probe + elementSize;
362 count = (cr < 0) ? half : (half + (count & 1) - 1);
364 return (ptr - (const char *)list) / elementSize;
367 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
368 const char *ptr = (const char *)list;
370 CFIndex half = count / 2;
371 const char *probe = ptr + elementSize * half;
372 CFComparisonResult cr = comparator(element, probe, context);
373 if (0 == cr) return (probe - (const char *)list) / elementSize;
374 ptr = (cr < 0) ? ptr : probe + elementSize;
375 count = (cr < 0) ? half : (half + (count & 1) - 1);
377 return (ptr - (const char *)list) / elementSize;
380 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
381 if (range.length == 0)
383 const void **values(new const void *[range.length]);
384 CFArrayGetValues(array, range, values);
386 #if HistogramInsertionSort > 0
387 uint32_t total(0), *offsets(new uint32_t[range.length]);
390 for (CFIndex index(1); index != range.length; ++index) {
391 const void *value(values[index]);
392 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
393 CFIndex correct(index);
394 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
395 #if HistogramInsertionSort > 1
396 NSLog(@"%@ < %@", value, values[correct - 1]);
401 if (correct != index) {
402 size_t offset(index - correct);
403 #if HistogramInsertionSort
407 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
409 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
410 values[correct] = value;
414 CFArrayReplaceValues(array, range, values, range.length);
417 #if HistogramInsertionSort > 0
418 for (CFIndex index(0); index != range.length; ++index)
419 if (offsets[index] != 0)
420 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
421 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
428 /* Apple Bug Fixes {{{ */
429 @implementation UIWebDocumentView (Cydia)
431 - (void) _setScrollerOffset:(CGPoint)offset {
432 UIScroller *scroller([self _scroller]);
434 CGSize size([scroller contentSize]);
435 CGSize bounds([scroller bounds].size);
438 max.x = size.width - bounds.width;
439 max.y = size.height - bounds.height;
447 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
448 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
450 [scroller setOffset:offset];
456 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
457 size_t length([self length] - state->state);
460 else if (length > count)
462 for (size_t i(0); i != length; ++i)
463 objects[i] = [self item:state->state++];
464 state->itemsPtr = objects;
465 state->mutationsPtr = (unsigned long *) self;
469 /* Cydia NSString Additions {{{ */
470 @interface NSString (Cydia)
471 - (NSComparisonResult) compareByPath:(NSString *)other;
472 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
475 @implementation NSString (Cydia)
477 - (NSComparisonResult) compareByPath:(NSString *)other {
478 NSString *prefix = [self commonPrefixWithString:other options:0];
479 size_t length = [prefix length];
481 NSRange lrange = NSMakeRange(length, [self length] - length);
482 NSRange rrange = NSMakeRange(length, [other length] - length);
484 lrange = [self rangeOfString:@"/" options:0 range:lrange];
485 rrange = [other rangeOfString:@"/" options:0 range:rrange];
487 NSComparisonResult value;
489 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
490 value = NSOrderedSame;
491 else if (lrange.location == NSNotFound)
492 value = NSOrderedAscending;
493 else if (rrange.location == NSNotFound)
494 value = NSOrderedDescending;
496 value = NSOrderedSame;
498 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
499 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
500 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
501 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
503 NSComparisonResult result = [lpath compare:rpath];
504 return result == NSOrderedSame ? value : result;
507 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
508 return [(id)CFURLCreateStringByAddingPercentEscapes(
513 kCFStringEncodingUTF8
520 /* C++ NSString Wrapper Cache {{{ */
521 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
522 return size == 0 ? NULL :
523 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
524 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
527 static _finline CFStringRef CYStringCreate(const char *data) {
528 return CYStringCreate(data, strlen(data));
537 _finline void clear_() {
538 if (cache_ != NULL) {
545 _finline bool empty() const {
549 _finline size_t size() const {
553 _finline char *data() const {
557 _finline void clear() {
562 _finline CYString() :
569 _finline ~CYString() {
573 void operator =(const CYString &rhs) {
577 if (rhs.cache_ == nil)
580 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
583 void copy(apr_pool_t *pool) {
584 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
585 memcpy(temp, data_, size_);
590 void set(apr_pool_t *pool, const char *data, size_t size) {
596 data_ = const_cast<char *>(data);
604 _finline void set(apr_pool_t *pool, const char *data) {
605 set(pool, data, data == NULL ? 0 : strlen(data));
608 _finline void set(apr_pool_t *pool, const std::string &rhs) {
609 set(pool, rhs.data(), rhs.size());
612 bool operator ==(const CYString &rhs) const {
613 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
616 _finline operator CFStringRef() {
618 cache_ = CYStringCreate(data_, size_);
622 _finline operator id() {
623 return (NSString *) static_cast<CFStringRef>(*this);
626 _finline operator const char *() {
627 return reinterpret_cast<const char *>(data_);
631 /* C++ NSString Algorithm Adapters {{{ */
633 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
636 struct NSStringMapHash :
637 std::unary_function<NSString *, size_t>
639 _finline size_t operator ()(NSString *value) const {
640 return CFStringHashNSString((CFStringRef) value);
644 struct NSStringMapLess :
645 std::binary_function<NSString *, NSString *, bool>
647 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
648 return [lhs compare:rhs] == NSOrderedAscending;
652 struct NSStringMapEqual :
653 std::binary_function<NSString *, NSString *, bool>
655 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
656 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
657 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
658 //[lhs isEqualToString:rhs];
663 /* CoreGraphics Primitives {{{ */
668 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
669 CGFloat color[] = {red, green, blue, alpha};
670 return CGColorCreate(space, color);
679 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
680 color_(Create_(space, red, green, blue, alpha))
682 Set(space, red, green, blue, alpha);
687 CGColorRelease(color_);
694 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
696 color_ = Create_(space, red, green, blue, alpha);
699 operator CGColorRef() {
705 /* Random Global Variables {{{ */
706 static int PulseInterval_ = 500000;
708 static const NSString *UI_;
711 static bool RestartSubstrate_;
712 static bool UpgradeCydia_;
713 static NSArray *Finishes_;
715 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
716 #define NotifyConfig_ "/etc/notify.conf"
718 static bool Queuing_;
720 static CYColor Blue_;
721 static CYColor Blueish_;
722 static CYColor Black_;
723 static CYColor Folder_;
725 static CYColor White_;
726 static CYColor Gray_;
727 static CYColor Green_;
728 static CYColor Purple_;
729 static CYColor Purplish_;
731 static UIColor *InstallingColor_;
732 static UIColor *RemovingColor_;
734 static NSString *App_;
736 static BOOL Advanced_;
737 static BOOL Ignored_;
739 static _H<UIFont> Font12_;
740 static _H<UIFont> Font12Bold_;
741 static _H<UIFont> Font14_;
742 static _H<UIFont> Font18_;
743 static _H<UIFont> Font18Bold_;
744 static _H<UIFont> Font22Bold_;
746 static const char *Machine_ = NULL;
747 static _H<NSString> System_;
748 static NSString *SerialNumber_ = nil;
749 static NSString *ChipID_ = nil;
750 static NSString *BBSNum_ = nil;
751 static _H<NSString> Token_;
752 static _H<NSString> UniqueID_;
753 static _H<NSString> UserAgent_;
754 static _H<NSString> Product_;
755 static _H<NSString> Safari_;
757 static _H<NSLocale> CollationLocale_;
758 static _H<NSArray> CollationThumbs_;
759 static std::vector<NSInteger> CollationOffset_;
760 static _H<NSArray> CollationTitles_;
761 static _H<NSArray> CollationStarts_;
762 static UTransliterator *CollationTransl_;
763 //static Function<NSString *, NSString *> CollationModify_;
765 typedef std::basic_string<UChar> ustring;
766 static ustring CollationString_;
768 #define CUC const ustring &str(*reinterpret_cast<const ustring *>(rep))
769 #define UC ustring &str(*reinterpret_cast<ustring *>(rep))
770 static struct UReplaceableCallbacks CollationUCalls_ = {
771 .length = [](const UReplaceable *rep) -> int32_t { CUC;
775 .charAt = [](const UReplaceable *rep, int32_t offset) -> UChar { CUC;
776 //fprintf(stderr, "charAt(%d) : %d\n", offset, str.size());
777 if (offset >= str.size())
782 .char32At = [](const UReplaceable *rep, int32_t offset) -> UChar32 { CUC;
783 //fprintf(stderr, "char32At(%d) : %d\n", offset, str.size());
784 if (offset >= str.size())
787 U16_GET(str.data(), 0, offset, str.size(), c);
791 .replace = [](UReplaceable *rep, int32_t start, int32_t limit, const UChar *text, int32_t length) -> void { UC;
792 //fprintf(stderr, "replace(%d, %d, %d) : %d\n", start, limit, length, str.size());
793 str.replace(start, limit - start, text, length);
796 .extract = [](UReplaceable *rep, int32_t start, int32_t limit, UChar *dst) -> void { UC;
797 //fprintf(stderr, "extract(%d, %d) : %d\n", start, limit, str.size());
798 str.copy(dst, limit - start, start);
801 .copy = [](UReplaceable *rep, int32_t start, int32_t limit, int32_t dest) -> void { UC;
802 //fprintf(stderr, "copy(%d, %d, %d) : %d\n", start, limit, dest, str.size());
803 str.replace(dest, 0, str, start, limit - start);
807 static CFLocaleRef Locale_;
808 static NSArray *Languages_;
809 static CGColorSpaceRef space_;
811 static NSDictionary *SectionMap_;
812 static NSMutableDictionary *Metadata_;
813 static _transient NSMutableDictionary *Settings_;
814 static _transient NSMutableDictionary *Packages_;
815 static _transient NSMutableDictionary *Values_;
816 static _transient NSMutableDictionary *Sections_;
817 _H<NSMutableDictionary> Sources_;
818 static _transient NSNumber *Version_;
823 CGFloat ScreenScale_;
824 static NSString *Idiom_;
825 static _H<NSString> Firmware_;
826 static NSString *Major_;
828 static _H<NSMutableDictionary> SessionData_;
829 static _H<NSObject> HostConfig_;
830 static _H<NSMutableSet> BridgedHosts_;
831 static _H<NSMutableSet> TokenHosts_;
832 static _H<NSMutableSet> InsecureHosts_;
833 static _H<NSMutableSet> PipelinedHosts_;
834 static _H<NSMutableSet> CachedURLs_;
836 static NSString *kCydiaProgressEventTypeError = @"Error";
837 static NSString *kCydiaProgressEventTypeInformation = @"Information";
838 static NSString *kCydiaProgressEventTypeStatus = @"Status";
839 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
842 /* Display Helpers {{{ */
843 inline float Interpolate(float begin, float end, float fraction) {
844 return (end - begin) * fraction + begin;
847 static inline double Retina(double value) {
848 value *= ScreenScale_;
849 value = round(value);
850 value /= ScreenScale_;
854 static inline CGRect Retina(CGRect value) {
855 value.origin.x *= ScreenScale_;
856 value.origin.y *= ScreenScale_;
857 value.size.width *= ScreenScale_;
858 value.size.height *= ScreenScale_;
859 value = CGRectIntegral(value);
860 value.origin.x /= ScreenScale_;
861 value.origin.y /= ScreenScale_;
862 value.size.width /= ScreenScale_;
863 value.size.height /= ScreenScale_;
867 static _finline const char *StripVersion_(const char *version) {
868 const char *colon(strchr(version, ':'));
869 return colon == NULL ? version : colon + 1;
872 NSString *LocalizeSection(NSString *section) {
873 static Pcre title_r("^(.*?) \\((.*)\\)$");
874 if (title_r(section)) {
875 NSString *parent(title_r[1]);
876 NSString *child(title_r[2]);
878 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
879 LocalizeSection(parent),
880 LocalizeSection(child)
884 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
887 NSString *Simplify(NSString *title) {
888 const char *data = [title UTF8String];
889 size_t size = [title lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
891 static Pcre square_r("^\\[(.*)\\]$");
892 if (square_r(data, size))
893 return Simplify(square_r[1]);
895 static Pcre paren_r("^\\((.*)\\)$");
896 if (paren_r(data, size))
897 return Simplify(paren_r[1]);
899 static Pcre title_r("^(.*?) \\((.*)\\)$");
900 if (title_r(data, size))
901 return Simplify(title_r[1]);
907 NSString *GetLastUpdate() {
908 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
911 return UCLocalize("NEVER_OR_UNKNOWN");
913 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
914 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
916 CFRelease(formatter);
918 return [(NSString *) formatted autorelease];
921 bool isSectionVisible(NSString *section) {
922 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
923 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
924 return hidden == nil || ![hidden boolValue];
927 static NSObject *CYIOGetValue(const char *path, NSString *property) {
928 io_registry_entry_t entry(IORegistryEntryFromPath(kIOMasterPortDefault, path));
929 if (entry == MACH_PORT_NULL)
932 CFTypeRef value(IORegistryEntryCreateCFProperty(entry, (CFStringRef) property, kCFAllocatorDefault, 0));
933 IOObjectRelease(entry);
937 return [(id) value autorelease];
940 static NSString *CYHex(NSData *data, bool reverse = false) {
944 size_t length([data length]);
945 uint8_t bytes[length];
946 [data getBytes:bytes];
948 char string[length * 2 + 1];
949 for (size_t i(0); i != length; ++i)
950 sprintf(string + i * 2, "%.2x", bytes[reverse ? length - i - 1 : i]);
952 return [NSString stringWithUTF8String:string];
957 /* Delegate Prototypes {{{ */
960 @class CydiaProgressEvent;
962 @protocol DatabaseDelegate
963 - (void) repairWithSelector:(SEL)selector;
964 - (void) setConfigurationData:(NSString *)data;
965 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
968 @class CYPackageController;
970 @protocol SourceDelegate
971 - (void) setFetch:(NSNumber *)fetch;
974 @protocol FetchDelegate
975 - (bool) isSourceCancelled;
976 - (void) startSourceFetch:(NSString *)uri;
977 - (void) stopSourceFetch:(NSString *)uri;
980 @protocol CydiaDelegate
981 - (void) returnToCydia;
983 - (void) retainNetworkActivityIndicator;
984 - (void) releaseNetworkActivityIndicator;
985 - (void) clearPackage:(Package *)package;
986 - (void) installPackage:(Package *)package;
987 - (void) installPackages:(NSArray *)packages;
988 - (void) removePackage:(Package *)package;
989 - (void) beginUpdate;
991 - (bool) requestUpdate;
992 - (void) distUpgrade;
995 - (void) _saveConfig;
997 - (void) addSource:(NSDictionary *)source;
998 - (void) addTrivialSource:(NSString *)href;
999 - (UIProgressHUD *) addProgressHUD;
1000 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1001 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
1002 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1006 /* CancelStatus {{{ */
1007 class CancelStatus :
1008 public pkgAcquireStatus
1019 virtual bool MediaChange(std::string media, std::string drive) {
1023 virtual void IMSHit(pkgAcquire::ItemDesc &desc) {
1027 virtual bool Pulse_(pkgAcquire *Owner) = 0;
1029 virtual bool Pulse(pkgAcquire *Owner) {
1030 if (pkgAcquireStatus::Pulse(Owner) && Pulse_(Owner))
1038 _finline bool WasCancelled() const {
1043 /* DelegateStatus {{{ */
1048 _transient NSObject<ProgressDelegate> *delegate_;
1056 void setDelegate(NSObject<ProgressDelegate> *delegate) {
1057 delegate_ = delegate;
1060 virtual void Fetch(pkgAcquire::ItemDesc &desc) {
1061 NSString *name([NSString stringWithUTF8String:desc.ShortDesc.c_str()]);
1062 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItemDesc:desc]);
1063 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1066 virtual void Done(pkgAcquire::ItemDesc &desc) {
1067 NSString *name([NSString stringWithUTF8String:desc.ShortDesc.c_str()]);
1068 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:Colon_, UCLocalize("DONE"), name] ofType:kCydiaProgressEventTypeStatus forItemDesc:desc]);
1069 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1072 virtual void Fail(pkgAcquire::ItemDesc &desc) {
1074 desc.Owner->Status == pkgAcquire::Item::StatIdle ||
1075 desc.Owner->Status == pkgAcquire::Item::StatDone
1079 std::string &error(desc.Owner->ErrorText);
1083 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItemDesc:desc]);
1084 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1087 virtual bool Pulse_(pkgAcquire *Owner) {
1089 double(CurrentBytes + CurrentItems) /
1090 double(TotalBytes + TotalItems)
1093 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
1094 [NSNumber numberWithDouble:percent], @"Percent",
1096 [NSNumber numberWithDouble:CurrentBytes], @"Current",
1097 [NSNumber numberWithDouble:TotalBytes], @"Total",
1098 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
1099 nil] waitUntilDone:YES];
1101 return ![delegate_ isProgressCancelled];
1104 virtual void Start() {
1105 pkgAcquireStatus::Start();
1106 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
1109 virtual void Stop() {
1110 pkgAcquireStatus::Stop();
1111 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
1112 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
1116 /* Database Interface {{{ */
1117 typedef std::map< unsigned long, _H<Source> > SourceMap;
1119 @interface Database : NSObject {
1125 pkgCacheFile cache_;
1126 pkgDepCache::Policy *policy_;
1127 pkgRecords *records_;
1128 pkgProblemResolver *resolver_;
1129 pkgAcquire *fetcher_;
1131 SPtr<pkgPackageManager> manager_;
1132 pkgSourceList *list_;
1134 SourceMap sourceMap_;
1135 _H<NSMutableArray> sourceList_;
1137 CFMutableArrayRef packages_;
1139 _transient NSObject<DatabaseDelegate> *delegate_;
1140 _transient NSObject<ProgressDelegate> *progress_;
1142 CydiaStatus status_;
1148 std::map<const char *, _H<NSString> > sections_;
1151 + (Database *) sharedInstance;
1154 - (void) _readCydia:(NSNumber *)fd;
1155 - (void) _readStatus:(NSNumber *)fd;
1156 - (void) _readOutput:(NSNumber *)fd;
1160 - (Package *) packageWithName:(NSString *)name;
1162 - (pkgCacheFile &) cache;
1163 - (pkgDepCache::Policy *) policy;
1164 - (pkgRecords *) records;
1165 - (pkgProblemResolver *) resolver;
1166 - (pkgAcquire &) fetcher;
1167 - (pkgSourceList &) list;
1168 - (NSArray *) packages;
1169 - (NSArray *) sources;
1170 - (Source *) sourceWithKey:(NSString *)key;
1171 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1179 - (void) updateWithStatus:(CancelStatus &)status;
1181 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1183 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1184 - (NSObject<ProgressDelegate> *) progressDelegate;
1186 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1187 - (void) setFetch:(bool)fetch forURI:(const char *)uri;
1188 - (void) resetFetch;
1190 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1194 /* SourceStatus {{{ */
1195 class SourceStatus :
1199 _transient NSObject<FetchDelegate> *delegate_;
1200 _transient Database *database_;
1201 std::set<std::string> fetches_;
1204 SourceStatus(NSObject<FetchDelegate> *delegate, Database *database) :
1205 delegate_(delegate),
1210 void Set(bool fetch, const std::string &uri) {
1212 if (!fetches_.insert(uri).second)
1215 if (fetches_.erase(uri) == 0)
1219 //printf("Set(%s, %s)\n", fetch ? "true" : "false", uri.c_str());
1220 [database_ setFetch:fetch forURI:uri.c_str()];
1223 _finline void Set(bool fetch, pkgAcquire::Item *item) {
1224 /*unsigned long ID(fetch ? 1 : 0);
1228 Set(fetch, item->DescURI());
1231 void Log(const char *tag, pkgAcquire::Item *item) {
1232 //printf("%s(%s) S:%u Q:%u\n", tag, item->DescURI().c_str(), item->Status, item->QueueCounter);
1235 virtual void Fetch(pkgAcquire::ItemDesc &desc) {
1236 Log("Fetch", desc.Owner);
1237 Set(true, desc.Owner);
1240 virtual void Done(pkgAcquire::ItemDesc &desc) {
1241 Log("Done", desc.Owner);
1242 Set(false, desc.Owner);
1245 virtual void Fail(pkgAcquire::ItemDesc &desc) {
1246 Log("Fail", desc.Owner);
1247 Set(false, desc.Owner);
1250 virtual bool Pulse_(pkgAcquire *Owner) {
1251 std::set<std::string> fetches;
1252 for (pkgAcquire::ItemCIterator item(Owner->ItemsBegin()); item != Owner->ItemsEnd(); ++item) {
1254 if ((*item)->QueueCounter == 0)
1256 else switch ((*item)->Status) {
1257 case pkgAcquire::Item::StatFetching:
1258 fetches.insert((*item)->DescURI());
1267 Log(fetch ? "Pulse<true>" : "Pulse<false>", *item);
1271 std::vector<std::string> stops;
1272 std::set_difference(fetches_.begin(), fetches_.end(), fetches.begin(), fetches.end(), std::back_insert_iterator<std::vector<std::string>>(stops));
1273 for (std::vector<std::string>::const_iterator stop(stops.begin()); stop != stops.end(); ++stop) {
1274 //printf("Stop(%s)\n", stop->c_str());
1278 return ![delegate_ isSourceCancelled];
1281 virtual void Stop() {
1282 pkgAcquireStatus::Stop();
1283 [database_ resetFetch];
1287 /* ProgressEvent Implementation {{{ */
1288 @implementation CydiaProgressEvent
1290 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1291 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1294 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1295 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1296 [event setPackage:package];
1300 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItemDesc:(pkgAcquire::ItemDesc &)desc {
1301 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1303 NSString *description([NSString stringWithUTF8String:desc.Description.c_str()]);
1304 NSArray *fields([description componentsSeparatedByString:@" "]);
1305 [event setItem:fields];
1307 if ([fields count] > 3) {
1308 [event setPackage:[fields objectAtIndex:2]];
1309 [event setVersion:[fields objectAtIndex:3]];
1312 [event setURL:[NSString stringWithUTF8String:desc.URI.c_str()]];
1317 + (NSArray *) _attributeKeys {
1318 return [NSArray arrayWithObjects:
1328 - (NSArray *) attributeKeys {
1329 return [[self class] _attributeKeys];
1332 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1333 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1336 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1337 if ((self = [super init]) != nil) {
1343 - (NSString *) message {
1347 - (NSString *) type {
1351 - (NSArray *) item {
1352 return (id) item_ ?: [NSNull null];
1355 - (void) setItem:(NSArray *)item {
1359 - (NSString *) package {
1360 return (id) package_ ?: [NSNull null];
1363 - (void) setPackage:(NSString *)package {
1367 - (NSString *) url {
1368 return (id) url_ ?: [NSNull null];
1371 - (void) setURL:(NSString *)url {
1375 - (void) setVersion:(NSString *)version {
1379 - (NSString *) version {
1380 return (id) version_ ?: [NSNull null];
1383 - (NSString *) compound:(NSString *)value {
1385 NSString *mode(nil); {
1386 NSString *type([self type]);
1387 if ([type isEqualToString:kCydiaProgressEventTypeError])
1388 mode = UCLocalize("ERROR");
1389 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1390 mode = UCLocalize("WARNING");
1394 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1400 - (NSString *) compoundMessage {
1401 return [self compound:[self message]];
1404 - (NSString *) compoundTitle {
1407 if (package_ == nil)
1409 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1410 title = [package name];
1414 return [self compound:title];
1420 // Cytore Definitions {{{
1421 struct PackageValue :
1424 Cytore::Offset<PackageValue> next_;
1426 uint32_t index_ : 23;
1427 uint32_t subscribed_ : 1;
1444 Cytore::Offset<PackageValue> packages_[1 << 16];
1447 static Cytore::File<MetaValue> MetaFile_;
1449 // Cytore Helper Functions {{{
1450 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1451 SplitHash nhash = { hashlittle(name, length) };
1453 PackageValue *metadata;
1455 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1456 for (;; offset = &metadata->next_) { if (offset->IsNull()) {
1457 *offset = MetaFile_.New<PackageValue>(length + 1);
1458 metadata = &MetaFile_.Get(*offset);
1460 if (metadata == NULL) {
1464 metadata = new PackageValue();
1465 memset(metadata, 0, sizeof(*metadata));
1468 memcpy(metadata->name_, name, length);
1469 metadata->name_[length] = '\0';
1470 metadata->nhash_ = nhash.u16[1];
1472 metadata = &MetaFile_.Get(*offset);
1473 if (metadata->nhash_ != nhash.u16[1])
1475 if (strncmp(metadata->name_, name, length) != 0)
1477 if (metadata->name_[length] != '\0')
1484 static void PackageImport(const void *key, const void *value, void *context) {
1485 bool &fail(*reinterpret_cast<bool *>(context));
1488 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1489 NSLog(@"failed to import package %@", key);
1493 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1494 NSDictionary *package((NSDictionary *) value);
1496 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1497 if ([subscribed boolValue] && !metadata->subscribed_)
1498 metadata->subscribed_ = true;
1500 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1501 time_t time([date timeIntervalSince1970]);
1502 if (metadata->first_ > time || metadata->first_ == 0)
1503 metadata->first_ = time;
1506 NSDate *date([package objectForKey:@"LastSeen"]);
1507 NSString *version([package objectForKey:@"LastVersion"]);
1509 if (date != nil && version != nil) {
1510 time_t time([date timeIntervalSince1970]);
1511 if (metadata->last_ < time || metadata->last_ == 0)
1512 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1513 size_t length(strlen(buffer));
1514 uint16_t vhash(hashlittle(buffer, length));
1516 size_t capped(std::min<size_t>(8, length));
1517 char *latest(buffer + length - capped);
1519 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1520 metadata->vhash_ = vhash;
1522 metadata->last_ = time;
1528 /* Source Class {{{ */
1529 @interface Source : NSObject {
1531 Database *database_;
1534 CYString depiction_;
1535 CYString description_;
1541 CYString distribution_;
1547 _H<NSString> authority_;
1549 CYString defaultIcon_;
1551 _H<NSMutableDictionary> record_;
1554 std::set<std::string> fetches_;
1555 std::set<std::string> files_;
1556 _transient NSObject<SourceDelegate> *delegate_;
1559 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool;
1561 - (NSComparisonResult) compareByName:(Source *)source;
1563 - (NSString *) depictionForPackage:(NSString *)package;
1564 - (NSString *) supportForPackage:(NSString *)package;
1566 - (metaIndex *) metaIndex;
1567 - (NSDictionary *) record;
1570 - (NSString *) rooturi;
1571 - (NSString *) distribution;
1572 - (NSString *) type;
1575 - (NSString *) host;
1577 - (NSString *) name;
1578 - (NSString *) shortDescription;
1579 - (NSString *) label;
1580 - (NSString *) origin;
1581 - (NSString *) version;
1583 - (NSString *) defaultIcon;
1584 - (NSURL *) iconURL;
1586 - (void) setFetch:(bool)fetch forURI:(const char *)uri;
1587 - (void) resetFetch;
1591 @implementation Source
1593 + (NSString *) webScriptNameForSelector:(SEL)selector {
1595 else if (selector == @selector(addSection:))
1596 return @"addSection";
1597 else if (selector == @selector(getField:))
1599 else if (selector == @selector(removeSection:))
1600 return @"removeSection";
1601 else if (selector == @selector(remove))
1607 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1608 return [self webScriptNameForSelector:selector] == nil;
1611 + (NSArray *) _attributeKeys {
1612 return [NSArray arrayWithObjects:
1623 @"shortDescription",
1630 - (NSArray *) attributeKeys {
1631 return [[self class] _attributeKeys];
1634 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1635 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1638 - (metaIndex *) metaIndex {
1642 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1643 trusted_ = index->IsTrusted();
1645 uri_.set(pool, index->GetURI());
1646 distribution_.set(pool, index->GetDist());
1647 type_.set(pool, index->GetType());
1649 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1650 if (dindex != NULL) {
1651 std::string file(dindex->MetaIndexURI(""));
1652 base_.set(pool, file);
1655 _profile(Source$setMetaIndex$GetIndexes)
1656 dindex->GetIndexes(&acquire, true);
1658 _profile(Source$setMetaIndex$DescURI)
1659 for (pkgAcquire::ItemIterator item(acquire.ItemsBegin()); item != acquire.ItemsEnd(); item++) {
1660 std::string file((*item)->DescURI());
1661 files_.insert(file);
1662 if (file.length() < sizeof("Packages.bz2") || file.substr(file.length() - sizeof("Packages.bz2")) != "/Packages.bz2")
1664 file = file.substr(0, file.length() - 4);
1665 files_.insert(file);
1666 files_.insert(file + ".gz");
1667 files_.insert(file + "Index");
1672 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1675 pkgTagFile tags(&fd);
1677 pkgTagSection section;
1684 {"default-icon", &defaultIcon_},
1685 {"depiction", &depiction_},
1686 {"description", &description_},
1688 {"origin", &origin_},
1689 {"support", &support_},
1690 {"version", &version_},
1693 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1694 const char *start, *end;
1696 if (section.Find(names[i].name_, start, end)) {
1697 CYString &value(*names[i].value_);
1698 value.set(pool, start, end - start);
1704 record_ = [Sources_ objectForKey:[self key]];
1706 NSURL *url([NSURL URLWithString:uri_]);
1710 host_ = [host_ lowercaseString];
1715 authority_ = [url path];
1718 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool {
1719 if ((self = [super init]) != nil) {
1720 era_ = [database era];
1721 database_ = database;
1724 _profile(Source$initWithMetaIndex$setMetaIndex)
1725 [self setMetaIndex:index inPool:pool];
1730 - (NSString *) getField:(NSString *)name {
1731 @synchronized (database_) {
1732 if ([database_ era] != era_ || index_ == NULL)
1735 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index_));
1740 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly)) {
1745 pkgTagFile tags(&fd);
1747 pkgTagSection section;
1750 const char *start, *end;
1751 if (!section.Find([name UTF8String], start, end))
1752 return (NSString *) [NSNull null];
1754 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
1757 - (NSComparisonResult) compareByName:(Source *)source {
1758 NSString *lhs = [self name];
1759 NSString *rhs = [source name];
1761 if ([lhs length] != 0 && [rhs length] != 0) {
1762 unichar lhc = [lhs characterAtIndex:0];
1763 unichar rhc = [rhs characterAtIndex:0];
1765 if (isalpha(lhc) && !isalpha(rhc))
1766 return NSOrderedAscending;
1767 else if (!isalpha(lhc) && isalpha(rhc))
1768 return NSOrderedDescending;
1771 return [lhs compare:rhs options:LaxCompareOptions_];
1774 - (NSString *) depictionForPackage:(NSString *)package {
1775 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1778 - (NSString *) supportForPackage:(NSString *)package {
1779 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1782 - (NSArray *) sections {
1783 return record_ == nil ? (id) [NSNull null] : [record_ objectForKey:@"Sections"] ?: [NSArray array];
1786 - (void) _addSection:(NSString *)section {
1789 else if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) {
1790 if (![sections containsObject:section]) {
1791 [sections addObject:section];
1795 [record_ setObject:[NSMutableArray arrayWithObject:section] forKey:@"Sections"];
1800 - (bool) addSection:(NSString *)section {
1804 [self performSelectorOnMainThread:@selector(_addSection:) withObject:section waitUntilDone:NO];
1808 - (void) _removeSection:(NSString *)section {
1812 if (NSMutableArray *sections = [record_ objectForKey:@"Sections"])
1813 if ([sections containsObject:section]) {
1814 [sections removeObject:section];
1819 - (bool) removeSection:(NSString *)section {
1823 [self performSelectorOnMainThread:@selector(_removeSection:) withObject:section waitUntilDone:NO];
1828 [Sources_ removeObjectForKey:[self key]];
1833 bool value(record_ != nil);
1834 [self performSelectorOnMainThread:@selector(_remove) withObject:nil waitUntilDone:NO];
1838 - (NSDictionary *) record {
1846 - (NSString *) rooturi {
1850 - (NSString *) distribution {
1851 return distribution_;
1854 - (NSString *) type {
1858 - (NSString *) baseuri {
1859 return base_.empty() ? nil : (id) base_;
1862 - (NSString *) iconuri {
1863 if (NSString *base = [self baseuri])
1864 return [base stringByAppendingString:@"CydiaIcon.png"];
1869 - (NSURL *) iconURL {
1870 if (NSString *uri = [self iconuri])
1871 return [NSURL URLWithString:uri];
1875 - (NSString *) key {
1876 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1879 - (NSString *) host {
1883 - (NSString *) name {
1884 return origin_.empty() ? (id) authority_ : origin_;
1887 - (NSString *) shortDescription {
1888 return description_;
1891 - (NSString *) label {
1892 return label_.empty() ? (id) authority_ : label_;
1895 - (NSString *) origin {
1899 - (NSString *) version {
1903 - (NSString *) defaultIcon {
1904 return defaultIcon_;
1907 - (void) setDelegate:(NSObject<SourceDelegate> *)delegate {
1908 delegate_ = delegate;
1912 return !fetches_.empty();
1915 - (void) setFetch:(bool)fetch forURI:(const char *)uri {
1917 if (fetches_.erase(uri) == 0)
1919 } else if (files_.find(uri) == files_.end())
1921 else if (!fetches_.insert(uri).second)
1924 [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:[self fetch]] waitUntilDone:NO];
1927 - (void) resetFetch {
1929 [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:NO];
1934 /* CydiaOperation Class {{{ */
1935 @interface CydiaOperation : NSObject {
1936 _H<NSString> operator_;
1937 _H<NSString> value_;
1940 - (NSString *) operator;
1941 - (NSString *) value;
1945 @implementation CydiaOperation
1947 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1948 if ((self = [super init]) != nil) {
1949 operator_ = [NSString stringWithUTF8String:_operator];
1950 value_ = [NSString stringWithUTF8String:value];
1954 + (NSArray *) _attributeKeys {
1955 return [NSArray arrayWithObjects:
1961 - (NSArray *) attributeKeys {
1962 return [[self class] _attributeKeys];
1965 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1966 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1969 - (NSString *) operator {
1973 - (NSString *) value {
1979 /* CydiaClause Class {{{ */
1980 @interface CydiaClause : NSObject {
1981 _H<NSString> package_;
1982 _H<CydiaOperation> version_;
1985 - (NSString *) package;
1986 - (CydiaOperation *) version;
1990 @implementation CydiaClause
1992 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1993 if ((self = [super init]) != nil) {
1994 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1996 if (const char *version = dep.TargetVer())
1997 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1999 version_ = (id) [NSNull null];
2003 + (NSArray *) _attributeKeys {
2004 return [NSArray arrayWithObjects:
2010 - (NSArray *) attributeKeys {
2011 return [[self class] _attributeKeys];
2014 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2015 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2018 - (NSString *) package {
2022 - (CydiaOperation *) version {
2028 /* CydiaRelation Class {{{ */
2029 @interface CydiaRelation : NSObject {
2030 _H<NSString> relationship_;
2031 _H<NSMutableArray> clauses_;
2034 - (NSString *) relationship;
2035 - (NSArray *) clauses;
2039 @implementation CydiaRelation
2041 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
2042 if ((self = [super init]) != nil) {
2043 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
2044 clauses_ = [NSMutableArray arrayWithCapacity:8];
2046 pkgCache::DepIterator start;
2047 pkgCache::DepIterator end;
2048 dep.GlobOr(start, end); // ++dep
2051 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
2053 // yes, seriously. (wtf?)
2061 + (NSArray *) _attributeKeys {
2062 return [NSArray arrayWithObjects:
2068 - (NSArray *) attributeKeys {
2069 return [[self class] _attributeKeys];
2072 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2073 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2076 - (NSString *) relationship {
2077 return relationship_;
2080 - (NSArray *) clauses {
2084 - (void) addClause:(CydiaClause *)clause {
2085 [clauses_ addObject:clause];
2090 /* Package Class {{{ */
2091 struct ParsedPackage {
2095 CYString architecture_;
2098 CYString depiction_;
2105 @interface Package : NSObject {
2107 @public uint32_t role_ : 3;
2108 uint32_t essential_ : 1;
2109 uint32_t obsolete_ : 1;
2110 uint32_t ignored_ : 1;
2111 uint32_t pooled_ : 1;
2117 _transient Database *database_;
2119 pkgCache::VerIterator version_;
2120 pkgCache::PkgIterator iterator_;
2121 pkgCache::VerFileIterator file_;
2125 CYString transform_;
2128 CYString installed_;
2131 const char *section_;
2132 _transient NSString *section$_;
2136 PackageValue *metadata_;
2137 ParsedPackage *parsed_;
2139 _H<NSMutableArray> tags_;
2142 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
2143 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
2145 - (pkgCache::PkgIterator) iterator;
2148 - (NSString *) section;
2149 - (NSString *) simpleSection;
2151 - (NSString *) longSection;
2152 - (NSString *) shortSection;
2156 - (MIMEAddress *) maintainer;
2158 - (NSString *) longDescription;
2159 - (NSString *) shortDescription;
2162 - (PackageValue *) metadata;
2165 - (bool) subscribed;
2166 - (bool) setSubscribed:(bool)subscribed;
2170 - (NSString *) latest;
2171 - (NSString *) installed;
2172 - (BOOL) uninstalled;
2175 - (BOOL) upgradableAndEssential:(BOOL)essential;
2178 - (BOOL) unfiltered;
2182 - (BOOL) halfConfigured;
2183 - (BOOL) halfInstalled;
2185 - (NSString *) mode;
2188 - (NSString *) name;
2190 - (NSString *) homepage;
2191 - (NSString *) depiction;
2192 - (MIMEAddress *) author;
2194 - (NSString *) support;
2196 - (NSArray *) files;
2197 - (NSArray *) warnings;
2198 - (NSArray *) applications;
2200 - (Source *) source;
2203 - (BOOL) matches:(NSArray *)query;
2205 - (BOOL) hasTag:(NSString *)tag;
2206 - (NSString *) primaryPurpose;
2207 - (NSArray *) purposes;
2208 - (bool) isCommercial;
2210 - (void) setIndex:(size_t)index;
2212 - (CYString &) cyname;
2214 - (uint32_t) compareBySection:(NSArray *)sections;
2221 uint32_t PackageChangesRadix(Package *self, void *) {
2226 uint32_t timestamp : 30;
2227 uint32_t ignored : 1;
2228 uint32_t upgradable : 1;
2232 bool upgradable([self upgradableAndEssential:YES]);
2233 value.bits.upgradable = upgradable ? 1 : 0;
2236 value.bits.timestamp = 0;
2237 value.bits.ignored = [self ignored] ? 0 : 1;
2238 value.bits.upgradable = 1;
2240 value.bits.timestamp = [self seen] >> 2;
2241 value.bits.ignored = 0;
2242 value.bits.upgradable = 0;
2245 return _not(uint32_t) - value.key;
2248 CYString &(*PackageName)(Package *self, SEL sel);
2250 uint32_t PackagePrefixRadix(Package *self, void *context) {
2251 size_t offset(reinterpret_cast<size_t>(context));
2252 CYString &name(PackageName(self, @selector(cyname)));
2254 size_t size(name.size());
2257 char *text(name.data());
2260 if (!isdigit(text[0]))
2264 while (size != digits && isdigit(text[digits]))
2272 if (offset == 0 && zeros != 0) {
2273 memset(data, '0', zeros);
2274 memcpy(data + zeros, text, 4 - zeros);
2276 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2277 if (size <= offset - zeros)
2280 text += offset - zeros;
2281 size -= offset - zeros;
2284 memcpy(data, text, 4);
2286 memcpy(data, text, size);
2287 memset(data + size, 0, 4 - size);
2290 for (size_t i(0); i != 4; ++i)
2291 if (isalpha(data[i]))
2299 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2301 /* XXX: ntohl may be more honest */
2302 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2305 CFComparisonResult StringNameCompare(CFStringRef lhn, CFStringRef rhn, size_t length) {
2306 _profile(PackageNameCompare)
2308 return rhn == NULL ? kCFCompareEqualTo : kCFCompareLessThan;
2309 else if (rhn == NULL)
2310 return kCFCompareGreaterThan;
2312 CFIndex length(CFStringGetLength(lhn));
2314 _profile(PackageNameCompare$NumbersLast)
2315 if (length != 0 && CFStringGetLength(rhn) != 0) {
2316 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2317 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2318 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2319 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2320 return lha ? kCFCompareLessThan : kCFCompareGreaterThan;
2324 _profile(PackageNameCompare$Compare)
2325 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, (CFLocaleRef) (id) CollationLocale_);
2330 _finline CFComparisonResult StringNameCompare(NSString *lhn, NSString*rhn, size_t length) {
2331 return StringNameCompare((CFStringRef) lhn, (CFStringRef) rhn, length);
2334 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2335 CYString &lhn(PackageName(lhs, @selector(cyname)));
2336 NSString *rhn(PackageName(rhs, @selector(cyname)));
2337 return StringNameCompare(lhn, rhn, lhn.size());
2340 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *arg) {
2341 return PackageNameCompare(*lhs, *rhs, arg);
2344 struct PackageNameOrdering :
2345 std::binary_function<Package *, Package *, bool>
2347 _finline bool operator ()(Package *lhs, Package *rhs) const {
2348 return PackageNameCompare(lhs, rhs, NULL) == kCFCompareLessThan;
2352 @implementation Package
2354 - (NSString *) description {
2355 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2360 apr_pool_destroy(pool_);
2361 if (parsed_ != NULL)
2366 + (NSString *) webScriptNameForSelector:(SEL)selector {
2368 else if (selector == @selector(clear))
2370 else if (selector == @selector(getField:))
2372 else if (selector == @selector(getRecord))
2373 return @"getRecord";
2374 else if (selector == @selector(hasTag:))
2376 else if (selector == @selector(install))
2378 else if (selector == @selector(remove))
2384 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2385 return [self webScriptNameForSelector:selector] == nil;
2388 + (NSArray *) _attributeKeys {
2389 return [NSArray arrayWithObjects:
2410 @"shortDescription",
2423 - (NSArray *) attributeKeys {
2424 return [[self class] _attributeKeys];
2427 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2428 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2431 - (NSArray *) relations {
2432 @synchronized (database_) {
2433 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2434 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2435 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2439 - (NSString *) architecture {
2441 @synchronized (database_) {
2442 return parsed_->architecture_.empty() ? [NSNull null] : (id) parsed_->architecture_;
2445 - (NSString *) getField:(NSString *)name {
2446 @synchronized (database_) {
2447 if ([database_ era] != era_ || file_.end())
2450 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2452 const char *start, *end;
2453 if (!parser.Find([name UTF8String], start, end))
2454 return (NSString *) [NSNull null];
2456 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2459 - (NSString *) getRecord {
2460 @synchronized (database_) {
2461 if ([database_ era] != era_ || file_.end())
2464 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2466 const char *start, *end;
2467 parser.GetRec(start, end);
2469 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2473 if (parsed_ != NULL)
2475 @synchronized (database_) {
2476 if ([database_ era] != era_ || file_.end())
2479 ParsedPackage *parsed(new ParsedPackage);
2482 _profile(Package$parse)
2483 pkgRecords::Parser *parser;
2485 _profile(Package$parse$Lookup)
2486 parser = &[database_ records]->Lookup(file_);
2492 _profile(Package$parse$Find)
2497 {"architecture", &parsed->architecture_},
2498 {"icon", &parsed->icon_},
2499 {"depiction", &parsed->depiction_},
2500 {"homepage", &parsed->homepage_},
2501 {"website", &website},
2503 {"support", &parsed->support_},
2504 {"author", &parsed->author_},
2505 {"md5sum", &parsed->md5sum_},
2508 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2509 const char *start, *end;
2511 if (parser->Find(names[i].name_, start, end)) {
2512 CYString &value(*names[i].value_);
2513 _profile(Package$parse$Value)
2514 value.set(pool_, start, end - start);
2520 _profile(Package$parse$Tagline)
2521 const char *start, *end;
2522 if (parser->ShortDesc(start, end)) {
2523 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2526 while (stop != start && stop[-1] == '\r')
2528 parsed->tagline_.set(pool_, start, stop - start);
2532 _profile(Package$parse$Retain)
2533 if (parsed->homepage_.empty())
2534 parsed->homepage_ = website;
2535 if (parsed->homepage_ == parsed->depiction_)
2536 parsed->homepage_.clear();
2537 if (parsed->support_.empty())
2538 parsed->support_ = bugs;
2543 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2544 if ((self = [super init]) != nil) {
2545 _profile(Package$initWithVersion)
2547 apr_pool_create(&pool_, NULL);
2553 database_ = database;
2554 era_ = [database era];
2558 pkgCache::PkgIterator iterator(version.ParentPkg());
2559 iterator_ = iterator;
2561 _profile(Package$initWithVersion$Version)
2562 if (!version_.end())
2563 file_ = version_.FileList();
2565 pkgCache &cache([database_ cache]);
2566 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2570 _profile(Package$initWithVersion$Cache)
2571 name_.set(NULL, iterator.Display());
2573 latest_.set(NULL, StripVersion_(version_.VerStr()));
2575 pkgCache::VerIterator current(iterator.CurrentVer());
2577 installed_.set(NULL, StripVersion_(current.VerStr()));
2580 _profile(Package$initWithVersion$Transliterate) do {
2581 if (CollationTransl_ == NULL)
2586 _profile(Package$initWithVersion$Transliterate$utf8)
2587 const uint8_t *data(reinterpret_cast<const uint8_t *>(name_.data()));
2588 for (size_t i(0), e(name_.size()); i != e; ++i)
2589 if (data[i] >= 0x80)
2594 UErrorCode code(U_ZERO_ERROR);
2597 _profile(Package$initWithVersion$Transliterate$u_strFromUTF8WithSub)
2598 CollationString_.resize(name_.size());
2599 u_strFromUTF8WithSub(&CollationString_[0], CollationString_.size(), &length, name_.data(), name_.size(), 0xfffd, NULL, &code);
2600 if (!U_SUCCESS(code))
2602 CollationString_.resize(length);
2605 _profile(Package$initWithVersion$Transliterate$utrans_trans)
2606 length = CollationString_.size();
2607 utrans_trans(CollationTransl_, reinterpret_cast<UReplaceable *>(&CollationString_), &CollationUCalls_, 0, &length, &code);
2608 if (!U_SUCCESS(code))
2610 _assert(CollationString_.size() == length);
2613 _profile(Package$initWithVersion$Transliterate$u_strToUTF8WithSub$preflight)
2614 u_strToUTF8WithSub(NULL, 0, &length, CollationString_.data(), CollationString_.size(), 0xfffd, NULL, &code);
2615 if (code == U_BUFFER_OVERFLOW_ERROR)
2616 code = U_ZERO_ERROR;
2617 else if (!U_SUCCESS(code))
2622 _profile(Package$initWithVersion$Transliterate$apr_palloc)
2623 transform = static_cast<char *>(apr_palloc(pool_, length));
2625 _profile(Package$initWithVersion$Transliterate$u_strToUTF8WithSub$transform)
2626 u_strToUTF8WithSub(transform, length, NULL, CollationString_.data(), CollationString_.size(), 0xfffd, NULL, &code);
2627 if (!U_SUCCESS(code))
2631 transform_.set(NULL, transform, length);
2632 } while (false); _end
2634 _profile(Package$initWithVersion$Tags)
2635 pkgCache::TagIterator tag(iterator.TagList());
2637 tags_ = [NSMutableArray arrayWithCapacity:8];
2639 goto tag; for (; !tag.end(); ++tag) tag: {
2640 const char *name(tag.Name());
2641 NSString *string((NSString *) CYStringCreate(name));
2645 [tags_ addObject:[string autorelease]];
2647 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2648 if (strcmp(name + 6, "enduser") == 0)
2650 else if (strcmp(name + 6, "hacker") == 0)
2652 else if (strcmp(name + 6, "developer") == 0)
2654 else if (strcmp(name + 6, "cydia") == 0)
2660 if (strncmp(name, "cydia::", 7) == 0) {
2661 if (strcmp(name + 7, "essential") == 0)
2663 else if (strcmp(name + 7, "obsolete") == 0)
2670 _profile(Package$initWithVersion$Metadata)
2671 const char *mixed(iterator.Name());
2672 size_t size(strlen(mixed));
2673 static const size_t prefix(sizeof("/var/lib/dpkg/info/") - 1);
2674 char lower[prefix + size + 5 + 1];
2676 for (size_t i(0); i != size; ++i)
2677 lower[prefix + i] = mixed[i] | 0x20;
2679 if (!installed_.empty()) {
2680 memcpy(lower, "/var/lib/dpkg/info/", prefix);
2681 memcpy(lower + prefix + size, ".list", 6);
2683 if (stat(lower, &info) != -1)
2684 upgraded_ = info.st_birthtime;
2687 PackageValue *metadata(PackageFind(lower + prefix, size));
2688 metadata_ = metadata;
2690 id_.set(NULL, metadata->name_, size);
2692 const char *latest(version_.VerStr());
2693 size_t length(strlen(latest));
2695 uint16_t vhash(hashlittle(latest, length));
2697 size_t capped(std::min<size_t>(8, length));
2698 latest = latest + length - capped;
2700 if (metadata->first_ == 0)
2701 metadata->first_ = now_;
2703 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2704 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2705 metadata->vhash_ = vhash;
2706 metadata->last_ = now_;
2707 } else if (metadata->last_ == 0)
2708 metadata->last_ = metadata->first_;
2711 _profile(Package$initWithVersion$Section)
2712 section_ = version_.Section();
2715 _profile(Package$initWithVersion$Flags)
2716 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2717 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2722 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2723 pkgCache::VerIterator version;
2725 _profile(Package$packageWithIterator$GetCandidateVer)
2726 version = [database policy]->GetCandidateVer(iterator);
2734 _profile(Package$packageWithIterator$Allocate)
2735 package = [Package allocWithZone:zone];
2738 _profile(Package$packageWithIterator$Initialize)
2740 initWithVersion:version
2747 _profile(Package$packageWithIterator$Autorelease)
2748 package = [package autorelease];
2754 - (pkgCache::PkgIterator) iterator {
2758 - (NSString *) section {
2759 if (section$_ == nil) {
2760 if (section_ == NULL)
2763 _profile(Package$section$mappedSectionForPointer)
2764 section$_ = [database_ mappedSectionForPointer:section_];
2769 - (NSString *) simpleSection {
2770 if (NSString *section = [self section])
2771 return Simplify(section);
2776 - (NSString *) longSection {
2777 return LocalizeSection([self section]);
2780 - (NSString *) shortSection {
2781 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2784 - (NSString *) uri {
2787 pkgIndexFile *index;
2788 pkgCache::PkgFileIterator file(file_.File());
2789 if (![database_ list].FindIndex(file, index))
2791 return [NSString stringWithUTF8String:iterator_->Path];
2792 //return [NSString stringWithUTF8String:file.Site()];
2793 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2797 - (MIMEAddress *) maintainer {
2798 @synchronized (database_) {
2799 if ([database_ era] != era_ || file_.end())
2802 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2803 const std::string &maintainer(parser->Maintainer());
2804 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2807 - (NSString *) md5sum {
2808 return parsed_ == NULL ? nil : (id) parsed_->md5sum_;
2812 @synchronized (database_) {
2813 if ([database_ era] != era_ || version_.end())
2816 return version_->InstalledSize;
2819 - (NSString *) longDescription {
2820 @synchronized (database_) {
2821 if ([database_ era] != era_ || file_.end())
2824 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2825 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2827 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2828 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2829 if ([lines count] < 2)
2832 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2833 for (size_t i(1), e([lines count]); i != e; ++i) {
2834 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2835 [trimmed addObject:trim];
2838 return [trimmed componentsJoinedByString:@"\n"];
2841 - (NSString *) shortDescription {
2842 if (parsed_ != NULL)
2843 return static_cast<NSString *>(parsed_->tagline_);
2845 @synchronized (database_) {
2846 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2848 const char *start, *end;
2849 if (!parser.ShortDesc(start, end))
2852 if (end - start > 200)
2856 if (const char *stop = reinterpret_cast<const char *>(memchr(start, '\n', end - start)))
2859 while (end != start && end[-1] == '\r')
2863 return [(id) CYStringCreate(start, end - start) autorelease];
2867 _profile(Package$index)
2868 CFStringRef name((CFStringRef) [self name]);
2869 if (CFStringGetLength(name) == 0)
2871 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2872 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2874 return toupper(character);
2878 - (PackageValue *) metadata {
2883 PackageValue *metadata([self metadata]);
2884 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2887 - (bool) subscribed {
2888 return [self metadata]->subscribed_;
2891 - (bool) setSubscribed:(bool)subscribed {
2892 PackageValue *metadata([self metadata]);
2893 if (metadata->subscribed_ == subscribed)
2895 metadata->subscribed_ = subscribed;
2903 - (NSString *) latest {
2907 - (NSString *) installed {
2911 - (BOOL) uninstalled {
2912 return installed_.empty();
2916 return !version_.end();
2919 - (BOOL) upgradableAndEssential:(BOOL)essential {
2920 _profile(Package$upgradableAndEssential)
2921 pkgCache::VerIterator current(iterator_.CurrentVer());
2923 return essential && essential_;
2925 return !version_.end() && version_ != current;
2929 - (BOOL) essential {
2934 return [database_ cache][iterator_].InstBroken();
2937 - (BOOL) unfiltered {
2938 _profile(Package$unfiltered$obsolete)
2939 if (_unlikely(obsolete_))
2943 _profile(Package$unfiltered$role)
2944 if (_unlikely(role_ > 3))
2952 if (![self unfiltered])
2957 _profile(Package$visible$section)
2958 section = [self section];
2961 _profile(Package$visible$isSectionVisible)
2962 if (!isSectionVisible(section))
2970 unsigned char current(iterator_->CurrentState);
2971 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2974 - (BOOL) halfConfigured {
2975 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2978 - (BOOL) halfInstalled {
2979 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2983 @synchronized (database_) {
2984 if ([database_ era] != era_ || iterator_.end())
2987 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2988 return state.Mode != pkgDepCache::ModeKeep;
2991 - (NSString *) mode {
2992 @synchronized (database_) {
2993 if ([database_ era] != era_ || iterator_.end())
2996 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2998 switch (state.Mode) {
2999 case pkgDepCache::ModeDelete:
3000 if ((state.iFlags & pkgDepCache::Purge) != 0)
3004 case pkgDepCache::ModeKeep:
3005 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
3006 return @"REINSTALL";
3007 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
3011 case pkgDepCache::ModeInstall:
3012 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
3013 return @"REINSTALL";
3014 else*/ switch (state.Status) {
3016 return @"DOWNGRADE";
3022 return @"NEW_INSTALL";
3033 - (NSString *) name {
3034 return name_.empty() ? id_ : name_;
3037 - (UIImage *) icon {
3038 NSString *section = [self simpleSection];
3041 if (parsed_ != NULL)
3042 if (NSString *href = parsed_->icon_)
3043 if ([href hasPrefix:@"file:///"])
3044 icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
3045 if (icon == nil) if (section != nil)
3046 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]];
3047 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
3048 if ([dicon hasPrefix:@"file:///"])
3049 icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
3051 icon = [UIImage imageNamed:@"unknown.png"];
3055 - (NSString *) homepage {
3056 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
3059 - (NSString *) depiction {
3060 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
3063 - (MIMEAddress *) author {
3064 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
3067 - (NSString *) support {
3068 return parsed_ != NULL && !parsed_->support_.empty() ? parsed_->support_ : [[self source] supportForPackage:id_];
3071 - (NSArray *) files {
3072 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
3073 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
3076 fin.open([path UTF8String]);
3081 while (std::getline(fin, line))
3082 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
3087 - (NSString *) state {
3088 @synchronized (database_) {
3089 if ([database_ era] != era_ || file_.end())
3092 switch (iterator_->CurrentState) {
3093 case pkgCache::State::NotInstalled:
3094 return @"NotInstalled";
3095 case pkgCache::State::UnPacked:
3097 case pkgCache::State::HalfConfigured:
3098 return @"HalfConfigured";
3099 case pkgCache::State::HalfInstalled:
3100 return @"HalfInstalled";
3101 case pkgCache::State::ConfigFiles:
3102 return @"ConfigFiles";
3103 case pkgCache::State::Installed:
3104 return @"Installed";
3105 case pkgCache::State::TriggersAwaited:
3106 return @"TriggersAwaited";
3107 case pkgCache::State::TriggersPending:
3108 return @"TriggersPending";
3111 return (NSString *) [NSNull null];
3114 - (NSString *) selection {
3115 @synchronized (database_) {
3116 if ([database_ era] != era_ || file_.end())
3119 switch (iterator_->SelectedState) {
3120 case pkgCache::State::Unknown:
3122 case pkgCache::State::Install:
3124 case pkgCache::State::Hold:
3126 case pkgCache::State::DeInstall:
3127 return @"DeInstall";
3128 case pkgCache::State::Purge:
3132 return (NSString *) [NSNull null];
3135 - (NSArray *) warnings {
3136 @synchronized (database_) {
3137 if ([database_ era] != era_ || file_.end())
3140 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
3141 const char *name(iterator_.Name());
3143 size_t length(strlen(name));
3144 if (length < 2) invalid:
3145 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
3146 else for (size_t i(0); i != length; ++i)
3148 /* XXX: technically this is not allowed */
3149 (name[i] < 'A' || name[i] > 'Z') &&
3150 (name[i] < 'a' || name[i] > 'z') &&
3151 (name[i] < '0' || name[i] > '9') &&
3152 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
3155 if (strcmp(name, "cydia") != 0) {
3158 bool _private = false;
3160 bool dbstash = false;
3161 bool dsstore = false;
3163 bool repository = [[self section] isEqualToString:@"Repositories"];
3165 if (NSArray *files = [self files])
3166 for (NSString *file in files)
3167 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
3169 else if (!user && [file isEqualToString:@"/User"])
3171 else if (!_private && [file isEqualToString:@"/private"])
3173 else if (!stash && [file isEqualToString:@"/var/stash"])
3175 else if (!dbstash && [file isEqualToString:@"/var/db/stash"])
3177 else if (!dsstore && [file hasSuffix:@"/.DS_Store"])
3180 /* XXX: this is not sensitive enough. only some folders are valid. */
3181 if (cydia && !repository)
3182 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
3184 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
3186 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
3188 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
3190 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/db/stash"]];
3192 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @".DS_Store"]];
3195 return [warnings count] == 0 ? nil : warnings;
3198 - (NSArray *) applications {
3199 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
3201 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
3203 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
3204 if (NSArray *files = [self files])
3205 for (NSString *file in files)
3206 if (application_r(file)) {
3207 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
3208 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
3209 if ([id isEqualToString:me])
3212 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
3214 display = application_r[1];
3216 NSString *bundle([file stringByDeletingLastPathComponent]);
3217 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
3218 // XXX: maybe this should check if this is really a string, not just for length
3219 if (icon == nil || ![icon respondsToSelector:@selector(length)] || [icon length] == 0)
3221 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
3223 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
3224 [applications addObject:application];
3226 [application addObject:id];
3227 [application addObject:display];
3228 [application addObject:url];
3231 return [applications count] == 0 ? nil : applications;
3234 - (Source *) source {
3235 if (source_ == nil) {
3236 @synchronized (database_) {
3237 if ([database_ era] != era_ || file_.end())
3238 source_ = (Source *) [NSNull null];
3240 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
3244 return source_ == (Source *) [NSNull null] ? nil : source_;
3247 - (time_t) upgraded {
3251 - (uint32_t) recent {
3252 return std::numeric_limits<uint32_t>::max() - upgraded_;
3259 - (BOOL) matches:(NSArray *)query {
3260 if (query == nil || [query count] == 0)
3269 string = [self name];
3270 length = [string length];
3273 for (NSString *term in query) {
3274 range = [string rangeOfString:term options:MatchCompareOptions_];
3275 if (range.location != NSNotFound)
3276 rank_ -= 6 * 1000000 / length;
3281 length = [string length];
3284 for (NSString *term in query) {
3285 range = [string rangeOfString:term options:MatchCompareOptions_];
3286 if (range.location != NSNotFound)
3287 rank_ -= 6 * 1000000 / length;
3291 string = [self shortDescription];
3292 length = [string length];
3293 NSUInteger stop(std::min<NSUInteger>(length, 200));
3296 for (NSString *term in query) {
3297 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
3298 if (range.location != NSNotFound)
3299 rank_ -= 2 * 100000;
3305 - (NSArray *) tags {
3309 - (BOOL) hasTag:(NSString *)tag {
3310 return tags_ == nil ? NO : [tags_ containsObject:tag];
3313 - (NSString *) primaryPurpose {
3314 for (NSString *tag in (NSArray *) tags_)
3315 if ([tag hasPrefix:@"purpose::"])
3316 return [tag substringFromIndex:9];
3320 - (NSArray *) purposes {
3321 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
3322 for (NSString *tag in (NSArray *) tags_)
3323 if ([tag hasPrefix:@"purpose::"])
3324 [purposes addObject:[tag substringFromIndex:9]];
3325 return [purposes count] == 0 ? nil : purposes;
3328 - (bool) isCommercial {
3329 return [self hasTag:@"cydia::commercial"];
3332 - (void) setIndex:(size_t)index {
3333 if (metadata_->index_ != index)
3334 metadata_->index_ = index;
3337 - (CYString &) cyname {
3338 return !transform_.empty() ? transform_ : !name_.empty() ? name_ : id_;
3341 - (uint32_t) compareBySection:(NSArray *)sections {
3342 NSString *section([self section]);
3343 for (size_t i(0), e([sections count]); i != e; ++i) {
3344 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3348 return _not(uint32_t);
3352 @synchronized (database_) {
3353 pkgProblemResolver *resolver = [database_ resolver];
3354 resolver->Clear(iterator_);
3356 pkgCacheFile &cache([database_ cache]);
3357 cache->SetReInstall(iterator_, false);
3358 cache->MarkKeep(iterator_, false);
3362 @synchronized (database_) {
3363 pkgProblemResolver *resolver = [database_ resolver];
3364 resolver->Clear(iterator_);
3365 resolver->Protect(iterator_);
3367 pkgCacheFile &cache([database_ cache]);
3368 cache->SetReInstall(iterator_, false);
3369 cache->MarkInstall(iterator_, false);
3371 pkgDepCache::StateCache &state((*cache)[iterator_]);
3372 if (!state.Install())
3373 cache->SetReInstall(iterator_, true);
3377 @synchronized (database_) {
3378 pkgProblemResolver *resolver = [database_ resolver];
3379 resolver->Clear(iterator_);
3380 resolver->Remove(iterator_);
3381 resolver->Protect(iterator_);
3383 pkgCacheFile &cache([database_ cache]);
3384 cache->SetReInstall(iterator_, false);
3385 cache->MarkDelete(iterator_, true);
3390 /* Section Class {{{ */
3391 @interface Section : NSObject {
3395 _H<NSString> localized_;
3398 - (NSComparisonResult) compareByLocalized:(Section *)section;
3399 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3400 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3401 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3403 - (NSString *) name;
3404 - (void) setName:(NSString *)name;
3410 - (void) addToCount;
3412 - (void) setCount:(size_t)count;
3413 - (NSString *) localized;
3417 @implementation Section
3419 - (NSComparisonResult) compareByLocalized:(Section *)section {
3420 NSString *lhs(localized_);
3421 NSString *rhs([section localized]);
3423 /*if ([lhs length] != 0 && [rhs length] != 0) {
3424 unichar lhc = [lhs characterAtIndex:0];
3425 unichar rhc = [rhs characterAtIndex:0];
3427 if (isalpha(lhc) && !isalpha(rhc))
3428 return NSOrderedAscending;
3429 else if (!isalpha(lhc) && isalpha(rhc))
3430 return NSOrderedDescending;
3433 return [lhs compare:rhs options:LaxCompareOptions_];
3436 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3437 if ((self = [self initWithName:name localize:NO]) != nil) {
3438 if (localized != nil)
3439 localized_ = localized;
3443 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3444 return [self initWithName:name row:0 localize:localize];
3447 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3448 if ((self = [super init]) != nil) {
3452 localized_ = LocalizeSection(name_);
3456 - (NSString *) name {
3460 - (void) setName:(NSString *)name {
3476 - (void) addToCount {
3480 - (void) setCount:(size_t)count {
3484 - (NSString *) localized {
3491 class CydiaLogCleaner :
3492 public pkgArchiveCleaner
3495 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3500 /* Database Implementation {{{ */
3501 @implementation Database
3503 + (Database *) sharedInstance {
3504 static _H<Database> instance;
3505 if (instance == nil)
3506 instance = [[[Database alloc] init] autorelease];
3514 - (void) releasePackages {
3515 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3516 CFArrayRemoveAllValues(packages_);
3520 // XXX: actually implement this thing
3522 [self releasePackages];
3523 apr_pool_destroy(pool_);
3524 NSRecycleZone(zone_);
3528 - (void) _readCydia:(NSNumber *)fd {
3529 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3530 std::istream is(&ib);
3533 static Pcre finish_r("^finish:([^:]*)$");
3535 while (std::getline(is, line)) {
3536 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3538 const char *data(line.c_str());
3539 size_t size = line.size();
3540 lprintf("C:%s\n", data);
3542 if (finish_r(data, size)) {
3543 NSString *finish = finish_r[1];
3544 int index = [Finishes_ indexOfObject:finish];
3545 if (index != INT_MAX && index > Finish_)
3555 - (void) _readStatus:(NSNumber *)fd {
3556 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3557 std::istream is(&ib);
3560 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3561 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3563 while (std::getline(is, line)) {
3564 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3566 const char *data(line.c_str());
3567 size_t size(line.size());
3568 lprintf("S:%s\n", data);
3570 if (conffile_r(data, size)) {
3571 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3572 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3573 } else if (strncmp(data, "status: ", 8) == 0) {
3574 // status: <package>: {unpacked,half-configured,installed}
3575 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3576 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3577 } else if (strncmp(data, "processing: ", 12) == 0) {
3578 // processing: configure: config-test
3579 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3580 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3581 } else if (pmstatus_r(data, size)) {
3582 std::string type([pmstatus_r[1] UTF8String]);
3584 NSString *package = pmstatus_r[2];
3585 if ([package isEqualToString:@"dpkg-exec"])
3588 float percent([pmstatus_r[3] floatValue]);
3589 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3591 NSString *string = pmstatus_r[4];
3593 if (type == "pmerror") {
3594 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3595 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3596 } else if (type == "pmstatus") {
3597 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3598 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3599 } else if (type == "pmconffile")
3600 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3602 lprintf("E:unknown pmstatus\n");
3604 lprintf("E:unknown status\n");
3612 - (void) _readOutput:(NSNumber *)fd {
3613 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3614 std::istream is(&ib);
3617 while (std::getline(is, line)) {
3618 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3620 lprintf("O:%s\n", line.c_str());
3622 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3623 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3635 - (Package *) packageWithName:(NSString *)name {
3638 @synchronized (self) {
3639 if (static_cast<pkgDepCache *>(cache_) == NULL)
3641 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3642 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:NULL database:self];
3646 if ((self = [super init]) != nil) {
3653 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3654 apr_pool_create(&pool_, NULL);
3656 size_t capacity(MetaFile_->active_);
3662 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3663 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3667 _assert(pipe(fds) != -1);
3670 _config->Set("APT::Keep-Fds::", cydiafd_);
3671 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3674 detachNewThreadSelector:@selector(_readCydia:)
3676 withObject:[NSNumber numberWithInt:fds[0]]
3679 _assert(pipe(fds) != -1);
3683 detachNewThreadSelector:@selector(_readStatus:)
3685 withObject:[NSNumber numberWithInt:fds[0]]
3688 _assert(pipe(fds) != -1);
3689 _assert(dup2(fds[0], 0) != -1);
3690 _assert(close(fds[0]) != -1);
3692 input_ = fdopen(fds[1], "a");
3694 _assert(pipe(fds) != -1);
3695 _assert(dup2(fds[1], 1) != -1);
3696 _assert(close(fds[1]) != -1);
3699 detachNewThreadSelector:@selector(_readOutput:)
3701 withObject:[NSNumber numberWithInt:fds[0]]
3706 - (pkgCacheFile &) cache {
3710 - (pkgDepCache::Policy *) policy {
3714 - (pkgRecords *) records {
3718 - (pkgProblemResolver *) resolver {
3722 - (pkgAcquire &) fetcher {
3726 - (pkgSourceList &) list {
3730 - (NSArray *) packages {
3731 return (NSArray *) packages_;
3734 - (NSArray *) sources {
3738 - (Source *) sourceWithKey:(NSString *)key {
3739 for (Source *source in [self sources]) {
3740 if ([[source key] isEqualToString:key])
3745 - (bool) popErrorWithTitle:(NSString *)title {
3748 while (!_error->empty()) {
3750 bool warning(!_error->PopMessage(error));
3755 size_t size(error.size());
3756 if (size == 0 || error[size - 1] != '\n')
3758 error.resize(size - 1);
3761 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3763 static Pcre no_pubkey("^GPG error:.* NO_PUBKEY .*$");
3764 if (warning && no_pubkey(error.c_str()))
3767 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3773 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3774 return [self popErrorWithTitle:title] || !success;
3777 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3778 @synchronized (self) {
3781 [self releasePackages];
3784 [sourceList_ removeAllObjects];
3804 apr_pool_clear(pool_);
3806 NSRecycleZone(zone_);
3807 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3809 int chk(creat("/tmp/cydia.chk", 0644));
3813 if (invocation != nil)
3814 [invocation invoke];
3816 NSString *title(UCLocalize("DATABASE"));
3818 list_ = new pkgSourceList();
3819 _profile(reloadDataWithInvocation$ReadMainList)
3820 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3824 _profile(reloadDataWithInvocation$Source$initWithMetaIndex)
3825 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3826 Source *object([[[Source alloc] initWithMetaIndex:*source forDatabase:self inPool:pool_] autorelease]);
3827 [sourceList_ addObject:object];
3831 _root(_system->Lock());
3834 OpProgress progress;
3837 _profile(reloadDataWithInvocation$pkgCacheFile)
3838 opened = cache_.Open(progress, false);
3841 // XXX: what if there are errors, but Open() == true? this should be merged with popError:
3842 while (!_error->empty()) {
3844 bool warning(!_error->PopMessage(error));
3846 lprintf("cache_.Open():[%s]\n", error.c_str());
3848 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3852 else if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3853 repair = @selector(configure);
3854 //else if (error == "The package lists or status file could not be parsed or opened.")
3855 // repair = @selector(update);
3856 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3857 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3858 // else if (error == "Malformed Status line")
3859 // else if (error == "The list of sources could not be read.")
3861 if (repair != NULL) {
3863 [delegate_ repairWithSelector:repair];
3873 unlink("/tmp/cydia.chk");
3875 now_ = [[NSDate date] timeIntervalSince1970];
3877 policy_ = new pkgDepCache::Policy();
3878 records_ = new pkgRecords(cache_);
3879 resolver_ = new pkgProblemResolver(cache_);
3880 fetcher_ = new pkgAcquire(&status_);
3883 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3884 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3888 _profile(reloadDataWithInvocation$pkgApplyStatus)
3889 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3893 if (cache_->BrokenCount() != 0) {
3894 _profile(pkgApplyStatus$pkgFixBroken)
3895 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3899 if (cache_->BrokenCount() != 0) {
3900 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3904 _profile(pkgApplyStatus$pkgMinimizeUpgrade)
3905 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3910 for (Source *object in (id) sourceList_) {
3911 metaIndex *source([object metaIndex]);
3912 std::vector<pkgIndexFile *> *indices = source->GetIndexFiles();
3913 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3914 // XXX: this could be more intelligent
3915 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3916 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3918 sourceMap_[cached->ID] = object;
3923 /*std::vector<Package *> packages;
3924 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3927 _profile(reloadDataWithInvocation$packageWithIterator)
3928 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3929 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3930 //packages.push_back(package);
3931 CFArrayAppendValue(packages_, CFRetain(package));
3935 /*if (packages.empty())
3936 packages_ = [[NSArray alloc] init];
3938 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3941 _profile(reloadDataWithInvocation$radix$8)
3942 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(8)];
3945 _profile(reloadDataWithInvocation$radix$4)
3946 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3949 _profile(reloadDataWithInvocation$radix$0)
3950 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3953 _profile(reloadDataWithInvocation$insertion)
3954 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3957 /*_profile(reloadDataWithInvocation$CFQSortArray)
3958 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);
3961 /*_profile(reloadDataWithInvocation$stdsort)
3962 std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3965 /*_profile(reloadDataWithInvocation$CFArraySortValues)
3966 CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3969 /*_profile(reloadDataWithInvocation$sortUsingFunction)
3970 [packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3974 size_t count(CFArrayGetCount(packages_));
3975 MetaFile_->active_ = count;
3976 for (size_t index(0); index != count; ++index)
3977 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3982 @synchronized (self) {
3984 resolver_ = new pkgProblemResolver(cache_);
3986 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3987 if (!cache_[iterator].Keep())
3988 cache_->MarkKeep(iterator, false);
3989 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3990 cache_->SetReInstall(iterator, false);
3993 - (void) configure {
3994 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3996 _root(system([dpkg UTF8String]));
4001 @synchronized (self) {
4002 // XXX: I don't remember this condition
4007 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
4009 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
4011 if ([self popErrorWithTitle:title])
4015 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
4017 CydiaLogCleaner cleaner;
4018 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
4025 fetcher_->Shutdown();
4027 pkgRecords records(cache_);
4029 lock_ = new FileFd();
4030 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
4032 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
4034 if ([self popErrorWithTitle:title])
4038 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
4041 manager_ = (_system->CreatePM(cache_));
4042 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
4049 bool substrate(RestartSubstrate_);
4050 RestartSubstrate_ = false;
4052 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
4054 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
4056 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
4058 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
4059 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
4062 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4064 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
4066 [self popErrorWithTitle:title];
4070 bool failed = false;
4071 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
4072 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
4074 if ((*item)->Status == pkgAcquire::Item::StatIdle)
4077 std::string uri = (*item)->DescURI();
4078 std::string error = (*item)->ErrorText;
4080 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
4083 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError]);
4084 [delegate_ addProgressEventOnMainThread:event forTask:title];
4087 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4095 RestartSubstrate_ = true;
4098 pkgPackageManager::OrderResult result(_root(manager_->DoInstall(statusfd_)));
4099 if ([self popErrorWithTitle:title])
4102 if (result == pkgPackageManager::Failed) {
4107 if (result != pkgPackageManager::Completed) {
4112 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
4114 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
4116 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
4117 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
4120 if (![before isEqualToArray:after])
4125 NSString *title(UCLocalize("UPGRADE"));
4126 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
4132 [self updateWithStatus:status_];
4135 - (void) updateWithStatus:(CancelStatus &)status {
4136 NSString *title(UCLocalize("REFRESHING_DATA"));
4139 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
4143 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
4144 if ([self popErrorWithTitle:title])
4147 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4149 bool success(ListUpdate(status, list, PulseInterval_));
4150 if (status.WasCancelled())
4153 [self popErrorWithTitle:title forOperation:success];
4154 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
4158 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4161 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
4162 delegate_ = delegate;
4165 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
4166 progress_ = delegate;
4167 status_.setDelegate(delegate);
4170 - (NSObject<ProgressDelegate> *) progressDelegate {
4174 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
4175 SourceMap::const_iterator i(sourceMap_.find(file->ID));
4176 return i == sourceMap_.end() ? nil : i->second;
4179 - (void) setFetch:(bool)fetch forURI:(const char *)uri {
4180 for (Source *source in (id) sourceList_)
4181 [source setFetch:fetch forURI:uri];
4184 - (void) resetFetch {
4185 for (Source *source in (id) sourceList_)
4186 [source resetFetch];
4189 - (NSString *) mappedSectionForPointer:(const char *)section {
4190 _H<NSString> *mapped;
4192 _profile(Database$mappedSectionForPointer$Cache)
4193 mapped = §ions_[section];
4196 if (*mapped == NULL) {
4197 size_t length(strlen(section));
4198 char spaced[length + 1];
4200 _profile(Database$mappedSectionForPointer$Replace)
4201 for (size_t index(0); index != length; ++index)
4202 spaced[index] = section[index] == '_' ? ' ' : section[index];
4203 spaced[length] = '\0';
4208 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
4209 string = [NSString stringWithUTF8String:spaced];
4212 _profile(Database$mappedSectionForPointer$Map)
4213 string = [SectionMap_ objectForKey:string] ?: string;
4223 static _H<NSMutableSet> Diversions_;
4225 @interface Diversion : NSObject {
4228 _H<NSString> format_;
4233 @implementation Diversion
4235 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
4236 if ((self = [super init]) != nil) {
4237 pattern_ = [from UTF8String];
4243 - (NSString *) divert:(NSString *)url {
4244 return !pattern_(url) ? nil : pattern_->*format_;
4247 + (NSURL *) divertURL:(NSURL *)url {
4249 NSString *href([url absoluteString]);
4251 for (Diversion *diversion in (id) Diversions_)
4252 if (NSString *diverted = [diversion divert:href]) {
4254 NSLog(@"div: %@", diverted);
4256 url = [NSURL URLWithString:diverted];
4263 - (NSString *) key {
4267 - (NSUInteger) hash {
4271 - (BOOL) isEqual:(Diversion *)object {
4272 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
4277 @interface CydiaObject : NSObject {
4278 _H<CyteWebViewController> indirect_;
4279 _transient id delegate_;
4282 - (id) initWithDelegate:(IndirectDelegate *)indirect;
4288 @interface CydiaWebViewController : CyteWebViewController {
4289 _H<CydiaObject> cydia_;
4292 + (void) addDiversion:(Diversion *)diversion;
4293 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request;
4294 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia;
4295 - (void) setDelegate:(id)delegate;
4299 /* Web Scripting {{{ */
4300 @implementation CydiaObject
4302 - (id) initWithDelegate:(IndirectDelegate *)indirect {
4303 if ((self = [super init]) != nil) {
4304 indirect_ = (CyteWebViewController *) indirect;
4308 - (void) setDelegate:(id)delegate {
4309 delegate_ = delegate;
4312 + (NSArray *) _attributeKeys {
4313 return [NSArray arrayWithObjects:
4316 @"coreFoundationVersionNumber",
4333 - (NSArray *) attributeKeys {
4334 return [[self class] _attributeKeys];
4337 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4338 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4341 - (NSString *) version {
4345 - (NSString *) build {
4349 - (NSString *) coreFoundationVersionNumber {
4350 return [NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber];
4353 - (NSString *) device {
4354 return UniqueIdentifier();
4357 - (NSString *) firmware {
4358 return [[UIDevice currentDevice] systemVersion];
4361 - (NSString *) hostname {
4362 return [[UIDevice currentDevice] name];
4365 - (NSString *) idiom {
4366 return (id) Idiom_ ?: [NSNull null];
4369 - (NSString *) mcc {
4370 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode")))
4371 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault) autorelease];
4375 - (NSString *) mnc {
4376 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberNetworkCode")))
4377 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault) autorelease];
4381 - (NSString *) operator {
4382 if (CFStringRef (*$CTRegistrationCopyOperatorName)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTRegistrationCopyOperatorName")))
4383 return [(NSString *) (*$CTRegistrationCopyOperatorName)(kCFAllocatorDefault) autorelease];
4387 - (NSString *) bbsnum {
4388 return (id) BBSNum_ ?: [NSNull null];
4391 - (NSString *) ecid {
4392 return (id) ChipID_ ?: [NSNull null];
4395 - (NSString *) serial {
4396 return SerialNumber_;
4399 - (NSString *) role {
4400 return (id) [NSNull null];
4403 - (NSString *) model {
4404 return [NSString stringWithUTF8String:Machine_];
4407 - (NSString *) token {
4408 return (id) Token_ ?: [NSNull null];
4411 + (NSString *) webScriptNameForSelector:(SEL)selector {
4413 else if (selector == @selector(addBridgedHost:))
4414 return @"addBridgedHost";
4415 else if (selector == @selector(addInsecureHost:))
4416 return @"addInsecureHost";
4417 else if (selector == @selector(addInternalRedirect::))
4418 return @"addInternalRedirect";
4419 else if (selector == @selector(addPipelinedHost:scheme:))
4420 return @"addPipelinedHost";
4421 else if (selector == @selector(addSource:::))
4422 return @"addSource";
4423 else if (selector == @selector(addTokenHost:))
4424 return @"addTokenHost";
4425 else if (selector == @selector(addTrivialSource:))
4426 return @"addTrivialSource";
4427 else if (selector == @selector(close))
4429 else if (selector == @selector(du:))
4431 else if (selector == @selector(stringWithFormat:arguments:))
4433 else if (selector == @selector(getAllSources))
4434 return @"getAllSources";
4435 else if (selector == @selector(getApplicationInfo:value:))
4436 return @"getApplicationInfoValue";
4437 else if (selector == @selector(getKernelNumber:))
4438 return @"getKernelNumber";
4439 else if (selector == @selector(getKernelString:))
4440 return @"getKernelString";
4441 else if (selector == @selector(getInstalledPackages))
4442 return @"getInstalledPackages";
4443 else if (selector == @selector(getIORegistryEntry::))
4444 return @"getIORegistryEntry";
4445 else if (selector == @selector(getLocaleIdentifier))
4446 return @"getLocaleIdentifier";
4447 else if (selector == @selector(getPreferredLanguages))
4448 return @"getPreferredLanguages";
4449 else if (selector == @selector(getPackageById:))
4450 return @"getPackageById";
4451 else if (selector == @selector(getMetadataKeys))
4452 return @"getMetadataKeys";
4453 else if (selector == @selector(getMetadataValue:))
4454 return @"getMetadataValue";
4455 else if (selector == @selector(getSessionValue:))
4456 return @"getSessionValue";
4457 else if (selector == @selector(installPackages:))
4458 return @"installPackages";
4459 else if (selector == @selector(isReachable:))
4460 return @"isReachable";
4461 else if (selector == @selector(localizedStringForKey:value:table:))
4463 else if (selector == @selector(popViewController:))
4464 return @"popViewController";
4465 else if (selector == @selector(refreshSources))
4466 return @"refreshSources";
4467 else if (selector == @selector(registerFrame:))
4468 return @"registerFrame";
4469 else if (selector == @selector(removeButton))
4470 return @"removeButton";
4471 else if (selector == @selector(saveConfig))
4472 return @"saveConfig";
4473 else if (selector == @selector(setMetadataValue::))
4474 return @"setMetadataValue";
4475 else if (selector == @selector(setSessionValue::))
4476 return @"setSessionValue";
4477 else if (selector == @selector(substitutePackageNames:))
4478 return @"substitutePackageNames";
4479 else if (selector == @selector(scrollToBottom:))
4480 return @"scrollToBottom";
4481 else if (selector == @selector(setAllowsNavigationAction:))
4482 return @"setAllowsNavigationAction";
4483 else if (selector == @selector(setBadgeValue:))
4484 return @"setBadgeValue";
4485 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4486 return @"setButtonImage";
4487 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4488 return @"setButtonTitle";
4489 else if (selector == @selector(setHidesBackButton:))
4490 return @"setHidesBackButton";
4491 else if (selector == @selector(setHidesNavigationBar:))
4492 return @"setHidesNavigationBar";
4493 else if (selector == @selector(setNavigationBarStyle:))
4494 return @"setNavigationBarStyle";
4495 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4496 return @"setNavigationBarTintColor";
4497 else if (selector == @selector(setPasteboardString:))
4498 return @"setPasteboardString";
4499 else if (selector == @selector(setPasteboardURL:))
4500 return @"setPasteboardURL";
4501 else if (selector == @selector(setScrollAlwaysBounceVertical:))
4502 return @"setScrollAlwaysBounceVertical";
4503 else if (selector == @selector(setScrollIndicatorStyle:))
4504 return @"setScrollIndicatorStyle";
4505 else if (selector == @selector(setToken:))
4507 else if (selector == @selector(setViewportWidth:))
4508 return @"setViewportWidth";
4509 else if (selector == @selector(statfs:))
4511 else if (selector == @selector(supports:))
4513 else if (selector == @selector(unload))
4519 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4520 return [self webScriptNameForSelector:selector] == nil;
4523 - (BOOL) supports:(NSString *)feature {
4524 return [feature isEqualToString:@"window.open"];
4528 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4531 - (void) setScrollAlwaysBounceVertical:(NSNumber *)value {
4532 [indirect_ performSelectorOnMainThread:@selector(setScrollAlwaysBounceVerticalNumber:) withObject:value waitUntilDone:NO];
4535 - (void) setScrollIndicatorStyle:(NSString *)style {
4536 [indirect_ performSelectorOnMainThread:@selector(setScrollIndicatorStyleWithName:) withObject:style waitUntilDone:NO];
4539 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4540 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4543 - (NSDictionary *) getApplicationInfo:(NSString *)display value:(NSString *)key {
4545 if (SBBundlePathForDisplayIdentifier(SBSSpringBoardServerPort(), [display UTF8String], path) != 0)
4546 return (id) [NSNull null];
4547 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:[[NSString stringWithUTF8String:path] stringByAppendingString:@"/Info.plist"]]);
4549 return (id) [NSNull null];
4550 return [info objectForKey:key];
4553 - (NSNumber *) getKernelNumber:(NSString *)name {
4554 const char *string([name UTF8String]);
4557 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4558 return (id) [NSNull null];
4560 if (size != sizeof(int))
4561 return (id) [NSNull null];
4564 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4565 return (id) [NSNull null];
4567 return [NSNumber numberWithInt:value];
4570 - (NSString *) getKernelString:(NSString *)name {
4571 const char *string([name UTF8String]);
4574 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4575 return (id) [NSNull null];
4577 char value[size + 1];
4578 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4579 return (id) [NSNull null];
4581 // XXX: just in case you request something ludicrous
4584 return [NSString stringWithCString:value];
4587 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4588 NSObject *value(CYIOGetValue([path UTF8String], entry));
4591 if ([value isKindOfClass:[NSData class]])
4592 value = CYHex((NSData *) value);
4597 - (NSArray *) getMetadataKeys {
4598 @synchronized (Values_) {
4599 return [Values_ allKeys];
4602 - (void) registerFrame:(DOMHTMLIFrameElement *)iframe {
4603 WebFrame *frame([iframe contentFrame]);
4604 [indirect_ registerFrame:frame];
4607 - (id) getMetadataValue:(NSString *)key {
4608 @synchronized (Values_) {
4609 return [Values_ objectForKey:key];
4612 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4613 @synchronized (Values_) {
4614 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4615 [Values_ removeObjectForKey:key];
4617 [Values_ setObject:value forKey:key];
4619 [delegate_ performSelectorOnMainThread:@selector(updateValues) withObject:nil waitUntilDone:YES];
4622 - (id) getSessionValue:(NSString *)key {
4623 @synchronized (SessionData_) {
4624 return [SessionData_ objectForKey:key];
4627 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4628 @synchronized (SessionData_) {
4629 if (value == (id) [WebUndefined undefined])
4630 [SessionData_ removeObjectForKey:key];
4632 [SessionData_ setObject:value forKey:key];
4635 - (void) addBridgedHost:(NSString *)host {
4636 @synchronized (HostConfig_) {
4637 [BridgedHosts_ addObject:host];
4640 - (void) addInsecureHost:(NSString *)host {
4641 @synchronized (HostConfig_) {
4642 [InsecureHosts_ addObject:host];
4645 - (void) addTokenHost:(NSString *)host {
4646 @synchronized (HostConfig_) {
4647 [TokenHosts_ addObject:host];
4650 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4651 @synchronized (HostConfig_) {
4652 if (scheme != (id) [WebUndefined undefined])
4653 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4655 [PipelinedHosts_ addObject:host];
4658 - (void) popViewController:(NSNumber *)value {
4659 if (value == (id) [WebUndefined undefined])
4660 value = [NSNumber numberWithBool:YES];
4661 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4664 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4665 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4667 for (NSString *section in sections)
4668 [array addObject:section];
4670 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4673 distribution, @"Distribution",
4675 nil] waitUntilDone:NO];
4678 - (void) addTrivialSource:(NSString *)href {
4679 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4682 - (void) refreshSources {
4683 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4686 - (void) saveConfig {
4687 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4690 - (NSArray *) getAllSources {
4691 return [[Database sharedInstance] sources];
4694 - (NSArray *) getInstalledPackages {
4695 Database *database([Database sharedInstance]);
4696 @synchronized (database) {
4697 NSArray *packages([database packages]);
4698 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4699 for (Package *package in packages)
4700 if (![package uninstalled])
4701 [installed addObject:package];
4705 - (Package *) getPackageById:(NSString *)id {
4706 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4710 return (Package *) [NSNull null];
4713 - (NSString *) getLocaleIdentifier {
4714 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4717 - (NSArray *) getPreferredLanguages {
4721 - (NSArray *) statfs:(NSString *)path {
4724 if (path == nil || statfs([path UTF8String], &stat) == -1)
4727 return [NSArray arrayWithObjects:
4728 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4729 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4730 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4734 - (NSNumber *) du:(NSString *)path {
4735 NSNumber *value(nil);
4738 _assert(pipe(fds) != -1);
4740 pid_t pid(ExecFork());
4742 _assert(dup2(fds[1], 1) != -1);
4743 _assert(close(fds[0]) != -1);
4744 _assert(close(fds[1]) != -1);
4745 /* XXX: this should probably not use du */
4746 _root(execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL));
4749 _assert(close(fds[1]) != -1);
4751 if (FILE *du = fdopen(fds[0], "r")) {
4753 while (fgets(line, sizeof(line), du) != NULL) {
4754 size_t length(strlen(line));
4755 while (length != 0 && line[length - 1] == '\n')
4756 line[--length] = '\0';
4757 if (char *tab = strchr(line, '\t')) {
4759 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4765 _assert(close(fds[0]) != -1);
4772 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4775 - (NSNumber *) isReachable:(NSString *)name {
4776 return [NSNumber numberWithBool:IsReachable([name UTF8String])];
4779 - (void) installPackages:(NSArray *)packages {
4780 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4783 - (NSString *) substitutePackageNames:(NSString *)message {
4784 NSMutableArray *words([[[message componentsSeparatedByString:@" "] mutableCopy] autorelease]);
4785 for (size_t i(0), e([words count]); i != e; ++i) {
4786 NSString *word([words objectAtIndex:i]);
4787 if (Package *package = [[Database sharedInstance] packageWithName:word])
4788 [words replaceObjectAtIndex:i withObject:[package name]];
4791 return [words componentsJoinedByString:@" "];
4794 - (void) removeButton {
4795 [indirect_ removeButton];
4798 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4799 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4802 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4803 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4806 - (void) setBadgeValue:(id)value {
4807 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4810 - (void) setAllowsNavigationAction:(NSString *)value {
4811 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4814 - (void) setHidesBackButton:(NSString *)value {
4815 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4818 - (void) setHidesNavigationBar:(NSString *)value {
4819 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4822 - (void) setNavigationBarStyle:(NSString *)value {
4823 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4826 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4827 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4828 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4829 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4832 - (void) setPasteboardString:(NSString *)value {
4833 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4836 - (void) setPasteboardURL:(NSString *)value {
4837 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4840 - (void) _setToken:(NSString *)token {
4844 [Metadata_ removeObjectForKey:@"Token"];
4846 [Metadata_ setObject:Token_ forKey:@"Token"];
4851 - (void) setToken:(NSString *)token {
4852 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4855 - (void) scrollToBottom:(NSNumber *)animated {
4856 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4859 - (void) setViewportWidth:(float)width {
4860 [indirect_ setViewportWidthOnMainThread:width];
4863 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4864 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4865 unsigned count([arguments count]);
4867 for (unsigned i(0); i != count; ++i)
4868 values[i] = [arguments objectAtIndex:i];
4869 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4872 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4873 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4875 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4877 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4883 @interface NSURL (CydiaSecure)
4886 @implementation NSURL (CydiaSecure)
4888 - (bool) isCydiaSecure {
4889 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4892 @synchronized (HostConfig_) {
4893 if ([InsecureHosts_ containsObject:[self host]])
4902 /* Cydia Browser Controller {{{ */
4903 @implementation CydiaWebViewController
4905 - (NSURL *) navigationURL {
4906 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4909 + (void) _initialize {
4910 [super _initialize];
4912 Diversions_ = [NSMutableSet setWithCapacity:0];
4915 + (void) addDiversion:(Diversion *)diversion {
4916 [Diversions_ addObject:diversion];
4919 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4920 [super webView:view didClearWindowObject:window forFrame:frame];
4921 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
4924 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia {
4925 WebDataSource *source([frame dataSource]);
4926 NSURLResponse *response([source response]);
4927 NSURL *url([response URL]);
4928 NSString *scheme([[url scheme] lowercaseString]);
4930 bool bridged(false);
4932 @synchronized (HostConfig_) {
4933 if ([scheme isEqualToString:@"file"])
4935 else if ([scheme isEqualToString:@"https"])
4936 if ([BridgedHosts_ containsObject:[url host]])
4941 [window setValue:cydia forKey:@"cydia"];
4944 - (void) _setupMail:(MFMailComposeViewController *)controller {
4945 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4947 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4948 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4951 - (NSURL *) URLWithURL:(NSURL *)url {
4952 return [Diversion divertURL:url];
4955 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4956 return [CydiaWebViewController requestWithHeaders:[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
4959 - (NSURLRequest *) webThreadWebView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4960 return [CydiaWebViewController requestWithHeaders:[super webThreadWebView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
4963 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request {
4964 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
4966 NSURL *url([copy URL]);
4967 NSString *href([url absoluteString]);
4968 NSString *host([url host]);
4970 if ([href hasPrefix:@"https://cydia.saurik.com/TSS/"]) {
4971 if (NSString *agent = [copy valueForHTTPHeaderField:@"X-User-Agent"]) {
4972 [copy setValue:agent forHTTPHeaderField:@"User-Agent"];
4973 [copy setValue:nil forHTTPHeaderField:@"X-User-Agent"];
4976 [copy setValue:nil forHTTPHeaderField:@"Referer"];
4977 [copy setValue:nil forHTTPHeaderField:@"Origin"];
4979 [copy setURL:[NSURL URLWithString:[@"http://gs.apple.com/TSS/" stringByAppendingString:[href substringFromIndex:29]]]];
4983 if ([copy valueForHTTPHeaderField:@"X-Cydia-Cf"] == nil)
4984 [copy setValue:[NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber] forHTTPHeaderField:@"X-Cydia-Cf"];
4985 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4986 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4991 @synchronized (HostConfig_) {
4992 bridged = [BridgedHosts_ containsObject:host];
4993 token = [TokenHosts_ containsObject:host];
4996 if ([url isCydiaSecure]) {
4998 if (UniqueID_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Id"] == nil)
4999 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
5001 if (Token_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Token"] == nil)
5002 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
5009 - (void) setDelegate:(id)delegate {
5010 [super setDelegate:delegate];
5011 [cydia_ setDelegate:delegate];
5014 - (NSString *) applicationNameForUserAgent {
5019 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
5020 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
5026 @interface AppCacheController : CydiaWebViewController {
5031 @implementation AppCacheController
5033 - (void) didReceiveMemoryWarning {
5034 // XXX: this doesn't work
5037 - (bool) retainsNetworkActivityIndicator {
5045 @interface NSObject (CydiaScript)
5046 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
5049 @implementation NSObject (CydiaScript)
5051 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5057 @implementation NSArray (CydiaScript)
5059 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5060 WebScriptObject *object([context evaluateWebScript:@"[]"]);
5061 for (size_t i(0), e([self count]); i != e; ++i)
5062 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
5068 @implementation NSDictionary (CydiaScript)
5070 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5071 WebScriptObject *object([context evaluateWebScript:@"({})"]);
5073 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
5080 /* Confirmation Controller {{{ */
5081 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
5082 if (!iterator.end())
5083 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
5084 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
5086 pkgCache::PkgIterator package(dep.TargetPkg());
5089 if (strcmp(package.Name(), "mobilesubstrate") == 0)
5096 @protocol ConfirmationControllerDelegate
5097 - (void) cancelAndClear:(bool)clear;
5098 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
5102 @interface ConfirmationController : CydiaWebViewController {
5103 _transient Database *database_;
5105 _H<UIAlertView> essential_;
5107 _H<NSDictionary> changes_;
5108 _H<NSMutableArray> issues_;
5109 _H<NSDictionary> sizes_;
5114 - (id) initWithDatabase:(Database *)database;
5118 @implementation ConfirmationController
5122 RestartSubstrate_ = true;
5123 [delegate_ confirmWithNavigationController:[self navigationController]];
5126 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
5127 NSString *context([alert context]);
5129 if ([context isEqualToString:@"remove"]) {
5130 if (button == [alert cancelButtonIndex])
5132 else if (button == [alert firstOtherButtonIndex]) {
5133 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
5136 [alert dismissWithClickedButtonIndex:-1 animated:YES];
5137 } else if ([context isEqualToString:@"unable"]) {
5138 [self dismissModalViewControllerAnimated:YES];
5139 [alert dismissWithClickedButtonIndex:-1 animated:YES];
5141 [super alertView:alert clickedButtonAtIndex:button];
5145 - (void) _doContinue {
5146 [delegate_ cancelAndClear:NO];
5147 [self dismissModalViewControllerAnimated:YES];
5150 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
5151 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
5155 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5156 [super webView:view didClearWindowObject:window forFrame:frame];
5158 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
5159 (id) changes_, @"changes",
5160 (id) issues_, @"issues",
5161 (id) sizes_, @"sizes",
5163 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
5166 - (id) initWithDatabase:(Database *)database {
5167 if ((self = [super init]) != nil) {
5168 database_ = database;
5170 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
5171 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
5172 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
5173 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
5174 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
5178 pkgCacheFile &cache([database_ cache]);
5179 NSArray *packages([database_ packages]);
5180 pkgDepCache::Policy *policy([database_ policy]);
5182 issues_ = [NSMutableArray arrayWithCapacity:4];
5184 UpgradeCydia_ = false;
5186 for (Package *package in packages) {
5187 pkgCache::PkgIterator iterator([package iterator]);
5188 NSString *name([package id]);
5190 if ([package broken]) {
5191 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
5193 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5195 reasons, @"reasons",
5198 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
5202 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
5203 pkgCache::DepIterator start;
5204 pkgCache::DepIterator end;
5205 dep.GlobOr(start, end); // ++dep
5207 if (!cache->IsImportantDep(end))
5209 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
5212 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
5214 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5215 [NSString stringWithUTF8String:start.DepType()], @"relationship",
5216 clauses, @"clauses",
5220 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
5222 pkgCache::PkgIterator target(start.TargetPkg());
5223 if (target->ProvidesList != 0)
5224 reason = @"missing";
5226 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
5228 reason = @"installed";
5229 installed = [NSString stringWithUTF8String:ver.VerStr()];
5230 } else if (!cache[target].CandidateVerIter(cache).end())
5231 reason = @"uninstalled";
5232 else if (target->ProvidesList == 0)
5233 reason = @"uninstallable";
5235 reason = @"virtual";
5238 NSDictionary *version(start.TargetVer() == 0 ? (NSDictionary *) [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
5239 [NSString stringWithUTF8String:start.CompType()], @"operator",
5240 [NSString stringWithUTF8String:start.TargetVer()], @"value",
5243 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5244 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
5245 version, @"version",
5247 installed, @"installed",
5250 // yes, seriously. (wtf?)
5258 pkgDepCache::StateCache &state(cache[iterator]);
5260 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
5262 if (state.NewInstall())
5263 [installs addObject:name];
5264 // XXX: else if (state.Install())
5265 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
5266 [reinstalls addObject:name];
5267 // XXX: move before previous if
5268 else if (state.Upgrade())
5269 [upgrades addObject:name];
5270 else if (state.Downgrade())
5271 [downgrades addObject:name];
5272 else if (!state.Delete())
5273 // XXX: _assert(state.Keep());
5275 else if (special_r(name))
5276 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5277 [NSNull null], @"package",
5278 [NSArray arrayWithObjects:
5279 [NSDictionary dictionaryWithObjectsAndKeys:
5280 @"Conflicts", @"relationship",
5281 [NSArray arrayWithObjects:
5282 [NSDictionary dictionaryWithObjectsAndKeys:
5284 [NSNull null], @"version",
5285 @"installed", @"reason",
5292 if ([package essential])
5294 [removes addObject:name];
5297 if ([name isEqualToString:@"cydia"])
5298 UpgradeCydia_ = true;
5300 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
5301 substrate_ |= DepSubstrate(iterator.CurrentVer());
5306 else if (Advanced_) {
5307 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
5309 essential_ = [[[UIAlertView alloc]
5310 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
5311 message:UCLocalize("REMOVING_ESSENTIALS_EX")
5313 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
5315 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
5319 [essential_ setContext:@"remove"];
5320 [essential_ setNumberOfRows:2];
5322 essential_ = [[[UIAlertView alloc]
5323 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
5324 message:UCLocalize("UNABLE_TO_COMPLY_EX")
5326 cancelButtonTitle:UCLocalize("OKAY")
5327 otherButtonTitles:nil
5330 [essential_ setContext:@"unable"];
5333 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5334 installs, @"installs",
5335 reinstalls, @"reinstalls",
5336 upgrades, @"upgrades",
5337 downgrades, @"downgrades",
5338 removes, @"removes",
5341 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5342 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
5343 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
5346 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
5350 - (UIBarButtonItem *) leftButton {
5351 return [[[UIBarButtonItem alloc]
5352 initWithTitle:UCLocalize("CANCEL")
5353 style:UIBarButtonItemStylePlain
5355 action:@selector(cancelButtonClicked)
5360 - (void) applyRightButton {
5361 if ([issues_ count] == 0 && ![self isLoading])
5362 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
5363 initWithTitle:UCLocalize("CONFIRM")
5364 style:UIBarButtonItemStyleDone
5366 action:@selector(confirmButtonClicked)
5369 [[self navigationItem] setRightBarButtonItem:nil];
5373 - (void) cancelButtonClicked {
5374 [delegate_ cancelAndClear:YES];
5375 [self dismissModalViewControllerAnimated:YES];
5379 - (void) confirmButtonClicked {
5380 if (essential_ != nil)
5390 /* Progress Data {{{ */
5391 @interface CydiaProgressData : NSObject {
5392 _transient id delegate_;
5401 _H<NSMutableArray> events_;
5402 _H<NSString> title_;
5404 _H<NSString> status_;
5405 _H<NSString> finish_;
5410 @implementation CydiaProgressData
5412 + (NSArray *) _attributeKeys {
5413 return [NSArray arrayWithObjects:
5425 - (NSArray *) attributeKeys {
5426 return [[self class] _attributeKeys];
5429 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5430 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5434 if ((self = [super init]) != nil) {
5435 events_ = [NSMutableArray arrayWithCapacity:32];
5443 - (void) setDelegate:(id)delegate {
5444 delegate_ = delegate;
5447 - (void) setPercent:(float)value {
5451 - (NSNumber *) percent {
5452 return [NSNumber numberWithFloat:percent_];
5455 - (void) setCurrent:(float)value {
5459 - (NSNumber *) current {
5460 return [NSNumber numberWithFloat:current_];
5463 - (void) setTotal:(float)value {
5467 - (NSNumber *) total {
5468 return [NSNumber numberWithFloat:total_];
5471 - (void) setSpeed:(float)value {
5475 - (NSNumber *) speed {
5476 return [NSNumber numberWithFloat:speed_];
5479 - (NSArray *) events {
5483 - (void) removeAllEvents {
5484 [events_ removeAllObjects];
5487 - (void) addEvent:(CydiaProgressEvent *)event {
5488 [events_ addObject:event];
5491 - (void) setTitle:(NSString *)text {
5495 - (NSString *) title {
5499 - (void) setFinish:(NSString *)text {
5503 - (NSString *) finish {
5504 return (id) finish_ ?: [NSNull null];
5507 - (void) setRunning:(bool)running {
5511 - (NSNumber *) running {
5512 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5517 /* Progress Controller {{{ */
5518 @interface ProgressController : CydiaWebViewController <
5521 _transient Database *database_;
5522 _H<CydiaProgressData, 1> progress_;
5526 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5528 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5530 - (void) setTitle:(NSString *)title;
5531 - (void) setCancellable:(bool)cancellable;
5535 @implementation ProgressController
5538 [database_ setProgressDelegate:nil];
5542 - (UIBarButtonItem *) leftButton {
5543 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5544 initWithTitle:UCLocalize("CANCEL")
5545 style:UIBarButtonItemStylePlain
5547 action:@selector(cancel)
5548 ] autorelease] : nil;
5551 - (void) updateCancel {
5552 [super applyLeftButton];
5555 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5556 if ((self = [super init]) != nil) {
5557 database_ = database;
5558 delegate_ = delegate;
5560 [database_ setProgressDelegate:self];
5562 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5563 [progress_ setDelegate:self];
5565 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5567 [scroller_ setBackgroundColor:[UIColor blackColor]];
5569 [[self navigationItem] setHidesBackButton:YES];
5571 [self updateCancel];
5575 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5576 [super webView:view didClearWindowObject:window forFrame:frame];
5577 [window setValue:progress_ forKey:@"cydiaProgress"];
5580 - (void) updateProgress {
5581 [self dispatchEvent:@"CydiaProgressUpdate"];
5584 - (void) viewWillAppear:(BOOL)animated {
5585 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5586 [super viewWillAppear:animated];
5589 - (void) reloadSpringBoard {
5590 if (kCFCoreFoundationVersionNumber > 700) { // XXX: iOS 6.x
5591 system("/bin/launchctl stop com.apple.backboardd");
5593 system("/usr/bin/killall backboardd SpringBoard sbreload");
5597 pid_t pid(ExecFork());
5602 pid_t pid(ExecFork());
5604 _root(execl("/usr/bin/sbreload", "sbreload", NULL));
5614 system("/usr/bin/killall backboardd SpringBoard sbreload");
5618 UpdateExternalStatus(0);
5621 [delegate_ saveState];
5625 [delegate_ returnToCydia];
5629 [delegate_ terminateWithSuccess];
5630 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5631 [delegate_ suspendWithAnimation:YES];
5633 [delegate_ suspend];*/
5645 UIProgressHUD *hud([delegate_ addProgressHUD]);
5646 [hud setText:UCLocalize("LOADING")];
5647 [self performSelector:@selector(reloadSpringBoard) withObject:nil afterDelay:0.5];
5653 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5654 SBReboot(SBSSpringBoardServerPort());
5656 reboot2(RB_AUTOBOOT);
5663 - (void) setTitle:(NSString *)title {
5664 [progress_ setTitle:title];
5665 [self updateProgress];
5668 - (UIBarButtonItem *) rightButton {
5669 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5670 initWithTitle:UCLocalize("CLOSE")
5671 style:UIBarButtonItemStylePlain
5673 action:@selector(close)
5677 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5678 UpdateExternalStatus(1);
5680 [progress_ setRunning:true];
5681 [self setTitle:title];
5682 // implicit updateProgress
5684 SHA1SumValue notifyconf; {
5686 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5689 MMap mmap(file, MMap::ReadOnly);
5691 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5692 notifyconf = sha1.Result();
5696 SHA1SumValue springlist; {
5698 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5701 MMap mmap(file, MMap::ReadOnly);
5703 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5704 springlist = sha1.Result();
5708 if (invocation != nil) {
5709 [invocation yieldToSelector:@selector(invoke)];
5710 [self setTitle:@"COMPLETE"];
5715 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5718 MMap mmap(file, MMap::ReadOnly);
5720 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5721 if (!(notifyconf == sha1.Result()))
5728 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5731 MMap mmap(file, MMap::ReadOnly);
5733 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5734 if (!(springlist == sha1.Result()))
5740 if (RestartSubstrate_)
5744 RestartSubstrate_ = false;
5747 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5748 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5749 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5750 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5751 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5754 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5756 [progress_ setRunning:false];
5757 [self updateProgress];
5759 [self applyRightButton];
5762 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5763 [progress_ addEvent:event];
5764 [self updateProgress];
5767 - (bool) isProgressCancelled {
5768 return cancel_ == 2;
5773 [self updateCancel];
5776 - (void) setCancellable:(bool)cancellable {
5777 unsigned cancel(cancel_);
5781 else if (cancel_ == 0)
5784 if (cancel != cancel_)
5785 [self updateCancel];
5788 - (void) setProgressCancellable:(NSNumber *)cancellable {
5789 [self setCancellable:[cancellable boolValue]];
5792 - (void) setProgressPercent:(NSNumber *)percent {
5793 [progress_ setPercent:[percent floatValue]];
5794 [self updateProgress];
5797 - (void) setProgressStatus:(NSDictionary *)status {
5798 if (status == nil) {
5799 [progress_ setCurrent:0];
5800 [progress_ setTotal:0];
5801 [progress_ setSpeed:0];
5803 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5805 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5806 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5807 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5810 [self updateProgress];
5816 /* Package Cell {{{ */
5817 @interface PackageCell : CyteTableViewCell <
5818 CyteTableViewCellDelegate
5822 _H<NSString> description_;
5824 _H<NSString> source_;
5826 _H<UIImage> placard_;
5830 - (PackageCell *) init;
5831 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5833 - (void) drawContentRect:(CGRect)rect;
5837 @implementation PackageCell
5839 - (PackageCell *) init {
5840 CGRect frame(CGRectMake(0, 0, 320, 74));
5841 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5842 UIView *content([self contentView]);
5843 CGRect bounds([content bounds]);
5845 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5846 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5847 [content addSubview:content_];
5849 [content_ setDelegate:self];
5850 [content_ setOpaque:YES];
5854 - (NSString *) accessibilityLabel {
5858 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5859 summarized_ = summary;
5869 [content_ setBackgroundColor:[UIColor whiteColor]];
5873 Source *source = [package source];
5875 icon_ = [package icon];
5877 if (NSString *name = [package name])
5878 name_ = [NSString stringWithString:name];
5880 if (NSString *description = [package shortDescription])
5881 description_ = [NSString stringWithString:description];
5883 commercial_ = [package isCommercial];
5885 NSString *label = nil;
5886 bool trusted = false;
5888 if (source != nil) {
5889 label = [source label];
5890 trusted = [source trusted];
5891 } else if ([[package id] isEqualToString:@"firmware"])
5892 label = UCLocalize("APPLE");
5894 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5896 NSString *from(label);
5898 NSString *section = [package simpleSection];
5899 if (section != nil && ![section isEqualToString:label]) {
5900 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5901 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5904 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5906 if (NSString *purpose = [package primaryPurpose])
5907 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5912 if (NSString *mode = [package mode]) {
5913 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5914 color = RemovingColor_;
5915 placard = @"removing";
5917 color = InstallingColor_;
5918 placard = @"installing";
5921 color = [UIColor whiteColor];
5923 if ([package installed] != nil)
5924 placard = @"installed";
5929 [content_ setBackgroundColor:color];
5932 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5935 [self setNeedsDisplay];
5936 [content_ setNeedsDisplay];
5939 - (void) drawSummaryContentRect:(CGRect)rect {
5940 bool highlighted(highlighted_);
5941 float width([self bounds].size.width);
5945 rect.size = [(UIImage *) icon_ size];
5947 while (rect.size.width > 16 || rect.size.height > 16) {
5948 rect.size.width /= 2;
5949 rect.size.height /= 2;
5952 rect.origin.x = 19 - rect.size.width / 2;
5953 rect.origin.y = 19 - rect.size.height / 2;
5955 [icon_ drawInRect:Retina(rect)];
5958 if (badge_ != nil) {
5960 rect.size = [(UIImage *) badge_ size];
5962 rect.size.width /= 4;
5963 rect.size.height /= 4;
5965 rect.origin.x = 25 - rect.size.width / 2;
5966 rect.origin.y = 25 - rect.size.height / 2;
5968 [badge_ drawInRect:Retina(rect)];
5971 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5975 UISetColor(commercial_ ? Purple_ : Black_);
5976 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
5978 if (placard_ != nil)
5979 [placard_ drawAtPoint:CGPointMake(width - 52, 11)];
5982 - (void) drawNormalContentRect:(CGRect)rect {
5983 bool highlighted(highlighted_);
5984 float width([self bounds].size.width);
5988 rect.size = [(UIImage *) icon_ size];
5990 while (rect.size.width > 32 || rect.size.height > 32) {
5991 rect.size.width /= 2;
5992 rect.size.height /= 2;
5995 rect.origin.x = 25 - rect.size.width / 2;
5996 rect.origin.y = 25 - rect.size.height / 2;
5998 [icon_ drawInRect:Retina(rect)];
6001 if (badge_ != nil) {
6003 rect.size = [(UIImage *) badge_ size];
6005 rect.size.width /= 2;
6006 rect.size.height /= 2;
6008 rect.origin.x = 36 - rect.size.width / 2;
6009 rect.origin.y = 36 - rect.size.height / 2;
6011 [badge_ drawInRect:Retina(rect)];
6014 if (highlighted && kCFCoreFoundationVersionNumber < 800)
6018 UISetColor(commercial_ ? Purple_ : Black_);
6019 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
6020 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
6023 UISetColor(commercial_ ? Purplish_ : Gray_);
6024 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:NSLineBreakByTruncatingTail];
6026 if (placard_ != nil)
6027 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
6030 - (void) drawContentRect:(CGRect)rect {
6032 [self drawSummaryContentRect:rect];
6034 [self drawNormalContentRect:rect];
6039 /* Section Cell {{{ */
6040 @interface SectionCell : CyteTableViewCell <
6041 CyteTableViewCellDelegate
6043 _H<NSString> basic_;
6044 _H<NSString> section_;
6046 _H<NSString> count_;
6048 _H<UISwitch> switch_;
6052 - (void) setSection:(Section *)section editing:(BOOL)editing;
6056 @implementation SectionCell
6058 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
6059 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
6060 icon_ = [UIImage imageNamed:@"folder.png"];
6061 // XXX: this initial frame is wrong, but is fixed later
6062 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
6063 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
6065 UIView *content([self contentView]);
6066 CGRect bounds([content bounds]);
6068 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
6069 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6070 [content addSubview:content_];
6071 [content_ setBackgroundColor:[UIColor whiteColor]];
6073 [content_ setDelegate:self];
6077 - (void) onSwitch:(id)sender {
6078 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
6079 if (metadata == nil) {
6080 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
6081 [Sections_ setObject:metadata forKey:basic_];
6084 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
6088 - (void) setSection:(Section *)section editing:(BOOL)editing {
6089 if (editing != editing_) {
6091 [switch_ removeFromSuperview];
6093 [self addSubview:switch_];
6102 if (section == nil) {
6103 name_ = UCLocalize("ALL_PACKAGES");
6106 basic_ = [section name];
6107 section_ = [section localized];
6109 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
6110 count_ = [NSString stringWithFormat:@"%zd", [section count]];
6113 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
6116 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
6117 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
6119 [content_ setNeedsDisplay];
6122 - (void) setFrame:(CGRect)frame {
6123 [super setFrame:frame];
6125 CGRect rect([switch_ frame]);
6126 [switch_ setFrame:CGRectMake(frame.size.width - rect.size.width - 9, 9, rect.size.width, rect.size.height)];
6129 - (NSString *) accessibilityLabel {
6133 - (void) drawContentRect:(CGRect)rect {
6134 bool highlighted(highlighted_ && !editing_);
6136 [icon_ drawInRect:CGRectMake(7, 7, 32, 32)];
6138 if (highlighted && kCFCoreFoundationVersionNumber < 800)
6141 float width(rect.size.width);
6143 width -= 9 + [switch_ frame].size.width;
6147 [name_ drawAtPoint:CGPointMake(48, 12) forWidth:(width - 58) withFont:Font18_ lineBreakMode:NSLineBreakByTruncatingTail];
6149 CGSize size = [count_ sizeWithFont:Font14_];
6151 UISetColor(Folder_);
6153 [count_ drawAtPoint:CGPointMake(Retina(10 + (30 - size.width) / 2), 18) withFont:Font12Bold_];
6159 /* File Table {{{ */
6160 @interface FileTable : CyteViewController <
6161 UITableViewDataSource,
6164 _transient Database *database_;
6165 _H<Package> package_;
6167 _H<NSMutableArray> files_;
6168 _H<UITableView, 2> list_;
6171 - (id) initWithDatabase:(Database *)database;
6172 - (void) setPackage:(Package *)package;
6176 @implementation FileTable
6178 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6179 return files_ == nil ? 0 : [files_ count];
6182 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6186 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6187 static NSString *reuseIdentifier = @"Cell";
6189 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6191 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6192 [cell setFont:[UIFont systemFontOfSize:16]];
6194 [cell setText:[files_ objectAtIndex:indexPath.row]];
6195 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
6200 - (NSURL *) navigationURL {
6201 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
6205 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
6206 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6207 [list_ setRowHeight:24.0f];
6208 [(UITableView *) list_ setDataSource:self];
6209 [list_ setDelegate:self];
6210 [self setView:list_];
6213 - (void) viewDidLoad {
6214 [super viewDidLoad];
6216 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
6219 - (void) releaseSubviews {
6225 [super releaseSubviews];
6228 - (id) initWithDatabase:(Database *)database {
6229 if ((self = [super init]) != nil) {
6230 database_ = database;
6234 - (void) setPackage:(Package *)package {
6238 files_ = [NSMutableArray arrayWithCapacity:32];
6240 if (package != nil) {
6242 name_ = [package id];
6244 if (NSArray *files = [package files])
6245 [files_ addObjectsFromArray:files];
6247 if ([files_ count] != 0) {
6248 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
6249 [files_ removeObjectAtIndex:0];
6250 [files_ sortUsingSelector:@selector(compareByPath:)];
6252 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
6253 [stack addObject:@"/"];
6255 for (int i(0), e([files_ count]); i != e; ++i) {
6256 NSString *file = [files_ objectAtIndex:i];
6257 while (![file hasPrefix:[stack lastObject]])
6258 [stack removeLastObject];
6259 NSString *directory = [stack lastObject];
6260 [stack addObject:[file stringByAppendingString:@"/"]];
6261 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
6262 ([stack count] - 2) * 3, "",
6263 [file substringFromIndex:[directory length]]
6272 - (void) reloadData {
6275 [self setPackage:[database_ packageWithName:name_]];
6280 /* Package Controller {{{ */
6281 @interface CYPackageController : CydiaWebViewController <
6282 UIActionSheetDelegate
6284 _transient Database *database_;
6285 _H<Package> package_;
6288 std::vector<std::pair<_H<NSString>, _H<NSString>>> buttons_;
6289 _H<UIBarButtonItem> button_;
6292 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer;
6296 @implementation CYPackageController
6298 - (NSURL *) navigationURL {
6299 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
6302 - (void) _clickButtonWithName:(NSString *)name {
6303 if ([name isEqualToString:@"CLEAR"])
6304 [delegate_ clearPackage:package_];
6305 else if ([name isEqualToString:@"INSTALL"])
6306 [delegate_ installPackage:package_];
6307 else if ([name isEqualToString:@"REINSTALL"])
6308 [delegate_ installPackage:package_];
6309 else if ([name isEqualToString:@"REMOVE"])
6310 [delegate_ removePackage:package_];
6311 else if ([name isEqualToString:@"UPGRADE"])
6312 [delegate_ installPackage:package_];
6313 else _assert(false);
6316 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
6317 NSString *context([sheet context]);
6319 if ([context isEqualToString:@"modify"]) {
6320 if (button != [sheet cancelButtonIndex]) {
6322 [self performSelector:@selector(_clickButtonWithName:) withObject:buttons_[button].first afterDelay:0];
6324 [self _clickButtonWithName:buttons_[button].first];
6327 [sheet dismissWithClickedButtonIndex:button animated:YES];
6331 - (bool) _allowJavaScriptPanel {
6336 - (void) _customButtonClicked {
6337 size_t count(buttons_.size());
6342 [self _clickButtonWithName:buttons_[0].first];
6344 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
6345 for (const auto &button : buttons_)
6346 [buttons addObject:button.second];
6348 UIActionSheet *sheet = [[[UIActionSheet alloc]
6351 cancelButtonTitle:nil
6352 destructiveButtonTitle:nil
6353 otherButtonTitles:nil
6356 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
6358 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
6359 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
6361 [sheet setContext:@"modify"];
6363 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
6367 - (void) reloadButtonClicked {
6368 if (commercial_ && function_ == nil && [package_ uninstalled])
6370 [self customButtonClicked];
6373 - (void) applyLoadingTitle {
6374 // Don't show "Loading" as the title. Ever.
6377 - (UIBarButtonItem *) rightButton {
6382 - (void) setPageColor:(UIColor *)color {
6383 return [super setPageColor:nil];
6386 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer {
6387 if ((self = [super init]) != nil) {
6388 database_ = database;
6389 name_ = name == nil ? @"" : [NSString stringWithString:name];
6390 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]] withReferrer:referrer];
6394 - (void) reloadData {
6397 package_ = [database_ packageWithName:name_];
6401 if (package_ != nil) {
6402 [(Package *) package_ parse];
6404 commercial_ = [package_ isCommercial];
6406 if ([package_ mode] != nil)
6407 buttons_.push_back(std::make_pair(@"CLEAR", UCLocalize("CLEAR")));
6408 if ([package_ source] == nil);
6409 else if ([package_ upgradableAndEssential:NO])
6410 buttons_.push_back(std::make_pair(@"UPGRADE", UCLocalize("UPGRADE")));
6411 else if ([package_ uninstalled])
6412 buttons_.push_back(std::make_pair(@"INSTALL", UCLocalize("INSTALL")));
6414 buttons_.push_back(std::make_pair(@"REINSTALL", UCLocalize("REINSTALL")));
6415 if (![package_ uninstalled])
6416 buttons_.push_back(std::make_pair(@"REMOVE", UCLocalize("REMOVE")));
6420 switch (buttons_.size()) {
6421 case 0: title = nil; break;
6422 case 1: title = buttons_[0].second; break;
6423 default: title = UCLocalize("MODIFY"); break;
6426 button_ = [[[UIBarButtonItem alloc]
6428 style:UIBarButtonItemStylePlain
6430 action:@selector(customButtonClicked)
6434 - (bool) isLoading {
6435 return commercial_ ? [super isLoading] : false;
6441 /* Package List Controller {{{ */
6442 @interface PackageListController : CyteViewController <
6443 UITableViewDataSource,
6446 _transient Database *database_;
6448 _H<NSArray> packages_;
6449 _H<NSArray> sections_;
6450 _H<UITableView, 2> list_;
6452 _H<NSArray> thumbs_;
6453 std::vector<NSInteger> offset_;
6455 _H<NSString> title_;
6456 unsigned reloading_;
6459 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6460 - (void) setDelegate:(id)delegate;
6461 - (void) resetCursor;
6464 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages;
6468 @implementation PackageListController
6470 - (NSURL *) referrerURL {
6471 return [self navigationURL];
6474 - (bool) isSummarized {
6478 - (bool) showsSections {
6482 - (void) deselectWithAnimation:(BOOL)animated {
6483 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6486 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6487 CGRect base = [[self view] bounds];
6488 base.size.height -= bounds.size.height;
6489 base.origin = [list_ frame].origin;
6491 [UIView beginAnimations:nil context:NULL];
6492 [UIView setAnimationBeginsFromCurrentState:YES];
6493 [UIView setAnimationCurve:curve];
6494 [UIView setAnimationDuration:duration];
6495 [list_ setFrame:base];
6496 [UIView commitAnimations];
6499 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6500 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6503 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6504 [self resizeForKeyboardBounds:bounds duration:0];
6507 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6508 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6509 *curve = UIViewAnimationCurveEaseInOut;
6511 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6513 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6516 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6519 - (void) keyboardWillShow:(NSNotification *)notification {
6522 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6523 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6525 NSTimeInterval duration;
6526 UIViewAnimationCurve curve;
6527 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6529 CGRect kbframe = CGRectMake(Retina(center.x - bounds.size.width / 2), Retina(center.y - bounds.size.height / 2), bounds.size.width, bounds.size.height);
6530 UIViewController *base = self;
6531 while ([base parentOrPresentingViewController] != nil)
6532 base = [base parentOrPresentingViewController];
6533 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6534 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6536 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6537 intersection.size.height += CYStatusBarHeight();
6539 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6542 - (void) keyboardWillHide:(NSNotification *)notification {
6543 NSTimeInterval duration;
6544 UIViewAnimationCurve curve;
6545 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6547 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6550 - (void) viewWillAppear:(BOOL)animated {
6551 [super viewWillAppear:animated];
6553 [self resizeForKeyboardBounds:CGRectZero];
6554 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6555 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6558 - (void) viewWillDisappear:(BOOL)animated {
6559 [super viewWillDisappear:animated];
6561 [self resizeForKeyboardBounds:CGRectZero];
6562 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6563 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6566 - (void) viewDidAppear:(BOOL)animated {
6567 [super viewDidAppear:animated];
6568 [self deselectWithAnimation:animated];
6571 - (void) didSelectPackage:(Package *)package {
6572 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[[self referrerURL] absoluteString]] autorelease]);
6573 [view setDelegate:delegate_];
6574 [[self navigationController] pushViewController:view animated:YES];
6577 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6578 NSInteger count([sections_ count]);
6579 return count == 0 ? 1 : count;
6582 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6583 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6585 return [[sections_ objectAtIndex:section] name];
6588 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6589 if ([sections_ count] == 0)
6591 return [[sections_ objectAtIndex:section] count];
6594 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6595 @synchronized (database_) {
6596 if ([database_ era] != era_)
6599 Section *section([sections_ objectAtIndex:[path section]]);
6600 NSInteger row([path row]);
6601 Package *package([packages_ objectAtIndex:([section row] + row)]);
6602 return [[package retain] autorelease];
6605 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6606 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6608 cell = [[[PackageCell alloc] init] autorelease];
6610 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6611 [cell setPackage:package asSummary:[self isSummarized]];
6615 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6616 Package *package([self packageAtIndexPath:path]);
6617 package = [database_ packageWithName:[package id]];
6618 [self didSelectPackage:package];
6621 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6625 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6626 return offset_[index];
6629 - (void) updateHeight {
6630 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6633 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6634 if ((self = [super init]) != nil) {
6635 database_ = database;
6636 title_ = [title copy];
6637 [[self navigationItem] setTitle:title_];
6642 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
6643 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
6644 [self setView:view];
6646 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6647 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6648 [view addSubview:list_];
6650 // XXX: is 20 the most optimal number here?
6651 [list_ setSectionIndexMinimumDisplayRowCount:20];
6653 [(UITableView *) list_ setDataSource:self];
6654 [list_ setDelegate:self];
6656 [self updateHeight];
6659 - (void) releaseSubviews {
6668 [super releaseSubviews];
6671 - (void) setDelegate:(id)delegate {
6672 delegate_ = delegate;
6675 - (bool) shouldYield {
6679 - (bool) shouldBlock {
6683 - (NSMutableArray *) _reloadPackages {
6684 @synchronized (database_) {
6685 era_ = [database_ era];
6686 NSArray *packages([database_ packages]);
6688 return [NSMutableArray arrayWithArray:packages];
6691 - (void) _reloadData {
6692 if (reloading_ != 0) {
6697 NSMutableArray *packages;
6700 if ([self shouldYield]) {
6704 if (![self shouldBlock])
6707 hud = [delegate_ addProgressHUD];
6708 [hud setText:UCLocalize("LOADING")];
6712 packages = [self yieldToSelector:@selector(_reloadPackages)];
6715 [delegate_ removeProgressHUD:hud];
6716 } while (reloading_ == 2);
6718 packages = [self _reloadPackages];
6721 @synchronized (database_) {
6722 if (era_ != [database_ era])
6729 packages_ = packages;
6731 if ([self showsSections])
6732 sections_ = [self sectionsForPackages:packages];
6734 Section *section([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6735 [section setCount:[packages_ count]];
6736 sections_ = [NSArray arrayWithObject:section];
6739 [self updateHeight];
6741 _profile(PackageTable$reloadData$List)
6742 [(UITableView *) list_ setDataSource:self];
6750 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
6751 Section *prefix([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6752 size_t end([packages count]);
6754 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
6755 Section *section(prefix);
6757 thumbs_ = CollationThumbs_;
6758 offset_ = CollationOffset_;
6761 size_t offsets([CollationStarts_ count]);
6763 NSString *start([CollationStarts_ objectAtIndex:offset]);
6764 size_t length([start length]);
6766 for (size_t index(0); index != end; ++index) {
6768 Package *package([packages objectAtIndex:index]);
6769 NSString *name(PackageName(package, @selector(cyname)));
6771 //while ([start compare:name options:NSNumericSearch range:NSMakeRange(0, length) locale:CollationLocale_] != NSOrderedDescending) {
6772 while (StringNameCompare(start, name, length) != kCFCompareGreaterThan) {
6773 NSString *title([CollationTitles_ objectAtIndex:offset]);
6774 section = [[[Section alloc] initWithName:title row:index localize:NO] autorelease];
6775 [sections addObject:section];
6777 start = ++offset == offsets ? nil : [CollationStarts_ objectAtIndex:offset];
6780 length = [start length];
6784 [section addToCount];
6787 for (; offset != offsets; ++offset) {
6788 NSString *title([CollationTitles_ objectAtIndex:offset]);
6789 Section *section([[[Section alloc] initWithName:title row:end localize:NO] autorelease]);
6790 [sections addObject:section];
6793 if ([prefix count] != 0) {
6794 Section *suffix([sections lastObject]);
6795 [prefix setName:[suffix name]];
6796 [suffix setName:nil];
6797 [sections insertObject:prefix atIndex:(offsets - 1)];
6803 - (void) reloadData {
6806 if ([self shouldYield])
6807 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6812 - (void) resetCursor {
6813 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6816 - (void) clearData {
6817 [self updateHeight];
6819 [list_ setDataSource:nil];
6827 /* Filtered Package List Controller {{{ */
6828 typedef Function<bool, Package *> PackageFilter;
6829 typedef Function<void, NSMutableArray *> PackageSorter;
6830 @interface FilteredPackageListController : PackageListController {
6831 PackageFilter filter_;
6832 PackageSorter sorter_;
6835 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter;
6837 - (void) setFilter:(PackageFilter)filter;
6838 - (void) setSorter:(PackageSorter)sorter;
6842 @implementation FilteredPackageListController
6844 - (void) setFilter:(PackageFilter)filter {
6845 @synchronized (self) {
6849 - (void) setSorter:(PackageSorter)sorter {
6850 @synchronized (self) {
6854 - (NSMutableArray *) _reloadPackages {
6855 @synchronized (database_) {
6856 era_ = [database_ era];
6858 NSArray *packages([database_ packages]);
6859 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6861 PackageFilter filter;
6862 PackageSorter sorter;
6864 @synchronized (self) {
6869 _profile(PackageTable$reloadData$Filter)
6870 for (Package *package in packages)
6871 if ([package valid] && filter(package))
6872 [filtered addObject:package];
6880 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter {
6881 if ((self = [super initWithDatabase:database title:title]) != nil) {
6882 [self setFilter:filter];
6889 /* Home Controller {{{ */
6890 @interface HomeController : CydiaWebViewController {
6891 CFRunLoopRef runloop_;
6892 SCNetworkReachabilityRef reachability_;
6897 @implementation HomeController
6899 static void HomeControllerReachabilityCallback(SCNetworkReachabilityRef reachability, SCNetworkReachabilityFlags flags, void *info) {
6900 [(HomeController *) info dispatchEvent:@"CydiaReachabilityCallback"];
6904 if ((self = [super init]) != nil) {
6905 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6908 reachability_ = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "cydia.saurik.com");
6909 if (reachability_ != NULL) {
6910 SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
6911 SCNetworkReachabilitySetCallback(reachability_, HomeControllerReachabilityCallback, &context);
6913 CFRunLoopRef runloop(CFRunLoopGetCurrent());
6914 if (SCNetworkReachabilityScheduleWithRunLoop(reachability_, runloop, kCFRunLoopDefaultMode))
6921 if (reachability_ != NULL && runloop_ != NULL)
6922 SCNetworkReachabilityUnscheduleFromRunLoop(reachability_, runloop_, kCFRunLoopDefaultMode);
6926 - (NSURL *) navigationURL {
6927 return [NSURL URLWithString:@"cydia://home"];
6930 - (void) aboutButtonClicked {
6931 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6933 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6934 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6935 [alert setCancelButtonIndex:0];
6938 @"Copyright \u00a9 2008-2014\n"
6941 "Jay Freeman (saurik)\n"
6942 "saurik@saurik.com\n"
6943 "http://www.saurik.com/"
6949 - (UIBarButtonItem *) leftButton {
6950 return [[[UIBarButtonItem alloc]
6951 initWithTitle:UCLocalize("ABOUT")
6952 style:UIBarButtonItemStylePlain
6954 action:@selector(aboutButtonClicked)
6961 /* Cydia Navigation Controller Interface {{{ */
6962 @interface UINavigationController (Cydia)
6964 - (NSArray *) navigationURLCollection;
6965 - (void) unloadData;
6970 /* Cydia Tab Bar Controller {{{ */
6971 @interface CydiaTabBarController : CyteTabBarController <
6972 UITabBarControllerDelegate,
6975 _transient Database *database_;
6977 _H<UIActivityIndicatorView> indicator_;
6980 // XXX: ok, "updatedelegate_"?...
6981 _transient NSObject<CydiaDelegate> *updatedelegate_;
6984 - (NSArray *) navigationURLCollection;
6985 - (void) beginUpdate;
6990 @implementation CydiaTabBarController
6992 - (NSArray *) navigationURLCollection {
6993 NSMutableArray *items([NSMutableArray array]);
6995 // XXX: Should this deal with transient view controllers?
6996 for (id navigation in [self viewControllers]) {
6997 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6999 [items addObject:stack];
7005 - (id) initWithDatabase:(Database *)database {
7006 if ((self = [super init]) != nil) {
7007 database_ = database;
7008 [self setDelegate:self];
7010 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteTiny] autorelease];
7011 [indicator_ setOrigin:CGPointMake(kCFCoreFoundationVersionNumber >= 800 ? 2 : 4, 2)];
7013 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7017 - (void) setUpdate:(NSDate *)date {
7021 - (void) beginUpdate {
7025 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
7026 UITabBarItem *item([controller tabBarItem]);
7028 [item setBadgeValue:@""];
7029 UIView *badge(MSHookIvar<UIView *>([item view], "_badge"));
7031 [indicator_ startAnimating];
7032 [badge addSubview:indicator_];
7034 [updatedelegate_ retainNetworkActivityIndicator];
7038 detachNewThreadSelector:@selector(performUpdate)
7044 - (void) performUpdate {
7045 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
7047 SourceStatus status(self, database_);
7048 [database_ updateWithStatus:status];
7051 performSelectorOnMainThread:@selector(completeUpdate)
7059 - (void) stopUpdateWithSelector:(SEL)selector {
7061 [updatedelegate_ releaseNetworkActivityIndicator];
7063 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
7064 [[controller tabBarItem] setBadgeValue:nil];
7066 [indicator_ removeFromSuperview];
7067 [indicator_ stopAnimating];
7069 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
7072 - (void) completeUpdate {
7075 [self stopUpdateWithSelector:@selector(reloadData)];
7078 - (void) cancelUpdate {
7079 [self stopUpdateWithSelector:@selector(updateDataAndLoad)];
7082 - (void) cancelPressed {
7083 [self cancelUpdate];
7090 - (bool) isSourceCancelled {
7094 - (void) startSourceFetch:(NSString *)uri {
7097 - (void) stopSourceFetch:(NSString *)uri {
7100 - (void) setUpdateDelegate:(id)delegate {
7101 updatedelegate_ = delegate;
7107 /* Cydia Navigation Controller Implementation {{{ */
7108 @implementation UINavigationController (Cydia)
7110 - (NSArray *) navigationURLCollection {
7111 NSMutableArray *stack([NSMutableArray array]);
7113 for (CyteViewController *controller in [self viewControllers]) {
7114 NSString *url = [[controller navigationURL] absoluteString];
7116 [stack addObject:url];
7122 - (void) reloadData {
7125 UIViewController *visible([self visibleViewController]);
7127 [visible reloadData];
7129 // on the iPad, this view controller is ALSO visible. :(
7131 if (UIViewController *modal = [self modalViewController])
7132 if ([modal modalPresentationStyle] == UIModalPresentationFormSheet)
7133 if (UIViewController *top = [self topViewController])
7138 - (void) unloadData {
7139 for (CyteViewController *page in [self viewControllers])
7148 /* Cydia:// Protocol {{{ */
7149 @interface CydiaURLProtocol : NSURLProtocol {
7154 @implementation CydiaURLProtocol
7156 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7157 NSURL *url([request URL]);
7161 NSString *scheme([[url scheme] lowercaseString]);
7162 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7164 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7170 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7174 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7175 id<NSURLProtocolClient> client([self client]);
7177 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7179 NSData *data(UIImagePNGRepresentation(icon));
7181 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7182 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7183 [client URLProtocol:self didLoadData:data];
7184 [client URLProtocolDidFinishLoading:self];
7188 - (void) startLoading {
7189 id<NSURLProtocolClient> client([self client]);
7190 NSURLRequest *request([self request]);
7192 NSURL *url([request URL]);
7193 NSString *href([url absoluteString]);
7194 NSString *scheme([[url scheme] lowercaseString]);
7198 if ([scheme isEqualToString:@"cydia"])
7199 path = [href substringFromIndex:8];
7200 else if ([scheme isEqualToString:@"about"])
7201 path = [href substringFromIndex:12];
7202 else _assert(false);
7204 NSRange slash([path rangeOfString:@"/"]);
7207 if (slash.location == NSNotFound) {
7211 command = [path substringToIndex:slash.location];
7212 path = [path substringFromIndex:(slash.location + 1)];
7215 Database *database([Database sharedInstance]);
7217 if ([command isEqualToString:@"package-icon"]) {
7220 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7221 Package *package([database packageWithName:path]);
7225 UIImage *icon([package icon]);
7226 [self _returnPNGWithImage:icon forRequest:request];
7227 } else if ([command isEqualToString:@"uikit-image"]) {
7230 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7231 UIImage *icon(_UIImageWithName(path));
7232 [self _returnPNGWithImage:icon forRequest:request];
7233 } else if ([command isEqualToString:@"section-icon"]) {
7236 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7237 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7239 icon = [UIImage imageNamed:@"unknown.png"];
7240 [self _returnPNGWithImage:icon forRequest:request];
7242 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7246 - (void) stopLoading {
7252 /* Section Controller {{{ */
7253 @interface SectionController : FilteredPackageListController {
7255 _H<NSString> section_;
7258 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section;
7262 @implementation SectionController
7264 - (NSURL *) referrerURL {
7265 NSString *name(section_);
7266 name = name ?: @"*";
7267 NSString *key(key_);
7269 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sections/%@/%@", UI_, [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7272 - (NSURL *) navigationURL {
7273 NSString *name(section_);
7274 name = name ?: @"*";
7275 NSString *key(key_);
7277 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@/%@", [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7280 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section {
7283 title = UCLocalize("ALL_PACKAGES");
7284 else if (![section isEqual:@""])
7285 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(section) value:nil table:@"Sections"];
7287 title = UCLocalize("NO_SECTION");
7289 if ((self = [super initWithDatabase:database title:title]) != nil) {
7290 key_ = [source key];
7295 - (void) reloadData {
7296 Source *source([database_ sourceWithKey:key_]);
7297 _H<NSString> name(section_);
7299 [self setFilter:[=](Package *package) {
7300 NSString *section([package section]);
7304 section == nil && [name length] == 0 ||
7305 [name isEqualToString:section]
7308 [package source] == source
7309 ) && [package visible];
7317 /* Sections Controller {{{ */
7318 @interface SectionsController : CyteViewController <
7319 UITableViewDataSource,
7322 _transient Database *database_;
7324 _H<NSMutableArray> sections_;
7325 _H<NSMutableArray> filtered_;
7326 _H<UITableView, 2> list_;
7329 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7330 - (void) editButtonClicked;
7334 @implementation SectionsController
7336 - (NSURL *) navigationURL {
7337 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
7340 - (Source *) source {
7343 return [database_ sourceWithKey:key_];
7346 - (void) updateNavigationItem {
7347 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7348 if ([sections_ count] == 0) {
7349 [[self navigationItem] setRightBarButtonItem:nil];
7351 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7352 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7354 action:@selector(editButtonClicked)
7355 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7359 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7360 [super setEditing:editing animated:animated];
7365 [delegate_ updateData];
7367 [self updateNavigationItem];
7370 - (void) viewDidAppear:(BOOL)animated {
7371 [super viewDidAppear:animated];
7372 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7375 - (void) viewWillDisappear:(BOOL)animated {
7376 [super viewWillDisappear:animated];
7377 [self setEditing:NO];
7380 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7381 Section *section = nil;
7382 int index = [indexPath row];
7383 if (![self isEditing]) {
7386 section = [filtered_ objectAtIndex:index];
7388 section = [sections_ objectAtIndex:index];
7393 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7394 if ([self isEditing])
7395 return [sections_ count];
7397 return [filtered_ count] + 1;
7400 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7404 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7405 static NSString *reuseIdentifier = @"SectionCell";
7407 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7409 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7411 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7416 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7417 if ([self isEditing])
7420 Section *section = [self sectionAtIndexPath:indexPath];
7422 SectionController *controller = [[[SectionController alloc]
7423 initWithDatabase:database_
7424 source:[self source]
7425 section:[section name]
7427 [controller setDelegate:delegate_];
7429 [[self navigationController] pushViewController:controller animated:YES];
7433 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
7434 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7435 [list_ setRowHeight:46];
7436 [(UITableView *) list_ setDataSource:self];
7437 [list_ setDelegate:self];
7438 [self setView:list_];
7441 - (void) viewDidLoad {
7442 [super viewDidLoad];
7444 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7447 - (void) releaseSubviews {
7453 [super releaseSubviews];
7456 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7457 if ((self = [super init]) != nil) {
7458 database_ = database;
7459 key_ = [source key];
7463 - (void) reloadData {
7466 NSArray *packages = [database_ packages];
7468 sections_ = [NSMutableArray arrayWithCapacity:16];
7469 filtered_ = [NSMutableArray arrayWithCapacity:16];
7471 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7473 Source *source([self source]);
7476 for (Package *package in packages) {
7477 if (source != nil && [package source] != source)
7480 NSString *name([package section]);
7481 NSString *key(name == nil ? @"" : name);
7485 _profile(SectionsView$reloadData$Section)
7486 section = [sections objectForKey:key];
7487 if (section == nil) {
7488 _profile(SectionsView$reloadData$Section$Allocate)
7489 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7490 [sections setObject:section forKey:key];
7495 [section addToCount];
7497 _profile(SectionsView$reloadData$Filter)
7498 if (![package valid] || ![package visible])
7506 [sections_ addObjectsFromArray:[sections allValues]];
7508 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7510 for (Section *section in (id) sections_) {
7511 size_t count([section row]);
7515 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7516 [section setCount:count];
7517 [filtered_ addObject:section];
7520 [self updateNavigationItem];
7525 - (void) editButtonClicked {
7526 [self setEditing:![self isEditing] animated:YES];
7532 /* Changes Controller {{{ */
7533 @interface ChangesController : FilteredPackageListController {
7537 - (id) initWithDatabase:(Database *)database;
7541 @implementation ChangesController
7543 - (NSURL *) referrerURL {
7544 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/changes/", UI_]];
7547 - (NSURL *) navigationURL {
7548 return [NSURL URLWithString:@"cydia://changes"];
7551 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7552 @synchronized (database_) {
7553 if ([database_ era] != era_)
7556 NSUInteger sectionIndex([path section]);
7557 if (sectionIndex >= [sections_ count])
7559 Section *section([sections_ objectAtIndex:sectionIndex]);
7560 NSInteger row([path row]);
7561 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7564 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7565 NSString *context([alert context]);
7567 if ([context isEqualToString:@"norefresh"])
7568 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7571 - (void) setLeftBarButtonItem {
7572 if ([delegate_ updating])
7573 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7574 initWithTitle:UCLocalize("CANCEL")
7575 style:UIBarButtonItemStyleDone
7577 action:@selector(cancelButtonClicked)
7578 ] autorelease] animated:YES];
7580 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7581 initWithTitle:UCLocalize("REFRESH")
7582 style:UIBarButtonItemStylePlain
7584 action:@selector(refreshButtonClicked)
7585 ] autorelease] animated:YES];
7588 - (void) refreshButtonClicked {
7589 if ([delegate_ requestUpdate])
7590 [self setLeftBarButtonItem];
7593 - (void) cancelButtonClicked {
7594 [delegate_ cancelUpdate];
7597 - (void) upgradeButtonClicked {
7598 [delegate_ distUpgrade];
7599 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7602 - (bool) shouldYield {
7606 - (bool) shouldBlock {
7610 - (void) useFilter {
7611 @synchronized (self) {
7612 [self setFilter:[](Package *package) {
7613 return [package upgradableAndEssential:YES] || [package visible];
7616 [self setSorter:[](NSMutableArray *packages) {
7617 [packages radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7621 - (id) initWithDatabase:(Database *)database {
7622 if ((self = [super initWithDatabase:database title:UCLocalize("CHANGES")]) != nil) {
7627 - (void) viewDidLoad {
7628 [super viewDidLoad];
7629 [self setLeftBarButtonItem];
7632 - (void) viewWillAppear:(BOOL)animated {
7633 [super viewWillAppear:animated];
7634 [self setLeftBarButtonItem];
7637 - (void) reloadData {
7638 [self setLeftBarButtonItem];
7642 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
7643 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
7645 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7646 Section *ignored = nil;
7647 Section *section = nil;
7651 bool unseens = false;
7653 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7655 for (size_t offset = 0, count = [packages count]; offset != count; ++offset) {
7656 Package *package = [packages objectAtIndex:offset];
7658 BOOL uae = [package upgradableAndEssential:YES];
7662 time_t seen([package seen]);
7664 if (section == nil || last != seen) {
7668 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7671 _profile(ChangesController$reloadData$Allocate)
7672 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7673 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7674 [sections addObject:section];
7678 [section addToCount];
7679 } else if ([package ignored]) {
7680 if (ignored == nil) {
7681 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7683 [ignored addToCount];
7686 [upgradable addToCount];
7691 CFRelease(formatter);
7694 Section *last = [sections lastObject];
7695 size_t count = [last count];
7696 [packages removeObjectsInRange:NSMakeRange([packages count] - count, count)];
7697 [sections removeLastObject];
7700 if ([ignored count] != 0)
7701 [sections insertObject:ignored atIndex:0];
7703 [sections insertObject:upgradable atIndex:0];
7707 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7708 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7709 style:UIBarButtonItemStylePlain
7711 action:@selector(upgradeButtonClicked)
7712 ] autorelease]) animated:YES];
7719 /* Search Controller {{{ */
7720 @interface SearchController : FilteredPackageListController <
7723 _H<UISearchBar, 1> search_;
7728 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7729 - (void) reloadData;
7733 @implementation SearchController
7735 - (NSURL *) referrerURL {
7736 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/search?q=%@", UI_, [([search_ text] ?: @"") stringByAddingPercentEscapesIncludingReserved]]];
7739 - (NSURL *) navigationURL {
7740 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7741 return [NSURL URLWithString:@"cydia://search"];
7743 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [[search_ text] stringByAddingPercentEscapesIncludingReserved]]];
7746 - (NSArray *) termsForQuery:(NSString *)query {
7747 NSMutableArray *terms([NSMutableArray arrayWithCapacity:2]);
7748 for (NSString *component in [query componentsSeparatedByString:@" "])
7749 if ([component length] != 0)
7750 [terms addObject:component];
7755 - (void) useSearch {
7756 _H<NSArray> query([self termsForQuery:[search_ text]]);
7759 @synchronized (self) {
7760 [self setFilter:[=](Package *package) {
7761 if (![package unfiltered])
7763 if (![package matches:query])
7768 [self setSorter:[](NSMutableArray *packages) {
7769 [packages radixSortUsingSelector:@selector(rank)];
7777 - (void) usePrefix:(NSString *)prefix {
7778 _H<NSString> query(prefix);
7781 @synchronized (self) {
7782 [self setFilter:[=](Package *package) {
7783 if ([query length] == 0)
7785 if (![package unfiltered])
7787 if ([[package name] compare:query options:MatchCompareOptions_ range:NSMakeRange(0, [query length])] != NSOrderedSame)
7792 [self setSorter:nullptr];
7798 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7800 [self usePrefix:[search_ text]];
7803 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7804 [search_ resignFirstResponder];
7808 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7809 [search_ setText:@""];
7810 [self searchBarButtonClicked:searchBar];
7813 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7814 [self searchBarButtonClicked:searchBar];
7817 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7818 [self usePrefix:text];
7821 - (bool) shouldYield {
7825 - (bool) shouldBlock {
7829 - (bool) isSummarized {
7833 - (bool) showsSections {
7837 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7838 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH")])) {
7839 search_ = [[[UISearchBar alloc] init] autorelease];
7840 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7841 [search_ setDelegate:self];
7843 UITextField *textField;
7844 if ([search_ respondsToSelector:@selector(searchField)])
7845 textField = [search_ searchField];
7847 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7849 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7850 [textField setEnablesReturnKeyAutomatically:NO];
7851 [[self navigationItem] setTitleView:textField];
7854 [search_ setText:query];
7859 - (void) viewDidAppear:(BOOL)animated {
7860 [super viewDidAppear:animated];
7862 if (!searchloaded_) {
7863 searchloaded_ = YES;
7864 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7865 [search_ layoutSubviews];
7868 if ([self isSummarized])
7869 [search_ becomeFirstResponder];
7872 - (void) reloadData {
7877 - (void) didSelectPackage:(Package *)package {
7878 [search_ resignFirstResponder];
7879 [super didSelectPackage:package];
7884 /* Package Settings Controller {{{ */
7885 @interface PackageSettingsController : CyteViewController <
7886 UITableViewDataSource,
7889 _transient Database *database_;
7891 _H<Package> package_;
7892 _H<UITableView, 2> table_;
7893 _H<UISwitch> subscribedSwitch_;
7894 _H<UISwitch> ignoredSwitch_;
7895 _H<UITableViewCell> subscribedCell_;
7896 _H<UITableViewCell> ignoredCell_;
7899 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7903 @implementation PackageSettingsController
7905 - (NSURL *) navigationURL {
7906 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
7909 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7910 if (package_ == nil)
7913 if ([package_ installed] == nil)
7919 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7920 if (package_ == nil)
7923 // both sections contain just one item right now.
7927 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7931 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7933 return UCLocalize("SHOW_ALL_CHANGES_EX");
7935 return UCLocalize("IGNORE_UPGRADES_EX");
7938 - (void) onSubscribed:(id)control {
7939 bool value([control isOn]);
7940 if (package_ == nil)
7942 if ([package_ setSubscribed:value])
7943 [delegate_ updateData];
7946 - (void) _updateIgnored {
7947 const char *package([name_ UTF8String]);
7948 bool on([ignoredSwitch_ isOn]);
7950 pid_t pid(ExecFork());
7952 FILE *dpkg(_root(popen("dpkg --set-selections", "w")));
7953 fwrite(package, strlen(package), 1, dpkg);
7956 fwrite(" hold\n", 6, 1, dpkg);
7958 fwrite(" install\n", 9, 1, dpkg);
7966 - (void) onIgnored:(id)control {
7967 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7968 [invocation setTarget:self];
7969 [invocation setSelector:@selector(_updateIgnored)];
7971 [delegate_ reloadDataWithInvocation:invocation];
7974 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7975 if (package_ == nil)
7978 switch ([indexPath section]) {
7979 case 0: return subscribedCell_;
7980 case 1: return ignoredCell_;
7989 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
7990 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
7991 [self setView:view];
7993 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7994 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7995 [(UITableView *) table_ setDataSource:self];
7996 [table_ setDelegate:self];
7997 [view addSubview:table_];
7999 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
8000 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
8001 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
8003 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
8004 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
8005 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
8007 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
8008 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
8009 [subscribedCell_ setAccessoryView:subscribedSwitch_];
8010 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
8012 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
8013 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
8014 [ignoredCell_ setAccessoryView:ignoredSwitch_];
8015 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
8018 - (void) viewDidLoad {
8019 [super viewDidLoad];
8021 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
8024 - (void) releaseSubviews {
8026 subscribedCell_ = nil;
8028 ignoredSwitch_ = nil;
8029 subscribedSwitch_ = nil;
8031 [super releaseSubviews];
8034 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
8035 if ((self = [super init]) != nil) {
8036 database_ = database;
8041 - (void) reloadData {
8044 package_ = [database_ packageWithName:name_];
8046 if (package_ != nil) {
8047 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
8048 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
8049 } // XXX: what now, G?
8051 [table_ reloadData];
8057 /* Installed Controller {{{ */
8058 @interface InstalledController : FilteredPackageListController {
8062 - (id) initWithDatabase:(Database *)database;
8063 - (void) queueStatusDidChange;
8067 @implementation InstalledController
8069 - (NSURL *) referrerURL {
8070 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/installed/", UI_]];
8073 - (NSURL *) navigationURL {
8074 return [NSURL URLWithString:@"cydia://installed"];
8077 - (void) useRecent {
8080 @synchronized (self) {
8081 [self setFilter:[](Package *package) {
8082 return ![package uninstalled] && package->role_ < 7;
8085 [self setSorter:[](NSMutableArray *packages) {
8086 [packages radixSortUsingSelector:@selector(recent)];
8090 - (void) useFilter:(UISegmentedControl *)segmented {
8091 NSInteger selected([segmented selectedSegmentIndex]);
8093 return [self useRecent];
8094 bool simple(selected == 0);
8097 @synchronized (self) {
8098 [self setFilter:[=](Package *package) {
8099 return ![package uninstalled] && package->role_ <= (simple ? 1 : 3);
8102 [self setSorter:nullptr];
8105 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
8107 return [super sectionsForPackages:packages];
8109 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterLongStyle, kCFDateFormatterNoStyle));
8111 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
8112 Section *section(nil);
8115 for (size_t offset(0), count([packages count]); offset != count; ++offset) {
8116 Package *package([packages objectAtIndex:offset]);
8118 time_t upgraded([package upgraded]);
8119 if (upgraded < 1168364520)
8122 upgraded -= upgraded % (60 * 60 * 24);
8124 if (section == nil || upgraded != last) {
8129 continue; // XXX: name = UCLocalize("...");
8131 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:upgraded]);
8135 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
8136 [sections addObject:section];
8139 [section addToCount];
8142 CFRelease(formatter);
8146 - (id) initWithDatabase:(Database *)database {
8147 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED")]) != nil) {
8148 UISegmentedControl *segmented([[[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:UCLocalize("USER"), UCLocalize("EXPERT"), UCLocalize("RECENT"), nil]] autorelease]);
8149 [segmented setSelectedSegmentIndex:0];
8150 [segmented setSegmentedControlStyle:UISegmentedControlStyleBar];
8151 [[self navigationItem] setTitleView:segmented];
8153 [segmented addTarget:self action:@selector(modeChanged:) forEvents:UIControlEventValueChanged];
8154 [self useFilter:segmented];
8156 [self queueStatusDidChange];
8161 - (void) queueButtonClicked {
8166 - (void) queueStatusDidChange {
8169 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8170 initWithTitle:UCLocalize("QUEUE")
8171 style:UIBarButtonItemStyleDone
8173 action:@selector(queueButtonClicked)
8176 [[self navigationItem] setRightBarButtonItem:nil];
8181 - (void) modeChanged:(UISegmentedControl *)segmented {
8182 [self useFilter:segmented];
8189 /* Source Cell {{{ */
8190 @interface SourceCell : CyteTableViewCell <
8191 CyteTableViewCellDelegate,
8194 _H<Source, 1> source_;
8197 _H<NSString> origin_;
8198 _H<NSString> label_;
8199 _H<UIActivityIndicatorView> indicator_;
8202 - (void) setSource:(Source *)source;
8203 - (void) setFetch:(NSNumber *)fetch;
8207 @implementation SourceCell
8209 - (void) _setImage:(NSArray *)data {
8210 if ([url_ isEqual:[data objectAtIndex:0]]) {
8211 icon_ = [data objectAtIndex:1];
8212 [content_ setNeedsDisplay];
8216 - (void) _setSource:(NSURL *) url {
8217 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8219 if (NSData *data = [NSURLConnection
8220 sendSynchronousRequest:[NSURLRequest
8222 cachePolicy:NSURLRequestUseProtocolCachePolicy
8226 returningResponse:NULL
8229 if (UIImage *image = [UIImage imageWithData:data])
8230 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
8235 - (void) setSource:(Source *)source {
8237 [source_ setDelegate:self];
8239 [self setFetch:[NSNumber numberWithBool:[source_ fetch]]];
8241 icon_ = [UIImage imageNamed:@"unknown.png"];
8243 origin_ = [source name];
8244 label_ = [source rooturi];
8246 [content_ setNeedsDisplay];
8248 url_ = [source iconURL];
8249 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
8252 - (void) setAllSource {
8254 [indicator_ stopAnimating];
8256 icon_ = [UIImage imageNamed:@"folder.png"];
8257 origin_ = UCLocalize("ALL_SOURCES");
8258 label_ = UCLocalize("ALL_SOURCES_EX");
8259 [content_ setNeedsDisplay];
8262 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8263 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8264 UIView *content([self contentView]);
8265 CGRect bounds([content bounds]);
8267 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8268 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8269 [content_ setBackgroundColor:[UIColor whiteColor]];
8270 [content addSubview:content_];
8272 [content_ setDelegate:self];
8273 [content_ setOpaque:YES];
8275 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGraySmall] autorelease];
8276 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin];// | UIViewAutoresizingFlexibleBottomMargin];
8277 [content addSubview:indicator_];
8279 [[content_ layer] setContentsGravity:kCAGravityTopLeft];
8283 - (void) layoutSubviews {
8284 [super layoutSubviews];
8286 UIView *content([self contentView]);
8287 CGRect bounds([content bounds]);
8289 CGRect frame([indicator_ frame]);
8290 frame.origin.x = bounds.size.width - frame.size.width;
8291 frame.origin.y = Retina((bounds.size.height - frame.size.height) / 2);
8293 if (kCFCoreFoundationVersionNumber < 800)
8294 frame.origin.x -= 8;
8295 [indicator_ setFrame:frame];
8298 - (NSString *) accessibilityLabel {
8302 - (void) drawContentRect:(CGRect)rect {
8303 bool highlighted(highlighted_);
8304 float width(rect.size.width);
8308 rect.size = [(UIImage *) icon_ size];
8310 while (rect.size.width > 32 || rect.size.height > 32) {
8311 rect.size.width /= 2;
8312 rect.size.height /= 2;
8315 rect.origin.x = 26 - rect.size.width / 2;
8316 rect.origin.y = 26 - rect.size.height / 2;
8318 [icon_ drawInRect:Retina(rect)];
8321 if (highlighted && kCFCoreFoundationVersionNumber < 800)
8326 [origin_ drawAtPoint:CGPointMake(52, 8) forWidth:(width - 49) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
8330 [label_ drawAtPoint:CGPointMake(52, 29) forWidth:(width - 49) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
8333 - (void) setFetch:(NSNumber *)fetch {
8334 if ([fetch boolValue])
8335 [indicator_ startAnimating];
8337 [indicator_ stopAnimating];
8342 /* Sources Controller {{{ */
8343 @interface SourcesController : CyteViewController <
8344 UITableViewDataSource,
8347 _transient Database *database_;
8350 _H<UITableView, 2> list_;
8351 _H<NSMutableArray> sources_;
8355 _H<UIProgressHUD> hud_;
8358 NSURLConnection *trivial_bz2_;
8359 NSURLConnection *trivial_gz_;
8364 - (id) initWithDatabase:(Database *)database;
8365 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated;
8369 @implementation SourcesController
8371 - (void) _releaseConnection:(NSURLConnection *)connection {
8372 if (connection != nil) {
8373 [connection cancel];
8374 //[connection setDelegate:nil];
8375 [connection release];
8380 [self _releaseConnection:trivial_gz_];
8381 [self _releaseConnection:trivial_bz2_];
8386 - (NSURL *) navigationURL {
8387 return [NSURL URLWithString:@"cydia://sources"];
8390 - (void) viewDidAppear:(BOOL)animated {
8391 [super viewDidAppear:animated];
8392 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8395 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8399 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8401 return UCLocalize("INDIVIDUAL_SOURCES");
8405 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8408 case 1: return [sources_ count];
8413 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8414 @synchronized (database_) {
8415 if ([database_ era] != era_)
8417 if ([indexPath section] != 1)
8419 NSUInteger index([indexPath row]);
8420 if (index >= [sources_ count])
8422 return [sources_ objectAtIndex:index];
8425 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8426 static NSString *cellIdentifier = @"SourceCell";
8428 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8429 if (cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8430 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8432 Source *source([self sourceAtIndexPath:indexPath]);
8434 [cell setAllSource];
8436 [cell setSource:source];
8441 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8442 SectionsController *controller([[[SectionsController alloc]
8443 initWithDatabase:database_
8444 source:[self sourceAtIndexPath:indexPath]
8447 [controller setDelegate:delegate_];
8448 [[self navigationController] pushViewController:controller animated:YES];
8451 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8452 if ([indexPath section] != 1)
8454 Source *source = [self sourceAtIndexPath:indexPath];
8455 return [source record] != nil;
8458 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8459 _assert([indexPath section] == 1);
8460 if (editingStyle == UITableViewCellEditingStyleDelete) {
8461 Source *source = [self sourceAtIndexPath:indexPath];
8462 if (source == nil) return;
8464 [Sources_ removeObjectForKey:[source key]];
8467 [delegate_ _saveConfig];
8468 [delegate_ reloadDataWithInvocation:nil];
8472 - (void) tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath {
8473 [self updateButtonsForEditingStatusAnimated:YES];
8477 [delegate_ addTrivialSource:href_];
8480 [delegate_ syncData];
8483 - (NSString *) getWarning {
8484 NSString *href(href_);
8485 NSRange colon([href rangeOfString:@"://"]);
8486 if (colon.location != NSNotFound)
8487 href = [href substringFromIndex:(colon.location + 3)];
8488 href = [href stringByAddingPercentEscapes];
8489 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8491 NSURL *url([NSURL URLWithString:href]);
8493 NSStringEncoding encoding;
8494 NSError *error(nil);
8496 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8497 return [warning length] == 0 ? nil : warning;
8501 - (void) _endConnection:(NSURLConnection *)connection {
8502 // XXX: the memory management in this method is horribly awkward
8504 NSURLConnection **field = NULL;
8505 if (connection == trivial_bz2_)
8506 field = &trivial_bz2_;
8507 else if (connection == trivial_gz_)
8508 field = &trivial_gz_;
8509 _assert(field != NULL);
8510 [connection release];
8514 trivial_bz2_ == nil &&
8517 NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil);
8519 [delegate_ releaseNetworkActivityIndicator];
8521 [delegate_ removeProgressHUD:hud_];
8525 if (warning != nil) {
8526 UIAlertView *alert = [[[UIAlertView alloc]
8527 initWithTitle:UCLocalize("SOURCE_WARNING")
8530 cancelButtonTitle:UCLocalize("CANCEL")
8532 UCLocalize("ADD_ANYWAY"),
8536 [alert setContext:@"warning"];
8537 [alert setNumberOfRows:1];
8540 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
8546 } else if (error_ != nil) {
8547 UIAlertView *alert = [[[UIAlertView alloc]
8548 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8549 message:[error_ localizedDescription]
8551 cancelButtonTitle:UCLocalize("OK")
8552 otherButtonTitles:nil
8555 [alert setContext:@"urlerror"];
8560 UIAlertView *alert = [[[UIAlertView alloc]
8561 initWithTitle:UCLocalize("NOT_REPOSITORY")
8562 message:UCLocalize("NOT_REPOSITORY_EX")
8564 cancelButtonTitle:UCLocalize("OK")
8565 otherButtonTitles:nil
8568 [alert setContext:@"trivial"];
8578 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8579 switch ([response statusCode]) {
8585 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8586 lprintf("connection:\"%s\" didFailWithError:\"%s\"\n", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8588 [self _endConnection:connection];
8591 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8592 [self _endConnection:connection];
8595 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8596 NSURL *url([NSURL URLWithString:href]);
8598 NSMutableURLRequest *request = [NSMutableURLRequest
8600 cachePolicy:NSURLRequestUseProtocolCachePolicy
8604 [request setHTTPMethod:method];
8606 if (Machine_ != NULL)
8607 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8609 if (UniqueID_ != nil)
8610 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8612 if ([url isCydiaSecure]) {
8613 if (UniqueID_ != nil)
8614 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
8617 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8620 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8621 NSString *context([alert context]);
8623 if ([context isEqualToString:@"source"]) {
8626 NSString *href = [[alert textField] text];
8628 static Pcre href_r("^(http(s?)://|file:///)[^# ]*$");
8629 if (!href_r(href)) {
8630 UIAlertView *alert = [[[UIAlertView alloc]
8631 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("INVALID_URL")]
8632 message:UCLocalize("INVALID_URL_EX")
8634 cancelButtonTitle:UCLocalize("OK")
8635 otherButtonTitles:nil
8638 [alert setContext:@"badurl"];
8644 if (![href hasSuffix:@"/"])
8645 href_ = [href stringByAppendingString:@"/"];
8649 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8650 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8654 // XXX: this is stupid
8655 hud_ = [delegate_ addProgressHUD];
8656 [hud_ setText:UCLocalize("VERIFYING_URL")];
8657 [delegate_ retainNetworkActivityIndicator];
8666 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8667 } else if ([context isEqualToString:@"trivial"])
8668 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8669 else if ([context isEqualToString:@"urlerror"])
8670 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8671 else if ([context isEqualToString:@"warning"]) {
8674 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
8683 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8687 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated {
8688 BOOL editing([list_ isEditing]);
8691 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8692 initWithTitle:UCLocalize("ADD")
8693 style:UIBarButtonItemStylePlain
8695 action:@selector(addButtonClicked)
8696 ] autorelease] animated:animated];
8697 else if ([delegate_ updating])
8698 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8699 initWithTitle:UCLocalize("CANCEL")
8700 style:UIBarButtonItemStyleDone
8702 action:@selector(cancelButtonClicked)
8703 ] autorelease] animated:animated];
8705 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8706 initWithTitle:UCLocalize("REFRESH")
8707 style:UIBarButtonItemStylePlain
8709 action:@selector(refreshButtonClicked)
8710 ] autorelease] animated:animated];
8712 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8713 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8714 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8716 action:@selector(editButtonClicked)
8717 ] autorelease] animated:animated];
8721 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease];
8722 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8723 [list_ setRowHeight:53];
8724 [(UITableView *) list_ setDataSource:self];
8725 [list_ setDelegate:self];
8726 [self setView:list_];
8729 - (void) viewDidLoad {
8730 [super viewDidLoad];
8732 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8733 [self updateButtonsForEditingStatusAnimated:NO];
8736 - (void) viewWillAppear:(BOOL)animated {
8737 [super viewWillAppear:animated];
8739 [list_ setEditing:NO];
8740 [self updateButtonsForEditingStatusAnimated:NO];
8743 - (void) releaseSubviews {
8748 [super releaseSubviews];
8751 - (id) initWithDatabase:(Database *)database {
8752 if ((self = [super init]) != nil) {
8753 database_ = database;
8757 - (void) reloadData {
8759 [self updateButtonsForEditingStatusAnimated:YES];
8761 @synchronized (database_) {
8762 era_ = [database_ era];
8764 sources_ = [NSMutableArray arrayWithCapacity:16];
8765 [sources_ addObjectsFromArray:[database_ sources]];
8767 [sources_ sortUsingSelector:@selector(compareByName:)];
8770 int count([sources_ count]);
8772 for (int i = 0; i != count; i++) {
8773 if ([[sources_ objectAtIndex:i] record] == nil)
8781 - (void) showAddSourcePrompt {
8782 UIAlertView *alert = [[[UIAlertView alloc]
8783 initWithTitle:UCLocalize("ENTER_APT_URL")
8786 cancelButtonTitle:UCLocalize("CANCEL")
8788 UCLocalize("ADD_SOURCE"),
8792 [alert setContext:@"source"];
8794 [alert setNumberOfRows:1];
8795 [alert addTextFieldWithValue:@"http://" label:@""];
8797 UITextInputTraits *traits = [[alert textField] textInputTraits];
8798 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8799 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8800 [traits setKeyboardType:UIKeyboardTypeURL];
8801 // XXX: UIReturnKeyDone
8802 [traits setReturnKeyType:UIReturnKeyNext];
8807 - (void) addButtonClicked {
8808 [self showAddSourcePrompt];
8811 - (void) refreshButtonClicked {
8812 if ([delegate_ requestUpdate])
8813 [self updateButtonsForEditingStatusAnimated:YES];
8816 - (void) cancelButtonClicked {
8817 [delegate_ cancelUpdate];
8820 - (void) editButtonClicked {
8821 [list_ setEditing:![list_ isEditing] animated:YES];
8822 [self updateButtonsForEditingStatusAnimated:YES];
8828 /* Stash Controller {{{ */
8829 @interface StashController : CyteViewController {
8830 _H<UIActivityIndicatorView> spinner_;
8831 _H<UILabel> status_;
8832 _H<UILabel> caption_;
8837 @implementation StashController
8840 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8841 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8842 [self setView:view];
8844 [view setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8846 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8847 CGRect spinrect = [spinner_ frame];
8848 spinrect.origin.x = Retina([[self view] frame].size.width / 2 - spinrect.size.width / 2);
8849 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8850 [spinner_ setFrame:spinrect];
8851 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8852 [view addSubview:spinner_];
8853 [spinner_ startAnimating];
8856 captrect.size.width = [[self view] frame].size.width;
8857 captrect.size.height = 40.0f;
8858 captrect.origin.x = 0;
8859 captrect.origin.y = Retina([[self view] frame].size.height / 2 - captrect.size.height * 2);
8860 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8861 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8862 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8863 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8864 [caption_ setTextColor:[UIColor whiteColor]];
8865 [caption_ setBackgroundColor:[UIColor clearColor]];
8866 [caption_ setShadowColor:[UIColor blackColor]];
8867 [caption_ setTextAlignment:NSTextAlignmentCenter];
8868 [view addSubview:caption_];
8871 statusrect.size.width = [[self view] frame].size.width;
8872 statusrect.size.height = 30.0f;
8873 statusrect.origin.x = 0;
8874 statusrect.origin.y = Retina([[self view] frame].size.height / 2 - statusrect.size.height);
8875 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8876 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8877 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8878 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8879 [status_ setTextColor:[UIColor whiteColor]];
8880 [status_ setBackgroundColor:[UIColor clearColor]];
8881 [status_ setShadowColor:[UIColor blackColor]];
8882 [status_ setTextAlignment:NSTextAlignmentCenter];
8883 [view addSubview:status_];
8886 - (void) releaseSubviews {
8891 [super releaseSubviews];
8897 @interface CYURLCache : SDURLCache {
8902 @implementation CYURLCache
8904 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8907 else if ([event isEqualToString:@"no-cache"])
8909 else if ([event isEqualToString:@"store"])
8911 else if ([event isEqualToString:@"invalid"])
8913 else if ([event isEqualToString:@"memory"])
8915 else if ([event isEqualToString:@"disk"])
8917 else if ([event isEqualToString:@"miss"])
8920 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8924 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
8925 if (NSURLResponse *response = [cached response])
8926 if (NSString *mime = [response MIMEType])
8927 if ([mime isEqualToString:@"text/cache-manifest"]) {
8928 NSURL *url([response URL]);
8931 NSLog(@"###: %@", [url absoluteString]);
8934 @synchronized (HostConfig_) {
8935 [CachedURLs_ addObject:url];
8939 [super storeCachedResponse:cached forRequest:request];
8942 - (void) createDiskCachePath {
8943 [super createDiskCachePath];
8944 _root(chown([[self diskCachePath] UTF8String], 501, 501));
8949 @interface Cydia : UIApplication <
8950 ConfirmationControllerDelegate,
8954 _H<UIWindow> window_;
8955 _H<CydiaTabBarController> tabbar_;
8956 _H<CyteTabBarController> emulated_;
8957 _H<AppCacheController> appcache_;
8959 _H<NSMutableArray> essential_;
8960 _H<NSMutableArray> broken_;
8962 Database *database_;
8964 _H<NSURL> starturl_;
8969 _H<StashController> stash_;
8978 @implementation Cydia
8980 - (void) lockSuspend {
8981 if (locked_++ == 0) {
8982 if ($SBSSetInterceptsMenuButtonForever != NULL)
8983 (*$SBSSetInterceptsMenuButtonForever)(true);
8985 [self setIdleTimerDisabled:YES];
8989 - (void) unlockSuspend {
8990 if (--locked_ == 0) {
8991 [self setIdleTimerDisabled:NO];
8993 if ($SBSSetInterceptsMenuButtonForever != NULL)
8994 (*$SBSSetInterceptsMenuButtonForever)(false);
8998 - (void) beginUpdate {
8999 [tabbar_ beginUpdate];
9002 - (void) cancelUpdate {
9003 [tabbar_ cancelUpdate];
9006 - (bool) requestUpdate {
9007 if (IsReachable("cydia.saurik.com")) {
9011 UIAlertView *alert = [[[UIAlertView alloc]
9012 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("REFRESH")]
9013 message:@"Host Unreachable" // XXX: Localize
9015 cancelButtonTitle:UCLocalize("OK")
9016 otherButtonTitles:nil
9019 [alert setContext:@"norefresh"];
9027 return [tabbar_ updating];
9031 if ([broken_ count] != 0) {
9032 int count = [broken_ count];
9034 UIAlertView *alert = [[[UIAlertView alloc]
9035 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
9036 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
9038 cancelButtonTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("FORCIBLY_CLEAR"), UCLocalize("UNSAFE")]
9040 UCLocalize("TEMPORARY_IGNORE"),
9044 [alert setContext:@"fixhalf"];
9045 [alert setNumberOfRows:2];
9047 } else if (!Ignored_ && [essential_ count] != 0) {
9048 int count = [essential_ count];
9050 UIAlertView *alert = [[[UIAlertView alloc]
9051 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
9052 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
9054 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
9056 UCLocalize("UPGRADE_ESSENTIAL"),
9057 UCLocalize("COMPLETE_UPGRADE"),
9061 [alert setContext:@"upgrade"];
9066 - (void) returnToCydia {
9070 - (void) _saveConfig {
9071 @synchronized (database_) {
9078 NSString *error(nil);
9080 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
9082 NSError *error(nil);
9083 if (!_root([data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error]))
9084 NSLog(@"failure to save metadata data: %@", error);
9089 NSLog(@"failure to serialize metadata: %@", error);
9093 _root(CydiaWriteSources());
9096 // Navigation controller for the queuing badge.
9097 - (UINavigationController *) queueNavigationController {
9098 NSArray *controllers = [tabbar_ viewControllers];
9099 return [controllers objectAtIndex:3];
9102 - (void) unloadData {
9103 [tabbar_ unloadData];
9106 - (void) _updateData {
9110 UINavigationController *navigation = [self queueNavigationController];
9112 id queuedelegate = nil;
9113 if ([[navigation viewControllers] count] > 0)
9114 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9116 [queuedelegate queueStatusDidChange];
9117 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9120 - (void) _refreshIfPossible:(NSDate *)update {
9121 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9123 bool recently = false;
9124 if (update != nil) {
9125 NSTimeInterval interval([update timeIntervalSinceNow]);
9126 if (interval > -(15*60))
9130 // Don't automatic refresh if:
9131 // - We already refreshed recently.
9132 // - We already auto-refreshed this launch.
9133 // - Auto-refresh is disabled.
9134 // - Cydia's server is not reachable
9135 if (recently || loaded_ || ManualRefresh || !IsReachable("cydia.saurik.com")) {
9136 // If we are cancelling, we need to make sure it knows it's already loaded.
9139 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9141 // We are going to load, so remember that.
9144 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
9150 - (void) refreshIfPossible {
9151 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
9154 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9155 _profile(reloadDataWithInvocation)
9156 @synchronized (self) {
9157 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9159 [hud setText:UCLocalize("RELOADING_DATA")];
9161 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9165 [essential_ removeAllObjects];
9166 [broken_ removeAllObjects];
9168 _profile(reloadDataWithInvocation$Essential)
9169 NSArray *packages([database_ packages]);
9170 for (Package *package in packages) {
9172 [broken_ addObject:package];
9173 if ([package upgradableAndEssential:YES] && ![package ignored]) {
9174 if ([package essential] && [package installed] != nil)
9175 [essential_ addObject:package];
9181 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9184 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9185 [changesItem setBadgeValue:badge];
9186 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9187 [self setApplicationIconBadgeNumber:changes];
9190 [changesItem setBadgeValue:nil];
9191 [changesItem setAnimatedBadge:NO];
9192 [self setApplicationIconBadgeNumber:0];
9199 [self removeProgressHUD:hud];
9206 - (void) updateData {
9210 - (void) updateDataAndLoad {
9212 if ([database_ progressDelegate] == nil)
9218 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9221 - (void) disemulate {
9222 if (emulated_ == nil)
9225 if ([window_ respondsToSelector:@selector(setRootViewController:)])
9226 [window_ setRootViewController:tabbar_];
9228 [window_ addSubview:[tabbar_ view]];
9229 [[emulated_ view] removeFromSuperview];
9233 [window_ setUserInteractionEnabled:YES];
9236 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9237 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9239 UIViewController *parent;
9240 if (emulated_ == nil)
9250 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9251 [parent presentModalViewController:navigation animated:YES];
9254 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9255 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9257 if (navigation != nil)
9258 [navigation pushViewController:progress animated:YES];
9260 [self presentModalViewController:progress force:YES];
9262 [progress invoke:invocation withTitle:title];
9266 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9267 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9270 - (void) repairWithInvocation:(NSInvocation *)invocation {
9272 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9276 - (void) repairWithSelector:(SEL)selector {
9277 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9280 - (void) reloadData {
9281 [self reloadDataWithInvocation:nil];
9282 if ([database_ progressDelegate] == nil)
9288 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9291 - (void) addSource:(NSDictionary *) source {
9292 CydiaAddSource(source);
9295 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9296 CydiaAddSource(href, distribution, sections);
9299 - (void) addTrivialSource:(NSString *)href {
9300 CydiaAddSource(href, @"./");
9303 - (void) updateValues {
9308 pkgProblemResolver *resolver = [database_ resolver];
9310 resolver->InstallProtect();
9311 if (!resolver->Resolve(true))
9316 // XXX: this is a really crappy way of doing this.
9317 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9318 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9319 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9320 if ([tabbar_ updating])
9321 [tabbar_ cancelUpdate];
9323 if (![database_ prepare])
9326 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9327 [page setDelegate:self];
9328 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9331 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9332 [tabbar_ presentModalViewController:confirm_ animated:YES];
9338 @synchronized (self) {
9343 - (void) clearPackage:(Package *)package {
9344 @synchronized (self) {
9351 - (void) installPackages:(NSArray *)packages {
9352 @synchronized (self) {
9353 for (Package *package in packages)
9360 - (void) installPackage:(Package *)package {
9361 @synchronized (self) {
9368 - (void) removePackage:(Package *)package {
9369 @synchronized (self) {
9376 - (void) distUpgrade {
9377 @synchronized (self) {
9378 if (![database_ upgrade])
9387 if (UpgradeCydia_ && Finish_ > 0) {
9389 system("su -c /usr/bin/uicache mobile");
9391 system("/usr/bin/uicache");
9398 UIProgressHUD *hud([self addProgressHUD]);
9399 [hud setText:UCLocalize("LOADING")];
9400 [self yieldToSelector:@selector(_uicache)];
9401 [self removeProgressHUD:hud];
9405 [database_ perform];
9406 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9407 [self performSelectorOnMainThread:@selector(uicache) withObject:nil waitUntilDone:YES];
9410 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9413 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9414 [self unlockSuspend];
9417 - (void) retainNetworkActivityIndicator {
9418 if (activity_++ == 0)
9419 [self setNetworkActivityIndicatorVisible:YES];
9422 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9426 - (void) releaseNetworkActivityIndicator {
9427 if (--activity_ == 0)
9428 [self setNetworkActivityIndicatorVisible:NO];
9431 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9436 - (void) cancelAndClear:(bool)clear {
9437 @synchronized (self) {
9449 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9450 NSString *context([alert context]);
9452 if ([context isEqualToString:@"conffile"]) {
9453 FILE *input = [database_ input];
9454 if (button == [alert cancelButtonIndex])
9455 fprintf(input, "N\n");
9456 else if (button == [alert firstOtherButtonIndex])
9457 fprintf(input, "Y\n");
9460 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9461 } else if ([context isEqualToString:@"fixhalf"]) {
9462 if (button == [alert cancelButtonIndex]) {
9463 @synchronized (self) {
9464 for (Package *broken in (id) broken_) {
9466 NSString *id = [broken id];
9469 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9470 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9471 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9472 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9479 } else if (button == [alert firstOtherButtonIndex]) {
9480 [broken_ removeAllObjects];
9484 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9485 } else if ([context isEqualToString:@"upgrade"]) {
9486 if (button == [alert firstOtherButtonIndex]) {
9487 @synchronized (self) {
9488 for (Package *essential in (id) essential_)
9489 [essential install];
9494 } else if (button == [alert firstOtherButtonIndex] + 1) {
9496 } else if (button == [alert cancelButtonIndex]) {
9500 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9504 - (void) system:(NSString *)command {
9505 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9508 _root(system([command UTF8String]));
9514 - (void) applicationWillSuspend {
9516 [super applicationWillSuspend];
9519 - (BOOL) isSafeToSuspend {
9522 NSLog(@"isSafeToSuspend: locked_ != 0");
9527 if ([tabbar_ modalViewController] != nil)
9530 // Use external process status API internally.
9531 // This is probably a really bad idea.
9532 // XXX: what is the point of this? does this solve anything at all?
9533 uint64_t status = 0;
9535 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9536 notify_get_state(notify_token, &status);
9537 notify_cancel(notify_token);
9542 NSLog(@"isSafeToSuspend: status != 0");
9548 NSLog(@"isSafeToSuspend: -> true");
9553 - (void) suspendReturningToLastApp:(BOOL)returning {
9554 if ([self isSafeToSuspend])
9555 [super suspendReturningToLastApp:returning];
9559 if ([self isSafeToSuspend])
9563 - (void) applicationSuspend {
9564 if ([self isSafeToSuspend])
9565 [super applicationSuspend];
9568 - (void) applicationSuspend:(__GSEvent *)event {
9569 if ([self isSafeToSuspend])
9570 [super applicationSuspend:event];
9573 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9574 if ([self isSafeToSuspend])
9575 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9578 - (void) _setSuspended:(BOOL)value {
9579 if ([self isSafeToSuspend])
9580 [super _setSuspended:value];
9583 - (UIProgressHUD *) addProgressHUD {
9584 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9585 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9587 [window_ setUserInteractionEnabled:NO];
9589 UIViewController *target(tabbar_);
9590 if (UIViewController *modal = [target modalViewController])
9593 [hud showInView:[target view]];
9599 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9600 [self unlockSuspend];
9602 [hud removeFromSuperview];
9603 [window_ setUserInteractionEnabled:YES];
9606 - (CyteViewController *) pageForPackage:(NSString *)name withReferrer:(NSString *)referrer {
9607 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name withReferrer:referrer] autorelease];
9610 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external withReferrer:(NSString *)referrer {
9611 NSString *scheme([[url scheme] lowercaseString]);
9612 if ([[url absoluteString] length] <= [scheme length] + 3)
9614 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9615 NSArray *components([path componentsSeparatedByString:@"/"]);
9617 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"]) {
9618 CyteViewController *controller([self pageForPackage:[components objectAtIndex:1] withReferrer:referrer]);
9619 if (controller != nil)
9620 [controller setDelegate:self];
9624 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9627 NSString *base([components objectAtIndex:0]);
9629 CyteViewController *controller = nil;
9631 if ([base isEqualToString:@"url"]) {
9632 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9633 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9634 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9635 } else if (!external && [components count] == 1) {
9636 if ([base isEqualToString:@"sources"]) {
9637 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9640 if ([base isEqualToString:@"home"]) {
9641 controller = [[[HomeController alloc] init] autorelease];
9644 if ([base isEqualToString:@"sections"]) {
9645 controller = [[[SectionsController alloc] initWithDatabase:database_ source:nil] autorelease];
9648 if ([base isEqualToString:@"search"]) {
9649 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9652 if ([base isEqualToString:@"changes"]) {
9653 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9656 if ([base isEqualToString:@"installed"]) {
9657 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9659 } else if ([components count] == 2) {
9660 NSString *argument = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9662 if ([base isEqualToString:@"package"]) {
9663 controller = [self pageForPackage:argument withReferrer:referrer];
9666 if (!external && [base isEqualToString:@"search"]) {
9667 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9670 if (!external && [base isEqualToString:@"sections"]) {
9671 if ([argument isEqualToString:@"all"] || [argument isEqualToString:@"*"])
9673 controller = [[[SectionController alloc] initWithDatabase:database_ source:nil section:argument] autorelease];
9676 if (!external && [base isEqualToString:@"sources"]) {
9677 if ([argument isEqualToString:@"add"]) {
9678 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9679 [(SourcesController *)controller showAddSourcePrompt];
9681 Source *source([database_ sourceWithKey:argument]);
9682 controller = [[[SectionsController alloc] initWithDatabase:database_ source:source] autorelease];
9686 if (!external && [base isEqualToString:@"launch"]) {
9687 [self launchApplicationWithIdentifier:argument suspended:NO];
9690 } else if (!external && [components count] == 3) {
9691 NSString *arg1 = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9692 NSString *arg2 = [[components objectAtIndex:2] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9694 if ([base isEqualToString:@"package"]) {
9695 if ([arg2 isEqualToString:@"settings"]) {
9696 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9697 } else if ([arg2 isEqualToString:@"files"]) {
9698 if (Package *package = [database_ packageWithName:arg1]) {
9699 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9700 [(FileTable *)controller setPackage:package];
9705 if ([base isEqualToString:@"sections"]) {
9706 Source *source([arg1 isEqualToString:@"*"] ? nil : [database_ sourceWithKey:arg1]);
9707 NSString *section([arg2 isEqualToString:@"*"] ? nil : arg2);
9708 controller = [[[SectionController alloc] initWithDatabase:database_ source:source section:section] autorelease];
9712 [controller setDelegate:self];
9716 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9717 CyteViewController *page([self pageForURL:url forExternal:external withReferrer:nil]);
9720 [tabbar_ setUnselectedViewController:page];
9725 - (void) applicationOpenURL:(NSURL *)url {
9726 [super applicationOpenURL:url];
9731 [self openCydiaURL:url forExternal:YES];
9734 - (void) applicationWillResignActive:(UIApplication *)application {
9735 // Stop refreshing if you get a phone call or lock the device.
9736 if ([tabbar_ updating])
9737 [tabbar_ cancelUpdate];
9739 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9740 [super applicationWillResignActive:application];
9743 - (void) saveState {
9744 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9745 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9746 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9752 - (void) applicationWillTerminate:(UIApplication *)application {
9756 - (void) applicationDidEnterBackground:(UIApplication *)application {
9757 if (kCFCoreFoundationVersionNumber < 1000 && [self isSafeToSuspend])
9758 return [self terminateWithSuccess];
9762 - (void) applicationWillEnterForeground:(UIApplication *)application {
9763 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9767 NSTimeInterval interval([closed timeIntervalSinceNow]);
9769 if (interval <= -(30*60)) {
9770 [tabbar_ setSelectedIndex:0];
9771 [[[tabbar_ viewControllers] objectAtIndex:0] popToRootViewControllerAnimated:NO];
9774 if (interval <= -(15*60)) {
9775 if (IsReachable("cydia.saurik.com")) {
9776 [tabbar_ beginUpdate];
9777 [appcache_ reloadURLWithCache:YES];
9782 - (void) setConfigurationData:(NSString *)data {
9783 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9785 if (!conffile_r(data)) {
9786 lprintf("E:invalid conffile\n");
9790 NSString *ofile = conffile_r[1];
9791 //NSString *nfile = conffile_r[2];
9793 UIAlertView *alert = [[[UIAlertView alloc]
9794 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9795 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9797 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9799 UCLocalize("ACCEPT_NEW_COPY"),
9800 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9804 [alert setContext:@"conffile"];
9805 [alert setNumberOfRows:2];
9809 - (void) addStashController {
9811 stash_ = [[[StashController alloc] init] autorelease];
9812 [window_ addSubview:[stash_ view]];
9815 - (void) removeStashController {
9816 [[stash_ view] removeFromSuperview];
9818 [self unlockSuspend];
9822 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9823 UpdateExternalStatus(1);
9824 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9825 UpdateExternalStatus(0);
9827 [self removeStashController];
9829 pid_t pid(ExecFork());
9831 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9832 perror("launchctl stop");
9838 - (void) setupViewControllers {
9839 tabbar_ = [[[CydiaTabBarController alloc] initWithDatabase:database_] autorelease];
9841 NSMutableArray *items;
9842 if (kCFCoreFoundationVersionNumber < 800) {
9843 items = [NSMutableArray arrayWithObjects:
9844 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage imageNamed:@"home.png"] tag:0] autorelease],
9845 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage imageNamed:@"install.png"] tag:0] autorelease],
9846 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage imageNamed:@"changes.png"] tag:0] autorelease],
9847 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage imageNamed:@"manage.png"] tag:0] autorelease],
9848 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage imageNamed:@"search.png"] tag:0] autorelease],
9851 items = [NSMutableArray arrayWithObjects:
9852 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage imageNamed:@"home7.png"] selectedImage:[UIImage imageNamed:@"home7s.png"]] autorelease],
9853 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage imageNamed:@"install7.png"] selectedImage:[UIImage imageNamed:@"install7s.png"]] autorelease],
9854 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage imageNamed:@"changes7.png"] selectedImage:[UIImage imageNamed:@"changes7s.png"]] autorelease],
9855 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage imageNamed:@"manage7.png"] selectedImage:[UIImage imageNamed:@"manage7s.png"]] autorelease],
9856 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage imageNamed:@"search7.png"] selectedImage:[UIImage imageNamed:@"search7s.png"]] autorelease],
9860 NSMutableArray *controllers([NSMutableArray array]);
9861 for (UITabBarItem *item in items) {
9862 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9863 [controller setTabBarItem:item];
9864 [controllers addObject:controller];
9866 [tabbar_ setViewControllers:controllers];
9868 [tabbar_ setUpdateDelegate:self];
9871 - (void) _sendMemoryWarningNotification {
9872 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: maybe 4_0?
9873 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationMemoryWarningNotification" object:[UIApplication sharedApplication]];
9875 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
9878 - (void) _sendMemoryWarningNotifications {
9880 [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO];
9886 - (void) applicationDidReceiveMemoryWarning:(UIApplication *)application {
9888 [[NSURLCache sharedURLCache] removeAllCachedResponses];
9891 - (void) applicationDidFinishLaunching:(id)unused {
9892 //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil];
9895 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9896 [self setApplicationSupportsShakeToEdit:NO];
9898 @synchronized (HostConfig_) {
9899 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9902 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9903 initWithMemoryCapacity:524288
9904 diskCapacity:10485760
9905 diskPath:Cache("SDURLCache")
9908 [CydiaWebViewController _initialize];
9910 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9912 // this would disallow http{,s} URLs from accessing this data
9913 //[WebView registerURLSchemeAsLocal:@"cydia"];
9915 Font12_ = [UIFont systemFontOfSize:12];
9916 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9917 Font14_ = [UIFont systemFontOfSize:14];
9918 Font18_ = [UIFont systemFontOfSize:18];
9919 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9920 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9922 essential_ = [NSMutableArray arrayWithCapacity:4];
9923 broken_ = [NSMutableArray arrayWithCapacity:4];
9925 // XXX: I really need this thing... like, seriously... I'm sorry
9926 appcache_ = [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] autorelease];
9927 [appcache_ reloadData];
9929 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9930 [window_ orderFront:self];
9931 [window_ makeKey:self];
9932 [window_ setHidden:NO];
9935 [self addStashController];
9936 // XXX: this would be much cleaner as a yieldToSelector:
9937 // that way the removeStashController could happen right here inline
9938 // we also could no longer require the useless stash_ field anymore
9939 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9944 int error(stat("/", &root));
9945 _assert(error != -1);
9947 #define Stash_(path) do { \
9948 struct stat folder; \
9949 int error(lstat((path), &folder)); \
9950 if (error != -1 && ( \
9951 folder.st_dev == root.st_dev && \
9952 S_ISDIR(folder.st_mode) \
9953 ) || error == -1 && ( \
9954 errno == ENOENT || \
9959 Stash_("/Applications");
9960 Stash_("/Library/Ringtones");
9961 Stash_("/Library/Wallpaper");
9962 //Stash_("/usr/bin");
9963 Stash_("/usr/include");
9964 Stash_("/usr/share");
9965 //Stash_("/var/lib");
9967 database_ = [Database sharedInstance];
9968 [database_ setDelegate:self];
9970 [window_ setUserInteractionEnabled:NO];
9971 [self setupViewControllers];
9973 CydiaLoadingViewController *loading([[[CydiaLoadingViewController alloc] init] autorelease]);
9974 UINavigationController *navigation([[[UINavigationController alloc] init] autorelease]);
9975 [navigation setViewControllers:[NSArray arrayWithObject:loading]];
9977 emulated_ = [[[CyteTabBarController alloc] init] autorelease];
9978 [emulated_ setViewControllers:[NSArray arrayWithObject:navigation]];
9979 [emulated_ setSelectedIndex:0];
9981 if ([emulated_ respondsToSelector:@selector(concealTabBarSelection)])
9982 [emulated_ concealTabBarSelection];
9984 if ([window_ respondsToSelector:@selector(setRootViewController:)])
9985 [window_ setRootViewController:emulated_];
9987 [window_ addSubview:[emulated_ view]];
9989 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9993 - (NSArray *) defaultStartPages {
9994 NSMutableArray *standard = [NSMutableArray array];
9995 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9996 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9997 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9998 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9999 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
10003 - (void) loadData {
10005 if ([emulated_ modalViewController] != nil)
10006 [emulated_ dismissModalViewControllerAnimated:YES];
10007 [window_ setUserInteractionEnabled:NO];
10009 [self reloadDataWithInvocation:nil];
10010 [self refreshIfPossible];
10013 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
10014 NSArray *saved = [[[Metadata_ objectForKey:@"InterfaceState"] mutableCopy] autorelease];
10015 int standardIndex = 0;
10016 NSArray *standard = [self defaultStartPages];
10023 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
10024 if (valid && closed != nil) {
10025 NSTimeInterval interval([closed timeIntervalSinceNow]);
10026 if (interval <= -(30*60))
10030 if (valid && [saved count] != [standard count])
10034 for (unsigned int i = 0; i < [standard count]; i++) {
10035 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
10036 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
10037 // but it's good enough for now.
10038 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
10045 NSArray *items = nil;
10047 [tabbar_ setSelectedIndex:savedIndex];
10050 [tabbar_ setSelectedIndex:standardIndex];
10054 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
10055 NSArray *stack = [items objectAtIndex:tab];
10056 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
10057 NSMutableArray *current = [NSMutableArray array];
10059 for (unsigned int nav = 0; nav < [stack count]; nav++) {
10060 NSString *addr = [stack objectAtIndex:nav];
10061 NSURL *url = [NSURL URLWithString:addr];
10062 CyteViewController *page = [self pageForURL:url forExternal:NO withReferrer:nil];
10064 [current addObject:page];
10067 [navigation setViewControllers:current];
10070 // (Try to) show the startup URL.
10071 if (starturl_ != nil) {
10072 [self openCydiaURL:starturl_ forExternal:YES];
10077 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
10078 if (item != nil && IsWildcat_) {
10079 [sheet showFromBarButtonItem:item animated:YES];
10081 [sheet showInView:window_];
10085 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
10086 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
10087 [progress setTitle:task];
10088 [progress addProgressEvent:event];
10091 - (void) addProgressEventForTask:(NSArray *)data {
10092 CydiaProgressEvent *event([data objectAtIndex:0]);
10093 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
10094 [self addProgressEvent:event forTask:task];
10097 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
10098 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
10104 id Alloc_(id self, SEL selector) {
10105 id object = alloc_(self, selector);
10106 lprintf("[%s]A-%p\n", self->isa->name, object);
10111 id Dealloc_(id self, SEL selector) {
10112 id object = dealloc_(self, selector);
10113 lprintf("[%s]D-%p\n", self->isa->name, object);
10117 Class $NSURLConnection;
10119 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
10120 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
10122 NSURL *url([copy URL]);
10124 NSString *host([url host]);
10125 NSString *scheme([[url scheme] lowercaseString]);
10127 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
10129 @synchronized (HostConfig_) {
10130 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
10131 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
10132 [copy setHTTPShouldUsePipelining:YES];
10134 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
10135 if ([control isEqualToString:@"max-age=0"])
10136 if ([CachedURLs_ containsObject:url]) {
10138 NSLog(@"~~~: %@", url);
10141 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
10143 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
10144 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
10145 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
10149 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
10155 static CGSize $WAKWindow$screenSize(WAKWindow *self, SEL _cmd) {
10156 CGSize size([[UIScreen mainScreen] bounds].size);
10157 /*if ([$WAKWindow respondsToSelector:@selector(hasLandscapeOrientation)])
10158 if ([$WAKWindow hasLandscapeOrientation])
10159 std::swap(size.width, size.height);*/
10163 Class $NSUserDefaults;
10165 MSHook(id, NSUserDefaults$objectForKey$, NSUserDefaults *self, SEL _cmd, NSString *key) {
10166 if ([key respondsToSelector:@selector(isEqualToString:)] && [key isEqualToString:@"WebKitLocalStorageDatabasePathPreferenceKey"])
10167 return Cache("LocalStorage");
10168 return _NSUserDefaults$objectForKey$(self, _cmd, key);
10171 int main(int argc, char *argv[]) {
10172 setreugid(501, 501);
10174 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10178 UpdateExternalStatus(0);
10180 UIScreen *screen([UIScreen mainScreen]);
10181 if ([screen respondsToSelector:@selector(scale)])
10182 ScreenScale_ = [screen scale];
10186 UIDevice *device([UIDevice currentDevice]);
10187 if ([device respondsToSelector:@selector(userInterfaceIdiom)]) {
10188 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10189 if (idiom == UIUserInterfaceIdiomPad)
10193 Idiom_ = IsWildcat_ ? @"ipad" : @"iphone";
10195 Pcre pattern("^([0-9]+\\.[0-9]+)");
10197 if (pattern([device systemVersion]))
10198 Firmware_ = pattern[1];
10199 if (pattern(Cydia_))
10200 Major_ = pattern[1];
10202 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
10204 HostConfig_ = [[[NSObject alloc] init] autorelease];
10205 @synchronized (HostConfig_) {
10206 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10207 TokenHosts_ = [NSMutableSet setWithCapacity:4];
10208 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
10209 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
10210 CachedURLs_ = [NSMutableSet setWithCapacity:32];
10213 NSString *ui(@"ui/ios");
10215 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
10216 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"/%@", Major_]];
10217 UI_ = CydiaURL(ui);
10219 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10221 /* Library Hacks {{{ */
10222 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10224 $WAKWindow = objc_getClass("WAKWindow");
10225 if ($WAKWindow != NULL)
10226 if (Method method = class_getInstanceMethod($WAKWindow, @selector(screenSize)))
10227 method_setImplementation(method, (IMP) &$WAKWindow$screenSize);
10229 $NSURLConnection = objc_getClass("NSURLConnection");
10230 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10231 if (NSURLConnection$init$ != NULL) {
10232 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10233 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10236 $NSUserDefaults = objc_getClass("NSUserDefaults");
10237 Method NSUserDefaults$objectForKey$(class_getInstanceMethod($NSUserDefaults, @selector(objectForKey:)));
10238 if (NSUserDefaults$objectForKey$ != NULL) {
10239 _NSUserDefaults$objectForKey$ = reinterpret_cast<id (*)(NSUserDefaults *, SEL, NSString *)>(method_getImplementation(NSUserDefaults$objectForKey$));
10240 method_setImplementation(NSUserDefaults$objectForKey$, reinterpret_cast<IMP>(&$NSUserDefaults$objectForKey$));
10243 /* Set Locale {{{ */
10244 Locale_ = CFLocaleCopyCurrent();
10245 Languages_ = [NSLocale preferredLanguages];
10247 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10248 //NSLog(@"%@", [Languages_ description]);
10251 if (Locale_ != NULL)
10252 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10253 else if (Languages_ != nil && [Languages_ count] != 0)
10254 lang = [[Languages_ objectAtIndex:0] UTF8String];
10256 // XXX: consider just setting to C and then falling through?
10259 if (lang != NULL) {
10260 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
10261 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10264 NSLog(@"Setting Language: %s", lang);
10266 if (lang != NULL) {
10267 setenv("LANG", lang, true);
10268 std::setlocale(LC_ALL, lang);
10271 /* Index Collation {{{ */
10272 if (Class $UILocalizedIndexedCollation = objc_getClass("UILocalizedIndexedCollation")) { @try {
10273 NSBundle *bundle([NSBundle bundleForClass:$UILocalizedIndexedCollation]);
10274 NSString *path([bundle pathForResource:@"UITableViewLocalizedSectionIndex" ofType:@"plist"]);
10275 //path = @"/System/Library/Frameworks/UIKit.framework/.lproj/UITableViewLocalizedSectionIndex.plist";
10276 NSDictionary *dictionary([NSDictionary dictionaryWithContentsOfFile:path]);
10277 _H<UILocalizedIndexedCollation> collation([[[$UILocalizedIndexedCollation alloc] initWithDictionary:dictionary] autorelease]);
10279 CollationLocale_ = MSHookIvar<NSLocale *>(collation, "_locale");
10281 if (kCFCoreFoundationVersionNumber >= 800 && [[CollationLocale_ localeIdentifier] isEqualToString:@"zh@collation=stroke"]) {
10282 CollationThumbs_ = [NSArray arrayWithObjects:@"1",@"•",@"4",@"•",@"7",@"•",@"10",@"•",@"13",@"•",@"16",@"•",@"19",@"A",@"•",@"E",@"•",@"I",@"•",@"M",@"•",@"R",@"•",@"V",@"•",@"Z",@"#",nil];
10283 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})
10284 CollationOffset_.push_back(offset);
10285 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];
10286 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];
10289 CollationThumbs_ = [collation sectionIndexTitles];
10290 for (size_t index(0), end([CollationThumbs_ count]); index != end; ++index)
10291 CollationOffset_.push_back([collation sectionForSectionIndexTitleAtIndex:index]);
10293 CollationTitles_ = [collation sectionTitles];
10294 CollationStarts_ = MSHookIvar<NSArray *>(collation, "_sectionStartStrings");
10296 NSString *&transform(MSHookIvar<NSString *>(collation, "_transform"));
10297 if (&transform != NULL && transform != nil) {
10298 /*if ([collation respondsToSelector:@selector(transformedCollationStringForString:)])
10299 CollationModify_ = [=](NSString *value) { return [collation transformedCollationStringForString:value]; };*/
10300 const UChar *uid(reinterpret_cast<const UChar *>([transform cStringUsingEncoding:NSUnicodeStringEncoding]));
10301 UErrorCode code(U_ZERO_ERROR);
10302 CollationTransl_ = utrans_openU(uid, -1, UTRANS_FORWARD, NULL, 0, NULL, &code);
10303 if (!U_SUCCESS(code))
10304 NSLog(@"%s", u_errorName(code));
10308 } @catch (NSException *e) {
10312 CollationLocale_ = [[[NSLocale alloc] initWithLocaleIdentifier:@"en@collation=dictionary"] autorelease];
10314 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];
10315 for (NSInteger offset(0); offset != 28; ++offset)
10316 CollationOffset_.push_back(offset);
10318 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];
10319 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];
10323 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
10325 /* Parse Arguments {{{ */
10326 bool substrate(false);
10332 for (int argi(1); argi != argc; ++argi)
10333 if (strcmp(argv[argi], "--") == 0) {
10335 argv[argi] = argv[0];
10341 for (int argi(1); argi != arge; ++argi)
10342 if (strcmp(args[argi], "--substrate") == 0)
10345 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10349 App_ = [[NSBundle mainBundle] bundlePath];
10352 Cache_ = [[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia", @"/var/mobile"] retain];
10354 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10355 alloc_ = alloc->method_imp;
10356 alloc->method_imp = (IMP) &Alloc_;*/
10358 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10359 dealloc_ = dealloc->method_imp;
10360 dealloc->method_imp = (IMP) &Dealloc_;*/
10362 void *gestalt(dlopen("/usr/lib/libMobileGestalt.dylib", RTLD_GLOBAL | RTLD_LAZY));
10363 $MGCopyAnswer = reinterpret_cast<CFStringRef (*)(CFStringRef)>(dlsym(gestalt, "MGCopyAnswer"));
10365 /* System Information {{{ */
10369 size = sizeof(maxproc);
10370 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10371 perror("sysctlbyname(\"kern.maxproc\", ?)");
10372 else if (maxproc < 64) {
10374 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10375 perror("sysctlbyname(\"kern.maxproc\", #)");
10378 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10379 char *osversion = new char[size];
10380 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10381 perror("sysctlbyname(\"kern.osversion\", ?)");
10383 System_ = [NSString stringWithUTF8String:osversion];
10385 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10386 char *machine = new char[size];
10387 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10388 perror("sysctlbyname(\"hw.machine\", ?)");
10390 Machine_ = machine;
10392 int64_t usermem(0);
10393 size = sizeof(usermem);
10394 if (sysctlbyname("hw.usermem", &usermem, &size, NULL, 0) == -1)
10397 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10398 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10399 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10401 UniqueID_ = UniqueIdentifier(device);
10403 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10404 Product_ = [info objectForKey:@"SafariProductVersion"];
10405 Safari_ = [info objectForKey:@"CFBundleVersion"];
10408 NSString *agent([NSString stringWithFormat:@"Cydia/%@ CyF/%.2f", Cydia_, kCFCoreFoundationVersionNumber]);
10410 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Safari_))
10411 agent = [NSString stringWithFormat:@"Safari/%@ %@", match[0], agent];
10412 if (Pcre match = Pcre("^[0-9]+[A-Z][0-9]+[a-z]?", System_))
10413 agent = [NSString stringWithFormat:@"Mobile/%@ %@", match[0], agent];
10414 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Product_))
10415 agent = [NSString stringWithFormat:@"Version/%@ %@", match[0], agent];
10417 UserAgent_ = agent;
10419 /* Load Database {{{ */
10421 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10423 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10425 if (Metadata_ == NULL)
10426 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10428 Settings_ = [Metadata_ objectForKey:@"Settings"];
10430 Packages_ = [Metadata_ objectForKey:@"Packages"];
10432 Values_ = [Metadata_ objectForKey:@"Values"];
10433 Sections_ = [Metadata_ objectForKey:@"Sections"];
10434 Sources_ = [Metadata_ objectForKey:@"Sources"];
10436 Token_ = [Metadata_ objectForKey:@"Token"];
10438 Version_ = [Metadata_ objectForKey:@"Version"];
10441 if (Values_ == nil) {
10442 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10443 [Metadata_ setObject:Values_ forKey:@"Values"];
10446 if (Sections_ == nil) {
10447 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10448 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10451 if (Sources_ == nil) {
10452 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10453 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10456 if (Version_ == nil) {
10457 Version_ = [NSNumber numberWithUnsignedInt:0];
10458 [Metadata_ setObject:Version_ forKey:@"Version"];
10461 if ([Version_ unsignedIntValue] == 0) {
10462 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10463 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10464 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10465 CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./");
10467 Version_ = [NSNumber numberWithUnsignedInt:1];
10468 [Metadata_ setObject:Version_ forKey:@"Version"];
10470 [Metadata_ removeObjectForKey:@"LastUpdate"];
10475 _H<NSMutableArray> broken([NSMutableArray array]);
10476 for (NSString *key in (id) Sources_)
10477 if ([key rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"# "]].location != NSNotFound)
10478 [broken addObject:key];
10479 if ([broken count] != 0) {
10480 for (NSString *key in (id) broken)
10481 [Sources_ removeObjectForKey:key];
10486 _root(CydiaWriteSources());
10489 mkdir("/var/mobile/Library/Cydia", 0755);
10490 MetaFile_.Open("/var/mobile/Library/Cydia/metadata.cb0");
10493 if (Packages_ != nil) {
10495 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10499 [Metadata_ removeObjectForKey:@"Packages"];
10505 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10507 #define MobileSubstrate_(name) \
10508 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10509 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10510 if (handle == NULL) \
10511 NSLog(@"%s", dlerror()); \
10514 MobileSubstrate_(Activator)
10515 MobileSubstrate_(libstatusbar)
10516 MobileSubstrate_(SimulatedKeyEvents)
10517 MobileSubstrate_(WinterBoard)
10519 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10520 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10522 if (kCFCoreFoundationVersionNumber > 1000)
10523 _root(system([[NSString stringWithFormat:@"/usr/libexec/cydia/setnsfpn /var/lib"] UTF8String]));
10525 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10527 if (access("/User", F_OK) != 0 || version != 6) {
10529 _root(system("/usr/libexec/cydia/firmware.sh"));
10533 if (access("/tmp/cydia.chk", F_OK) == 0) {
10534 if (unlink([Cache("pkgcache.bin") UTF8String]) == -1)
10535 _assert(errno == ENOENT);
10536 if (unlink([Cache("srcpkgcache.bin") UTF8String]) == -1)
10537 _assert(errno == ENOENT);
10540 /* APT Initialization {{{ */
10541 _assert(pkgInitConfig(*_config));
10542 _assert(pkgInitSystem(*_config, _system));
10545 _config->Set("APT::Acquire::Translation", lang);
10547 // XXX: this timeout might be important :(
10548 //_config->Set("Acquire::http::Timeout", 15);
10550 _config->Set("Acquire::http::MaxParallel", usermem >= 384 * 1024 * 1024 ? 16 : 3);
10552 mkdir([Cache_ UTF8String], 0755);
10553 mkdir([Cache("archives") UTF8String], 0755);
10554 mkdir([Cache("archives/partial") UTF8String], 0755);
10555 _config->Set("Dir::Cache", [Cache_ UTF8String]);
10557 mkdir([Cache("lists") UTF8String], 0755);
10558 mkdir([Cache("lists/partial") UTF8String], 0755);
10559 mkdir([Cache("periodic") UTF8String], 0755);
10560 _config->Set("Dir::State::Lists", [Cache("lists") UTF8String]);
10562 /* Color Choices {{{ */
10563 space_ = CGColorSpaceCreateDeviceRGB();
10565 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10566 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10567 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10568 Folder_.Set(space_, 0x8e/255.f, 0x8e/255.f, 0x93/255.f, 1.0);
10569 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10570 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10571 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10572 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10573 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10574 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10576 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10577 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10579 /* UIKit Configuration {{{ */
10580 // XXX: I have a feeling this was important
10581 //UIKeyboardDisableAutomaticAppearance();
10585 chown([Cache("ApplicationCache.db") UTF8String], 501, 501);
10586 chown([Cache("Cache.db") UTF8String], 501, 501);
10587 chown([Cache("Cache.db-shm") UTF8String], 501, 501);
10588 chown([Cache("Cache.db-wal") UTF8String], 501, 501);
10591 $SBSSetInterceptsMenuButtonForever = reinterpret_cast<void (*)(bool)>(dlsym(RTLD_DEFAULT, "SBSSetInterceptsMenuButtonForever"));
10593 const char *symbol(kCFCoreFoundationVersionNumber >= 800 ? "MGGetBoolAnswer" : "GSSystemHasCapability");
10594 BOOL (*GSSystemHasCapability)(CFStringRef) = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, symbol));
10595 bool fast = GSSystemHasCapability != NULL && GSSystemHasCapability(CFSTR("armv7"));
10597 PulseInterval_ = fast ? 50000 : 500000;
10599 Colon_ = UCLocalize("COLON_DELIMITED");
10600 Elision_ = UCLocalize("ELISION");
10601 Error_ = UCLocalize("ERROR");
10602 Warning_ = UCLocalize("WARNING");
10605 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10607 CGColorSpaceRelease(space_);
10608 CFRelease(Locale_);