1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2015 Jay Freeman (saurik)
5 /* GNU General Public License, Version 3 {{{ */
7 * Cydia is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published
9 * by the Free Software Foundation, either version 3 of the License,
10 * or (at your option) any later version.
12 * Cydia is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Cydia. If not, see <http://www.gnu.org/licenses/>.
22 // XXX: wtf/FastMalloc.h... wtf?
23 #define USE_SYSTEM_MALLOC 1
25 /* #include Directives {{{ */
26 #include "CyteKit/UCPlatform.h"
27 #include "CyteKit/Localize.h"
29 #include <unicode/ustring.h>
30 #include <unicode/utrans.h>
32 #include <objc/objc.h>
33 #include <objc/runtime.h>
35 #include <CoreGraphics/CoreGraphics.h>
36 #include <Foundation/Foundation.h>
39 #define DEPLOYMENT_TARGET_MACOSX 1
40 #define CF_BUILDING_CF 1
41 #include <CoreFoundation/CFInternal.h>
44 #include <CoreFoundation/CFUniChar.h>
46 #include <SystemConfiguration/SystemConfiguration.h>
48 #include <UIKit/UIKit.h>
49 #include "iPhonePrivate.h"
51 #include <IOKit/IOKitLib.h>
53 #include <QuartzCore/CALayer.h>
55 #include <WebCore/WebCoreThread.h>
56 #include <WebKit/DOMHTMLIFrameElement.h>
65 #include "fdstream.hpp"
70 #include <apt-pkg/acquire.h>
71 #include <apt-pkg/acquire-item.h>
72 #include <apt-pkg/algorithms.h>
73 #include <apt-pkg/cachefile.h>
74 #include <apt-pkg/clean.h>
75 #include <apt-pkg/configuration.h>
76 #include <apt-pkg/debindexfile.h>
77 #include <apt-pkg/debmetaindex.h>
78 #include <apt-pkg/error.h>
79 #include <apt-pkg/init.h>
80 #include <apt-pkg/mmap.h>
81 #include <apt-pkg/pkgrecords.h>
82 #include <apt-pkg/sha1.h>
83 #include <apt-pkg/sourcelist.h>
84 #include <apt-pkg/sptr.h>
85 #include <apt-pkg/strutl.h>
86 #include <apt-pkg/tagfile.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>
101 #include <mach-o/nlist.h>
110 #include <Cytore.hpp>
113 #include "Substrate.hpp"
114 #include "Menes/Menes.h"
116 #include "CyteKit/IndirectDelegate.h"
117 #include "CyteKit/RegEx.hpp"
118 #include "CyteKit/TableViewCell.h"
119 #include "CyteKit/TabBarController.h"
120 #include "CyteKit/WebScriptObject-Cyte.h"
121 #include "CyteKit/WebViewController.h"
122 #include "CyteKit/WebViewTableViewCell.h"
123 #include "CyteKit/stringWithUTF8Bytes.h"
125 #include "Cydia/MIMEAddress.h"
126 #include "Cydia/LoadingViewController.h"
127 #include "Cydia/ProgressEvent.h"
129 #include "SDURLCache/SDURLCache.h"
136 #define _timestamp ({ \
138 gettimeofday(&tv, NULL); \
139 tv.tv_sec * 1000000 + tv.tv_usec; \
142 typedef std::vector<class ProfileTime *> TimeList;
152 ProfileTime(const char *name) :
156 times_.push_back(this);
159 void AddTime(uint64_t time) {
166 std::cerr << std::setw(7) << count_ << ", " << std::setw(8) << total_ << " : " << name_ << std::endl;
178 ProfileTimer(ProfileTime &time) :
185 time_.AddTime(_timestamp - start_);
190 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
192 std::cerr << "========" << std::endl;
195 #define _profile(name) { \
196 static ProfileTime name(#name); \
197 ProfileTimer _ ## name(name);
202 // XXX: I hate clang. Apple: please get over your petty hatred of GPL and fix your gcc fork
203 #define synchronized(lock) \
204 synchronized(static_cast<NSObject *>(lock))
206 extern NSString *Cydia_;
208 #define lprintf(args...) fprintf(stderr, args)
211 #define TraceLogging (1 && !ForRelease)
212 #define HistogramInsertionSort (0 && !ForRelease)
213 #define ProfileTimes (0 && !ForRelease)
214 #define ForSaurik (0 && !ForRelease)
215 #define LogBrowser (0 && !ForRelease)
216 #define TrackResize (0 && !ForRelease)
217 #define ManualRefresh (1 && !ForRelease)
218 #define ShowInternals (0 && !ForRelease)
219 #define AlwaysReload (0 && !ForRelease)
223 #define _trace(args...)
228 #define _profile(name) {
231 #define PrintTimes() do {} while (false)
234 // Hash Functions/Structures {{{
235 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
243 @implementation NSDictionary (Cydia)
244 - (id) invokeUndefinedMethodFromWebScript:(NSString *)name withArguments:(NSArray *)arguments {
246 else if ([name isEqualToString:@"get"])
247 return [self objectForKey:[arguments objectAtIndex:0]];
248 else if ([name isEqualToString:@"keys"])
249 return [self allKeys];
253 static NSString *Colon_;
255 static NSString *Error_;
256 static NSString *Warning_;
258 static NSString *Cache_;
259 #define Cache(file) \
260 [NSString stringWithFormat:@"%@/%s", Cache_, file]
262 static void (*$SBSSetInterceptsMenuButtonForever)(bool);
263 static NSData *(*$SBSCopyIconImagePNGDataForDisplayIdentifier)(NSString *);
265 static CFStringRef (*$MGCopyAnswer)(CFStringRef);
267 static NSString *UniqueIdentifier(UIDevice *device = nil) {
268 if (kCFCoreFoundationVersionNumber < 800) // iOS 7.x
269 return [device ?: [UIDevice currentDevice] uniqueIdentifier];
271 return [(id)$MGCopyAnswer(CFSTR("UniqueDeviceID")) autorelease];
274 static bool IsReachable(const char *name) {
275 SCNetworkReachabilityFlags flags; {
276 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, name));
277 SCNetworkReachabilityGetFlags(reachability, &flags);
278 CFRelease(reachability);
281 // XXX: this elaborate mess is what Apple is using to determine this? :(
282 // XXX: do we care if the user has to intervene? maybe that's ok?
284 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
285 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
286 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
287 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
288 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
289 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
294 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
296 static _finline NSString *CydiaURL(NSString *path) {
298 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
299 page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
300 page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
301 page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
302 page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
304 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
307 static NSString *ShellEscape(NSString *value) {
308 return [NSString stringWithFormat:@"'%@'", [value stringByReplacingOccurrencesOfString:@"'" withString:@"'\\''"]];
311 static _finline void UpdateExternalStatus(uint64_t newStatus) {
313 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
314 notify_set_state(notify_token, newStatus);
315 notify_cancel(notify_token);
317 notify_post("com.saurik.Cydia.status");
320 static CGFloat CYStatusBarHeight() {
321 CGSize size([[UIApplication sharedApplication] statusBarFrame].size);
322 return UIInterfaceOrientationIsPortrait([[UIApplication sharedApplication] statusBarOrientation]) ? size.height : size.width;
325 /* NSForcedOrderingSearch doesn't work on the iPhone */
326 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
327 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
328 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
330 /* Insertion Sort {{{ */
332 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
333 const char *ptr = (const char *)list;
335 CFIndex half = count / 2;
336 const char *probe = ptr + elementSize * half;
337 CFComparisonResult cr = comparator(element, probe, context);
338 if (0 == cr) return (probe - (const char *)list) / elementSize;
339 ptr = (cr < 0) ? ptr : probe + elementSize;
340 count = (cr < 0) ? half : (half + (count & 1) - 1);
342 return (ptr - (const char *)list) / elementSize;
345 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
346 const char *ptr = (const char *)list;
348 CFIndex half = count / 2;
349 const char *probe = ptr + elementSize * half;
350 CFComparisonResult cr = comparator(element, probe, context);
351 if (0 == cr) return (probe - (const char *)list) / elementSize;
352 ptr = (cr < 0) ? ptr : probe + elementSize;
353 count = (cr < 0) ? half : (half + (count & 1) - 1);
355 return (ptr - (const char *)list) / elementSize;
358 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
359 if (range.length == 0)
361 const void **values(new const void *[range.length]);
362 CFArrayGetValues(array, range, values);
364 #if HistogramInsertionSort > 0
365 uint32_t total(0), *offsets(new uint32_t[range.length]);
368 for (CFIndex index(1); index != range.length; ++index) {
369 const void *value(values[index]);
370 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
371 CFIndex correct(index);
372 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
373 #if HistogramInsertionSort > 1
374 NSLog(@"%@ < %@", value, values[correct - 1]);
379 if (correct != index) {
380 size_t offset(index - correct);
381 #if HistogramInsertionSort
385 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
387 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
388 values[correct] = value;
392 CFArrayReplaceValues(array, range, values, range.length);
395 #if HistogramInsertionSort > 0
396 for (CFIndex index(0); index != range.length; ++index)
397 if (offsets[index] != 0)
398 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
399 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
406 /* Apple Bug Fixes {{{ */
407 @implementation UIWebDocumentView (Cydia)
409 - (void) _setScrollerOffset:(CGPoint)offset {
410 UIScroller *scroller([self _scroller]);
412 CGSize size([scroller contentSize]);
413 CGSize bounds([scroller bounds].size);
416 max.x = size.width - bounds.width;
417 max.y = size.height - bounds.height;
425 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
426 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
428 [scroller setOffset:offset];
434 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
435 size_t length([self length] - state->state);
438 else if (length > count)
440 for (size_t i(0); i != length; ++i)
441 objects[i] = [self item:state->state++];
442 state->itemsPtr = objects;
443 state->mutationsPtr = (unsigned long *) self;
447 /* Cydia NSString Additions {{{ */
448 @interface NSString (Cydia)
449 - (NSComparisonResult) compareByPath:(NSString *)other;
450 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
453 @implementation NSString (Cydia)
455 - (NSComparisonResult) compareByPath:(NSString *)other {
456 NSString *prefix = [self commonPrefixWithString:other options:0];
457 size_t length = [prefix length];
459 NSRange lrange = NSMakeRange(length, [self length] - length);
460 NSRange rrange = NSMakeRange(length, [other length] - length);
462 lrange = [self rangeOfString:@"/" options:0 range:lrange];
463 rrange = [other rangeOfString:@"/" options:0 range:rrange];
465 NSComparisonResult value;
467 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
468 value = NSOrderedSame;
469 else if (lrange.location == NSNotFound)
470 value = NSOrderedAscending;
471 else if (rrange.location == NSNotFound)
472 value = NSOrderedDescending;
474 value = NSOrderedSame;
476 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
477 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
478 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
479 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
481 NSComparisonResult result = [lpath compare:rpath];
482 return result == NSOrderedSame ? value : result;
485 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
486 return [(id)CFURLCreateStringByAddingPercentEscapes(
491 kCFStringEncodingUTF8
498 /* C++ NSString Wrapper Cache {{{ */
499 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
500 return size == 0 ? NULL :
501 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
502 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
505 static _finline CFStringRef CYStringCreate(const std::string &data) {
506 return CYStringCreate(data.data(), data.size());
509 static _finline CFStringRef CYStringCreate(const char *data) {
510 return CYStringCreate(data, strlen(data));
519 _finline void clear_() {
520 if (cache_ != NULL) {
527 _finline bool empty() const {
531 _finline size_t size() const {
535 _finline char *data() const {
539 _finline void clear() {
544 _finline CYString() :
551 _finline ~CYString() {
555 void operator =(const CYString &rhs) {
559 if (rhs.cache_ == nil)
562 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
565 void copy(CYPool *pool) {
566 char *temp(pool->malloc<char>(size_ + 1));
567 memcpy(temp, data_, size_);
572 void set(CYPool *pool, const char *data, size_t size) {
578 data_ = const_cast<char *>(data);
586 _finline void set(CYPool *pool, const char *data) {
587 set(pool, data, data == NULL ? 0 : strlen(data));
590 _finline void set(CYPool *pool, const std::string &rhs) {
591 set(pool, rhs.data(), rhs.size());
594 bool operator ==(const CYString &rhs) const {
595 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
598 _finline operator CFStringRef() {
600 cache_ = CYStringCreate(data_, size_);
604 _finline operator id() {
605 return (NSString *) static_cast<CFStringRef>(*this);
608 _finline operator const char *() {
609 return reinterpret_cast<const char *>(data_);
613 /* C++ NSString Algorithm Adapters {{{ */
615 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
618 struct NSStringMapHash :
619 std::unary_function<NSString *, size_t>
621 _finline size_t operator ()(NSString *value) const {
622 return CFStringHashNSString((CFStringRef) value);
626 struct NSStringMapLess :
627 std::binary_function<NSString *, NSString *, bool>
629 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
630 return [lhs compare:rhs] == NSOrderedAscending;
634 struct NSStringMapEqual :
635 std::binary_function<NSString *, NSString *, bool>
637 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
638 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
639 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
640 //[lhs isEqualToString:rhs];
645 /* CoreGraphics Primitives {{{ */
650 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
651 CGFloat color[] = {red, green, blue, alpha};
652 return CGColorCreate(space, color);
661 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
662 color_(Create_(space, red, green, blue, alpha))
664 Set(space, red, green, blue, alpha);
669 CGColorRelease(color_);
676 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
678 color_ = Create_(space, red, green, blue, alpha);
681 operator CGColorRef() {
687 /* Random Global Variables {{{ */
688 static int PulseInterval_ = 500000;
690 static const NSString *UI_;
693 static bool RestartSubstrate_;
694 static NSArray *Finishes_;
696 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
697 #define NotifyConfig_ "/etc/notify.conf"
699 static bool Queuing_;
701 static CYColor Blue_;
702 static CYColor Blueish_;
703 static CYColor Black_;
704 static CYColor Folder_;
706 static CYColor White_;
707 static CYColor Gray_;
708 static CYColor Green_;
709 static CYColor Purple_;
710 static CYColor Purplish_;
712 static UIColor *InstallingColor_;
713 static UIColor *RemovingColor_;
715 static NSString *App_;
717 static BOOL Advanced_;
718 static BOOL Ignored_;
720 static _H<UIFont> Font12_;
721 static _H<UIFont> Font12Bold_;
722 static _H<UIFont> Font14_;
723 static _H<UIFont> Font18_;
724 static _H<UIFont> Font18Bold_;
725 static _H<UIFont> Font22Bold_;
727 static const char *Machine_ = NULL;
728 static _H<NSString> System_;
729 static NSString *SerialNumber_ = nil;
730 static NSString *ChipID_ = nil;
731 static NSString *BBSNum_ = nil;
732 static _H<NSString> UniqueID_;
733 static _H<NSString> UserAgent_;
734 static _H<NSString> Product_;
735 static _H<NSString> Safari_;
737 static _H<NSLocale> CollationLocale_;
738 static _H<NSArray> CollationThumbs_;
739 static std::vector<NSInteger> CollationOffset_;
740 static _H<NSArray> CollationTitles_;
741 static _H<NSArray> CollationStarts_;
742 static UTransliterator *CollationTransl_;
743 //static Function<NSString *, NSString *> CollationModify_;
745 typedef std::basic_string<UChar> ustring;
746 static ustring CollationString_;
748 #define CUC const ustring &str(*reinterpret_cast<const ustring *>(rep))
749 #define UC ustring &str(*reinterpret_cast<ustring *>(rep))
750 static struct UReplaceableCallbacks CollationUCalls_ = {
751 .length = [](const UReplaceable *rep) -> int32_t { CUC;
755 .charAt = [](const UReplaceable *rep, int32_t offset) -> UChar { CUC;
756 //fprintf(stderr, "charAt(%d) : %d\n", offset, str.size());
757 if (offset >= str.size())
762 .char32At = [](const UReplaceable *rep, int32_t offset) -> UChar32 { CUC;
763 //fprintf(stderr, "char32At(%d) : %d\n", offset, str.size());
764 if (offset >= str.size())
767 U16_GET(str.data(), 0, offset, str.size(), c);
771 .replace = [](UReplaceable *rep, int32_t start, int32_t limit, const UChar *text, int32_t length) -> void { UC;
772 //fprintf(stderr, "replace(%d, %d, %d) : %d\n", start, limit, length, str.size());
773 str.replace(start, limit - start, text, length);
776 .extract = [](UReplaceable *rep, int32_t start, int32_t limit, UChar *dst) -> void { UC;
777 //fprintf(stderr, "extract(%d, %d) : %d\n", start, limit, str.size());
778 str.copy(dst, limit - start, start);
781 .copy = [](UReplaceable *rep, int32_t start, int32_t limit, int32_t dest) -> void { UC;
782 //fprintf(stderr, "copy(%d, %d, %d) : %d\n", start, limit, dest, str.size());
783 str.replace(dest, 0, str, start, limit - start);
787 static CFLocaleRef Locale_;
788 static NSArray *Languages_;
789 static CGColorSpaceRef space_;
791 #define CacheState_ "/var/mobile/Library/Caches/com.saurik.Cydia/CacheState.plist"
792 #define SavedState_ "/var/mobile/Library/Caches/com.saurik.Cydia/SavedState.plist"
794 static NSDictionary *SectionMap_;
795 static _H<NSDate> Backgrounded_;
796 static _transient NSMutableDictionary *Values_;
797 static _transient NSMutableDictionary *Sections_;
798 _H<NSMutableDictionary> Sources_;
799 static _transient NSNumber *Version_;
803 CGFloat ScreenScale_;
804 static NSString *Idiom_;
805 static _H<NSString> Firmware_;
806 static NSString *Major_;
808 static _H<NSMutableDictionary> SessionData_;
809 static _H<NSObject> HostConfig_;
810 static _H<NSMutableSet> BridgedHosts_;
811 static _H<NSMutableSet> InsecureHosts_;
812 static _H<NSMutableSet> PipelinedHosts_;
813 static _H<NSMutableSet> CachedURLs_;
815 static NSString *kCydiaProgressEventTypeError = @"Error";
816 static NSString *kCydiaProgressEventTypeInformation = @"Information";
817 static NSString *kCydiaProgressEventTypeStatus = @"Status";
818 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
821 /* Display Helpers {{{ */
822 inline float Interpolate(float begin, float end, float fraction) {
823 return (end - begin) * fraction + begin;
826 static inline double Retina(double value) {
827 value *= ScreenScale_;
828 value = round(value);
829 value /= ScreenScale_;
833 static inline CGRect Retina(CGRect value) {
834 value.origin.x *= ScreenScale_;
835 value.origin.y *= ScreenScale_;
836 value.size.width *= ScreenScale_;
837 value.size.height *= ScreenScale_;
838 value = CGRectIntegral(value);
839 value.origin.x /= ScreenScale_;
840 value.origin.y /= ScreenScale_;
841 value.size.width /= ScreenScale_;
842 value.size.height /= ScreenScale_;
846 static _finline const char *StripVersion_(const char *version) {
847 const char *colon(strchr(version, ':'));
848 return colon == NULL ? version : colon + 1;
851 NSString *LocalizeSection(NSString *section) {
852 static RegEx title_r("(.*?) \\((.*)\\)");
853 if (title_r(section)) {
854 NSString *parent(title_r[1]);
855 NSString *child(title_r[2]);
857 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
858 LocalizeSection(parent),
859 LocalizeSection(child)
863 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
866 NSString *Simplify(NSString *title) {
867 const char *data = [title UTF8String];
868 size_t size = [title lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
870 static RegEx square_r("\\[(.*)\\]");
871 if (square_r(data, size))
872 return Simplify(square_r[1]);
874 static RegEx paren_r("\\((.*)\\)");
875 if (paren_r(data, size))
876 return Simplify(paren_r[1]);
878 static RegEx title_r("(.*?) \\((.*)\\)");
879 if (title_r(data, size))
880 return Simplify(title_r[1]);
886 bool isSectionVisible(NSString *section) {
887 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
888 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
889 return hidden == nil || ![hidden boolValue];
892 static NSObject *CYIOGetValue(const char *path, NSString *property) {
893 io_registry_entry_t entry(IORegistryEntryFromPath(kIOMasterPortDefault, path));
894 if (entry == MACH_PORT_NULL)
897 CFTypeRef value(IORegistryEntryCreateCFProperty(entry, (CFStringRef) property, kCFAllocatorDefault, 0));
898 IOObjectRelease(entry);
902 return [(id) value autorelease];
905 static NSString *CYHex(NSData *data, bool reverse = false) {
909 size_t length([data length]);
910 uint8_t bytes[length];
911 [data getBytes:bytes];
913 char string[length * 2 + 1];
914 for (size_t i(0); i != length; ++i)
915 sprintf(string + i * 2, "%.2x", bytes[reverse ? length - i - 1 : i]);
917 return [NSString stringWithUTF8String:string];
920 static NSString *VerifySource(NSString *href) {
921 static RegEx href_r("(http(s?)://|file:///)[^# ]*");
923 [[[[UIAlertView alloc]
924 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("INVALID_URL")]
925 message:UCLocalize("INVALID_URL_EX")
927 cancelButtonTitle:UCLocalize("OK")
928 otherButtonTitles:nil
929 ] autorelease] show];
934 if (![href hasSuffix:@"/"])
935 href = [href stringByAppendingString:@"/"];
941 /* Delegate Prototypes {{{ */
944 @class CydiaProgressEvent;
946 @protocol DatabaseDelegate
947 - (void) repairWithSelector:(SEL)selector;
948 - (void) setConfigurationData:(NSString *)data;
949 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
952 @class CYPackageController;
954 @protocol SourceDelegate
955 - (void) setFetch:(NSNumber *)fetch;
958 @protocol FetchDelegate
959 - (bool) isSourceCancelled;
960 - (void) startSourceFetch:(NSString *)uri;
961 - (void) stopSourceFetch:(NSString *)uri;
964 @protocol CydiaDelegate
965 - (void) returnToCydia;
967 - (void) retainNetworkActivityIndicator;
968 - (void) releaseNetworkActivityIndicator;
969 - (void) clearPackage:(Package *)package;
970 - (void) installPackage:(Package *)package;
971 - (void) installPackages:(NSArray *)packages;
972 - (void) removePackage:(Package *)package;
973 - (void) beginUpdate;
975 - (bool) requestUpdate;
976 - (void) distUpgrade;
979 - (void) _saveConfig;
981 - (void) addSource:(NSDictionary *)source;
982 - (BOOL) addTrivialSource:(NSString *)href;
983 - (UIProgressHUD *) addProgressHUD;
984 - (void) removeProgressHUD:(UIProgressHUD *)hud;
985 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
986 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
990 /* CancelStatus {{{ */
992 public pkgAcquireStatus
1003 virtual bool MediaChange(std::string media, std::string drive) {
1007 virtual void IMSHit(pkgAcquire::ItemDesc &desc) {
1011 virtual bool Pulse_(pkgAcquire *Owner) = 0;
1013 virtual bool Pulse(pkgAcquire *Owner) {
1014 if (pkgAcquireStatus::Pulse(Owner) && Pulse_(Owner))
1022 _finline bool WasCancelled() const {
1027 /* DelegateStatus {{{ */
1032 _transient NSObject<ProgressDelegate> *delegate_;
1040 void setDelegate(NSObject<ProgressDelegate> *delegate) {
1041 delegate_ = delegate;
1044 virtual void Fetch(pkgAcquire::ItemDesc &desc) {
1045 NSString *name([NSString stringWithUTF8String:desc.ShortDesc.c_str()]);
1046 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItemDesc:desc]);
1047 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1050 virtual void Done(pkgAcquire::ItemDesc &desc) {
1051 NSString *name([NSString stringWithUTF8String:desc.ShortDesc.c_str()]);
1052 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:Colon_, UCLocalize("DONE"), name] ofType:kCydiaProgressEventTypeStatus forItemDesc:desc]);
1053 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1056 virtual void Fail(pkgAcquire::ItemDesc &desc) {
1058 desc.Owner->Status == pkgAcquire::Item::StatIdle ||
1059 desc.Owner->Status == pkgAcquire::Item::StatDone
1063 std::string &error(desc.Owner->ErrorText);
1067 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItemDesc:desc]);
1068 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1071 virtual bool Pulse_(pkgAcquire *Owner) {
1073 double(CurrentBytes + CurrentItems) /
1074 double(TotalBytes + TotalItems)
1077 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
1078 [NSNumber numberWithDouble:percent], @"Percent",
1080 [NSNumber numberWithDouble:CurrentBytes], @"Current",
1081 [NSNumber numberWithDouble:TotalBytes], @"Total",
1082 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
1083 nil] waitUntilDone:YES];
1085 return ![delegate_ isProgressCancelled];
1088 virtual void Start() {
1089 pkgAcquireStatus::Start();
1090 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
1093 virtual void Stop() {
1094 pkgAcquireStatus::Stop();
1095 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
1096 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
1100 /* Database Interface {{{ */
1101 typedef std::map< unsigned long, _H<Source> > SourceMap;
1103 @interface Database : NSObject {
1110 pkgCacheFile cache_;
1111 pkgDepCache::Policy *policy_;
1112 pkgRecords *records_;
1113 pkgProblemResolver *resolver_;
1114 pkgAcquire *fetcher_;
1116 SPtr<pkgPackageManager> manager_;
1117 pkgSourceList *list_;
1119 SourceMap sourceMap_;
1120 _H<NSMutableArray> sourceList_;
1122 CFMutableArrayRef packages_;
1124 _transient NSObject<DatabaseDelegate> *delegate_;
1125 _transient NSObject<ProgressDelegate> *progress_;
1127 CydiaStatus status_;
1133 std::map<const char *, _H<NSString> > sections_;
1136 + (Database *) sharedInstance;
1139 - (void) _readCydia:(NSNumber *)fd;
1140 - (void) _readStatus:(NSNumber *)fd;
1141 - (void) _readOutput:(NSNumber *)fd;
1145 - (Package *) packageWithName:(NSString *)name;
1147 - (pkgCacheFile &) cache;
1148 - (pkgDepCache::Policy *) policy;
1149 - (pkgRecords *) records;
1150 - (pkgProblemResolver *) resolver;
1151 - (pkgAcquire &) fetcher;
1152 - (pkgSourceList &) list;
1153 - (NSArray *) packages;
1154 - (NSArray *) sources;
1155 - (Source *) sourceWithKey:(NSString *)key;
1156 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1164 - (void) updateWithStatus:(CancelStatus &)status;
1166 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1168 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1169 - (NSObject<ProgressDelegate> *) progressDelegate;
1171 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1172 - (void) setFetch:(bool)fetch forURI:(const char *)uri;
1173 - (void) resetFetch;
1175 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1179 /* SourceStatus {{{ */
1180 class SourceStatus :
1184 _transient NSObject<FetchDelegate> *delegate_;
1185 _transient Database *database_;
1186 std::set<std::string> fetches_;
1189 SourceStatus(NSObject<FetchDelegate> *delegate, Database *database) :
1190 delegate_(delegate),
1195 void Set(bool fetch, const std::string &uri) {
1197 if (!fetches_.insert(uri).second)
1200 if (fetches_.erase(uri) == 0)
1204 //printf("Set(%s, %s)\n", fetch ? "true" : "false", uri.c_str());
1205 [database_ setFetch:fetch forURI:uri.c_str()];
1208 _finline void Set(bool fetch, pkgAcquire::Item *item) {
1209 /*unsigned long ID(fetch ? 1 : 0);
1213 Set(fetch, item->DescURI());
1216 void Log(const char *tag, pkgAcquire::Item *item) {
1217 //printf("%s(%s) S:%u Q:%u\n", tag, item->DescURI().c_str(), item->Status, item->QueueCounter);
1220 virtual void Fetch(pkgAcquire::ItemDesc &desc) {
1221 Log("Fetch", desc.Owner);
1222 Set(true, desc.Owner);
1225 virtual void Done(pkgAcquire::ItemDesc &desc) {
1226 Log("Done", desc.Owner);
1227 Set(false, desc.Owner);
1230 virtual void Fail(pkgAcquire::ItemDesc &desc) {
1231 Log("Fail", desc.Owner);
1232 Set(false, desc.Owner);
1235 virtual bool Pulse_(pkgAcquire *Owner) {
1236 std::set<std::string> fetches;
1237 for (pkgAcquire::ItemCIterator item(Owner->ItemsBegin()); item != Owner->ItemsEnd(); ++item) {
1239 if ((*item)->QueueCounter == 0)
1241 else switch ((*item)->Status) {
1242 case pkgAcquire::Item::StatFetching:
1243 fetches.insert((*item)->DescURI());
1252 Log(fetch ? "Pulse<true>" : "Pulse<false>", *item);
1256 std::vector<std::string> stops;
1257 std::set_difference(fetches_.begin(), fetches_.end(), fetches.begin(), fetches.end(), std::back_insert_iterator<std::vector<std::string>>(stops));
1258 for (std::vector<std::string>::const_iterator stop(stops.begin()); stop != stops.end(); ++stop) {
1259 //printf("Stop(%s)\n", stop->c_str());
1263 return ![delegate_ isSourceCancelled];
1266 virtual void Stop() {
1267 pkgAcquireStatus::Stop();
1268 [database_ resetFetch];
1272 /* ProgressEvent Implementation {{{ */
1273 @implementation CydiaProgressEvent
1275 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1276 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1279 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1280 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1281 [event setPackage:package];
1285 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItemDesc:(pkgAcquire::ItemDesc &)desc {
1286 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1288 NSString *description([NSString stringWithUTF8String:desc.Description.c_str()]);
1289 NSArray *fields([description componentsSeparatedByString:@" "]);
1290 [event setItem:fields];
1292 if ([fields count] > 3) {
1293 [event setPackage:[fields objectAtIndex:2]];
1294 [event setVersion:[fields objectAtIndex:3]];
1297 [event setURL:[NSString stringWithUTF8String:desc.URI.c_str()]];
1302 + (NSArray *) _attributeKeys {
1303 return [NSArray arrayWithObjects:
1313 - (NSArray *) attributeKeys {
1314 return [[self class] _attributeKeys];
1317 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1318 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1321 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1322 if ((self = [super init]) != nil) {
1328 - (NSString *) message {
1332 - (NSString *) type {
1336 - (NSArray *) item {
1337 return (id) item_ ?: [NSNull null];
1340 - (void) setItem:(NSArray *)item {
1344 - (NSString *) package {
1345 return (id) package_ ?: [NSNull null];
1348 - (void) setPackage:(NSString *)package {
1352 - (NSString *) url {
1353 return (id) url_ ?: [NSNull null];
1356 - (void) setURL:(NSString *)url {
1360 - (void) setVersion:(NSString *)version {
1364 - (NSString *) version {
1365 return (id) version_ ?: [NSNull null];
1368 - (NSString *) compound:(NSString *)value {
1370 NSString *mode(nil); {
1371 NSString *type([self type]);
1372 if ([type isEqualToString:kCydiaProgressEventTypeError])
1373 mode = UCLocalize("ERROR");
1374 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1375 mode = UCLocalize("WARNING");
1379 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1385 - (NSString *) compoundMessage {
1386 return [self compound:[self message]];
1389 - (NSString *) compoundTitle {
1392 if (package_ == nil)
1394 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1395 title = [package name];
1399 return [self compound:title];
1405 // Cytore Definitions {{{
1406 struct PackageValue :
1409 Cytore::Offset<PackageValue> next_;
1411 uint32_t index_ : 23;
1412 uint32_t subscribed_ : 1;
1429 Cytore::Offset<PackageValue> packages_[1 << 16];
1432 static Cytore::File<MetaValue> MetaFile_;
1434 // Cytore Helper Functions {{{
1435 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1436 SplitHash nhash = { hashlittle(name, length) };
1438 PackageValue *metadata;
1440 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1441 for (;; offset = &metadata->next_) { if (offset->IsNull()) {
1442 *offset = MetaFile_.New<PackageValue>(length + 1);
1443 metadata = &MetaFile_.Get(*offset);
1445 if (metadata == NULL) {
1449 metadata = new PackageValue();
1450 memset(metadata, 0, sizeof(*metadata));
1453 memcpy(metadata->name_, name, length);
1454 metadata->name_[length] = '\0';
1455 metadata->nhash_ = nhash.u16[1];
1457 metadata = &MetaFile_.Get(*offset);
1458 if (metadata->nhash_ != nhash.u16[1])
1460 if (strncmp(metadata->name_, name, length) != 0)
1462 if (metadata->name_[length] != '\0')
1469 static void PackageImport(const void *key, const void *value, void *context) {
1470 bool &fail(*reinterpret_cast<bool *>(context));
1473 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1474 NSLog(@"failed to import package %@", key);
1478 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1479 NSDictionary *package((NSDictionary *) value);
1481 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1482 if ([subscribed boolValue] && !metadata->subscribed_)
1483 metadata->subscribed_ = true;
1485 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1486 time_t time([date timeIntervalSince1970]);
1487 if (metadata->first_ > time || metadata->first_ == 0)
1488 metadata->first_ = time;
1491 NSDate *date([package objectForKey:@"LastSeen"]);
1492 NSString *version([package objectForKey:@"LastVersion"]);
1494 if (date != nil && version != nil) {
1495 time_t time([date timeIntervalSince1970]);
1496 if (metadata->last_ < time || metadata->last_ == 0)
1497 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1498 size_t length(strlen(buffer));
1499 uint16_t vhash(hashlittle(buffer, length));
1501 size_t capped(std::min<size_t>(8, length));
1502 char *latest(buffer + length - capped);
1504 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1505 metadata->vhash_ = vhash;
1507 metadata->last_ = time;
1513 static NSDate *GetStatusDate() {
1514 return [[[NSFileManager defaultManager] attributesOfItemAtPath:@"/var/lib/dpkg/status" error:NULL] fileModificationDate];
1517 static void SaveConfig(NSObject *lock) {
1518 @synchronized (lock) {
1524 CFPreferencesSetMultiple((CFDictionaryRef) [NSDictionary dictionaryWithObjectsAndKeys:
1525 Values_, @"CydiaValues",
1526 Sections_, @"CydiaSections",
1527 (id) Sources_, @"CydiaSources",
1528 Version_, @"CydiaVersion",
1529 nil], NULL, CFSTR("com.saurik.Cydia"), kCFPreferencesCurrentUser, kCFPreferencesCurrentHost);
1531 if (!CFPreferencesAppSynchronize(CFSTR("com.saurik.Cydia")))
1532 NSLog(@"CFPreferencesAppSynchronize(com.saurik.Cydia) == false");
1534 CydiaWriteSources();
1537 /* Source Class {{{ */
1538 @interface Source : NSObject {
1540 Database *database_;
1543 CYString depiction_;
1544 CYString description_;
1550 CYString distribution_;
1556 _H<NSString> authority_;
1558 CYString defaultIcon_;
1560 _H<NSMutableDictionary> record_;
1563 std::set<std::string> fetches_;
1564 std::set<std::string> files_;
1565 _transient NSObject<SourceDelegate> *delegate_;
1568 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(CYPool *)pool;
1570 - (NSComparisonResult) compareByName:(Source *)source;
1572 - (NSString *) depictionForPackage:(NSString *)package;
1573 - (NSString *) supportForPackage:(NSString *)package;
1575 - (metaIndex *) metaIndex;
1576 - (NSDictionary *) record;
1579 - (NSString *) rooturi;
1580 - (NSString *) distribution;
1581 - (NSString *) type;
1584 - (NSString *) host;
1586 - (NSString *) name;
1587 - (NSString *) shortDescription;
1588 - (NSString *) label;
1589 - (NSString *) origin;
1590 - (NSString *) version;
1592 - (NSString *) defaultIcon;
1593 - (NSURL *) iconURL;
1595 - (void) setFetch:(bool)fetch forURI:(const char *)uri;
1596 - (void) resetFetch;
1600 @implementation Source
1602 + (NSString *) webScriptNameForSelector:(SEL)selector {
1604 else if (selector == @selector(addSection:))
1605 return @"addSection";
1606 else if (selector == @selector(getField:))
1608 else if (selector == @selector(removeSection:))
1609 return @"removeSection";
1610 else if (selector == @selector(remove))
1616 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1617 return [self webScriptNameForSelector:selector] == nil;
1620 + (NSArray *) _attributeKeys {
1621 return [NSArray arrayWithObjects:
1632 @"shortDescription",
1639 - (NSArray *) attributeKeys {
1640 return [[self class] _attributeKeys];
1643 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1644 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1647 - (metaIndex *) metaIndex {
1651 - (void) setMetaIndex:(metaIndex *)index inPool:(CYPool *)pool {
1652 trusted_ = index->IsTrusted();
1654 uri_.set(pool, index->GetURI());
1655 distribution_.set(pool, index->GetDist());
1656 type_.set(pool, index->GetType());
1658 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1659 if (dindex != NULL) {
1660 std::string file(dindex->MetaIndexURI(""));
1661 base_.set(pool, file);
1664 _profile(Source$setMetaIndex$GetIndexes)
1665 dindex->GetIndexes(&acquire, true);
1667 _profile(Source$setMetaIndex$DescURI)
1668 for (pkgAcquire::ItemIterator item(acquire.ItemsBegin()); item != acquire.ItemsEnd(); item++) {
1669 std::string file((*item)->DescURI());
1670 files_.insert(file);
1671 if (file.length() < sizeof("Packages.bz2") || file.substr(file.length() - sizeof("Packages.bz2")) != "/Packages.bz2")
1673 file = file.substr(0, file.length() - 4);
1674 files_.insert(file);
1675 files_.insert(file + ".gz");
1676 files_.insert(file + "Index");
1681 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1684 pkgTagFile tags(&fd);
1686 pkgTagSection section;
1693 {"default-icon", &defaultIcon_},
1694 {"depiction", &depiction_},
1695 {"description", &description_},
1697 {"origin", &origin_},
1698 {"support", &support_},
1699 {"version", &version_},
1702 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1703 const char *start, *end;
1705 if (section.Find(names[i].name_, start, end)) {
1706 CYString &value(*names[i].value_);
1707 value.set(pool, start, end - start);
1713 record_ = [Sources_ objectForKey:[self key]];
1715 NSURL *url([NSURL URLWithString:uri_]);
1719 host_ = [host_ lowercaseString];
1724 authority_ = [url path];
1727 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(CYPool *)pool {
1728 if ((self = [super init]) != nil) {
1729 era_ = [database era];
1730 database_ = database;
1733 _profile(Source$initWithMetaIndex$setMetaIndex)
1734 [self setMetaIndex:index inPool:pool];
1739 - (NSString *) getField:(NSString *)name {
1740 @synchronized (database_) {
1741 if ([database_ era] != era_ || index_ == NULL)
1744 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index_));
1749 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly)) {
1754 pkgTagFile tags(&fd);
1756 pkgTagSection section;
1759 const char *start, *end;
1760 if (!section.Find([name UTF8String], start, end))
1761 return (NSString *) [NSNull null];
1763 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
1766 - (NSComparisonResult) compareByName:(Source *)source {
1767 NSString *lhs = [self name];
1768 NSString *rhs = [source name];
1770 if ([lhs length] != 0 && [rhs length] != 0) {
1771 unichar lhc = [lhs characterAtIndex:0];
1772 unichar rhc = [rhs characterAtIndex:0];
1774 if (isalpha(lhc) && !isalpha(rhc))
1775 return NSOrderedAscending;
1776 else if (!isalpha(lhc) && isalpha(rhc))
1777 return NSOrderedDescending;
1780 return [lhs compare:rhs options:LaxCompareOptions_];
1783 - (NSString *) depictionForPackage:(NSString *)package {
1784 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1787 - (NSString *) supportForPackage:(NSString *)package {
1788 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1791 - (NSArray *) sections {
1792 return record_ == nil ? (id) [NSNull null] : [record_ objectForKey:@"Sections"] ?: [NSArray array];
1795 - (void) _addSection:(NSString *)section {
1798 else if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) {
1799 if (![sections containsObject:section])
1800 [sections addObject:section];
1802 [record_ setObject:[NSMutableArray arrayWithObject:section] forKey:@"Sections"];
1805 - (bool) addSection:(NSString *)section {
1809 [self performSelectorOnMainThread:@selector(_addSection:) withObject:section waitUntilDone:NO];
1813 - (void) _removeSection:(NSString *)section {
1817 if (NSMutableArray *sections = [record_ objectForKey:@"Sections"])
1818 if ([sections containsObject:section])
1819 [sections removeObject:section];
1822 - (bool) removeSection:(NSString *)section {
1826 [self performSelectorOnMainThread:@selector(_removeSection:) withObject:section waitUntilDone:NO];
1831 [Sources_ removeObjectForKey:[self key]];
1835 bool value(record_ != nil);
1836 [self performSelectorOnMainThread:@selector(_remove) withObject:nil waitUntilDone:NO];
1840 - (NSDictionary *) record {
1848 - (NSString *) rooturi {
1852 - (NSString *) distribution {
1853 return distribution_;
1856 - (NSString *) type {
1860 - (NSString *) baseuri {
1861 return base_.empty() ? nil : (id) base_;
1864 - (NSString *) iconuri {
1865 if (NSString *base = [self baseuri])
1866 return [base stringByAppendingString:@"CydiaIcon.png"];
1871 - (NSURL *) iconURL {
1872 if (NSString *uri = [self iconuri])
1873 return [NSURL URLWithString:uri];
1877 - (NSString *) key {
1878 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1881 - (NSString *) host {
1885 - (NSString *) name {
1886 return origin_.empty() ? (id) authority_ : origin_;
1889 - (NSString *) shortDescription {
1890 return description_;
1893 - (NSString *) label {
1894 return label_.empty() ? (id) authority_ : label_;
1897 - (NSString *) origin {
1901 - (NSString *) version {
1905 - (NSString *) defaultIcon {
1906 return defaultIcon_;
1909 - (void) setDelegate:(NSObject<SourceDelegate> *)delegate {
1910 delegate_ = delegate;
1914 return !fetches_.empty();
1917 - (void) setFetch:(bool)fetch forURI:(const char *)uri {
1919 if (fetches_.erase(uri) == 0)
1921 } else if (files_.find(uri) == files_.end())
1923 else if (!fetches_.insert(uri).second)
1926 [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:[self fetch]] waitUntilDone:NO];
1929 - (void) resetFetch {
1931 [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:NO];
1936 /* CydiaOperation Class {{{ */
1937 @interface CydiaOperation : NSObject {
1938 _H<NSString> operator_;
1939 _H<NSString> value_;
1942 - (NSString *) operator;
1943 - (NSString *) value;
1947 @implementation CydiaOperation
1949 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1950 if ((self = [super init]) != nil) {
1951 operator_ = [NSString stringWithUTF8String:_operator];
1952 value_ = [NSString stringWithUTF8String:value];
1956 + (NSArray *) _attributeKeys {
1957 return [NSArray arrayWithObjects:
1963 - (NSArray *) attributeKeys {
1964 return [[self class] _attributeKeys];
1967 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1968 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1971 - (NSString *) operator {
1975 - (NSString *) value {
1981 /* CydiaClause Class {{{ */
1982 @interface CydiaClause : NSObject {
1983 _H<NSString> package_;
1984 _H<CydiaOperation> version_;
1987 - (NSString *) package;
1988 - (CydiaOperation *) version;
1992 @implementation CydiaClause
1994 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1995 if ((self = [super init]) != nil) {
1996 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1998 if (const char *version = dep.TargetVer())
1999 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
2001 version_ = (id) [NSNull null];
2005 + (NSArray *) _attributeKeys {
2006 return [NSArray arrayWithObjects:
2012 - (NSArray *) attributeKeys {
2013 return [[self class] _attributeKeys];
2016 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2017 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2020 - (NSString *) package {
2024 - (CydiaOperation *) version {
2030 /* CydiaRelation Class {{{ */
2031 @interface CydiaRelation : NSObject {
2032 _H<NSString> relationship_;
2033 _H<NSMutableArray> clauses_;
2036 - (NSString *) relationship;
2037 - (NSArray *) clauses;
2041 @implementation CydiaRelation
2043 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
2044 if ((self = [super init]) != nil) {
2045 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
2046 clauses_ = [NSMutableArray arrayWithCapacity:8];
2048 pkgCache::DepIterator start;
2049 pkgCache::DepIterator end;
2050 dep.GlobOr(start, end); // ++dep
2053 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
2055 // yes, seriously. (wtf?)
2063 + (NSArray *) _attributeKeys {
2064 return [NSArray arrayWithObjects:
2070 - (NSArray *) attributeKeys {
2071 return [[self class] _attributeKeys];
2074 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2075 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2078 - (NSString *) relationship {
2079 return relationship_;
2082 - (NSArray *) clauses {
2086 - (void) addClause:(CydiaClause *)clause {
2087 [clauses_ addObject:clause];
2092 /* Package Class {{{ */
2093 struct ParsedPackage {
2097 CYString architecture_;
2100 CYString depiction_;
2107 @interface Package : NSObject {
2109 @public uint32_t role_ : 3;
2110 uint32_t essential_ : 1;
2111 uint32_t obsolete_ : 1;
2112 uint32_t ignored_ : 1;
2113 uint32_t pooled_ : 1;
2119 _transient Database *database_;
2121 pkgCache::VerIterator version_;
2122 pkgCache::PkgIterator iterator_;
2123 pkgCache::VerFileIterator file_;
2127 CYString transform_;
2130 CYString installed_;
2133 const char *section_;
2134 _transient NSString *section$_;
2138 PackageValue *metadata_;
2139 ParsedPackage *parsed_;
2141 _H<NSMutableArray> tags_;
2144 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database;
2145 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database;
2147 - (pkgCache::PkgIterator) iterator;
2150 - (NSString *) section;
2151 - (NSString *) simpleSection;
2153 - (NSString *) longSection;
2154 - (NSString *) shortSection;
2158 - (MIMEAddress *) maintainer;
2160 - (NSString *) longDescription;
2161 - (NSString *) shortDescription;
2164 - (PackageValue *) metadata;
2167 - (bool) subscribed;
2168 - (bool) setSubscribed:(bool)subscribed;
2172 - (NSString *) latest;
2173 - (NSString *) installed;
2174 - (BOOL) uninstalled;
2176 - (BOOL) upgradableAndEssential:(BOOL)essential;
2179 - (BOOL) unfiltered;
2183 - (BOOL) halfConfigured;
2184 - (BOOL) halfInstalled;
2186 - (NSString *) mode;
2189 - (NSString *) name;
2191 - (NSString *) homepage;
2192 - (NSString *) depiction;
2193 - (MIMEAddress *) author;
2195 - (NSString *) support;
2197 - (NSArray *) files;
2198 - (NSArray *) warnings;
2199 - (NSArray *) applications;
2201 - (Source *) source;
2204 - (BOOL) matches:(NSArray *)query;
2206 - (BOOL) hasTag:(NSString *)tag;
2207 - (NSString *) primaryPurpose;
2208 - (NSArray *) purposes;
2209 - (bool) isCommercial;
2211 - (void) setIndex:(size_t)index;
2213 - (CYString &) cyname;
2215 - (uint32_t) compareBySection:(NSArray *)sections;
2222 uint32_t PackageChangesRadix(Package *self, void *) {
2227 uint32_t timestamp : 30;
2228 uint32_t ignored : 1;
2229 uint32_t upgradable : 1;
2233 bool upgradable([self upgradableAndEssential:YES]);
2234 value.bits.upgradable = upgradable ? 1 : 0;
2237 value.bits.timestamp = 0;
2238 value.bits.ignored = [self ignored] ? 0 : 1;
2239 value.bits.upgradable = 1;
2241 value.bits.timestamp = [self seen] >> 2;
2242 value.bits.ignored = 0;
2243 value.bits.upgradable = 0;
2246 return _not(uint32_t) - value.key;
2249 CYString &(*PackageName)(Package *self, SEL sel);
2251 uint32_t PackagePrefixRadix(Package *self, void *context) {
2252 size_t offset(reinterpret_cast<size_t>(context));
2253 CYString &name(PackageName(self, @selector(cyname)));
2255 size_t size(name.size());
2258 char *text(name.data());
2261 if (!isdigit(text[0]))
2265 while (size != digits && isdigit(text[digits]))
2273 if (offset == 0 && zeros != 0) {
2274 memset(data, '0', zeros);
2275 memcpy(data + zeros, text, 4 - zeros);
2277 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2278 if (size <= offset - zeros)
2281 text += offset - zeros;
2282 size -= offset - zeros;
2285 memcpy(data, text, 4);
2287 memcpy(data, text, size);
2288 memset(data + size, 0, 4 - size);
2291 for (size_t i(0); i != 4; ++i)
2292 if (isalpha(data[i]))
2300 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2302 /* XXX: ntohl may be more honest */
2303 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2306 CFComparisonResult StringNameCompare(CFStringRef lhn, CFStringRef rhn, size_t length) {
2307 _profile(PackageNameCompare)
2309 return rhn == NULL ? kCFCompareEqualTo : kCFCompareLessThan;
2310 else if (rhn == NULL)
2311 return kCFCompareGreaterThan;
2313 CFIndex length(CFStringGetLength(lhn));
2315 _profile(PackageNameCompare$NumbersLast)
2316 if (length != 0 && CFStringGetLength(rhn) != 0) {
2317 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2318 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2319 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2320 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2321 return lha ? kCFCompareLessThan : kCFCompareGreaterThan;
2325 _profile(PackageNameCompare$Compare)
2326 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, (CFLocaleRef) (id) CollationLocale_);
2331 _finline CFComparisonResult StringNameCompare(NSString *lhn, NSString*rhn, size_t length) {
2332 return StringNameCompare((CFStringRef) lhn, (CFStringRef) rhn, length);
2335 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2336 CYString &lhn(PackageName(lhs, @selector(cyname)));
2337 NSString *rhn(PackageName(rhs, @selector(cyname)));
2338 return StringNameCompare(lhn, rhn, lhn.size());
2341 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *arg) {
2342 return PackageNameCompare(*lhs, *rhs, arg);
2345 struct PackageNameOrdering :
2346 std::binary_function<Package *, Package *, bool>
2348 _finline bool operator ()(Package *lhs, Package *rhs) const {
2349 return PackageNameCompare(lhs, rhs, NULL) == kCFCompareLessThan;
2353 @implementation Package
2355 - (NSString *) description {
2356 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2362 if (parsed_ != NULL)
2367 + (NSString *) webScriptNameForSelector:(SEL)selector {
2369 else if (selector == @selector(clear))
2371 else if (selector == @selector(getField:))
2373 else if (selector == @selector(getRecord))
2374 return @"getRecord";
2375 else if (selector == @selector(hasTag:))
2377 else if (selector == @selector(install))
2379 else if (selector == @selector(remove))
2385 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2386 return [self webScriptNameForSelector:selector] == nil;
2389 + (NSArray *) _attributeKeys {
2390 return [NSArray arrayWithObjects:
2411 @"shortDescription",
2424 - (NSArray *) attributeKeys {
2425 return [[self class] _attributeKeys];
2428 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2429 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2432 - (NSArray *) relations {
2433 @synchronized (database_) {
2434 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2435 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2436 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2440 - (NSString *) architecture {
2442 @synchronized (database_) {
2443 return parsed_->architecture_.empty() ? [NSNull null] : (id) parsed_->architecture_;
2446 - (NSString *) getField:(NSString *)name {
2447 @synchronized (database_) {
2448 if ([database_ era] != era_ || file_.end())
2451 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2453 const char *start, *end;
2454 if (!parser.Find([name UTF8String], start, end))
2455 return (NSString *) [NSNull null];
2457 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2460 - (NSString *) getRecord {
2461 @synchronized (database_) {
2462 if ([database_ era] != era_ || file_.end())
2465 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2467 const char *start, *end;
2468 parser.GetRec(start, end);
2470 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2474 if (parsed_ != NULL)
2476 @synchronized (database_) {
2477 if ([database_ era] != era_ || file_.end())
2480 ParsedPackage *parsed(new ParsedPackage);
2483 _profile(Package$parse)
2484 pkgRecords::Parser *parser;
2486 _profile(Package$parse$Lookup)
2487 parser = &[database_ records]->Lookup(file_);
2493 _profile(Package$parse$Find)
2498 {"architecture", &parsed->architecture_},
2499 {"icon", &parsed->icon_},
2500 {"depiction", &parsed->depiction_},
2501 {"homepage", &parsed->homepage_},
2502 {"website", &website},
2504 {"support", &parsed->support_},
2505 {"author", &parsed->author_},
2506 {"md5sum", &parsed->md5sum_},
2509 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2510 const char *start, *end;
2512 if (parser->Find(names[i].name_, start, end)) {
2513 CYString &value(*names[i].value_);
2514 _profile(Package$parse$Value)
2515 value.set(pool_, start, end - start);
2521 _profile(Package$parse$Tagline)
2522 parsed->tagline_.set(pool_, parser->ShortDesc());
2525 _profile(Package$parse$Retain)
2526 if (parsed->homepage_.empty())
2527 parsed->homepage_ = website;
2528 if (parsed->homepage_ == parsed->depiction_)
2529 parsed->homepage_.clear();
2530 if (parsed->support_.empty())
2531 parsed->support_ = bugs;
2536 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database {
2537 if ((self = [super init]) != nil) {
2538 _profile(Package$initWithVersion)
2540 pool_ = new CYPool();
2546 database_ = database;
2547 era_ = [database era];
2551 pkgCache::PkgIterator iterator(version_.ParentPkg());
2552 iterator_ = iterator;
2554 _profile(Package$initWithVersion$Version)
2555 file_ = version_.FileList();
2558 _profile(Package$initWithVersion$Cache)
2559 name_.set(NULL, version_.Display());
2561 latest_.set(NULL, StripVersion_(version_.VerStr()));
2563 pkgCache::VerIterator current(iterator.CurrentVer());
2565 installed_.set(NULL, StripVersion_(current.VerStr()));
2568 _profile(Package$initWithVersion$Transliterate) do {
2569 if (CollationTransl_ == NULL)
2574 _profile(Package$initWithVersion$Transliterate$utf8)
2575 const uint8_t *data(reinterpret_cast<const uint8_t *>(name_.data()));
2576 for (size_t i(0), e(name_.size()); i != e; ++i)
2577 if (data[i] >= 0x80)
2582 UErrorCode code(U_ZERO_ERROR);
2585 _profile(Package$initWithVersion$Transliterate$u_strFromUTF8WithSub)
2586 CollationString_.resize(name_.size());
2587 u_strFromUTF8WithSub(&CollationString_[0], CollationString_.size(), &length, name_.data(), name_.size(), 0xfffd, NULL, &code);
2588 if (!U_SUCCESS(code))
2590 CollationString_.resize(length);
2593 _profile(Package$initWithVersion$Transliterate$utrans_trans)
2594 length = CollationString_.size();
2595 utrans_trans(CollationTransl_, reinterpret_cast<UReplaceable *>(&CollationString_), &CollationUCalls_, 0, &length, &code);
2596 if (!U_SUCCESS(code))
2598 _assert(CollationString_.size() == length);
2601 _profile(Package$initWithVersion$Transliterate$u_strToUTF8WithSub$preflight)
2602 u_strToUTF8WithSub(NULL, 0, &length, CollationString_.data(), CollationString_.size(), 0xfffd, NULL, &code);
2603 if (code == U_BUFFER_OVERFLOW_ERROR)
2604 code = U_ZERO_ERROR;
2605 else if (!U_SUCCESS(code))
2610 _profile(Package$initWithVersion$Transliterate$apr_palloc)
2611 transform = pool_->malloc<char>(length);
2613 _profile(Package$initWithVersion$Transliterate$u_strToUTF8WithSub$transform)
2614 u_strToUTF8WithSub(transform, length, NULL, CollationString_.data(), CollationString_.size(), 0xfffd, NULL, &code);
2615 if (!U_SUCCESS(code))
2619 transform_.set(NULL, transform, length);
2620 } while (false); _end
2622 _profile(Package$initWithVersion$Tags)
2624 pkgCache::TagIterator tag(version_.TagList());
2626 pkgCache::TagIterator tag(iterator.TagList());
2629 tags_ = [NSMutableArray arrayWithCapacity:8];
2631 goto tag; for (; !tag.end(); ++tag) tag: {
2632 const char *name(tag.Name());
2633 NSString *string((NSString *) CYStringCreate(name));
2637 [tags_ addObject:[string autorelease]];
2639 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2640 if (strcmp(name + 6, "enduser") == 0)
2642 else if (strcmp(name + 6, "hacker") == 0)
2644 else if (strcmp(name + 6, "developer") == 0)
2646 else if (strcmp(name + 6, "cydia") == 0)
2652 if (strncmp(name, "cydia::", 7) == 0) {
2653 if (strcmp(name + 7, "essential") == 0)
2655 else if (strcmp(name + 7, "obsolete") == 0)
2662 _profile(Package$initWithVersion$Metadata)
2663 const char *mixed(iterator.Name());
2664 size_t size(strlen(mixed));
2665 static const size_t prefix(sizeof("/var/lib/dpkg/info/") - 1);
2666 char lower[prefix + size + 5 + 1];
2668 for (size_t i(0); i != size; ++i)
2669 lower[prefix + i] = mixed[i] | 0x20;
2671 if (!installed_.empty()) {
2672 memcpy(lower, "/var/lib/dpkg/info/", prefix);
2673 memcpy(lower + prefix + size, ".list", 6);
2675 if (stat(lower, &info) != -1)
2676 upgraded_ = info.st_birthtime;
2679 PackageValue *metadata(PackageFind(lower + prefix, size));
2680 metadata_ = metadata;
2682 id_.set(NULL, metadata->name_, size);
2684 const char *latest(version_.VerStr());
2685 size_t length(strlen(latest));
2687 uint16_t vhash(hashlittle(latest, length));
2689 size_t capped(std::min<size_t>(8, length));
2690 latest = latest + length - capped;
2692 if (metadata->first_ == 0)
2693 metadata->first_ = now_;
2695 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2696 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2697 metadata->vhash_ = vhash;
2698 metadata->last_ = now_;
2699 } else if (metadata->last_ == 0)
2700 metadata->last_ = metadata->first_;
2703 _profile(Package$initWithVersion$Section)
2704 section_ = version_.Section();
2707 _profile(Package$initWithVersion$Flags)
2708 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2709 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2714 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database {
2715 pkgCache::VerIterator version;
2717 _profile(Package$packageWithIterator$GetCandidateVer)
2718 version = [database policy]->GetCandidateVer(iterator);
2726 _profile(Package$packageWithIterator$Allocate)
2727 package = [Package allocWithZone:zone];
2730 _profile(Package$packageWithIterator$Initialize)
2732 initWithVersion:version
2739 _profile(Package$packageWithIterator$Autorelease)
2740 package = [package autorelease];
2746 - (pkgCache::PkgIterator) iterator {
2750 - (NSArray *) downgrades {
2751 NSMutableArray *versions([NSMutableArray arrayWithCapacity:4]);
2753 for (auto version(iterator_.VersionList()); !version.end(); ++version) {
2754 if (version == version_)
2756 Package *package([[[Package allocWithZone:NULL] initWithVersion:version withZone:NULL inPool:NULL database:database_] autorelease]);
2757 if ([package source] == nil)
2759 [versions addObject:package];
2765 - (NSString *) section {
2766 if (section$_ == nil) {
2767 if (section_ == NULL)
2770 _profile(Package$section$mappedSectionForPointer)
2771 section$_ = [database_ mappedSectionForPointer:section_];
2776 - (NSString *) simpleSection {
2777 if (NSString *section = [self section])
2778 return Simplify(section);
2783 - (NSString *) longSection {
2784 if (NSString *section = [self section])
2785 return LocalizeSection(section);
2790 - (NSString *) shortSection {
2791 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2794 - (NSString *) uri {
2797 pkgIndexFile *index;
2798 pkgCache::PkgFileIterator file(file_.File());
2799 if (![database_ list].FindIndex(file, index))
2801 return [NSString stringWithUTF8String:iterator_->Path];
2802 //return [NSString stringWithUTF8String:file.Site()];
2803 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2807 - (MIMEAddress *) maintainer {
2808 @synchronized (database_) {
2809 if ([database_ era] != era_ || file_.end())
2812 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2813 const std::string &maintainer(parser->Maintainer());
2814 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2817 - (NSString *) md5sum {
2818 return parsed_ == NULL ? nil : (id) parsed_->md5sum_;
2822 @synchronized (database_) {
2823 if ([database_ era] != era_ || version_.end())
2826 return version_->InstalledSize;
2829 - (NSString *) longDescription {
2830 @synchronized (database_) {
2831 if ([database_ era] != era_ || file_.end())
2834 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2835 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2837 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2838 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2839 if ([lines count] < 2)
2842 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2843 for (size_t i(1), e([lines count]); i != e; ++i) {
2844 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2845 [trimmed addObject:trim];
2848 return [trimmed componentsJoinedByString:@"\n"];
2851 - (NSString *) shortDescription {
2852 if (parsed_ != NULL)
2853 return static_cast<NSString *>(parsed_->tagline_);
2855 @synchronized (database_) {
2856 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2857 std::string value(parser.ShortDesc());
2860 if (value.size() > 200)
2862 return [(id) CYStringCreate(value) autorelease];
2866 _profile(Package$index)
2867 CFStringRef name((CFStringRef) [self name]);
2868 if (CFStringGetLength(name) == 0)
2870 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2871 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2873 return toupper(character);
2877 - (PackageValue *) metadata {
2882 PackageValue *metadata([self metadata]);
2883 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2886 - (bool) subscribed {
2887 return [self metadata]->subscribed_;
2890 - (bool) setSubscribed:(bool)subscribed {
2891 PackageValue *metadata([self metadata]);
2892 if (metadata->subscribed_ == subscribed)
2894 metadata->subscribed_ = subscribed;
2902 - (NSString *) latest {
2906 - (NSString *) installed {
2910 - (BOOL) uninstalled {
2911 return installed_.empty();
2914 - (BOOL) upgradableAndEssential:(BOOL)essential {
2915 _profile(Package$upgradableAndEssential)
2916 pkgCache::VerIterator current(iterator_.CurrentVer());
2918 return essential && essential_;
2920 return version_ != current;
2924 - (BOOL) essential {
2929 return [database_ cache][iterator_].InstBroken();
2932 - (BOOL) unfiltered {
2933 _profile(Package$unfiltered$obsolete)
2934 if (_unlikely(obsolete_))
2938 _profile(Package$unfiltered$role)
2939 if (_unlikely(role_ > 3))
2947 if (![self unfiltered])
2952 _profile(Package$visible$section)
2953 section = [self section];
2956 _profile(Package$visible$isSectionVisible)
2957 if (!isSectionVisible(section))
2965 unsigned char current(iterator_->CurrentState);
2966 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2969 - (BOOL) halfConfigured {
2970 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2973 - (BOOL) halfInstalled {
2974 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2978 @synchronized (database_) {
2979 if ([database_ era] != era_ || iterator_.end())
2982 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2983 return state.Mode != pkgDepCache::ModeKeep;
2986 - (NSString *) mode {
2987 @synchronized (database_) {
2988 if ([database_ era] != era_ || iterator_.end())
2991 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2993 switch (state.Mode) {
2994 case pkgDepCache::ModeDelete:
2995 if ((state.iFlags & pkgDepCache::Purge) != 0)
2999 case pkgDepCache::ModeKeep:
3000 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
3001 return @"REINSTALL";
3002 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
3006 case pkgDepCache::ModeInstall:
3007 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
3008 return @"REINSTALL";
3009 else*/ switch (state.Status) {
3011 return @"DOWNGRADE";
3017 return @"NEW_INSTALL";
3028 - (NSString *) name {
3029 return name_.empty() ? id_ : name_;
3032 - (UIImage *) icon {
3033 NSString *section = [self simpleSection];
3036 if (parsed_ != NULL)
3037 if (NSString *href = parsed_->icon_)
3038 if ([href hasPrefix:@"file:///"])
3039 icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
3040 if (icon == nil) if (section != nil)
3041 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]];
3042 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
3043 if ([dicon hasPrefix:@"file:///"])
3044 icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
3046 icon = [UIImage imageNamed:@"unknown.png"];
3050 - (NSString *) homepage {
3051 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
3054 - (NSString *) depiction {
3055 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
3058 - (MIMEAddress *) author {
3059 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
3062 - (NSString *) support {
3063 return parsed_ != NULL && !parsed_->support_.empty() ? parsed_->support_ : [[self source] supportForPackage:id_];
3066 - (NSArray *) files {
3067 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
3068 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
3071 fin.open([path UTF8String]);
3076 while (std::getline(fin, line))
3077 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
3082 - (NSString *) state {
3083 @synchronized (database_) {
3084 if ([database_ era] != era_ || file_.end())
3087 switch (iterator_->CurrentState) {
3088 case pkgCache::State::NotInstalled:
3089 return @"NotInstalled";
3090 case pkgCache::State::UnPacked:
3092 case pkgCache::State::HalfConfigured:
3093 return @"HalfConfigured";
3094 case pkgCache::State::HalfInstalled:
3095 return @"HalfInstalled";
3096 case pkgCache::State::ConfigFiles:
3097 return @"ConfigFiles";
3098 case pkgCache::State::Installed:
3099 return @"Installed";
3100 case pkgCache::State::TriggersAwaited:
3101 return @"TriggersAwaited";
3102 case pkgCache::State::TriggersPending:
3103 return @"TriggersPending";
3106 return (NSString *) [NSNull null];
3109 - (NSString *) selection {
3110 @synchronized (database_) {
3111 if ([database_ era] != era_ || file_.end())
3114 switch (iterator_->SelectedState) {
3115 case pkgCache::State::Unknown:
3117 case pkgCache::State::Install:
3119 case pkgCache::State::Hold:
3121 case pkgCache::State::DeInstall:
3122 return @"DeInstall";
3123 case pkgCache::State::Purge:
3127 return (NSString *) [NSNull null];
3130 - (NSArray *) warnings {
3131 @synchronized (database_) {
3132 if ([database_ era] != era_ || file_.end())
3135 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
3136 const char *name(iterator_.Name());
3138 size_t length(strlen(name));
3139 if (length < 2) invalid:
3140 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
3141 else for (size_t i(0); i != length; ++i)
3143 /* XXX: technically this is not allowed */
3144 (name[i] < 'A' || name[i] > 'Z') &&
3145 (name[i] < 'a' || name[i] > 'z') &&
3146 (name[i] < '0' || name[i] > '9') &&
3147 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
3150 if (strcmp(name, "cydia") != 0) {
3153 bool _private = false;
3155 bool dbstash = false;
3156 bool dsstore = false;
3158 bool repository = [[self section] isEqualToString:@"Repositories"];
3160 if (NSArray *files = [self files])
3161 for (NSString *file in files)
3162 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
3164 else if (!user && [file isEqualToString:@"/User"])
3166 else if (!_private && [file isEqualToString:@"/private"])
3168 else if (!stash && [file isEqualToString:@"/var/stash"])
3170 else if (!dbstash && [file isEqualToString:@"/var/db/stash"])
3172 else if (!dsstore && [file hasSuffix:@"/.DS_Store"])
3175 /* XXX: this is not sensitive enough. only some folders are valid. */
3176 if (cydia && !repository)
3177 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
3179 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
3181 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
3183 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
3185 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/db/stash"]];
3187 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @".DS_Store"]];
3190 return [warnings count] == 0 ? nil : warnings;
3193 - (NSArray *) applications {
3194 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
3196 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
3198 static RegEx application_r("/Applications/(.*)\\.app/Info.plist");
3199 if (NSArray *files = [self files])
3200 for (NSString *file in files)
3201 if (application_r(file)) {
3202 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
3205 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
3206 if (id == nil || [id isEqualToString:me])
3209 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
3211 display = application_r[1];
3213 NSString *bundle([file stringByDeletingLastPathComponent]);
3214 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
3215 // XXX: maybe this should check if this is really a string, not just for length
3216 if (icon == nil || ![icon respondsToSelector:@selector(length)] || [icon length] == 0)
3218 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
3220 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
3221 [applications addObject:application];
3223 [application addObject:id];
3224 [application addObject:display];
3225 [application addObject:url];
3228 return [applications count] == 0 ? nil : applications;
3231 - (Source *) source {
3232 if (source_ == nil) {
3233 @synchronized (database_) {
3234 if ([database_ era] != era_ || file_.end())
3235 source_ = (Source *) [NSNull null];
3237 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
3241 return source_ == (Source *) [NSNull null] ? nil : source_;
3244 - (time_t) upgraded {
3248 - (uint32_t) recent {
3249 return std::numeric_limits<uint32_t>::max() - upgraded_;
3256 - (BOOL) matches:(NSArray *)query {
3257 if (query == nil || [query count] == 0)
3266 string = [self name];
3267 length = [string length];
3270 for (NSString *term in query) {
3271 range = [string rangeOfString:term options:MatchCompareOptions_];
3272 if (range.location != NSNotFound)
3273 rank_ -= 6 * 1000000 / length;
3278 length = [string length];
3281 for (NSString *term in query) {
3282 range = [string rangeOfString:term options:MatchCompareOptions_];
3283 if (range.location != NSNotFound)
3284 rank_ -= 6 * 1000000 / length;
3288 string = [self shortDescription];
3289 length = [string length];
3290 NSUInteger stop(std::min<NSUInteger>(length, 200));
3293 for (NSString *term in query) {
3294 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
3295 if (range.location != NSNotFound)
3296 rank_ -= 2 * 100000;
3302 - (NSArray *) tags {
3306 - (BOOL) hasTag:(NSString *)tag {
3307 return tags_ == nil ? NO : [tags_ containsObject:tag];
3310 - (NSString *) primaryPurpose {
3311 for (NSString *tag in (NSArray *) tags_)
3312 if ([tag hasPrefix:@"purpose::"])
3313 return [tag substringFromIndex:9];
3317 - (NSArray *) purposes {
3318 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
3319 for (NSString *tag in (NSArray *) tags_)
3320 if ([tag hasPrefix:@"purpose::"])
3321 [purposes addObject:[tag substringFromIndex:9]];
3322 return [purposes count] == 0 ? nil : purposes;
3325 - (bool) isCommercial {
3326 return [self hasTag:@"cydia::commercial"];
3329 - (void) setIndex:(size_t)index {
3330 if (metadata_->index_ != index)
3331 metadata_->index_ = index;
3334 - (CYString &) cyname {
3335 return !transform_.empty() ? transform_ : !name_.empty() ? name_ : id_;
3338 - (uint32_t) compareBySection:(NSArray *)sections {
3339 NSString *section([self section]);
3340 for (size_t i(0), e([sections count]); i != e; ++i) {
3341 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3345 return _not(uint32_t);
3349 @synchronized (database_) {
3350 if ([database_ era] != era_ || file_.end())
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 if ([database_ era] != era_ || file_.end())
3366 pkgProblemResolver *resolver = [database_ resolver];
3367 resolver->Clear(iterator_);
3368 resolver->Protect(iterator_);
3370 pkgCacheFile &cache([database_ cache]);
3371 cache->SetCandidateVersion(version_);
3372 cache->SetReInstall(iterator_, false);
3373 cache->MarkInstall(iterator_, false);
3375 pkgDepCache::StateCache &state((*cache)[iterator_]);
3376 if (!state.Install())
3377 cache->SetReInstall(iterator_, true);
3381 @synchronized (database_) {
3382 if ([database_ era] != era_ || file_.end())
3385 pkgProblemResolver *resolver = [database_ resolver];
3386 resolver->Clear(iterator_);
3387 resolver->Remove(iterator_);
3388 resolver->Protect(iterator_);
3390 pkgCacheFile &cache([database_ cache]);
3391 cache->SetReInstall(iterator_, false);
3392 cache->MarkDelete(iterator_, true);
3397 /* Section Class {{{ */
3398 @interface Section : NSObject {
3402 _H<NSString> localized_;
3405 - (NSComparisonResult) compareByLocalized:(Section *)section;
3406 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3407 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3408 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3410 - (NSString *) name;
3411 - (void) setName:(NSString *)name;
3417 - (void) addToCount;
3419 - (void) setCount:(size_t)count;
3420 - (NSString *) localized;
3424 @implementation Section
3426 - (NSComparisonResult) compareByLocalized:(Section *)section {
3427 NSString *lhs(localized_);
3428 NSString *rhs([section localized]);
3430 /*if ([lhs length] != 0 && [rhs length] != 0) {
3431 unichar lhc = [lhs characterAtIndex:0];
3432 unichar rhc = [rhs characterAtIndex:0];
3434 if (isalpha(lhc) && !isalpha(rhc))
3435 return NSOrderedAscending;
3436 else if (!isalpha(lhc) && isalpha(rhc))
3437 return NSOrderedDescending;
3440 return [lhs compare:rhs options:LaxCompareOptions_];
3443 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3444 if ((self = [self initWithName:name localize:NO]) != nil) {
3445 if (localized != nil)
3446 localized_ = localized;
3450 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3451 return [self initWithName:name row:0 localize:localize];
3454 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3455 if ((self = [super init]) != nil) {
3459 localized_ = LocalizeSection(name_);
3463 - (NSString *) name {
3467 - (void) setName:(NSString *)name {
3483 - (void) addToCount {
3487 - (void) setCount:(size_t)count {
3491 - (NSString *) localized {
3498 class CydiaLogCleaner :
3499 public pkgArchiveCleaner
3502 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3507 /* Database Implementation {{{ */
3508 @implementation Database
3510 + (Database *) sharedInstance {
3511 static _H<Database> instance;
3512 if (instance == nil)
3513 instance = [[[Database alloc] init] autorelease];
3521 - (void) releasePackages {
3522 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3523 CFArrayRemoveAllValues(packages_);
3527 // XXX: actually implement this thing
3529 [self releasePackages];
3530 NSRecycleZone(zone_);
3534 - (void) _readCydia:(NSNumber *)fd {
3535 boost::fdistream is([fd intValue]);
3538 static RegEx finish_r("finish:([^:]*)");
3540 while (std::getline(is, line)) {
3541 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3543 const char *data(line.c_str());
3544 size_t size = line.size();
3545 lprintf("C:%s\n", data);
3547 if (finish_r(data, size)) {
3548 NSString *finish = finish_r[1];
3549 int index = [Finishes_ indexOfObject:finish];
3550 if (index != INT_MAX && index > Finish_)
3560 - (void) _readStatus:(NSNumber *)fd {
3561 boost::fdistream is([fd intValue]);
3564 static RegEx conffile_r("status: [^ ]* : conffile-prompt : (.*?) *");
3565 static RegEx pmstatus_r("([^:]*):([^:]*):([^:]*):(.*)");
3567 while (std::getline(is, line)) {
3568 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3570 const char *data(line.c_str());
3571 size_t size(line.size());
3572 lprintf("S:%s\n", data);
3574 if (conffile_r(data, size)) {
3575 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3576 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3577 } else if (strncmp(data, "status: ", 8) == 0) {
3578 // status: <package>: {unpacked,half-configured,installed}
3579 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3580 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3581 } else if (strncmp(data, "processing: ", 12) == 0) {
3582 // processing: configure: config-test
3583 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3584 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3585 } else if (pmstatus_r(data, size)) {
3586 std::string type([pmstatus_r[1] UTF8String]);
3588 NSString *package = pmstatus_r[2];
3589 if ([package isEqualToString:@"dpkg-exec"])
3592 float percent([pmstatus_r[3] floatValue]);
3593 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3595 NSString *string = pmstatus_r[4];
3597 if (type == "pmerror") {
3598 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3599 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3600 } else if (type == "pmstatus") {
3601 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3602 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3603 } else if (type == "pmconffile")
3604 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3606 lprintf("E:unknown pmstatus\n");
3608 lprintf("E:unknown status\n");
3616 - (void) _readOutput:(NSNumber *)fd {
3617 boost::fdistream is([fd intValue]);
3620 while (std::getline(is, line)) {
3621 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3623 lprintf("O:%s\n", line.c_str());
3625 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3626 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3638 - (Package *) packageWithName:(NSString *)name {
3641 @synchronized (self) {
3642 if (static_cast<pkgDepCache *>(cache_) == NULL)
3644 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]
3649 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:NULL database:self];
3653 if ((self = [super init]) != nil) {
3660 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3662 size_t capacity(MetaFile_->active_);
3668 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3669 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3673 _assert(pipe(fds) != -1);
3676 _config->Set("APT::Keep-Fds::", cydiafd_);
3677 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3680 detachNewThreadSelector:@selector(_readCydia:)
3682 withObject:[NSNumber numberWithInt:fds[0]]
3685 _assert(pipe(fds) != -1);
3689 detachNewThreadSelector:@selector(_readStatus:)
3691 withObject:[NSNumber numberWithInt:fds[0]]
3694 _assert(pipe(fds) != -1);
3695 _assert(dup2(fds[0], 0) != -1);
3696 _assert(close(fds[0]) != -1);
3698 input_ = fdopen(fds[1], "a");
3700 _assert(pipe(fds) != -1);
3701 _assert(dup2(fds[1], 1) != -1);
3702 _assert(close(fds[1]) != -1);
3705 detachNewThreadSelector:@selector(_readOutput:)
3707 withObject:[NSNumber numberWithInt:fds[0]]
3712 - (pkgCacheFile &) cache {
3716 - (pkgDepCache::Policy *) policy {
3720 - (pkgRecords *) records {
3724 - (pkgProblemResolver *) resolver {
3728 - (pkgAcquire &) fetcher {
3732 - (pkgSourceList &) list {
3736 - (NSArray *) packages {
3737 return (NSArray *) packages_;
3740 - (NSArray *) sources {
3744 - (Source *) sourceWithKey:(NSString *)key {
3745 for (Source *source in [self sources]) {
3746 if ([[source key] isEqualToString:key])
3751 - (bool) popErrorWithTitle:(NSString *)title {
3754 while (!_error->empty()) {
3756 bool warning(!_error->PopMessage(error));
3761 size_t size(error.size());
3762 if (size == 0 || error[size - 1] != '\n')
3764 error.resize(size - 1);
3767 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3769 static RegEx no_pubkey("GPG error:.* NO_PUBKEY .*");
3770 if (warning && no_pubkey(error.c_str()))
3773 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3779 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3780 return [self popErrorWithTitle:title] || !success;
3783 - (bool) popErrorWithTitle:(NSString *)title forReadList:(pkgSourceList &)list {
3784 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3792 if (access("/etc/apt/sources.list", F_OK) == 0)
3793 error |= [self popErrorWithTitle:title forOperation:list.ReadAppend("/etc/apt/sources.list")];
3795 std::string base("/etc/apt/sources.list.d");
3796 if (DIR *sources = opendir(base.c_str())) {
3797 while (dirent *source = readdir(sources))
3798 if (source->d_name[0] != '.' && source->d_namlen > 5 && strcmp(source->d_name + source->d_namlen - 5, ".list") == 0 && strcmp(source->d_name, "cydia.list") != 0)
3799 error |= [self popErrorWithTitle:title forOperation:list.ReadAppend((base + "/" + source->d_name).c_str())];
3803 error |= [self popErrorWithTitle:title forOperation:list.ReadAppend(SOURCES_LIST)];
3808 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3809 @synchronized (self) {
3812 [self releasePackages];
3815 [sourceList_ removeAllObjects];
3836 new (&pool_) CYPool();
3838 NSRecycleZone(zone_);
3839 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3841 int chk(creat("/tmp/cydia.chk", 0644));
3845 if (invocation != nil)
3846 [invocation invoke];
3848 NSString *title(UCLocalize("DATABASE"));
3850 list_ = new pkgSourceList();
3851 _profile(reloadDataWithInvocation$ReadMainList)
3852 if ([self popErrorWithTitle:title forReadList:*list_])
3856 _profile(reloadDataWithInvocation$Source$initWithMetaIndex)
3857 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3858 Source *object([[[Source alloc] initWithMetaIndex:*source forDatabase:self inPool:&pool_] autorelease]);
3859 [sourceList_ addObject:object];
3864 OpProgress progress;
3867 delock_ = GetStatusDate();
3868 _profile(reloadDataWithInvocation$pkgCacheFile)
3869 opened = cache_.Open(progress, false);
3872 // XXX: what if there are errors, but Open() == true? this should be merged with popError:
3873 while (!_error->empty()) {
3875 bool warning(!_error->PopMessage(error));
3877 lprintf("cache_.Open():[%s]\n", error.c_str());
3879 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3883 else if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3884 repair = @selector(configure);
3885 //else if (error == "The package lists or status file could not be parsed or opened.")
3886 // repair = @selector(update);
3887 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3888 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3889 // else if (error == "Malformed Status line")
3890 // else if (error == "The list of sources could not be read.")
3892 if (repair != NULL) {
3894 [delegate_ repairWithSelector:repair];
3903 unlink("/tmp/cydia.chk");
3905 now_ = [[NSDate date] timeIntervalSince1970];
3907 policy_ = new pkgDepCache::Policy();
3908 records_ = new pkgRecords(cache_);
3909 resolver_ = new pkgProblemResolver(cache_);
3910 fetcher_ = new pkgAcquire(&status_);
3913 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3914 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3918 _profile(reloadDataWithInvocation$pkgApplyStatus)
3919 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3923 if (cache_->BrokenCount() != 0) {
3924 _profile(pkgApplyStatus$pkgFixBroken)
3925 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3929 if (cache_->BrokenCount() != 0) {
3930 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3934 _profile(pkgApplyStatus$pkgMinimizeUpgrade)
3935 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3940 for (Source *object in (id) sourceList_) {
3941 metaIndex *source([object metaIndex]);
3942 std::vector<pkgIndexFile *> *indices = source->GetIndexFiles();
3943 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3944 // XXX: this could be more intelligent
3945 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3946 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3948 sourceMap_[cached->ID] = object;
3953 /*std::vector<Package *> packages;
3954 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3957 _profile(reloadDataWithInvocation$packageWithIterator)
3958 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3959 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:&pool_ database:self])
3960 //packages.push_back(package);
3961 CFArrayAppendValue(packages_, CFRetain(package));
3965 /*if (packages.empty())
3966 packages_ = [[NSArray alloc] init];
3968 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3971 _profile(reloadDataWithInvocation$radix$8)
3972 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(8)];
3975 _profile(reloadDataWithInvocation$radix$4)
3976 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3979 _profile(reloadDataWithInvocation$radix$0)
3980 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3983 _profile(reloadDataWithInvocation$insertion)
3984 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3987 /*_profile(reloadDataWithInvocation$CFQSortArray)
3988 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);
3991 /*_profile(reloadDataWithInvocation$stdsort)
3992 std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3995 /*_profile(reloadDataWithInvocation$CFArraySortValues)
3996 CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3999 /*_profile(reloadDataWithInvocation$sortUsingFunction)
4000 [packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
4004 size_t count(CFArrayGetCount(packages_));
4005 MetaFile_->active_ = count;
4006 for (size_t index(0); index != count; ++index)
4007 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
4012 @synchronized (self) {
4014 resolver_ = new pkgProblemResolver(cache_);
4016 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
4017 if (!cache_[iterator].Keep())
4018 cache_->MarkKeep(iterator, false);
4019 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
4020 cache_->SetReInstall(iterator, false);
4023 - (void) configure {
4024 NSString *dpkg = [NSString stringWithFormat:@"/usr/libexec/cydo --configure -a --status-fd %u", statusfd_];
4026 system([dpkg UTF8String]);
4031 @synchronized (self) {
4032 // XXX: I don't remember this condition
4037 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
4039 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
4041 if ([self popErrorWithTitle:title])
4045 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
4047 CydiaLogCleaner cleaner;
4048 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
4055 fetcher_->Shutdown();
4057 pkgRecords records(cache_);
4059 lock_ = new FileFd();
4060 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
4062 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
4064 if ([self popErrorWithTitle:title])
4068 if ([self popErrorWithTitle:title forReadList:list])
4071 manager_ = (_system->CreatePM(cache_));
4072 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
4079 bool substrate(RestartSubstrate_);
4080 RestartSubstrate_ = false;
4082 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
4084 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
4086 if ([self popErrorWithTitle:title forReadList:list])
4088 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
4089 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
4092 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4094 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
4096 [self popErrorWithTitle:title];
4100 bool failed = false;
4101 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
4102 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
4104 if ((*item)->Status == pkgAcquire::Item::StatIdle)
4107 std::string uri = (*item)->DescURI();
4108 std::string error = (*item)->ErrorText;
4110 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
4113 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError]);
4114 [delegate_ addProgressEventOnMainThread:event forTask:title];
4117 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4125 RestartSubstrate_ = true;
4127 if (![delock_ isEqual:GetStatusDate()]) {
4128 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("DPKG_LOCKED") ofType:kCydiaProgressEventTypeError] forTask:title];
4134 pkgPackageManager::OrderResult result(manager_->DoInstall(statusfd_));
4136 NSString *oextended(@"/var/lib/apt/extended_states");
4137 NSString *nextended(Cache("extended_states"));
4140 if (stat([nextended UTF8String], &info) != -1 && (info.st_mode & S_IFMT) == S_IFREG)
4141 system([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /bin/cp --remove-destination %@ %@", ShellEscape(nextended), ShellEscape(oextended)] UTF8String]);
4143 unlink([nextended UTF8String]);
4144 symlink([oextended UTF8String], [nextended UTF8String]);
4146 if ([self popErrorWithTitle:title])
4149 if (result == pkgPackageManager::Failed) {
4154 if (result != pkgPackageManager::Completed) {
4159 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
4161 if ([self popErrorWithTitle:title forReadList:list])
4163 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
4164 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
4167 if (![before isEqualToArray:after])
4172 return ![delock_ isEqual:GetStatusDate()];
4176 NSString *title(UCLocalize("UPGRADE"));
4177 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
4183 [self updateWithStatus:status_];
4186 - (void) updateWithStatus:(CancelStatus &)status {
4187 NSString *title(UCLocalize("REFRESHING_DATA"));
4190 if ([self popErrorWithTitle:title forReadList:list])
4194 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
4195 if ([self popErrorWithTitle:title])
4198 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4200 bool success(ListUpdate(status, list, PulseInterval_));
4201 if (status.WasCancelled())
4204 [self popErrorWithTitle:title forOperation:success];
4206 [[NSDictionary dictionaryWithObjectsAndKeys:
4207 [NSDate date], @"LastUpdate",
4208 nil] writeToFile:@ CacheState_ atomically:YES];
4211 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4214 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
4215 delegate_ = delegate;
4218 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
4219 progress_ = delegate;
4220 status_.setDelegate(delegate);
4223 - (NSObject<ProgressDelegate> *) progressDelegate {
4227 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
4228 SourceMap::const_iterator i(sourceMap_.find(file->ID));
4229 return i == sourceMap_.end() ? nil : i->second;
4232 - (void) setFetch:(bool)fetch forURI:(const char *)uri {
4233 for (Source *source in (id) sourceList_)
4234 [source setFetch:fetch forURI:uri];
4237 - (void) resetFetch {
4238 for (Source *source in (id) sourceList_)
4239 [source resetFetch];
4242 - (NSString *) mappedSectionForPointer:(const char *)section {
4243 _H<NSString> *mapped;
4245 _profile(Database$mappedSectionForPointer$Cache)
4246 mapped = §ions_[section];
4249 if (*mapped == NULL) {
4250 size_t length(strlen(section));
4251 char spaced[length + 1];
4253 _profile(Database$mappedSectionForPointer$Replace)
4254 for (size_t index(0); index != length; ++index)
4255 spaced[index] = section[index] == '_' ? ' ' : section[index];
4256 spaced[length] = '\0';
4261 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
4262 string = [NSString stringWithUTF8String:spaced];
4265 _profile(Database$mappedSectionForPointer$Map)
4266 string = [SectionMap_ objectForKey:string] ?: string;
4276 static _H<NSMutableSet> Diversions_;
4278 @interface Diversion : NSObject {
4281 _H<NSString> format_;
4286 @implementation Diversion
4288 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
4289 if ((self = [super init]) != nil) {
4290 pattern_ = [from UTF8String];
4296 - (NSString *) divert:(NSString *)url {
4297 return !pattern_(url) ? nil : pattern_->*format_;
4300 + (NSURL *) divertURL:(NSURL *)url {
4302 NSString *href([url absoluteString]);
4304 for (Diversion *diversion in (id) Diversions_)
4305 if (NSString *diverted = [diversion divert:href]) {
4307 NSLog(@"div: %@", diverted);
4309 url = [NSURL URLWithString:diverted];
4316 - (NSString *) key {
4320 - (NSUInteger) hash {
4324 - (BOOL) isEqual:(Diversion *)object {
4325 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
4330 @interface CydiaObject : NSObject {
4331 _H<CyteWebViewController> indirect_;
4332 _transient id delegate_;
4335 - (id) initWithDelegate:(IndirectDelegate *)indirect;
4341 @interface CydiaWebViewController : CyteWebViewController {
4342 _H<CydiaObject> cydia_;
4345 + (void) addDiversion:(Diversion *)diversion;
4346 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request;
4347 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia;
4348 - (void) setDelegate:(id)delegate;
4352 /* Web Scripting {{{ */
4353 @implementation CydiaObject
4355 - (id) initWithDelegate:(IndirectDelegate *)indirect {
4356 if ((self = [super init]) != nil) {
4357 indirect_ = (CyteWebViewController *) indirect;
4361 - (void) setDelegate:(id)delegate {
4362 delegate_ = delegate;
4365 + (NSArray *) _attributeKeys {
4366 return [NSArray arrayWithObjects:
4371 @"coreFoundationVersionNumber",
4387 - (NSArray *) attributeKeys {
4388 return [[self class] _attributeKeys];
4391 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4392 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4395 - (NSString *) version {
4399 - (unsigned) bittage {
4401 #elif defined(__arm64__)
4403 #elif defined(__arm__)
4410 - (NSString *) build {
4414 - (NSString *) coreFoundationVersionNumber {
4415 return [NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber];
4418 - (NSString *) device {
4419 return UniqueIdentifier();
4422 - (NSString *) firmware {
4423 return [[UIDevice currentDevice] systemVersion];
4426 - (NSString *) hostname {
4427 return [[UIDevice currentDevice] name];
4430 - (NSString *) idiom {
4431 return (id) Idiom_ ?: [NSNull null];
4434 - (NSArray *) cells {
4435 auto *$_CTServerConnectionCreate(reinterpret_cast<id (*)(void *, void *, void *)>(dlsym(RTLD_DEFAULT, "_CTServerConnectionCreate")));
4436 if ($_CTServerConnectionCreate == NULL)
4439 struct CTResult { int flag; int error; };
4440 auto *$_CTServerConnectionCellMonitorCopyCellInfo(reinterpret_cast<CTResult (*)(CFTypeRef, void *, CFArrayRef *)>(dlsym(RTLD_DEFAULT, "_CTServerConnectionCellMonitorCopyCellInfo")));
4441 if ($_CTServerConnectionCellMonitorCopyCellInfo == NULL)
4444 _H<const void> connection($_CTServerConnectionCreate(NULL, NULL, NULL), true);
4445 if (connection == nil)
4449 CFArrayRef cells(NULL);
4450 auto result($_CTServerConnectionCellMonitorCopyCellInfo(connection, &count, &cells));
4451 if (result.flag != 0)
4454 return [(NSArray *) cells autorelease];
4457 - (NSString *) mcc {
4458 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode")))
4459 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault) autorelease];
4463 - (NSString *) mnc {
4464 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberNetworkCode")))
4465 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault) autorelease];
4469 - (NSString *) operator {
4470 if (CFStringRef (*$CTRegistrationCopyOperatorName)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTRegistrationCopyOperatorName")))
4471 return [(NSString *) (*$CTRegistrationCopyOperatorName)(kCFAllocatorDefault) autorelease];
4475 - (NSString *) bbsnum {
4476 return (id) BBSNum_ ?: [NSNull null];
4479 - (NSString *) ecid {
4480 return (id) ChipID_ ?: [NSNull null];
4483 - (NSString *) serial {
4484 return SerialNumber_;
4487 - (NSString *) role {
4488 return (id) [NSNull null];
4491 - (NSString *) model {
4492 return [NSString stringWithUTF8String:Machine_];
4495 + (NSString *) webScriptNameForSelector:(SEL)selector {
4497 else if (selector == @selector(addBridgedHost:))
4498 return @"addBridgedHost";
4499 else if (selector == @selector(addInsecureHost:))
4500 return @"addInsecureHost";
4501 else if (selector == @selector(addInternalRedirect::))
4502 return @"addInternalRedirect";
4503 else if (selector == @selector(addPipelinedHost:scheme:))
4504 return @"addPipelinedHost";
4505 else if (selector == @selector(addSource:::))
4506 return @"addSource";
4507 else if (selector == @selector(addTrivialSource:))
4508 return @"addTrivialSource";
4509 else if (selector == @selector(close))
4511 else if (selector == @selector(du:))
4513 else if (selector == @selector(stringWithFormat:arguments:))
4515 else if (selector == @selector(getAllSources))
4516 return @"getAllSources";
4517 else if (selector == @selector(getApplicationInfo:value:))
4518 return @"getApplicationInfoValue";
4519 else if (selector == @selector(getDisplayIdentifiers))
4520 return @"getDisplayIdentifiers";
4521 else if (selector == @selector(getLocalizedNameForDisplayIdentifier:))
4522 return @"getLocalizedNameForDisplayIdentifier";
4523 else if (selector == @selector(getKernelNumber:))
4524 return @"getKernelNumber";
4525 else if (selector == @selector(getKernelString:))
4526 return @"getKernelString";
4527 else if (selector == @selector(getInstalledPackages))
4528 return @"getInstalledPackages";
4529 else if (selector == @selector(getIORegistryEntry::))
4530 return @"getIORegistryEntry";
4531 else if (selector == @selector(getLocaleIdentifier))
4532 return @"getLocaleIdentifier";
4533 else if (selector == @selector(getPreferredLanguages))
4534 return @"getPreferredLanguages";
4535 else if (selector == @selector(getPackageById:))
4536 return @"getPackageById";
4537 else if (selector == @selector(getMetadataKeys))
4538 return @"getMetadataKeys";
4539 else if (selector == @selector(getMetadataValue:))
4540 return @"getMetadataValue";
4541 else if (selector == @selector(getSessionValue:))
4542 return @"getSessionValue";
4543 else if (selector == @selector(installPackages:))
4544 return @"installPackages";
4545 else if (selector == @selector(isReachable:))
4546 return @"isReachable";
4547 else if (selector == @selector(localizedStringForKey:value:table:))
4549 else if (selector == @selector(popViewController:))
4550 return @"popViewController";
4551 else if (selector == @selector(refreshSources))
4552 return @"refreshSources";
4553 else if (selector == @selector(registerFrame:))
4554 return @"registerFrame";
4555 else if (selector == @selector(removeButton))
4556 return @"removeButton";
4557 else if (selector == @selector(saveConfig))
4558 return @"saveConfig";
4559 else if (selector == @selector(setMetadataValue::))
4560 return @"setMetadataValue";
4561 else if (selector == @selector(setSessionValue::))
4562 return @"setSessionValue";
4563 else if (selector == @selector(substitutePackageNames:))
4564 return @"substitutePackageNames";
4565 else if (selector == @selector(scrollToBottom:))
4566 return @"scrollToBottom";
4567 else if (selector == @selector(setAllowsNavigationAction:))
4568 return @"setAllowsNavigationAction";
4569 else if (selector == @selector(setBadgeValue:))
4570 return @"setBadgeValue";
4571 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4572 return @"setButtonImage";
4573 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4574 return @"setButtonTitle";
4575 else if (selector == @selector(setHidesBackButton:))
4576 return @"setHidesBackButton";
4577 else if (selector == @selector(setHidesNavigationBar:))
4578 return @"setHidesNavigationBar";
4579 else if (selector == @selector(setNavigationBarStyle:))
4580 return @"setNavigationBarStyle";
4581 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4582 return @"setNavigationBarTintColor";
4583 else if (selector == @selector(setPasteboardString:))
4584 return @"setPasteboardString";
4585 else if (selector == @selector(setPasteboardURL:))
4586 return @"setPasteboardURL";
4587 else if (selector == @selector(setScrollAlwaysBounceVertical:))
4588 return @"setScrollAlwaysBounceVertical";
4589 else if (selector == @selector(setScrollIndicatorStyle:))
4590 return @"setScrollIndicatorStyle";
4591 else if (selector == @selector(setToken:))
4593 else if (selector == @selector(setViewportWidth:))
4594 return @"setViewportWidth";
4595 else if (selector == @selector(statfs:))
4597 else if (selector == @selector(supports:))
4599 else if (selector == @selector(unload))
4605 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4606 return [self webScriptNameForSelector:selector] == nil;
4609 - (BOOL) supports:(NSString *)feature {
4610 return [feature isEqualToString:@"window.open"];
4614 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4617 - (void) setScrollAlwaysBounceVertical:(NSNumber *)value {
4618 [indirect_ performSelectorOnMainThread:@selector(setScrollAlwaysBounceVerticalNumber:) withObject:value waitUntilDone:NO];
4621 - (void) setScrollIndicatorStyle:(NSString *)style {
4622 [indirect_ performSelectorOnMainThread:@selector(setScrollIndicatorStyleWithName:) withObject:style waitUntilDone:NO];
4625 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4626 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4629 - (NSDictionary *) getApplicationInfo:(NSString *)display value:(NSString *)key {
4631 if (SBBundlePathForDisplayIdentifier(SBSSpringBoardServerPort(), [display UTF8String], path) != 0)
4632 return (id) [NSNull null];
4633 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:[[NSString stringWithUTF8String:path] stringByAppendingString:@"/Info.plist"]]);
4635 return (id) [NSNull null];
4636 return [info objectForKey:key];
4639 - (NSArray *) getDisplayIdentifiers {
4640 NSSet *set([SBSCopyApplicationDisplayIdentifiers() autorelease]);
4641 if (set == nil || ![set isKindOfClass:[NSSet class]])
4642 return [NSArray array];
4643 return [set allObjects];
4646 - (NSString *) getLocalizedNameForDisplayIdentifier:(NSString *)identifier {
4647 return [SBSCopyLocalizedApplicationNameForDisplayIdentifier(identifier) autorelease] ?: (id) [NSNull null];
4650 - (NSNumber *) getKernelNumber:(NSString *)name {
4651 const char *string([name UTF8String]);
4654 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4655 return (id) [NSNull null];
4657 if (size != sizeof(int))
4658 return (id) [NSNull null];
4661 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4662 return (id) [NSNull null];
4664 return [NSNumber numberWithInt:value];
4667 - (NSString *) getKernelString:(NSString *)name {
4668 const char *string([name UTF8String]);
4671 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4672 return (id) [NSNull null];
4674 char value[size + 1];
4675 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4676 return (id) [NSNull null];
4678 // XXX: just in case you request something ludicrous
4681 return [NSString stringWithCString:value];
4684 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4685 NSObject *value(CYIOGetValue([path UTF8String], entry));
4688 if ([value isKindOfClass:[NSData class]])
4689 value = CYHex((NSData *) value);
4694 - (NSArray *) getMetadataKeys {
4695 @synchronized (Values_) {
4696 return [Values_ allKeys];
4699 - (void) registerFrame:(DOMHTMLIFrameElement *)iframe {
4700 WebFrame *frame([iframe contentFrame]);
4701 [indirect_ registerFrame:frame];
4704 - (id) getMetadataValue:(NSString *)key {
4705 @synchronized (Values_) {
4706 return [Values_ objectForKey:key];
4709 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4710 @synchronized (Values_) {
4711 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4712 [Values_ removeObjectForKey:key];
4714 [Values_ setObject:value forKey:key];
4717 - (id) getSessionValue:(NSString *)key {
4718 @synchronized (SessionData_) {
4719 return [SessionData_ objectForKey:key];
4722 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4723 @synchronized (SessionData_) {
4724 if (value == (id) [WebUndefined undefined])
4725 [SessionData_ removeObjectForKey:key];
4727 [SessionData_ setObject:value forKey:key];
4730 - (void) addBridgedHost:(NSString *)host {
4731 @synchronized (HostConfig_) {
4732 [BridgedHosts_ addObject:host];
4735 - (void) addInsecureHost:(NSString *)host {
4736 @synchronized (HostConfig_) {
4737 [InsecureHosts_ addObject:host];
4740 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4741 @synchronized (HostConfig_) {
4742 if (scheme != (id) [WebUndefined undefined])
4743 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4745 [PipelinedHosts_ addObject:host];
4748 - (void) popViewController:(NSNumber *)value {
4749 if (value == (id) [WebUndefined undefined])
4750 value = [NSNumber numberWithBool:YES];
4751 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4754 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4755 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4757 for (NSString *section in sections)
4758 [array addObject:section];
4760 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4763 distribution, @"Distribution",
4765 nil] waitUntilDone:NO];
4768 - (BOOL) addTrivialSource:(NSString *)href {
4769 href = VerifySource(href);
4772 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4776 - (void) refreshSources {
4777 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4780 - (void) saveConfig {
4781 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4784 - (NSArray *) getAllSources {
4785 return [[Database sharedInstance] sources];
4788 - (NSArray *) getInstalledPackages {
4789 Database *database([Database sharedInstance]);
4790 @synchronized (database) {
4791 NSArray *packages([database packages]);
4792 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4793 for (Package *package in packages)
4794 if (![package uninstalled])
4795 [installed addObject:package];
4799 - (Package *) getPackageById:(NSString *)id {
4800 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4804 return (Package *) [NSNull null];
4807 - (NSString *) getLocaleIdentifier {
4808 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4811 - (NSArray *) getPreferredLanguages {
4815 - (NSArray *) statfs:(NSString *)path {
4818 if (path == nil || statfs([path UTF8String], &stat) == -1)
4821 return [NSArray arrayWithObjects:
4822 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4823 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4824 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4828 - (NSNumber *) du:(NSString *)path {
4829 NSNumber *value(nil);
4831 FILE *du(popen([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /usr/libexec/cydia/du -ks %@", ShellEscape(path)] UTF8String], "r"));
4834 while (fgets(line, sizeof(line), du) != NULL) {
4835 size_t length(strlen(line));
4836 while (length != 0 && line[length - 1] == '\n')
4837 line[--length] = '\0';
4838 if (char *tab = strchr(line, '\t')) {
4840 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4850 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4853 - (NSNumber *) isReachable:(NSString *)name {
4854 return [NSNumber numberWithBool:IsReachable([name UTF8String])];
4857 - (void) installPackages:(NSArray *)packages {
4858 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4861 - (NSString *) substitutePackageNames:(NSString *)message {
4862 NSMutableArray *words([[[message componentsSeparatedByString:@" "] mutableCopy] autorelease]);
4863 for (size_t i(0), e([words count]); i != e; ++i) {
4864 NSString *word([words objectAtIndex:i]);
4865 if (Package *package = [[Database sharedInstance] packageWithName:word])
4866 [words replaceObjectAtIndex:i withObject:[package name]];
4869 return [words componentsJoinedByString:@" "];
4872 - (void) removeButton {
4873 [indirect_ removeButton];
4876 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4877 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4880 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4881 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4884 - (void) setBadgeValue:(id)value {
4885 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4888 - (void) setAllowsNavigationAction:(NSString *)value {
4889 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4892 - (void) setHidesBackButton:(NSString *)value {
4893 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4896 - (void) setHidesNavigationBar:(NSString *)value {
4897 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4900 - (void) setNavigationBarStyle:(NSString *)value {
4901 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4904 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4905 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4906 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4907 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4910 - (void) setPasteboardString:(NSString *)value {
4911 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4914 - (void) setPasteboardURL:(NSString *)value {
4915 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4918 - (void) setToken:(NSString *)token {
4919 // XXX: the website expects this :/
4922 - (void) scrollToBottom:(NSNumber *)animated {
4923 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4926 - (void) setViewportWidth:(float)width {
4927 [indirect_ setViewportWidthOnMainThread:width];
4930 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4931 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4932 unsigned count([arguments count]);
4934 for (unsigned i(0); i != count; ++i)
4935 values[i] = [arguments objectAtIndex:i];
4936 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4939 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4940 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4942 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4944 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4950 @interface NSURL (CydiaSecure)
4953 @implementation NSURL (CydiaSecure)
4955 - (bool) isCydiaSecure {
4956 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4959 @synchronized (HostConfig_) {
4960 if ([InsecureHosts_ containsObject:[self host]])
4969 /* Cydia Browser Controller {{{ */
4970 @implementation CydiaWebViewController
4972 - (NSURL *) navigationURL {
4973 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4976 + (void) _initialize {
4977 [super _initialize];
4979 Diversions_ = [NSMutableSet setWithCapacity:0];
4982 + (void) addDiversion:(Diversion *)diversion {
4983 [Diversions_ addObject:diversion];
4986 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4987 [super webView:view didClearWindowObject:window forFrame:frame];
4988 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
4991 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia {
4992 WebDataSource *source([frame dataSource]);
4993 NSURLResponse *response([source response]);
4994 NSURL *url([response URL]);
4995 NSString *scheme([[url scheme] lowercaseString]);
4997 bool bridged(false);
4999 @synchronized (HostConfig_) {
5000 if ([scheme isEqualToString:@"file"])
5002 else if ([scheme isEqualToString:@"https"])
5003 if ([BridgedHosts_ containsObject:[url host]])
5008 [window setValue:cydia forKey:@"cydia"];
5011 - (void) _setupMail:(MFMailComposeViewController *)controller {
5012 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
5014 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
5015 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
5018 - (NSURL *) URLWithURL:(NSURL *)url {
5019 return [Diversion divertURL:url];
5022 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
5023 return [CydiaWebViewController requestWithHeaders:[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
5026 - (NSURLRequest *) webThreadWebView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
5027 return [CydiaWebViewController requestWithHeaders:[super webThreadWebView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
5030 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request {
5031 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
5033 NSURL *url([copy URL]);
5034 NSString *href([url absoluteString]);
5035 NSString *host([url host]);
5037 if ([href hasPrefix:@"https://cydia.saurik.com/TSS/"]) {
5038 if (NSString *agent = [copy valueForHTTPHeaderField:@"X-User-Agent"]) {
5039 [copy setValue:agent forHTTPHeaderField:@"User-Agent"];
5040 [copy setValue:nil forHTTPHeaderField:@"X-User-Agent"];
5043 [copy setValue:nil forHTTPHeaderField:@"Referer"];
5044 [copy setValue:nil forHTTPHeaderField:@"Origin"];
5046 [copy setURL:[NSURL URLWithString:[@"http://gs.apple.com/TSS/" stringByAppendingString:[href substringFromIndex:29]]]];
5050 if ([copy valueForHTTPHeaderField:@"X-Cydia-Cf"] == nil)
5051 [copy setValue:[NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber] forHTTPHeaderField:@"X-Cydia-Cf"];
5052 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
5053 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
5055 bool bridged; @synchronized (HostConfig_) {
5056 bridged = [BridgedHosts_ containsObject:host];
5059 if ([url isCydiaSecure] && bridged && UniqueID_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Id"] == nil)
5060 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
5065 - (void) setDelegate:(id)delegate {
5066 [super setDelegate:delegate];
5067 [cydia_ setDelegate:delegate];
5070 - (NSString *) applicationNameForUserAgent {
5075 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
5076 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
5082 @interface AppCacheController : CydiaWebViewController {
5087 @implementation AppCacheController
5089 - (void) didReceiveMemoryWarning {
5090 // XXX: this doesn't work
5093 - (bool) retainsNetworkActivityIndicator {
5101 @interface NSObject (CydiaScript)
5102 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
5105 @implementation NSObject (CydiaScript)
5107 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5113 @implementation NSArray (CydiaScript)
5115 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5116 WebScriptObject *object([context evaluateWebScript:@"[]"]);
5117 for (size_t i(0), e([self count]); i != e; ++i)
5118 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
5124 @implementation NSDictionary (CydiaScript)
5126 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5127 WebScriptObject *object([context evaluateWebScript:@"({})"]);
5129 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
5136 /* Confirmation Controller {{{ */
5137 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
5138 if (!iterator.end())
5139 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
5140 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
5142 pkgCache::PkgIterator package(dep.TargetPkg());
5145 if (strcmp(package.Name(), "mobilesubstrate") == 0)
5152 @protocol ConfirmationControllerDelegate
5153 - (void) cancelAndClear:(bool)clear;
5154 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
5158 @interface ConfirmationController : CydiaWebViewController {
5159 _transient Database *database_;
5161 _H<UIAlertView> essential_;
5163 _H<NSDictionary> changes_;
5164 _H<NSMutableArray> issues_;
5165 _H<NSDictionary> sizes_;
5170 - (id) initWithDatabase:(Database *)database;
5174 @implementation ConfirmationController
5178 RestartSubstrate_ = true;
5179 [delegate_ confirmWithNavigationController:[self navigationController]];
5182 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
5183 NSString *context([alert context]);
5185 if ([context isEqualToString:@"remove"]) {
5186 if (button == [alert cancelButtonIndex])
5188 else if (button == [alert firstOtherButtonIndex]) {
5189 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
5192 [alert dismissWithClickedButtonIndex:-1 animated:YES];
5193 } else if ([context isEqualToString:@"unable"]) {
5194 [self dismissModalViewControllerAnimated:YES];
5195 [alert dismissWithClickedButtonIndex:-1 animated:YES];
5197 [super alertView:alert clickedButtonAtIndex:button];
5201 - (void) _doContinue {
5202 [delegate_ cancelAndClear:NO];
5203 [self dismissModalViewControllerAnimated:YES];
5206 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
5207 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
5211 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5212 [super webView:view didClearWindowObject:window forFrame:frame];
5214 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
5215 (id) changes_, @"changes",
5216 (id) issues_, @"issues",
5217 (id) sizes_, @"sizes",
5219 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
5222 - (id) initWithDatabase:(Database *)database {
5223 if ((self = [super init]) != nil) {
5224 database_ = database;
5226 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
5227 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
5228 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
5229 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
5230 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
5234 pkgCacheFile &cache([database_ cache]);
5235 NSArray *packages([database_ packages]);
5236 pkgDepCache::Policy *policy([database_ policy]);
5238 issues_ = [NSMutableArray arrayWithCapacity:4];
5240 for (Package *package in packages) {
5241 pkgCache::PkgIterator iterator([package iterator]);
5242 NSString *name([package id]);
5244 if ([package broken]) {
5245 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
5247 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5249 reasons, @"reasons",
5252 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
5256 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
5257 pkgCache::DepIterator start;
5258 pkgCache::DepIterator end;
5259 dep.GlobOr(start, end); // ++dep
5261 if (!cache->IsImportantDep(end))
5263 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
5266 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
5268 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5269 [NSString stringWithUTF8String:start.DepType()], @"relationship",
5270 clauses, @"clauses",
5274 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
5276 pkgCache::PkgIterator target(start.TargetPkg());
5277 if (target->ProvidesList != 0)
5278 reason = @"missing";
5280 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
5282 reason = @"installed";
5283 installed = [NSString stringWithUTF8String:ver.VerStr()];
5284 } else if (!cache[target].CandidateVerIter(cache).end())
5285 reason = @"uninstalled";
5286 else if (target->ProvidesList == 0)
5287 reason = @"uninstallable";
5289 reason = @"virtual";
5292 NSDictionary *version(start.TargetVer() == 0 ? (NSDictionary *) [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
5293 [NSString stringWithUTF8String:start.CompType()], @"operator",
5294 [NSString stringWithUTF8String:start.TargetVer()], @"value",
5297 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5298 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
5299 version, @"version",
5301 installed, @"installed",
5304 // yes, seriously. (wtf?)
5312 pkgDepCache::StateCache &state(cache[iterator]);
5314 static RegEx special_r("(firmware|gsc\\..*|cy\\+.*)");
5316 if (state.NewInstall())
5317 [installs addObject:name];
5318 // XXX: else if (state.Install())
5319 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
5320 [reinstalls addObject:name];
5321 // XXX: move before previous if
5322 else if (state.Upgrade())
5323 [upgrades addObject:name];
5324 else if (state.Downgrade())
5325 [downgrades addObject:name];
5326 else if (!state.Delete())
5327 // XXX: _assert(state.Keep());
5329 else if (special_r(name))
5330 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5331 [NSNull null], @"package",
5332 [NSArray arrayWithObjects:
5333 [NSDictionary dictionaryWithObjectsAndKeys:
5334 @"Conflicts", @"relationship",
5335 [NSArray arrayWithObjects:
5336 [NSDictionary dictionaryWithObjectsAndKeys:
5338 [NSNull null], @"version",
5339 @"installed", @"reason",
5346 if ([package essential])
5348 [removes addObject:name];
5351 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
5352 substrate_ |= DepSubstrate(iterator.CurrentVer());
5357 else if (Advanced_) {
5358 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
5360 essential_ = [[[UIAlertView alloc]
5361 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
5362 message:UCLocalize("REMOVING_ESSENTIALS_EX")
5364 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
5366 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
5370 [essential_ setContext:@"remove"];
5371 [essential_ setNumberOfRows:2];
5373 essential_ = [[[UIAlertView alloc]
5374 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
5375 message:UCLocalize("UNABLE_TO_COMPLY_EX")
5377 cancelButtonTitle:UCLocalize("OKAY")
5378 otherButtonTitles:nil
5381 [essential_ setContext:@"unable"];
5384 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5385 installs, @"installs",
5386 reinstalls, @"reinstalls",
5387 upgrades, @"upgrades",
5388 downgrades, @"downgrades",
5389 removes, @"removes",
5392 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5393 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
5394 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
5397 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
5401 - (UIBarButtonItem *) leftButton {
5402 return [[[UIBarButtonItem alloc]
5403 initWithTitle:UCLocalize("CANCEL")
5404 style:UIBarButtonItemStylePlain
5406 action:@selector(cancelButtonClicked)
5411 - (void) applyRightButton {
5412 if ([issues_ count] == 0 && ![self isLoading])
5413 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
5414 initWithTitle:UCLocalize("CONFIRM")
5415 style:UIBarButtonItemStyleDone
5417 action:@selector(confirmButtonClicked)
5420 [[self navigationItem] setRightBarButtonItem:nil];
5424 - (void) cancelButtonClicked {
5425 [delegate_ cancelAndClear:YES];
5426 [self dismissModalViewControllerAnimated:YES];
5430 - (void) confirmButtonClicked {
5431 if (essential_ != nil)
5441 /* Progress Data {{{ */
5442 @interface CydiaProgressData : NSObject {
5443 _transient id delegate_;
5452 _H<NSMutableArray> events_;
5453 _H<NSString> title_;
5455 _H<NSString> status_;
5456 _H<NSString> finish_;
5461 @implementation CydiaProgressData
5463 + (NSArray *) _attributeKeys {
5464 return [NSArray arrayWithObjects:
5476 - (NSArray *) attributeKeys {
5477 return [[self class] _attributeKeys];
5480 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5481 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5485 if ((self = [super init]) != nil) {
5486 events_ = [NSMutableArray arrayWithCapacity:32];
5494 - (void) setDelegate:(id)delegate {
5495 delegate_ = delegate;
5498 - (void) setPercent:(float)value {
5502 - (NSNumber *) percent {
5503 return [NSNumber numberWithFloat:percent_];
5506 - (void) setCurrent:(float)value {
5510 - (NSNumber *) current {
5511 return [NSNumber numberWithFloat:current_];
5514 - (void) setTotal:(float)value {
5518 - (NSNumber *) total {
5519 return [NSNumber numberWithFloat:total_];
5522 - (void) setSpeed:(float)value {
5526 - (NSNumber *) speed {
5527 return [NSNumber numberWithFloat:speed_];
5530 - (NSArray *) events {
5534 - (void) removeAllEvents {
5535 [events_ removeAllObjects];
5538 - (void) addEvent:(CydiaProgressEvent *)event {
5539 [events_ addObject:event];
5542 - (void) setTitle:(NSString *)text {
5546 - (NSString *) title {
5550 - (void) setFinish:(NSString *)text {
5554 - (NSString *) finish {
5555 return (id) finish_ ?: [NSNull null];
5558 - (void) setRunning:(bool)running {
5562 - (NSNumber *) running {
5563 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5568 /* Progress Controller {{{ */
5569 @interface ProgressController : CydiaWebViewController <
5572 _transient Database *database_;
5573 _H<CydiaProgressData, 1> progress_;
5577 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5579 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5581 - (void) setTitle:(NSString *)title;
5582 - (void) setCancellable:(bool)cancellable;
5586 @implementation ProgressController
5589 [database_ setProgressDelegate:nil];
5593 - (UIBarButtonItem *) leftButton {
5594 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5595 initWithTitle:UCLocalize("CANCEL")
5596 style:UIBarButtonItemStylePlain
5598 action:@selector(cancel)
5599 ] autorelease] : nil;
5602 - (void) updateCancel {
5603 [super applyLeftButton];
5606 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5607 if ((self = [super init]) != nil) {
5608 database_ = database;
5609 delegate_ = delegate;
5611 [database_ setProgressDelegate:self];
5613 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5614 [progress_ setDelegate:self];
5616 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5618 [scroller_ setBackgroundColor:[UIColor blackColor]];
5620 [[self navigationItem] setHidesBackButton:YES];
5622 [self updateCancel];
5626 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5627 [super webView:view didClearWindowObject:window forFrame:frame];
5628 [window setValue:progress_ forKey:@"cydiaProgress"];
5631 - (void) updateProgress {
5632 [self dispatchEvent:@"CydiaProgressUpdate"];
5635 - (void) viewWillAppear:(BOOL)animated {
5636 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5637 [super viewWillAppear:animated];
5641 UpdateExternalStatus(0);
5644 [delegate_ saveState];
5648 [delegate_ returnToCydia];
5652 [delegate_ terminateWithSuccess];
5653 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5654 [delegate_ suspendWithAnimation:YES];
5656 [delegate_ suspend];*/
5668 UIProgressHUD *hud([delegate_ addProgressHUD]);
5669 [hud setText:UCLocalize("LOADING")];
5670 [delegate_ performSelector:@selector(reloadSpringBoard) withObject:nil afterDelay:0.5];
5676 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5677 SBReboot(SBSSpringBoardServerPort());
5679 reboot2(RB_AUTOBOOT);
5686 - (void) setTitle:(NSString *)title {
5687 [progress_ setTitle:title];
5688 [self updateProgress];
5691 - (UIBarButtonItem *) rightButton {
5692 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5693 initWithTitle:UCLocalize("CLOSE")
5694 style:UIBarButtonItemStylePlain
5696 action:@selector(close)
5700 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5701 UpdateExternalStatus(1);
5703 [progress_ setRunning:true];
5704 [self setTitle:title];
5705 // implicit updateProgress
5707 SHA1SumValue notifyconf; {
5709 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5712 MMap mmap(file, MMap::ReadOnly);
5714 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5715 notifyconf = sha1.Result();
5719 SHA1SumValue springlist; {
5721 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5724 MMap mmap(file, MMap::ReadOnly);
5726 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5727 springlist = sha1.Result();
5731 if (invocation != nil) {
5732 [invocation yieldToSelector:@selector(invoke)];
5733 [self setTitle:@"COMPLETE"];
5738 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5741 MMap mmap(file, MMap::ReadOnly);
5743 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5744 if (!(notifyconf == sha1.Result()))
5751 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5754 MMap mmap(file, MMap::ReadOnly);
5756 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5757 if (!(springlist == sha1.Result()))
5763 if (RestartSubstrate_)
5767 RestartSubstrate_ = false;
5770 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5771 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5772 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5773 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5774 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5777 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5779 [progress_ setRunning:false];
5780 [self updateProgress];
5782 [self applyRightButton];
5785 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5786 [progress_ addEvent:event];
5787 [self updateProgress];
5790 - (bool) isProgressCancelled {
5791 return cancel_ == 2;
5796 [self updateCancel];
5799 - (void) setCancellable:(bool)cancellable {
5800 unsigned cancel(cancel_);
5804 else if (cancel_ == 0)
5807 if (cancel != cancel_)
5808 [self updateCancel];
5811 - (void) setProgressCancellable:(NSNumber *)cancellable {
5812 [self setCancellable:[cancellable boolValue]];
5815 - (void) setProgressPercent:(NSNumber *)percent {
5816 [progress_ setPercent:[percent floatValue]];
5817 [self updateProgress];
5820 - (void) setProgressStatus:(NSDictionary *)status {
5821 if (status == nil) {
5822 [progress_ setCurrent:0];
5823 [progress_ setTotal:0];
5824 [progress_ setSpeed:0];
5826 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5828 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5829 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5830 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5833 [self updateProgress];
5839 /* Package Cell {{{ */
5840 @interface PackageCell : CyteTableViewCell <
5841 CyteTableViewCellDelegate
5845 _H<NSString> description_;
5847 _H<NSString> source_;
5849 _H<UIImage> placard_;
5853 - (PackageCell *) init;
5854 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5856 - (void) drawContentRect:(CGRect)rect;
5860 @implementation PackageCell
5862 - (PackageCell *) init {
5863 CGRect frame(CGRectMake(0, 0, 320, 74));
5864 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5865 UIView *content([self contentView]);
5866 CGRect bounds([content bounds]);
5868 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5869 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5870 [content addSubview:content_];
5872 [content_ setDelegate:self];
5873 [content_ setOpaque:YES];
5877 - (NSString *) accessibilityLabel {
5881 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5882 summarized_ = summary;
5892 [content_ setBackgroundColor:[UIColor whiteColor]];
5896 Source *source = [package source];
5898 icon_ = [package icon];
5900 if (NSString *name = [package name])
5901 name_ = [NSString stringWithString:name];
5903 if (NSString *description = [package shortDescription])
5904 description_ = [NSString stringWithString:description];
5906 commercial_ = [package isCommercial];
5908 NSString *label = nil;
5909 bool trusted = false;
5911 if (source != nil) {
5912 label = [source label];
5913 trusted = [source trusted];
5914 } else if ([[package id] isEqualToString:@"firmware"])
5915 label = UCLocalize("APPLE");
5917 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5919 NSString *from(label);
5921 NSString *section = [package simpleSection];
5922 if (section != nil && ![section isEqualToString:label]) {
5923 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5924 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5927 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5929 if (NSString *purpose = [package primaryPurpose])
5930 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5935 if (NSString *mode = [package mode]) {
5936 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5937 color = RemovingColor_;
5938 placard = @"removing";
5940 color = InstallingColor_;
5941 placard = @"installing";
5944 color = [UIColor whiteColor];
5946 if ([package installed] != nil)
5947 placard = @"installed";
5952 [content_ setBackgroundColor:color];
5955 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5958 [self setNeedsDisplay];
5959 [content_ setNeedsDisplay];
5962 - (void) drawSummaryContentRect:(CGRect)rect {
5963 bool highlighted(highlighted_);
5964 float width([self bounds].size.width);
5968 rect.size = [(UIImage *) icon_ size];
5970 while (rect.size.width > 16 || rect.size.height > 16) {
5971 rect.size.width /= 2;
5972 rect.size.height /= 2;
5975 rect.origin.x = 19 - rect.size.width / 2;
5976 rect.origin.y = 19 - rect.size.height / 2;
5978 [icon_ drawInRect:Retina(rect)];
5981 if (badge_ != nil) {
5983 rect.size = [(UIImage *) badge_ size];
5985 rect.size.width /= 4;
5986 rect.size.height /= 4;
5988 rect.origin.x = 25 - rect.size.width / 2;
5989 rect.origin.y = 25 - rect.size.height / 2;
5991 [badge_ drawInRect:Retina(rect)];
5994 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5998 UISetColor(commercial_ ? Purple_ : Black_);
5999 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
6001 if (placard_ != nil)
6002 [placard_ drawAtPoint:CGPointMake(width - 52, 11)];
6005 - (void) drawNormalContentRect:(CGRect)rect {
6006 bool highlighted(highlighted_);
6007 float width([self bounds].size.width);
6011 rect.size = [(UIImage *) icon_ size];
6013 while (rect.size.width > 32 || rect.size.height > 32) {
6014 rect.size.width /= 2;
6015 rect.size.height /= 2;
6018 rect.origin.x = 25 - rect.size.width / 2;
6019 rect.origin.y = 25 - rect.size.height / 2;
6021 [icon_ drawInRect:Retina(rect)];
6024 if (badge_ != nil) {
6026 rect.size = [(UIImage *) badge_ size];
6028 rect.size.width /= 2;
6029 rect.size.height /= 2;
6031 rect.origin.x = 36 - rect.size.width / 2;
6032 rect.origin.y = 36 - rect.size.height / 2;
6034 [badge_ drawInRect:Retina(rect)];
6037 if (highlighted && kCFCoreFoundationVersionNumber < 800)
6041 UISetColor(commercial_ ? Purple_ : Black_);
6042 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
6043 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
6046 UISetColor(commercial_ ? Purplish_ : Gray_);
6047 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:NSLineBreakByTruncatingTail];
6049 if (placard_ != nil)
6050 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
6053 - (void) drawContentRect:(CGRect)rect {
6055 [self drawSummaryContentRect:rect];
6057 [self drawNormalContentRect:rect];
6062 /* Section Cell {{{ */
6063 @interface SectionCell : CyteTableViewCell <
6064 CyteTableViewCellDelegate
6066 _H<NSString> basic_;
6067 _H<NSString> section_;
6069 _H<NSString> count_;
6071 _H<UISwitch> switch_;
6075 - (void) setSection:(Section *)section editing:(BOOL)editing;
6079 @implementation SectionCell
6081 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
6082 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
6083 icon_ = [UIImage imageNamed:@"folder.png"];
6084 // XXX: this initial frame is wrong, but is fixed later
6085 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
6086 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
6088 UIView *content([self contentView]);
6089 CGRect bounds([content bounds]);
6091 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
6092 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6093 [content addSubview:content_];
6094 [content_ setBackgroundColor:[UIColor whiteColor]];
6096 [content_ setDelegate:self];
6100 - (void) onSwitch:(id)sender {
6101 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
6102 if (metadata == nil) {
6103 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
6104 [Sections_ setObject:metadata forKey:basic_];
6107 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
6110 - (void) setSection:(Section *)section editing:(BOOL)editing {
6111 if (editing != editing_) {
6113 [switch_ removeFromSuperview];
6115 [self addSubview:switch_];
6124 if (section == nil) {
6125 name_ = UCLocalize("ALL_PACKAGES");
6128 basic_ = [section name];
6129 section_ = [section localized];
6131 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
6132 count_ = [NSString stringWithFormat:@"%zd", [section count]];
6135 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
6138 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
6139 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
6141 [content_ setNeedsDisplay];
6144 - (void) setFrame:(CGRect)frame {
6145 [super setFrame:frame];
6147 CGRect rect([switch_ frame]);
6148 [switch_ setFrame:CGRectMake(frame.size.width - rect.size.width - 9, 9, rect.size.width, rect.size.height)];
6151 - (NSString *) accessibilityLabel {
6155 - (void) drawContentRect:(CGRect)rect {
6156 bool highlighted(highlighted_ && !editing_);
6158 [icon_ drawInRect:CGRectMake(7, 7, 32, 32)];
6160 if (highlighted && kCFCoreFoundationVersionNumber < 800)
6163 float width(rect.size.width);
6165 width -= 9 + [switch_ frame].size.width;
6169 [name_ drawAtPoint:CGPointMake(48, 12) forWidth:(width - 58) withFont:Font18_ lineBreakMode:NSLineBreakByTruncatingTail];
6171 CGSize size = [count_ sizeWithFont:Font14_];
6173 UISetColor(Folder_);
6175 [count_ drawAtPoint:CGPointMake(Retina(10 + (30 - size.width) / 2), 18) withFont:Font12Bold_];
6181 /* File Table {{{ */
6182 @interface FileTable : CyteViewController <
6183 UITableViewDataSource,
6186 _transient Database *database_;
6187 _H<Package> package_;
6189 _H<NSMutableArray> files_;
6190 _H<UITableView, 2> list_;
6193 - (id) initWithDatabase:(Database *)database;
6194 - (void) setPackage:(Package *)package;
6198 @implementation FileTable
6200 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6201 return files_ == nil ? 0 : [files_ count];
6204 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6208 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6209 static NSString *reuseIdentifier = @"Cell";
6211 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6213 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6214 [cell setFont:[UIFont systemFontOfSize:16]];
6216 [cell setText:[files_ objectAtIndex:indexPath.row]];
6217 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
6222 - (NSURL *) navigationURL {
6223 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
6227 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
6228 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6229 [list_ setRowHeight:24.0f];
6230 [(UITableView *) list_ setDataSource:self];
6231 [list_ setDelegate:self];
6232 [self setView:list_];
6235 - (void) viewDidLoad {
6236 [super viewDidLoad];
6238 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
6241 - (void) releaseSubviews {
6247 [super releaseSubviews];
6250 - (id) initWithDatabase:(Database *)database {
6251 if ((self = [super init]) != nil) {
6252 database_ = database;
6256 - (void) setPackage:(Package *)package {
6260 files_ = [NSMutableArray arrayWithCapacity:32];
6262 if (package != nil) {
6264 name_ = [package id];
6266 if (NSArray *files = [package files])
6267 [files_ addObjectsFromArray:files];
6269 if ([files_ count] != 0) {
6270 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
6271 [files_ removeObjectAtIndex:0];
6272 [files_ sortUsingSelector:@selector(compareByPath:)];
6274 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
6275 [stack addObject:@"/"];
6277 for (int i(0), e([files_ count]); i != e; ++i) {
6278 NSString *file = [files_ objectAtIndex:i];
6279 while (![file hasPrefix:[stack lastObject]])
6280 [stack removeLastObject];
6281 NSString *directory = [stack lastObject];
6282 [stack addObject:[file stringByAppendingString:@"/"]];
6283 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
6284 int(([stack count] - 2) * 3), "",
6285 [file substringFromIndex:[directory length]]
6294 - (void) reloadData {
6297 [self setPackage:[database_ packageWithName:name_]];
6302 /* Package Controller {{{ */
6303 @interface CYPackageController : CydiaWebViewController <
6304 UIActionSheetDelegate
6306 _transient Database *database_;
6307 _H<Package> package_;
6310 std::vector<std::pair<_H<NSString>, _H<NSString>>> buttons_;
6311 _H<UIActionSheet> sheet_;
6312 _H<UIBarButtonItem> button_;
6313 _H<NSArray> versions_;
6316 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer;
6320 @implementation CYPackageController
6322 - (NSURL *) navigationURL {
6323 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
6326 - (void) _clickButtonWithPackage:(Package *)package {
6327 [delegate_ installPackage:package];
6330 - (void) _clickButtonWithName:(NSString *)name {
6331 if ([name isEqualToString:@"CLEAR"])
6332 return [delegate_ clearPackage:package_];
6333 else if ([name isEqualToString:@"REMOVE"])
6334 return [delegate_ removePackage:package_];
6335 else if ([name isEqualToString:@"DOWNGRADE"]) {
6336 sheet_ = [[[UIActionSheet alloc]
6339 cancelButtonTitle:nil
6340 destructiveButtonTitle:nil
6341 otherButtonTitles:nil
6344 for (Package *version in (id) versions_)
6345 [sheet_ addButtonWithTitle:[version latest]];
6346 [sheet_ setContext:@"version"];
6348 [delegate_ showActionSheet:sheet_ fromItem:[[self navigationItem] rightBarButtonItem]];
6352 else if ([name isEqualToString:@"INSTALL"]);
6353 else if ([name isEqualToString:@"REINSTALL"]);
6354 else if ([name isEqualToString:@"UPGRADE"]);
6355 else _assert(false);
6357 [delegate_ installPackage:package_];
6360 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
6361 NSString *context([sheet context]);
6362 if (sheet_ == sheet)
6365 if ([context isEqualToString:@"modify"]) {
6366 if (button != [sheet cancelButtonIndex]) {
6368 [self performSelector:@selector(_clickButtonWithName:) withObject:buttons_[button].first afterDelay:0];
6370 [self _clickButtonWithName:buttons_[button].first];
6373 [sheet dismissWithClickedButtonIndex:button animated:YES];
6374 } else if ([context isEqualToString:@"version"]) {
6375 if (button != [sheet cancelButtonIndex]) {
6376 Package *version([versions_ objectAtIndex:button]);
6378 [self performSelector:@selector(_clickButtonWithPackage:) withObject:version afterDelay:0];
6380 [self _clickButtonWithPackage:version];
6383 [sheet dismissWithClickedButtonIndex:button animated:YES];
6387 - (bool) _allowJavaScriptPanel {
6392 - (void) _customButtonClicked {
6393 size_t count(buttons_.size());
6398 [self _clickButtonWithName:buttons_[0].first];
6400 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
6401 for (const auto &button : buttons_)
6402 [buttons addObject:button.second];
6404 sheet_ = [[[UIActionSheet alloc]
6407 cancelButtonTitle:nil
6408 destructiveButtonTitle:nil
6409 otherButtonTitles:nil
6412 for (NSString *button in buttons)
6413 [sheet_ addButtonWithTitle:button];
6414 [sheet_ setContext:@"modify"];
6416 [delegate_ showActionSheet:sheet_ fromItem:[[self navigationItem] rightBarButtonItem]];
6420 - (void) reloadButtonClicked {
6421 if (commercial_ && function_ == nil && [package_ uninstalled])
6423 [self customButtonClicked];
6426 - (void) applyLoadingTitle {
6427 // Don't show "Loading" as the title. Ever.
6430 - (UIBarButtonItem *) rightButton {
6435 - (void) setPageColor:(UIColor *)color {
6436 return [super setPageColor:nil];
6439 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer {
6440 if ((self = [super init]) != nil) {
6441 database_ = database;
6442 name_ = name == nil ? @"" : [NSString stringWithString:name];
6443 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]] withReferrer:referrer];
6447 - (void) reloadData {
6450 [sheet_ dismissWithClickedButtonIndex:[sheet_ cancelButtonIndex] animated:YES];
6453 package_ = [database_ packageWithName:name_];
6454 versions_ = [package_ downgrades];
6458 if (package_ != nil) {
6459 [(Package *) package_ parse];
6461 commercial_ = [package_ isCommercial];
6463 if ([package_ mode] != nil)
6464 buttons_.push_back(std::make_pair(@"CLEAR", UCLocalize("CLEAR")));
6465 if ([package_ source] == nil);
6466 else if ([package_ upgradableAndEssential:NO])
6467 buttons_.push_back(std::make_pair(@"UPGRADE", UCLocalize("UPGRADE")));
6468 else if ([package_ uninstalled])
6469 buttons_.push_back(std::make_pair(@"INSTALL", UCLocalize("INSTALL")));
6471 buttons_.push_back(std::make_pair(@"REINSTALL", UCLocalize("REINSTALL")));
6472 if (![package_ uninstalled])
6473 buttons_.push_back(std::make_pair(@"REMOVE", UCLocalize("REMOVE")));
6474 if ([versions_ count] != 0)
6475 buttons_.push_back(std::make_pair(@"DOWNGRADE", UCLocalize("DOWNGRADE")));
6479 switch (buttons_.size()) {
6480 case 0: title = nil; break;
6481 case 1: title = buttons_[0].second; break;
6482 default: title = UCLocalize("MODIFY"); break;
6485 button_ = [[[UIBarButtonItem alloc]
6487 style:UIBarButtonItemStylePlain
6489 action:@selector(customButtonClicked)
6493 - (bool) isLoading {
6494 return commercial_ ? [super isLoading] : false;
6500 /* Package List Controller {{{ */
6501 @interface PackageListController : CyteViewController <
6502 UITableViewDataSource,
6505 _transient Database *database_;
6507 _H<NSArray> packages_;
6508 _H<NSArray> sections_;
6509 _H<UITableView, 2> list_;
6511 _H<NSArray> thumbs_;
6512 std::vector<NSInteger> offset_;
6514 _H<NSString> title_;
6515 unsigned reloading_;
6518 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6519 - (void) setDelegate:(id)delegate;
6520 - (void) resetCursor;
6523 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages;
6527 @implementation PackageListController
6529 - (NSURL *) referrerURL {
6530 return [self navigationURL];
6533 - (bool) isSummarized {
6537 - (bool) showsSections {
6541 - (void) deselectWithAnimation:(BOOL)animated {
6542 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6545 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6546 CGRect base = [[self view] bounds];
6547 base.size.height -= bounds.size.height;
6548 base.origin = [list_ frame].origin;
6550 [UIView beginAnimations:nil context:NULL];
6551 [UIView setAnimationBeginsFromCurrentState:YES];
6552 [UIView setAnimationCurve:curve];
6553 [UIView setAnimationDuration:duration];
6554 [list_ setFrame:base];
6555 [UIView commitAnimations];
6558 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6559 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6562 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6563 [self resizeForKeyboardBounds:bounds duration:0];
6566 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6567 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6568 *curve = UIViewAnimationCurveEaseInOut;
6570 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6572 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6575 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6578 - (void) keyboardWillShow:(NSNotification *)notification {
6581 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6582 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6584 NSTimeInterval duration;
6585 UIViewAnimationCurve curve;
6586 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6588 CGRect kbframe = CGRectMake(Retina(center.x - bounds.size.width / 2), Retina(center.y - bounds.size.height / 2), bounds.size.width, bounds.size.height);
6589 UIViewController *base = self;
6590 while ([base parentOrPresentingViewController] != nil)
6591 base = [base parentOrPresentingViewController];
6592 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6593 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6595 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6596 intersection.size.height += CYStatusBarHeight();
6598 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6601 - (void) keyboardWillHide:(NSNotification *)notification {
6602 NSTimeInterval duration;
6603 UIViewAnimationCurve curve;
6604 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6606 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6609 - (void) viewWillAppear:(BOOL)animated {
6610 [super viewWillAppear:animated];
6612 [self resizeForKeyboardBounds:CGRectZero];
6613 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6614 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6617 - (void) viewWillDisappear:(BOOL)animated {
6618 [super viewWillDisappear:animated];
6620 [self resizeForKeyboardBounds:CGRectZero];
6621 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6622 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6625 - (void) viewDidAppear:(BOOL)animated {
6626 [super viewDidAppear:animated];
6627 [self deselectWithAnimation:animated];
6630 - (void) didSelectPackage:(Package *)package {
6631 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[[self referrerURL] absoluteString]] autorelease]);
6632 [view setDelegate:delegate_];
6633 [[self navigationController] pushViewController:view animated:YES];
6636 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6637 NSInteger count([sections_ count]);
6638 return count == 0 ? 1 : count;
6641 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6642 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6644 return [[sections_ objectAtIndex:section] name];
6647 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6648 if ([sections_ count] == 0)
6650 return [[sections_ objectAtIndex:section] count];
6653 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6654 @synchronized (database_) {
6655 if ([database_ era] != era_)
6658 Section *section([sections_ objectAtIndex:[path section]]);
6659 NSInteger row([path row]);
6660 Package *package([packages_ objectAtIndex:([section row] + row)]);
6661 return [[package retain] autorelease];
6664 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6665 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6667 cell = [[[PackageCell alloc] init] autorelease];
6669 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6670 [cell setPackage:package asSummary:[self isSummarized]];
6674 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6675 Package *package([self packageAtIndexPath:path]);
6676 package = [database_ packageWithName:[package id]];
6677 [self didSelectPackage:package];
6680 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6684 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6685 return offset_[index];
6688 - (void) updateHeight {
6689 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6692 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6693 if ((self = [super init]) != nil) {
6694 database_ = database;
6695 title_ = [title copy];
6696 [[self navigationItem] setTitle:title_];
6701 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
6702 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
6703 [self setView:view];
6705 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6706 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6707 [view addSubview:list_];
6709 // XXX: is 20 the most optimal number here?
6710 [list_ setSectionIndexMinimumDisplayRowCount:20];
6712 [(UITableView *) list_ setDataSource:self];
6713 [list_ setDelegate:self];
6715 [self updateHeight];
6718 - (void) releaseSubviews {
6727 [super releaseSubviews];
6730 - (void) setDelegate:(id)delegate {
6731 delegate_ = delegate;
6734 - (bool) shouldYield {
6738 - (bool) shouldBlock {
6742 - (NSMutableArray *) _reloadPackages {
6743 @synchronized (database_) {
6744 era_ = [database_ era];
6745 NSArray *packages([database_ packages]);
6747 return [NSMutableArray arrayWithArray:packages];
6750 - (void) _reloadData {
6751 if (reloading_ != 0) {
6756 NSMutableArray *packages;
6759 if ([self shouldYield]) {
6763 if (![self shouldBlock])
6766 hud = [delegate_ addProgressHUD];
6767 [hud setText:UCLocalize("LOADING")];
6771 packages = [self yieldToSelector:@selector(_reloadPackages)];
6774 [delegate_ removeProgressHUD:hud];
6775 } while (reloading_ == 2);
6777 packages = [self _reloadPackages];
6780 @synchronized (database_) {
6781 if (era_ != [database_ era])
6788 packages_ = packages;
6790 if ([self showsSections])
6791 sections_ = [self sectionsForPackages:packages];
6793 Section *section([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6794 [section setCount:[packages_ count]];
6795 sections_ = [NSArray arrayWithObject:section];
6798 [self updateHeight];
6800 _profile(PackageTable$reloadData$List)
6801 [(UITableView *) list_ setDataSource:self];
6809 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
6810 Section *prefix([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6811 size_t end([packages count]);
6813 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
6814 Section *section(prefix);
6816 thumbs_ = CollationThumbs_;
6817 offset_ = CollationOffset_;
6820 size_t offsets([CollationStarts_ count]);
6822 NSString *start([CollationStarts_ objectAtIndex:offset]);
6823 size_t length([start length]);
6825 for (size_t index(0); index != end; ++index) {
6827 Package *package([packages objectAtIndex:index]);
6828 NSString *name(PackageName(package, @selector(cyname)));
6830 //while ([start compare:name options:NSNumericSearch range:NSMakeRange(0, length) locale:CollationLocale_] != NSOrderedDescending) {
6831 while (StringNameCompare(start, name, length) != kCFCompareGreaterThan) {
6832 NSString *title([CollationTitles_ objectAtIndex:offset]);
6833 section = [[[Section alloc] initWithName:title row:index localize:NO] autorelease];
6834 [sections addObject:section];
6836 start = ++offset == offsets ? nil : [CollationStarts_ objectAtIndex:offset];
6839 length = [start length];
6843 [section addToCount];
6846 for (; offset != offsets; ++offset) {
6847 NSString *title([CollationTitles_ objectAtIndex:offset]);
6848 Section *section([[[Section alloc] initWithName:title row:end localize:NO] autorelease]);
6849 [sections addObject:section];
6852 if ([prefix count] != 0) {
6853 Section *suffix([sections lastObject]);
6854 [prefix setName:[suffix name]];
6855 [suffix setName:nil];
6856 [sections insertObject:prefix atIndex:(offsets - 1)];
6862 - (void) reloadData {
6865 if ([self shouldYield])
6866 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6871 - (void) resetCursor {
6872 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6875 - (void) clearData {
6876 [self updateHeight];
6878 [list_ setDataSource:nil];
6886 /* Filtered Package List Controller {{{ */
6887 typedef Function<bool, Package *> PackageFilter;
6888 typedef Function<void, NSMutableArray *> PackageSorter;
6889 @interface FilteredPackageListController : PackageListController {
6890 PackageFilter filter_;
6891 PackageSorter sorter_;
6894 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter;
6896 - (void) setFilter:(PackageFilter)filter;
6897 - (void) setSorter:(PackageSorter)sorter;
6901 @implementation FilteredPackageListController
6903 - (void) setFilter:(PackageFilter)filter {
6904 @synchronized (self) {
6908 - (void) setSorter:(PackageSorter)sorter {
6909 @synchronized (self) {
6913 - (NSMutableArray *) _reloadPackages {
6914 @synchronized (database_) {
6915 era_ = [database_ era];
6917 NSArray *packages([database_ packages]);
6918 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6920 PackageFilter filter;
6921 PackageSorter sorter;
6923 @synchronized (self) {
6928 _profile(PackageTable$reloadData$Filter)
6929 for (Package *package in packages)
6930 if (filter(package))
6931 [filtered addObject:package];
6939 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter {
6940 if ((self = [super initWithDatabase:database title:title]) != nil) {
6941 [self setFilter:filter];
6948 /* Home Controller {{{ */
6949 @interface HomeController : CydiaWebViewController {
6950 CFRunLoopRef runloop_;
6951 SCNetworkReachabilityRef reachability_;
6956 @implementation HomeController
6958 static void HomeControllerReachabilityCallback(SCNetworkReachabilityRef reachability, SCNetworkReachabilityFlags flags, void *info) {
6959 [(HomeController *) info dispatchEvent:@"CydiaReachabilityCallback"];
6963 if ((self = [super init]) != nil) {
6964 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6967 reachability_ = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "cydia.saurik.com");
6968 if (reachability_ != NULL) {
6969 SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
6970 SCNetworkReachabilitySetCallback(reachability_, HomeControllerReachabilityCallback, &context);
6972 CFRunLoopRef runloop(CFRunLoopGetCurrent());
6973 if (SCNetworkReachabilityScheduleWithRunLoop(reachability_, runloop, kCFRunLoopDefaultMode))
6980 if (reachability_ != NULL && runloop_ != NULL)
6981 SCNetworkReachabilityUnscheduleFromRunLoop(reachability_, runloop_, kCFRunLoopDefaultMode);
6985 - (NSURL *) navigationURL {
6986 return [NSURL URLWithString:@"cydia://home"];
6989 - (void) aboutButtonClicked {
6990 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6992 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6993 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6994 [alert setCancelButtonIndex:0];
6997 @"Copyright \u00a9 2008-2015\n"
7000 "Jay Freeman (saurik)\n"
7001 "saurik@saurik.com\n"
7002 "http://www.saurik.com/"
7008 - (UIBarButtonItem *) leftButton {
7009 return [[[UIBarButtonItem alloc]
7010 initWithTitle:UCLocalize("ABOUT")
7011 style:UIBarButtonItemStylePlain
7013 action:@selector(aboutButtonClicked)
7020 /* Cydia Navigation Controller Interface {{{ */
7021 @interface UINavigationController (Cydia)
7023 - (NSArray *) navigationURLCollection;
7024 - (void) unloadData;
7029 /* Cydia Tab Bar Controller {{{ */
7030 @interface CydiaTabBarController : CyteTabBarController <
7031 UITabBarControllerDelegate,
7034 _transient Database *database_;
7036 _H<UIActivityIndicatorView> indicator_;
7039 // XXX: ok, "updatedelegate_"?...
7040 _transient NSObject<CydiaDelegate> *updatedelegate_;
7043 - (NSArray *) navigationURLCollection;
7044 - (void) beginUpdate;
7049 @implementation CydiaTabBarController
7051 - (NSArray *) navigationURLCollection {
7052 NSMutableArray *items([NSMutableArray array]);
7054 // XXX: Should this deal with transient view controllers?
7055 for (id navigation in [self viewControllers]) {
7056 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
7058 [items addObject:stack];
7064 - (id) initWithDatabase:(Database *)database {
7065 if ((self = [super init]) != nil) {
7066 database_ = database;
7067 [self setDelegate:self];
7069 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteTiny] autorelease];
7070 [indicator_ setOrigin:CGPointMake(kCFCoreFoundationVersionNumber >= 800 ? 2 : 4, 2)];
7072 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7076 - (void) beginUpdate {
7080 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
7081 UITabBarItem *item([controller tabBarItem]);
7083 [item setBadgeValue:@""];
7084 UIView *badge(MSHookIvar<UIView *>([item view], "_badge"));
7086 [indicator_ startAnimating];
7087 [badge addSubview:indicator_];
7089 [updatedelegate_ retainNetworkActivityIndicator];
7093 detachNewThreadSelector:@selector(performUpdate)
7099 - (void) performUpdate {
7100 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
7102 SourceStatus status(self, database_);
7103 [database_ updateWithStatus:status];
7106 performSelectorOnMainThread:@selector(completeUpdate)
7114 - (void) stopUpdateWithSelector:(SEL)selector {
7116 [updatedelegate_ releaseNetworkActivityIndicator];
7118 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
7119 [[controller tabBarItem] setBadgeValue:nil];
7121 [indicator_ removeFromSuperview];
7122 [indicator_ stopAnimating];
7124 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
7127 - (void) completeUpdate {
7130 [self stopUpdateWithSelector:@selector(reloadData)];
7133 - (void) cancelUpdate {
7134 [self stopUpdateWithSelector:@selector(updateDataAndLoad)];
7137 - (void) cancelPressed {
7138 [self cancelUpdate];
7145 - (bool) isSourceCancelled {
7149 - (void) startSourceFetch:(NSString *)uri {
7152 - (void) stopSourceFetch:(NSString *)uri {
7155 - (void) setUpdateDelegate:(id)delegate {
7156 updatedelegate_ = delegate;
7162 /* Cydia Navigation Controller Implementation {{{ */
7163 @implementation UINavigationController (Cydia)
7165 - (NSArray *) navigationURLCollection {
7166 NSMutableArray *stack([NSMutableArray array]);
7168 for (CyteViewController *controller in [self viewControllers]) {
7169 NSString *url = [[controller navigationURL] absoluteString];
7171 [stack addObject:url];
7177 - (void) reloadData {
7180 UIViewController *visible([self visibleViewController]);
7182 [visible reloadData];
7184 // on the iPad, this view controller is ALSO visible. :(
7186 if (UIViewController *modal = [self modalViewController])
7187 if ([modal modalPresentationStyle] == UIModalPresentationFormSheet)
7188 if (UIViewController *top = [self topViewController])
7193 - (void) unloadData {
7194 for (CyteViewController *page in [self viewControllers])
7203 /* Cydia:// Protocol {{{ */
7204 @interface CydiaURLProtocol : NSURLProtocol {
7209 @implementation CydiaURLProtocol
7211 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7212 NSURL *url([request URL]);
7216 NSString *scheme([[url scheme] lowercaseString]);
7217 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7219 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7225 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7229 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7230 id<NSURLProtocolClient> client([self client]);
7232 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7234 NSData *data(UIImagePNGRepresentation(icon));
7236 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7237 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7238 [client URLProtocol:self didLoadData:data];
7239 [client URLProtocolDidFinishLoading:self];
7243 - (void) startLoading {
7244 id<NSURLProtocolClient> client([self client]);
7245 NSURLRequest *request([self request]);
7247 NSURL *url([request URL]);
7248 NSString *href([url absoluteString]);
7249 NSString *scheme([[url scheme] lowercaseString]);
7253 if ([scheme isEqualToString:@"cydia"])
7254 path = [href substringFromIndex:8];
7255 else if ([scheme isEqualToString:@"about"])
7256 path = [href substringFromIndex:12];
7257 else _assert(false);
7259 NSRange slash([path rangeOfString:@"/"]);
7262 if (slash.location == NSNotFound) {
7266 command = [path substringToIndex:slash.location];
7267 path = [path substringFromIndex:(slash.location + 1)];
7270 Database *database([Database sharedInstance]);
7273 else if ([command isEqualToString:@"application-icon"]) {
7276 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7280 if (icon == nil && $SBSCopyIconImagePNGDataForDisplayIdentifier != NULL) {
7281 NSData *data([$SBSCopyIconImagePNGDataForDisplayIdentifier(path) autorelease]);
7282 icon = [UIImage imageWithData:data];
7286 if (NSString *file = SBSCopyIconImagePathForDisplayIdentifier(path))
7287 icon = [UIImage imageAtPath:file];
7290 icon = [UIImage imageNamed:@"unknown.png"];
7292 [self _returnPNGWithImage:icon forRequest:request];
7293 } else if ([command isEqualToString:@"package-icon"]) {
7296 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7297 Package *package([database packageWithName:path]);
7301 UIImage *icon([package icon]);
7302 [self _returnPNGWithImage:icon forRequest:request];
7303 } else if ([command isEqualToString:@"uikit-image"]) {
7306 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7307 UIImage *icon(_UIImageWithName(path));
7308 [self _returnPNGWithImage:icon forRequest:request];
7309 } else if ([command isEqualToString:@"section-icon"]) {
7312 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7313 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7315 icon = [UIImage imageNamed:@"unknown.png"];
7316 [self _returnPNGWithImage:icon forRequest:request];
7318 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7322 - (void) stopLoading {
7328 /* Section Controller {{{ */
7329 @interface SectionController : FilteredPackageListController {
7331 _H<NSString> section_;
7334 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section;
7338 @implementation SectionController
7340 - (NSURL *) referrerURL {
7341 NSString *name(section_);
7342 name = name ?: @"*";
7343 NSString *key(key_);
7345 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sections/%@/%@", UI_, [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7348 - (NSURL *) navigationURL {
7349 NSString *name(section_);
7350 name = name ?: @"*";
7351 NSString *key(key_);
7353 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@/%@", [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7356 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section {
7359 title = UCLocalize("ALL_PACKAGES");
7360 else if (![section isEqual:@""])
7361 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(section) value:nil table:@"Sections"];
7363 title = UCLocalize("NO_SECTION");
7365 if ((self = [super initWithDatabase:database title:title]) != nil) {
7366 key_ = [source key];
7371 - (void) reloadData {
7372 Source *source([database_ sourceWithKey:key_]);
7373 _H<NSString> name(section_);
7375 [self setFilter:[=](Package *package) {
7376 NSString *section([package section]);
7380 section == nil && [name length] == 0 ||
7381 [name isEqualToString:section]
7384 [package source] == source
7385 ) && [package visible];
7393 /* Sections Controller {{{ */
7394 @interface SectionsController : CyteViewController <
7395 UITableViewDataSource,
7398 _transient Database *database_;
7400 _H<NSMutableArray> sections_;
7401 _H<NSMutableArray> filtered_;
7402 _H<UITableView, 2> list_;
7405 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7406 - (void) editButtonClicked;
7410 @implementation SectionsController
7412 - (NSURL *) navigationURL {
7413 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
7416 - (Source *) source {
7419 return [database_ sourceWithKey:key_];
7422 - (void) updateNavigationItem {
7423 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7424 if ([sections_ count] == 0) {
7425 [[self navigationItem] setRightBarButtonItem:nil];
7427 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7428 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7430 action:@selector(editButtonClicked)
7431 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7435 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7436 [super setEditing:editing animated:animated];
7441 [delegate_ updateData];
7443 [self updateNavigationItem];
7446 - (void) viewDidAppear:(BOOL)animated {
7447 [super viewDidAppear:animated];
7448 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7451 - (void) viewWillDisappear:(BOOL)animated {
7452 [super viewWillDisappear:animated];
7453 [self setEditing:NO];
7456 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7457 Section *section = nil;
7458 int index = [indexPath row];
7459 if (![self isEditing]) {
7462 section = [filtered_ objectAtIndex:index];
7464 section = [sections_ objectAtIndex:index];
7469 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7470 if ([self isEditing])
7471 return [sections_ count];
7473 return [filtered_ count] + 1;
7476 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7480 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7481 static NSString *reuseIdentifier = @"SectionCell";
7483 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7485 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7487 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7492 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7493 if ([self isEditing])
7496 Section *section = [self sectionAtIndexPath:indexPath];
7498 SectionController *controller = [[[SectionController alloc]
7499 initWithDatabase:database_
7500 source:[self source]
7501 section:[section name]
7503 [controller setDelegate:delegate_];
7505 [[self navigationController] pushViewController:controller animated:YES];
7509 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
7510 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7511 [list_ setRowHeight:46];
7512 [(UITableView *) list_ setDataSource:self];
7513 [list_ setDelegate:self];
7514 [self setView:list_];
7517 - (void) viewDidLoad {
7518 [super viewDidLoad];
7520 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7523 - (void) releaseSubviews {
7529 [super releaseSubviews];
7532 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7533 if ((self = [super init]) != nil) {
7534 database_ = database;
7535 key_ = [source key];
7539 - (void) reloadData {
7542 NSArray *packages = [database_ packages];
7544 sections_ = [NSMutableArray arrayWithCapacity:16];
7545 filtered_ = [NSMutableArray arrayWithCapacity:16];
7547 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7549 Source *source([self source]);
7552 for (Package *package in packages) {
7553 if (source != nil && [package source] != source)
7556 NSString *name([package section]);
7557 NSString *key(name == nil ? @"" : name);
7561 _profile(SectionsView$reloadData$Section)
7562 section = [sections objectForKey:key];
7563 if (section == nil) {
7564 _profile(SectionsView$reloadData$Section$Allocate)
7565 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7566 [sections setObject:section forKey:key];
7571 [section addToCount];
7573 _profile(SectionsView$reloadData$Filter)
7574 if (![package visible])
7582 [sections_ addObjectsFromArray:[sections allValues]];
7584 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7586 for (Section *section in (id) sections_) {
7587 size_t count([section row]);
7591 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7592 [section setCount:count];
7593 [filtered_ addObject:section];
7596 [self updateNavigationItem];
7601 - (void) editButtonClicked {
7602 [self setEditing:![self isEditing] animated:YES];
7608 /* Changes Controller {{{ */
7609 @interface ChangesController : FilteredPackageListController {
7613 - (id) initWithDatabase:(Database *)database;
7617 @implementation ChangesController
7619 - (NSURL *) referrerURL {
7620 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/changes/", UI_]];
7623 - (NSURL *) navigationURL {
7624 return [NSURL URLWithString:@"cydia://changes"];
7627 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7628 @synchronized (database_) {
7629 if ([database_ era] != era_)
7632 NSUInteger sectionIndex([path section]);
7633 if (sectionIndex >= [sections_ count])
7635 Section *section([sections_ objectAtIndex:sectionIndex]);
7636 NSInteger row([path row]);
7637 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7640 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7641 NSString *context([alert context]);
7643 if ([context isEqualToString:@"norefresh"])
7644 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7647 - (void) setLeftBarButtonItem {
7648 if ([delegate_ updating])
7649 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7650 initWithTitle:UCLocalize("CANCEL")
7651 style:UIBarButtonItemStyleDone
7653 action:@selector(cancelButtonClicked)
7654 ] autorelease] animated:YES];
7656 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7657 initWithTitle:UCLocalize("REFRESH")
7658 style:UIBarButtonItemStylePlain
7660 action:@selector(refreshButtonClicked)
7661 ] autorelease] animated:YES];
7664 - (void) refreshButtonClicked {
7665 if ([delegate_ requestUpdate])
7666 [self setLeftBarButtonItem];
7669 - (void) cancelButtonClicked {
7670 [delegate_ cancelUpdate];
7673 - (void) upgradeButtonClicked {
7674 [delegate_ distUpgrade];
7675 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7678 - (bool) shouldYield {
7682 - (bool) shouldBlock {
7686 - (void) useFilter {
7687 @synchronized (self) {
7688 [self setFilter:[](Package *package) {
7689 return [package upgradableAndEssential:YES] || [package visible];
7692 [self setSorter:[](NSMutableArray *packages) {
7693 [packages radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7697 - (id) initWithDatabase:(Database *)database {
7698 if ((self = [super initWithDatabase:database title:UCLocalize("CHANGES")]) != nil) {
7703 - (void) viewDidLoad {
7704 [super viewDidLoad];
7705 [self setLeftBarButtonItem];
7708 - (void) viewWillAppear:(BOOL)animated {
7709 [super viewWillAppear:animated];
7710 [self setLeftBarButtonItem];
7713 - (void) reloadData {
7714 [self setLeftBarButtonItem];
7718 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
7719 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
7721 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7722 Section *ignored = nil;
7723 Section *section = nil;
7727 bool unseens = false;
7729 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7731 for (size_t offset = 0, count = [packages count]; offset != count; ++offset) {
7732 Package *package = [packages objectAtIndex:offset];
7734 BOOL uae = [package upgradableAndEssential:YES];
7738 time_t seen([package seen]);
7740 if (section == nil || last != seen) {
7744 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7747 _profile(ChangesController$reloadData$Allocate)
7748 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7749 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7750 [sections addObject:section];
7754 [section addToCount];
7755 } else if ([package ignored]) {
7756 if (ignored == nil) {
7757 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7759 [ignored addToCount];
7762 [upgradable addToCount];
7767 CFRelease(formatter);
7770 Section *last = [sections lastObject];
7771 size_t count = [last count];
7772 [packages removeObjectsInRange:NSMakeRange([packages count] - count, count)];
7773 [sections removeLastObject];
7776 if ([ignored count] != 0)
7777 [sections insertObject:ignored atIndex:0];
7779 [sections insertObject:upgradable atIndex:0];
7783 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7784 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7785 style:UIBarButtonItemStylePlain
7787 action:@selector(upgradeButtonClicked)
7788 ] autorelease]) animated:YES];
7795 /* Search Controller {{{ */
7796 @interface SearchController : FilteredPackageListController <
7799 _H<UISearchBar, 1> search_;
7804 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7805 - (void) reloadData;
7809 @implementation SearchController
7811 - (NSURL *) referrerURL {
7812 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/search?q=%@", UI_, [([search_ text] ?: @"") stringByAddingPercentEscapesIncludingReserved]]];
7815 - (NSURL *) navigationURL {
7816 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7817 return [NSURL URLWithString:@"cydia://search"];
7819 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [[search_ text] stringByAddingPercentEscapesIncludingReserved]]];
7822 - (NSArray *) termsForQuery:(NSString *)query {
7823 NSMutableArray *terms([NSMutableArray arrayWithCapacity:2]);
7824 for (NSString *component in [query componentsSeparatedByString:@" "])
7825 if ([component length] != 0)
7826 [terms addObject:component];
7831 - (void) useSearch {
7832 _H<NSArray> query([self termsForQuery:[search_ text]]);
7835 @synchronized (self) {
7836 [self setFilter:[=](Package *package) {
7837 if (![package unfiltered])
7839 if (![package matches:query])
7844 [self setSorter:[](NSMutableArray *packages) {
7845 [packages radixSortUsingSelector:@selector(rank)];
7853 - (void) usePrefix:(NSString *)prefix {
7854 _H<NSString> query(prefix);
7857 @synchronized (self) {
7858 [self setFilter:[=](Package *package) {
7859 if ([query length] == 0)
7861 if (![package unfiltered])
7863 if ([[package name] compare:query options:MatchCompareOptions_ range:NSMakeRange(0, [query length])] != NSOrderedSame)
7868 [self setSorter:nullptr];
7874 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7876 [self usePrefix:[search_ text]];
7879 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7880 [search_ resignFirstResponder];
7884 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7885 [search_ setText:@""];
7886 [self searchBarButtonClicked:searchBar];
7889 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7890 [self searchBarButtonClicked:searchBar];
7893 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7894 [self usePrefix:text];
7897 - (bool) shouldYield {
7901 - (bool) shouldBlock {
7905 - (bool) isSummarized {
7909 - (bool) showsSections {
7913 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7914 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH")])) {
7915 search_ = [[[UISearchBar alloc] init] autorelease];
7916 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7917 [search_ setDelegate:self];
7919 UITextField *textField;
7920 if ([search_ respondsToSelector:@selector(searchField)])
7921 textField = [search_ searchField];
7923 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7925 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7926 [textField setEnablesReturnKeyAutomatically:NO];
7927 [[self navigationItem] setTitleView:textField];
7930 [search_ setText:query];
7935 - (void) viewDidAppear:(BOOL)animated {
7936 [super viewDidAppear:animated];
7938 if (!searchloaded_) {
7939 searchloaded_ = YES;
7940 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7941 [search_ layoutSubviews];
7944 if ([self isSummarized])
7945 [search_ becomeFirstResponder];
7948 - (void) reloadData {
7953 - (void) didSelectPackage:(Package *)package {
7954 [search_ resignFirstResponder];
7955 [super didSelectPackage:package];
7960 /* Package Settings Controller {{{ */
7961 @interface PackageSettingsController : CyteViewController <
7962 UITableViewDataSource,
7965 _transient Database *database_;
7967 _H<Package> package_;
7968 _H<UITableView, 2> table_;
7969 _H<UISwitch> subscribedSwitch_;
7970 _H<UISwitch> ignoredSwitch_;
7971 _H<UITableViewCell> subscribedCell_;
7972 _H<UITableViewCell> ignoredCell_;
7975 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7979 @implementation PackageSettingsController
7981 - (NSURL *) navigationURL {
7982 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
7985 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7986 if (package_ == nil)
7989 if ([package_ installed] == nil)
7995 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7996 if (package_ == nil)
7999 // both sections contain just one item right now.
8003 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8007 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8009 return UCLocalize("SHOW_ALL_CHANGES_EX");
8011 return UCLocalize("IGNORE_UPGRADES_EX");
8014 - (void) onSubscribed:(id)control {
8015 bool value([control isOn]);
8016 if (package_ == nil)
8018 if ([package_ setSubscribed:value])
8019 [delegate_ updateData];
8022 - (void) _updateIgnored {
8023 const char *package([name_ UTF8String]);
8024 bool on([ignoredSwitch_ isOn]);
8026 FILE *dpkg(popen("/usr/libexec/cydia/cydo --set-selections", "w"));
8027 fwrite(package, strlen(package), 1, dpkg);
8030 fwrite(" hold\n", 6, 1, dpkg);
8032 fwrite(" install\n", 9, 1, dpkg);
8037 - (void) onIgnored:(id)control {
8038 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
8039 [invocation setTarget:self];
8040 [invocation setSelector:@selector(_updateIgnored)];
8042 [delegate_ reloadDataWithInvocation:invocation];
8045 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8046 if (package_ == nil)
8049 switch ([indexPath section]) {
8050 case 0: return subscribedCell_;
8051 case 1: return ignoredCell_;
8060 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8061 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8062 [self setView:view];
8064 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
8065 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8066 [(UITableView *) table_ setDataSource:self];
8067 [table_ setDelegate:self];
8068 [view addSubview:table_];
8070 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
8071 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
8072 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
8074 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
8075 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
8076 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
8078 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
8079 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
8080 [subscribedCell_ setAccessoryView:subscribedSwitch_];
8081 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
8083 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
8084 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
8085 [ignoredCell_ setAccessoryView:ignoredSwitch_];
8086 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
8089 - (void) viewDidLoad {
8090 [super viewDidLoad];
8092 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
8095 - (void) releaseSubviews {
8097 subscribedCell_ = nil;
8099 ignoredSwitch_ = nil;
8100 subscribedSwitch_ = nil;
8102 [super releaseSubviews];
8105 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
8106 if ((self = [super init]) != nil) {
8107 database_ = database;
8112 - (void) reloadData {
8115 package_ = [database_ packageWithName:name_];
8117 if (package_ != nil) {
8118 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
8119 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
8120 } // XXX: what now, G?
8122 [table_ reloadData];
8128 /* Installed Controller {{{ */
8129 @interface InstalledController : FilteredPackageListController {
8133 - (id) initWithDatabase:(Database *)database;
8134 - (void) queueStatusDidChange;
8138 @implementation InstalledController
8140 - (NSURL *) referrerURL {
8141 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/installed/", UI_]];
8144 - (NSURL *) navigationURL {
8145 return [NSURL URLWithString:@"cydia://installed"];
8148 - (void) useRecent {
8151 @synchronized (self) {
8152 [self setFilter:[](Package *package) {
8153 return ![package uninstalled] && package->role_ < 7;
8156 [self setSorter:[](NSMutableArray *packages) {
8157 [packages radixSortUsingSelector:@selector(recent)];
8161 - (void) useFilter:(UISegmentedControl *)segmented {
8162 NSInteger selected([segmented selectedSegmentIndex]);
8164 return [self useRecent];
8165 bool simple(selected == 0);
8168 @synchronized (self) {
8169 [self setFilter:[=](Package *package) {
8170 return ![package uninstalled] && package->role_ <= (simple ? 1 : 3);
8173 [self setSorter:nullptr];
8176 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
8178 return [super sectionsForPackages:packages];
8180 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterLongStyle, kCFDateFormatterNoStyle));
8182 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
8183 Section *section(nil);
8186 for (size_t offset(0), count([packages count]); offset != count; ++offset) {
8187 Package *package([packages objectAtIndex:offset]);
8189 time_t upgraded([package upgraded]);
8190 if (upgraded < 1168364520)
8193 upgraded -= upgraded % (60 * 60 * 24);
8195 if (section == nil || upgraded != last) {
8200 continue; // XXX: name = UCLocalize("...");
8202 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:upgraded]);
8206 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
8207 [sections addObject:section];
8210 [section addToCount];
8213 CFRelease(formatter);
8217 - (id) initWithDatabase:(Database *)database {
8218 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED")]) != nil) {
8219 UISegmentedControl *segmented([[[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:UCLocalize("USER"), UCLocalize("EXPERT"), UCLocalize("RECENT"), nil]] autorelease]);
8220 [segmented setSelectedSegmentIndex:0];
8221 [segmented setSegmentedControlStyle:UISegmentedControlStyleBar];
8222 [[self navigationItem] setTitleView:segmented];
8224 [segmented addTarget:self action:@selector(modeChanged:) forEvents:UIControlEventValueChanged];
8225 [self useFilter:segmented];
8227 [self queueStatusDidChange];
8232 - (void) queueButtonClicked {
8237 - (void) queueStatusDidChange {
8240 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8241 initWithTitle:UCLocalize("QUEUE")
8242 style:UIBarButtonItemStyleDone
8244 action:@selector(queueButtonClicked)
8247 [[self navigationItem] setRightBarButtonItem:nil];
8252 - (void) modeChanged:(UISegmentedControl *)segmented {
8253 [self useFilter:segmented];
8260 /* Source Cell {{{ */
8261 @interface SourceCell : CyteTableViewCell <
8262 CyteTableViewCellDelegate,
8265 _H<Source, 1> source_;
8268 _H<NSString> origin_;
8269 _H<NSString> label_;
8270 _H<UIActivityIndicatorView> indicator_;
8273 - (void) setSource:(Source *)source;
8274 - (void) setFetch:(NSNumber *)fetch;
8278 @implementation SourceCell
8280 - (void) _setImage:(NSArray *)data {
8281 if ([url_ isEqual:[data objectAtIndex:0]]) {
8282 icon_ = [data objectAtIndex:1];
8283 [content_ setNeedsDisplay];
8287 - (void) _setSource:(NSURL *) url {
8288 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8290 if (NSData *data = [NSURLConnection
8291 sendSynchronousRequest:[NSURLRequest
8293 cachePolicy:NSURLRequestUseProtocolCachePolicy
8297 returningResponse:NULL
8300 if (UIImage *image = [UIImage imageWithData:data])
8301 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
8306 - (void) setSource:(Source *)source {
8308 [source_ setDelegate:self];
8310 [self setFetch:[NSNumber numberWithBool:[source_ fetch]]];
8312 icon_ = [UIImage imageNamed:@"unknown.png"];
8314 origin_ = [source name];
8315 label_ = [source rooturi];
8317 [content_ setNeedsDisplay];
8319 url_ = [source iconURL];
8320 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
8323 - (void) setAllSource {
8325 [indicator_ stopAnimating];
8327 icon_ = [UIImage imageNamed:@"folder.png"];
8328 origin_ = UCLocalize("ALL_SOURCES");
8329 label_ = UCLocalize("ALL_SOURCES_EX");
8330 [content_ setNeedsDisplay];
8333 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8334 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8335 UIView *content([self contentView]);
8336 CGRect bounds([content bounds]);
8338 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8339 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8340 [content_ setBackgroundColor:[UIColor whiteColor]];
8341 [content addSubview:content_];
8343 [content_ setDelegate:self];
8344 [content_ setOpaque:YES];
8346 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGraySmall] autorelease];
8347 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin];// | UIViewAutoresizingFlexibleBottomMargin];
8348 [content addSubview:indicator_];
8350 [[content_ layer] setContentsGravity:kCAGravityTopLeft];
8354 - (void) layoutSubviews {
8355 [super layoutSubviews];
8357 UIView *content([self contentView]);
8358 CGRect bounds([content bounds]);
8360 CGRect frame([indicator_ frame]);
8361 frame.origin.x = bounds.size.width - frame.size.width;
8362 frame.origin.y = Retina((bounds.size.height - frame.size.height) / 2);
8364 if (kCFCoreFoundationVersionNumber < 800)
8365 frame.origin.x -= 8;
8366 [indicator_ setFrame:frame];
8369 - (NSString *) accessibilityLabel {
8373 - (void) drawContentRect:(CGRect)rect {
8374 bool highlighted(highlighted_);
8375 float width(rect.size.width);
8379 rect.size = [(UIImage *) icon_ size];
8381 while (rect.size.width > 32 || rect.size.height > 32) {
8382 rect.size.width /= 2;
8383 rect.size.height /= 2;
8386 rect.origin.x = 26 - rect.size.width / 2;
8387 rect.origin.y = 26 - rect.size.height / 2;
8389 [icon_ drawInRect:Retina(rect)];
8392 if (highlighted && kCFCoreFoundationVersionNumber < 800)
8397 [origin_ drawAtPoint:CGPointMake(52, 8) forWidth:(width - 49) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
8401 [label_ drawAtPoint:CGPointMake(52, 29) forWidth:(width - 49) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
8404 - (void) setFetch:(NSNumber *)fetch {
8405 if ([fetch boolValue])
8406 [indicator_ startAnimating];
8408 [indicator_ stopAnimating];
8413 /* Sources Controller {{{ */
8414 @interface SourcesController : CyteViewController <
8415 UITableViewDataSource,
8418 _transient Database *database_;
8421 _H<UITableView, 2> list_;
8422 _H<NSMutableArray> sources_;
8426 _H<UIProgressHUD> hud_;
8429 NSURLConnection *trivial_bz2_;
8430 NSURLConnection *trivial_gz_;
8435 - (id) initWithDatabase:(Database *)database;
8436 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated;
8440 @implementation SourcesController
8442 - (void) _releaseConnection:(NSURLConnection *)connection {
8443 if (connection != nil) {
8444 [connection cancel];
8445 //[connection setDelegate:nil];
8446 [connection release];
8451 [self _releaseConnection:trivial_gz_];
8452 [self _releaseConnection:trivial_bz2_];
8457 - (NSURL *) navigationURL {
8458 return [NSURL URLWithString:@"cydia://sources"];
8461 - (void) viewDidAppear:(BOOL)animated {
8462 [super viewDidAppear:animated];
8463 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8466 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8470 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8472 return UCLocalize("INDIVIDUAL_SOURCES");
8476 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8479 case 1: return [sources_ count];
8484 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8485 @synchronized (database_) {
8486 if ([database_ era] != era_)
8488 if ([indexPath section] != 1)
8490 NSUInteger index([indexPath row]);
8491 if (index >= [sources_ count])
8493 return [sources_ objectAtIndex:index];
8496 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8497 static NSString *cellIdentifier = @"SourceCell";
8499 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8500 if (cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8501 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8503 Source *source([self sourceAtIndexPath:indexPath]);
8505 [cell setAllSource];
8507 [cell setSource:source];
8512 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8513 SectionsController *controller([[[SectionsController alloc]
8514 initWithDatabase:database_
8515 source:[self sourceAtIndexPath:indexPath]
8518 [controller setDelegate:delegate_];
8519 [[self navigationController] pushViewController:controller animated:YES];
8522 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8523 if ([indexPath section] != 1)
8525 Source *source = [self sourceAtIndexPath:indexPath];
8526 return [source record] != nil;
8529 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8530 _assert([indexPath section] == 1);
8531 if (editingStyle == UITableViewCellEditingStyleDelete) {
8532 Source *source = [self sourceAtIndexPath:indexPath];
8533 if (source == nil) return;
8535 [Sources_ removeObjectForKey:[source key]];
8537 [delegate_ _saveConfig];
8538 [delegate_ reloadDataWithInvocation:nil];
8542 - (void) tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath {
8543 [self updateButtonsForEditingStatusAnimated:YES];
8547 [delegate_ addTrivialSource:href_];
8550 [delegate_ syncData];
8553 - (NSString *) getWarning {
8554 NSString *href(href_);
8555 NSRange colon([href rangeOfString:@"://"]);
8556 if (colon.location != NSNotFound)
8557 href = [href substringFromIndex:(colon.location + 3)];
8558 href = [href stringByAddingPercentEscapes];
8559 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8561 NSURL *url([NSURL URLWithString:href]);
8563 NSStringEncoding encoding;
8564 NSError *error(nil);
8566 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8567 return [warning length] == 0 ? nil : warning;
8571 - (void) _endConnection:(NSURLConnection *)connection {
8572 // XXX: the memory management in this method is horribly awkward
8574 NSURLConnection **field = NULL;
8575 if (connection == trivial_bz2_)
8576 field = &trivial_bz2_;
8577 else if (connection == trivial_gz_)
8578 field = &trivial_gz_;
8579 _assert(field != NULL);
8580 [connection release];
8584 trivial_bz2_ == nil &&
8587 NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil);
8589 [delegate_ releaseNetworkActivityIndicator];
8591 [delegate_ removeProgressHUD:hud_];
8595 if (warning != nil) {
8596 UIAlertView *alert = [[[UIAlertView alloc]
8597 initWithTitle:UCLocalize("SOURCE_WARNING")
8600 cancelButtonTitle:UCLocalize("CANCEL")
8602 UCLocalize("ADD_ANYWAY"),
8606 [alert setContext:@"warning"];
8607 [alert setNumberOfRows:1];
8610 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
8616 } else if (error_ != nil) {
8617 UIAlertView *alert = [[[UIAlertView alloc]
8618 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8619 message:[error_ localizedDescription]
8621 cancelButtonTitle:UCLocalize("OK")
8622 otherButtonTitles:nil
8625 [alert setContext:@"urlerror"];
8630 UIAlertView *alert = [[[UIAlertView alloc]
8631 initWithTitle:UCLocalize("NOT_REPOSITORY")
8632 message:UCLocalize("NOT_REPOSITORY_EX")
8634 cancelButtonTitle:UCLocalize("OK")
8635 otherButtonTitles:nil
8638 [alert setContext:@"trivial"];
8648 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8649 switch ([response statusCode]) {
8655 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8656 lprintf("connection:\"%s\" didFailWithError:\"%s\"\n", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8658 [self _endConnection:connection];
8661 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8662 [self _endConnection:connection];
8665 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8666 NSURL *url([NSURL URLWithString:href]);
8668 NSMutableURLRequest *request = [NSMutableURLRequest
8670 cachePolicy:NSURLRequestUseProtocolCachePolicy
8674 [request setHTTPMethod:method];
8676 if (Machine_ != NULL)
8677 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8679 if (UniqueID_ != nil)
8680 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8682 if ([url isCydiaSecure]) {
8683 if (UniqueID_ != nil)
8684 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
8687 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8690 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8691 NSString *context([alert context]);
8693 if ([context isEqualToString:@"source"]) {
8696 NSString *href = [[alert textField] text];
8697 href = VerifySource(href);
8702 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8703 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8707 // XXX: this is stupid
8708 hud_ = [delegate_ addProgressHUD];
8709 [hud_ setText:UCLocalize("VERIFYING_URL")];
8710 [delegate_ retainNetworkActivityIndicator];
8719 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8720 } else if ([context isEqualToString:@"trivial"])
8721 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8722 else if ([context isEqualToString:@"urlerror"])
8723 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8724 else if ([context isEqualToString:@"warning"]) {
8727 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
8736 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8740 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated {
8741 BOOL editing([list_ isEditing]);
8744 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8745 initWithTitle:UCLocalize("ADD")
8746 style:UIBarButtonItemStylePlain
8748 action:@selector(addButtonClicked)
8749 ] autorelease] animated:animated];
8750 else if ([delegate_ updating])
8751 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8752 initWithTitle:UCLocalize("CANCEL")
8753 style:UIBarButtonItemStyleDone
8755 action:@selector(cancelButtonClicked)
8756 ] autorelease] animated:animated];
8758 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8759 initWithTitle:UCLocalize("REFRESH")
8760 style:UIBarButtonItemStylePlain
8762 action:@selector(refreshButtonClicked)
8763 ] autorelease] animated:animated];
8765 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8766 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8767 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8769 action:@selector(editButtonClicked)
8770 ] autorelease] animated:animated];
8774 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease];
8775 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8776 [list_ setRowHeight:53];
8777 [(UITableView *) list_ setDataSource:self];
8778 [list_ setDelegate:self];
8779 [self setView:list_];
8782 - (void) viewDidLoad {
8783 [super viewDidLoad];
8785 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8786 [self updateButtonsForEditingStatusAnimated:NO];
8789 - (void) viewWillAppear:(BOOL)animated {
8790 [super viewWillAppear:animated];
8792 [list_ setEditing:NO];
8793 [self updateButtonsForEditingStatusAnimated:NO];
8796 - (void) releaseSubviews {
8801 [super releaseSubviews];
8804 - (id) initWithDatabase:(Database *)database {
8805 if ((self = [super init]) != nil) {
8806 database_ = database;
8810 - (void) reloadData {
8812 [self updateButtonsForEditingStatusAnimated:YES];
8814 @synchronized (database_) {
8815 era_ = [database_ era];
8817 sources_ = [NSMutableArray arrayWithCapacity:16];
8818 [sources_ addObjectsFromArray:[database_ sources]];
8820 [sources_ sortUsingSelector:@selector(compareByName:)];
8823 int count([sources_ count]);
8825 for (int i = 0; i != count; i++) {
8826 if ([[sources_ objectAtIndex:i] record] == nil)
8834 - (void) showAddSourcePrompt {
8835 UIAlertView *alert = [[[UIAlertView alloc]
8836 initWithTitle:UCLocalize("ENTER_APT_URL")
8839 cancelButtonTitle:UCLocalize("CANCEL")
8841 UCLocalize("ADD_SOURCE"),
8845 [alert setContext:@"source"];
8847 [alert setNumberOfRows:1];
8848 [alert addTextFieldWithValue:@"http://" label:@""];
8850 UITextInputTraits *traits = [[alert textField] textInputTraits];
8851 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8852 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8853 [traits setKeyboardType:UIKeyboardTypeURL];
8854 // XXX: UIReturnKeyDone
8855 [traits setReturnKeyType:UIReturnKeyNext];
8860 - (void) addButtonClicked {
8861 [self showAddSourcePrompt];
8864 - (void) refreshButtonClicked {
8865 if ([delegate_ requestUpdate])
8866 [self updateButtonsForEditingStatusAnimated:YES];
8869 - (void) cancelButtonClicked {
8870 [delegate_ cancelUpdate];
8873 - (void) editButtonClicked {
8874 [list_ setEditing:![list_ isEditing] animated:YES];
8875 [self updateButtonsForEditingStatusAnimated:YES];
8881 /* Stash Controller {{{ */
8882 @interface StashController : CyteViewController {
8883 _H<UIActivityIndicatorView> spinner_;
8884 _H<UILabel> status_;
8885 _H<UILabel> caption_;
8890 @implementation StashController
8893 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8894 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8895 [self setView:view];
8897 [view setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8899 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8900 CGRect spinrect = [spinner_ frame];
8901 spinrect.origin.x = Retina([[self view] frame].size.width / 2 - spinrect.size.width / 2);
8902 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8903 [spinner_ setFrame:spinrect];
8904 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8905 [view addSubview:spinner_];
8906 [spinner_ startAnimating];
8909 captrect.size.width = [[self view] frame].size.width;
8910 captrect.size.height = 40.0f;
8911 captrect.origin.x = 0;
8912 captrect.origin.y = Retina([[self view] frame].size.height / 2 - captrect.size.height * 2);
8913 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8914 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8915 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8916 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8917 [caption_ setTextColor:[UIColor whiteColor]];
8918 [caption_ setBackgroundColor:[UIColor clearColor]];
8919 [caption_ setShadowColor:[UIColor blackColor]];
8920 [caption_ setTextAlignment:NSTextAlignmentCenter];
8921 [view addSubview:caption_];
8924 statusrect.size.width = [[self view] frame].size.width;
8925 statusrect.size.height = 30.0f;
8926 statusrect.origin.x = 0;
8927 statusrect.origin.y = Retina([[self view] frame].size.height / 2 - statusrect.size.height);
8928 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8929 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8930 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8931 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8932 [status_ setTextColor:[UIColor whiteColor]];
8933 [status_ setBackgroundColor:[UIColor clearColor]];
8934 [status_ setShadowColor:[UIColor blackColor]];
8935 [status_ setTextAlignment:NSTextAlignmentCenter];
8936 [view addSubview:status_];
8939 - (void) releaseSubviews {
8944 [super releaseSubviews];
8950 @interface CYURLCache : SDURLCache {
8955 @implementation CYURLCache
8957 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8960 else if ([event isEqualToString:@"no-cache"])
8962 else if ([event isEqualToString:@"store"])
8964 else if ([event isEqualToString:@"invalid"])
8966 else if ([event isEqualToString:@"memory"])
8968 else if ([event isEqualToString:@"disk"])
8970 else if ([event isEqualToString:@"miss"])
8973 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8977 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
8978 if (NSURLResponse *response = [cached response])
8979 if (NSString *mime = [response MIMEType])
8980 if ([mime isEqualToString:@"text/cache-manifest"]) {
8981 NSURL *url([response URL]);
8984 NSLog(@"###: %@", [url absoluteString]);
8987 @synchronized (HostConfig_) {
8988 [CachedURLs_ addObject:url];
8992 [super storeCachedResponse:cached forRequest:request];
8995 - (void) createDiskCachePath {
8996 [super createDiskCachePath];
9001 @interface Cydia : UIApplication <
9002 ConfirmationControllerDelegate,
9006 _H<UIWindow> window_;
9007 _H<CydiaTabBarController> tabbar_;
9008 _H<CyteTabBarController> emulated_;
9009 _H<AppCacheController> appcache_;
9011 _H<NSMutableArray> essential_;
9012 _H<NSMutableArray> broken_;
9014 Database *database_;
9016 _H<NSURL> starturl_;
9021 _H<StashController> stash_;
9030 @implementation Cydia
9032 - (void) lockSuspend {
9033 if (locked_++ == 0) {
9034 if ($SBSSetInterceptsMenuButtonForever != NULL)
9035 (*$SBSSetInterceptsMenuButtonForever)(true);
9037 [self setIdleTimerDisabled:YES];
9041 - (void) unlockSuspend {
9042 if (--locked_ == 0) {
9043 [self setIdleTimerDisabled:NO];
9045 if ($SBSSetInterceptsMenuButtonForever != NULL)
9046 (*$SBSSetInterceptsMenuButtonForever)(false);
9050 - (void) beginUpdate {
9051 [tabbar_ beginUpdate];
9054 - (void) cancelUpdate {
9055 [tabbar_ cancelUpdate];
9058 - (bool) requestUpdate {
9059 if (IsReachable("cydia.saurik.com")) {
9063 UIAlertView *alert = [[[UIAlertView alloc]
9064 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("REFRESH")]
9065 message:@"Host Unreachable" // XXX: Localize
9067 cancelButtonTitle:UCLocalize("OK")
9068 otherButtonTitles:nil
9071 [alert setContext:@"norefresh"];
9079 return [tabbar_ updating];
9083 if ([broken_ count] != 0) {
9084 int count = [broken_ count];
9086 UIAlertView *alert = [[[UIAlertView alloc]
9087 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
9088 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
9090 cancelButtonTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("FORCIBLY_CLEAR"), UCLocalize("UNSAFE")]
9092 UCLocalize("TEMPORARY_IGNORE"),
9096 [alert setContext:@"fixhalf"];
9097 [alert setNumberOfRows:2];
9099 } else if (!Ignored_ && [essential_ count] != 0) {
9100 int count = [essential_ count];
9102 UIAlertView *alert = [[[UIAlertView alloc]
9103 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
9104 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
9106 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
9108 UCLocalize("UPGRADE_ESSENTIAL"),
9109 UCLocalize("COMPLETE_UPGRADE"),
9113 [alert setContext:@"upgrade"];
9118 - (void) returnToCydia {
9122 - (void) reloadSpringBoard {
9123 if (kCFCoreFoundationVersionNumber >= 700) // XXX: iOS 6.x
9124 system("/bin/launchctl stop com.apple.backboardd");
9126 system("/bin/launchctl stop com.apple.SpringBoard");
9128 system("/usr/bin/killall backboardd SpringBoard");
9131 - (void) _saveConfig {
9132 SaveConfig(database_);
9135 // Navigation controller for the queuing badge.
9136 - (UINavigationController *) queueNavigationController {
9137 NSArray *controllers = [tabbar_ viewControllers];
9138 return [controllers objectAtIndex:3];
9141 - (void) unloadData {
9142 [tabbar_ unloadData];
9145 - (void) _updateData {
9149 UINavigationController *navigation = [self queueNavigationController];
9151 id queuedelegate = nil;
9152 if ([[navigation viewControllers] count] > 0)
9153 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9155 [queuedelegate queueStatusDidChange];
9156 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9159 - (void) _refreshIfPossible {
9160 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9162 NSDate *update([[NSDictionary dictionaryWithContentsOfFile:@ CacheState_] objectForKey:@"LastUpdate"]);
9164 bool recently = false;
9165 if (update != nil) {
9166 NSTimeInterval interval([update timeIntervalSinceNow]);
9167 if (interval > -(15*60))
9171 // Don't automatic refresh if:
9172 // - We already refreshed recently.
9173 // - We already auto-refreshed this launch.
9174 // - Auto-refresh is disabled.
9175 // - Cydia's server is not reachable
9176 if (recently || loaded_ || ManualRefresh || !IsReachable("cydia.saurik.com")) {
9177 // If we are cancelling, we need to make sure it knows it's already loaded.
9180 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9182 // We are going to load, so remember that.
9185 [tabbar_ performSelectorOnMainThread:@selector(beginUpdate) withObject:nil waitUntilDone:NO];
9191 - (void) refreshIfPossible {
9192 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
9195 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9196 _profile(reloadDataWithInvocation)
9197 @synchronized (self) {
9198 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9200 [hud setText:UCLocalize("RELOADING_DATA")];
9202 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9206 [essential_ removeAllObjects];
9207 [broken_ removeAllObjects];
9209 _profile(reloadDataWithInvocation$Essential)
9210 NSArray *packages([database_ packages]);
9211 for (Package *package in packages) {
9213 [broken_ addObject:package];
9214 if ([package upgradableAndEssential:YES] && ![package ignored]) {
9215 if ([package essential] && [package installed] != nil)
9216 [essential_ addObject:package];
9222 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9225 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9226 [changesItem setBadgeValue:badge];
9227 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9228 [self setApplicationIconBadgeNumber:changes];
9231 [changesItem setBadgeValue:nil];
9232 [changesItem setAnimatedBadge:NO];
9233 [self setApplicationIconBadgeNumber:0];
9240 [self removeProgressHUD:hud];
9247 - (void) updateData {
9251 - (void) updateDataAndLoad {
9253 if ([database_ progressDelegate] == nil)
9259 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9262 - (void) disemulate {
9263 if (emulated_ == nil)
9266 if ([window_ respondsToSelector:@selector(setRootViewController:)])
9267 [window_ setRootViewController:tabbar_];
9269 [window_ addSubview:[tabbar_ view]];
9270 [[emulated_ view] removeFromSuperview];
9274 [window_ setUserInteractionEnabled:YES];
9277 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9278 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9280 UIViewController *parent;
9281 if (emulated_ == nil)
9291 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9292 [parent presentModalViewController:navigation animated:YES];
9295 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9296 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9298 if (navigation != nil)
9299 [navigation pushViewController:progress animated:YES];
9301 [self presentModalViewController:progress force:YES];
9303 [progress invoke:invocation withTitle:title];
9307 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9308 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9311 - (void) repairWithInvocation:(NSInvocation *)invocation {
9313 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9317 - (void) repairWithSelector:(SEL)selector {
9318 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9321 - (void) reloadData {
9322 [self reloadDataWithInvocation:nil];
9323 if ([database_ progressDelegate] == nil)
9329 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9332 - (void) addSource:(NSDictionary *) source {
9333 CydiaAddSource(source);
9336 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9337 CydiaAddSource(href, distribution, sections);
9340 // XXX: this method should not return anything
9341 - (BOOL) addTrivialSource:(NSString *)href {
9342 CydiaAddSource(href, @"./");
9347 pkgProblemResolver *resolver = [database_ resolver];
9349 resolver->InstallProtect();
9350 if (!resolver->Resolve(true))
9355 // XXX: this is a really crappy way of doing this.
9356 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9357 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9358 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9359 if ([tabbar_ updating])
9360 [tabbar_ cancelUpdate];
9362 if (![database_ prepare])
9365 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9366 [page setDelegate:self];
9367 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9370 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9371 [tabbar_ presentModalViewController:confirm_ animated:YES];
9377 @synchronized (self) {
9382 - (void) clearPackage:(Package *)package {
9383 @synchronized (self) {
9390 - (void) installPackages:(NSArray *)packages {
9391 @synchronized (self) {
9392 for (Package *package in packages)
9399 - (void) installPackage:(Package *)package {
9400 @synchronized (self) {
9407 - (void) removePackage:(Package *)package {
9408 @synchronized (self) {
9415 - (void) distUpgrade {
9416 @synchronized (self) {
9417 if (![database_ upgrade])
9425 system("/usr/bin/uicache");
9430 UIProgressHUD *hud([self addProgressHUD]);
9431 [hud setText:UCLocalize("LOADING")];
9432 [self yieldToSelector:@selector(_uicache)];
9433 [self removeProgressHUD:hud];
9437 [database_ perform];
9438 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9439 [self performSelectorOnMainThread:@selector(uicache) withObject:nil waitUntilDone:YES];
9442 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9445 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9446 [self unlockSuspend];
9449 - (void) retainNetworkActivityIndicator {
9450 if (activity_++ == 0)
9451 [self setNetworkActivityIndicatorVisible:YES];
9454 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9458 - (void) releaseNetworkActivityIndicator {
9459 if (--activity_ == 0)
9460 [self setNetworkActivityIndicatorVisible:NO];
9463 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9468 - (void) cancelAndClear:(bool)clear {
9469 @synchronized (self) {
9481 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9482 NSString *context([alert context]);
9484 if ([context isEqualToString:@"conffile"]) {
9485 FILE *input = [database_ input];
9486 if (button == [alert cancelButtonIndex])
9487 fprintf(input, "N\n");
9488 else if (button == [alert firstOtherButtonIndex])
9489 fprintf(input, "Y\n");
9492 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9493 } else if ([context isEqualToString:@"fixhalf"]) {
9494 if (button == [alert cancelButtonIndex]) {
9495 @synchronized (self) {
9496 for (Package *broken in (id) broken_) {
9498 NSString *id(ShellEscape([broken id]));
9499 system([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /bin/rm -f"
9500 " /var/lib/dpkg/info/%@.prerm"
9501 " /var/lib/dpkg/info/%@.postrm"
9502 " /var/lib/dpkg/info/%@.preinst"
9503 " /var/lib/dpkg/info/%@.postinst"
9504 " /var/lib/dpkg/info/%@.extrainst_"
9505 "", id, id, id, id, id] UTF8String]);
9511 } else if (button == [alert firstOtherButtonIndex]) {
9512 [broken_ removeAllObjects];
9516 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9517 } else if ([context isEqualToString:@"upgrade"]) {
9518 if (button == [alert firstOtherButtonIndex]) {
9519 @synchronized (self) {
9520 for (Package *essential in (id) essential_)
9521 [essential install];
9526 } else if (button == [alert firstOtherButtonIndex] + 1) {
9528 } else if (button == [alert cancelButtonIndex]) {
9532 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9536 - (void) system:(NSString *)command {
9537 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9540 system([command UTF8String]);
9546 - (void) applicationWillSuspend {
9548 [super applicationWillSuspend];
9551 - (BOOL) isSafeToSuspend {
9554 NSLog(@"isSafeToSuspend: locked_ != 0");
9559 if ([tabbar_ modalViewController] != nil)
9562 // Use external process status API internally.
9563 // This is probably a really bad idea.
9564 // XXX: what is the point of this? does this solve anything at all?
9565 uint64_t status = 0;
9567 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9568 notify_get_state(notify_token, &status);
9569 notify_cancel(notify_token);
9574 NSLog(@"isSafeToSuspend: status != 0");
9580 NSLog(@"isSafeToSuspend: -> true");
9585 - (void) suspendReturningToLastApp:(BOOL)returning {
9586 if ([self isSafeToSuspend])
9587 [super suspendReturningToLastApp:returning];
9591 if ([self isSafeToSuspend])
9595 - (void) applicationSuspend {
9596 if ([self isSafeToSuspend])
9597 [super applicationSuspend];
9600 - (void) applicationSuspend:(__GSEvent *)event {
9601 if ([self isSafeToSuspend])
9602 [super applicationSuspend:event];
9605 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9606 if ([self isSafeToSuspend])
9607 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9610 - (void) _setSuspended:(BOOL)value {
9611 if ([self isSafeToSuspend])
9612 [super _setSuspended:value];
9615 - (UIProgressHUD *) addProgressHUD {
9616 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9617 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9619 [window_ setUserInteractionEnabled:NO];
9621 UIViewController *target(tabbar_);
9622 if (UIViewController *modal = [target modalViewController])
9625 [hud showInView:[target view]];
9631 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9632 [self unlockSuspend];
9634 [hud removeFromSuperview];
9635 [window_ setUserInteractionEnabled:YES];
9638 - (CyteViewController *) pageForPackage:(NSString *)name withReferrer:(NSString *)referrer {
9639 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name withReferrer:referrer] autorelease];
9642 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external withReferrer:(NSString *)referrer {
9643 NSString *scheme([[url scheme] lowercaseString]);
9644 if ([[url absoluteString] length] <= [scheme length] + 3)
9646 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9647 NSArray *components([path componentsSeparatedByString:@"/"]);
9649 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"]) {
9650 CyteViewController *controller([self pageForPackage:[components objectAtIndex:1] withReferrer:referrer]);
9651 if (controller != nil)
9652 [controller setDelegate:self];
9656 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9659 NSString *base([components objectAtIndex:0]);
9661 CyteViewController *controller = nil;
9663 if ([base isEqualToString:@"url"]) {
9664 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9665 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9666 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9667 } else if (!external && [components count] == 1) {
9668 if ([base isEqualToString:@"sources"]) {
9669 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9672 if ([base isEqualToString:@"home"]) {
9673 controller = [[[HomeController alloc] init] autorelease];
9676 if ([base isEqualToString:@"sections"]) {
9677 controller = [[[SectionsController alloc] initWithDatabase:database_ source:nil] autorelease];
9680 if ([base isEqualToString:@"search"]) {
9681 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9684 if ([base isEqualToString:@"changes"]) {
9685 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9688 if ([base isEqualToString:@"installed"]) {
9689 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9691 } else if ([components count] == 2) {
9692 NSString *argument = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9694 if ([base isEqualToString:@"package"]) {
9695 controller = [self pageForPackage:argument withReferrer:referrer];
9698 if (!external && [base isEqualToString:@"search"]) {
9699 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9702 if (!external && [base isEqualToString:@"sections"]) {
9703 if ([argument isEqualToString:@"all"] || [argument isEqualToString:@"*"])
9705 controller = [[[SectionController alloc] initWithDatabase:database_ source:nil section:argument] autorelease];
9708 if ([base isEqualToString:@"sources"]) {
9709 if ([argument isEqualToString:@"add"]) {
9710 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9711 [(SourcesController *)controller showAddSourcePrompt];
9713 Source *source([database_ sourceWithKey:argument]);
9714 controller = [[[SectionsController alloc] initWithDatabase:database_ source:source] autorelease];
9718 if (!external && [base isEqualToString:@"launch"]) {
9719 [self launchApplicationWithIdentifier:argument suspended:NO];
9722 } else if (!external && [components count] == 3) {
9723 NSString *arg1 = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9724 NSString *arg2 = [[components objectAtIndex:2] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9726 if ([base isEqualToString:@"package"]) {
9727 if ([arg2 isEqualToString:@"settings"]) {
9728 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9729 } else if ([arg2 isEqualToString:@"files"]) {
9730 if (Package *package = [database_ packageWithName:arg1]) {
9731 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9732 [(FileTable *)controller setPackage:package];
9737 if ([base isEqualToString:@"sections"]) {
9738 Source *source([arg1 isEqualToString:@"*"] ? nil : [database_ sourceWithKey:arg1]);
9739 NSString *section([arg2 isEqualToString:@"*"] ? nil : arg2);
9740 controller = [[[SectionController alloc] initWithDatabase:database_ source:source section:section] autorelease];
9744 [controller setDelegate:self];
9748 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9749 CyteViewController *page([self pageForURL:url forExternal:external withReferrer:nil]);
9752 [tabbar_ setUnselectedViewController:page];
9757 - (void) applicationOpenURL:(NSURL *)url {
9758 [super applicationOpenURL:url];
9763 [self openCydiaURL:url forExternal:YES];
9766 - (void) applicationWillResignActive:(UIApplication *)application {
9767 // Stop refreshing if you get a phone call or lock the device.
9768 if ([tabbar_ updating])
9769 [tabbar_ cancelUpdate];
9771 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9772 [super applicationWillResignActive:application];
9775 - (void) saveState {
9776 [[NSDictionary dictionaryWithObjectsAndKeys:
9777 @"InterfaceState", [tabbar_ navigationURLCollection],
9778 @"LastClosed", [NSDate date],
9779 @"InterfaceIndex", [NSNumber numberWithInt:[tabbar_ selectedIndex]],
9780 nil] writeToFile:@ SavedState_ atomically:YES];
9785 - (void) applicationWillTerminate:(UIApplication *)application {
9789 - (void) applicationDidEnterBackground:(UIApplication *)application {
9790 if (kCFCoreFoundationVersionNumber < 1000 && [self isSafeToSuspend])
9791 return [self terminateWithSuccess];
9792 Backgrounded_ = [NSDate date];
9796 - (void) applicationWillEnterForeground:(UIApplication *)application {
9797 if (Backgrounded_ == nil)
9800 NSTimeInterval interval([Backgrounded_ timeIntervalSinceNow]);
9802 if (interval <= -(30*60)) {
9803 [tabbar_ setSelectedIndex:0];
9804 [[[tabbar_ viewControllers] objectAtIndex:0] popToRootViewControllerAnimated:NO];
9807 if (interval <= -(15*60)) {
9808 if (IsReachable("cydia.saurik.com")) {
9809 [tabbar_ beginUpdate];
9810 [appcache_ reloadURLWithCache:YES];
9814 if ([database_ delocked])
9818 - (void) setConfigurationData:(NSString *)data {
9819 static RegEx conffile_r("'(.*)' '(.*)' ([01]) ([01])");
9821 if (!conffile_r(data)) {
9822 lprintf("E:invalid conffile\n");
9826 NSString *ofile = conffile_r[1];
9827 //NSString *nfile = conffile_r[2];
9829 UIAlertView *alert = [[[UIAlertView alloc]
9830 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9831 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9833 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9835 UCLocalize("ACCEPT_NEW_COPY"),
9836 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9840 [alert setContext:@"conffile"];
9841 [alert setNumberOfRows:2];
9845 - (void) addStashController {
9847 stash_ = [[[StashController alloc] init] autorelease];
9848 [window_ addSubview:[stash_ view]];
9851 - (void) removeStashController {
9852 [[stash_ view] removeFromSuperview];
9854 [self unlockSuspend];
9858 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9859 UpdateExternalStatus(1);
9860 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/cydo /usr/libexec/cydia/free.sh"];
9861 UpdateExternalStatus(0);
9863 [self removeStashController];
9864 [self reloadSpringBoard];
9867 - (void) setupViewControllers {
9868 tabbar_ = [[[CydiaTabBarController alloc] initWithDatabase:database_] autorelease];
9870 NSMutableArray *items;
9871 if (kCFCoreFoundationVersionNumber < 800) {
9872 items = [NSMutableArray arrayWithObjects:
9873 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage imageNamed:@"home.png"] tag:0] autorelease],
9874 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage imageNamed:@"install.png"] tag:0] autorelease],
9875 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage imageNamed:@"changes.png"] tag:0] autorelease],
9876 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage imageNamed:@"manage.png"] tag:0] autorelease],
9877 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage imageNamed:@"search.png"] tag:0] autorelease],
9880 items = [NSMutableArray arrayWithObjects:
9881 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage imageNamed:@"home7.png"] selectedImage:[UIImage imageNamed:@"home7s.png"]] autorelease],
9882 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage imageNamed:@"install7.png"] selectedImage:[UIImage imageNamed:@"install7s.png"]] autorelease],
9883 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage imageNamed:@"changes7.png"] selectedImage:[UIImage imageNamed:@"changes7s.png"]] autorelease],
9884 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage imageNamed:@"manage7.png"] selectedImage:[UIImage imageNamed:@"manage7s.png"]] autorelease],
9885 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage imageNamed:@"search7.png"] selectedImage:[UIImage imageNamed:@"search7s.png"]] autorelease],
9889 NSMutableArray *controllers([NSMutableArray array]);
9890 for (UITabBarItem *item in items) {
9891 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9892 [controller setTabBarItem:item];
9893 [controllers addObject:controller];
9895 [tabbar_ setViewControllers:controllers];
9897 [tabbar_ setUpdateDelegate:self];
9900 - (void) _sendMemoryWarningNotification {
9901 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: maybe 4_0?
9902 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationMemoryWarningNotification" object:[UIApplication sharedApplication]];
9904 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
9907 - (void) _sendMemoryWarningNotifications {
9909 [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO];
9915 - (void) applicationDidReceiveMemoryWarning:(UIApplication *)application {
9917 [[NSURLCache sharedURLCache] removeAllCachedResponses];
9920 - (void) applicationDidFinishLaunching:(id)unused {
9921 //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil];
9924 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9925 [self setApplicationSupportsShakeToEdit:NO];
9927 @synchronized (HostConfig_) {
9928 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9931 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9932 initWithMemoryCapacity:524288
9933 diskCapacity:10485760
9934 diskPath:Cache("SDURLCache")
9937 [CydiaWebViewController _initialize];
9939 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9941 // this would disallow http{,s} URLs from accessing this data
9942 //[WebView registerURLSchemeAsLocal:@"cydia"];
9944 Font12_ = [UIFont systemFontOfSize:12];
9945 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9946 Font14_ = [UIFont systemFontOfSize:14];
9947 Font18_ = [UIFont systemFontOfSize:18];
9948 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9949 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9951 essential_ = [NSMutableArray arrayWithCapacity:4];
9952 broken_ = [NSMutableArray arrayWithCapacity:4];
9954 // XXX: I really need this thing... like, seriously... I'm sorry
9955 appcache_ = [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] autorelease];
9956 [appcache_ reloadData];
9958 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9959 [window_ orderFront:self];
9960 [window_ makeKey:self];
9961 [window_ setHidden:NO];
9963 if (access("/.cydia_no_stash", F_OK) == 0);
9967 [self addStashController];
9968 // XXX: this would be much cleaner as a yieldToSelector:
9969 // that way the removeStashController could happen right here inline
9970 // we also could no longer require the useless stash_ field anymore
9971 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9976 int error(stat("/", &root));
9977 _assert(error != -1);
9979 #define Stash_(path) do { \
9980 struct stat folder; \
9981 int error(lstat((path), &folder)); \
9982 if (error != -1 && ( \
9983 folder.st_dev == root.st_dev && \
9984 S_ISDIR(folder.st_mode) \
9985 ) || error == -1 && ( \
9986 errno == ENOENT || \
9991 Stash_("/Applications");
9992 Stash_("/Library/Ringtones");
9993 Stash_("/Library/Wallpaper");
9994 //Stash_("/usr/bin");
9995 Stash_("/usr/include");
9996 Stash_("/usr/share");
9997 //Stash_("/var/lib");
10001 database_ = [Database sharedInstance];
10002 [database_ setDelegate:self];
10004 [window_ setUserInteractionEnabled:NO];
10005 [self setupViewControllers];
10007 CydiaLoadingViewController *loading([[[CydiaLoadingViewController alloc] init] autorelease]);
10008 UINavigationController *navigation([[[UINavigationController alloc] init] autorelease]);
10009 [navigation setViewControllers:[NSArray arrayWithObject:loading]];
10011 emulated_ = [[[CyteTabBarController alloc] init] autorelease];
10012 [emulated_ setViewControllers:[NSArray arrayWithObject:navigation]];
10013 [emulated_ setSelectedIndex:0];
10015 if ([emulated_ respondsToSelector:@selector(concealTabBarSelection)])
10016 [emulated_ concealTabBarSelection];
10018 if ([window_ respondsToSelector:@selector(setRootViewController:)])
10019 [window_ setRootViewController:emulated_];
10021 [window_ addSubview:[emulated_ view]];
10023 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
10027 - (NSArray *) defaultStartPages {
10028 NSMutableArray *standard = [NSMutableArray array];
10029 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
10030 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
10031 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
10032 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
10033 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
10037 - (void) loadData {
10039 if ([emulated_ modalViewController] != nil)
10040 [emulated_ dismissModalViewControllerAnimated:YES];
10041 [window_ setUserInteractionEnabled:NO];
10043 [self reloadDataWithInvocation:nil];
10044 [self refreshIfPossible];
10047 NSDictionary *state([NSDictionary dictionaryWithContentsOfFile:@ SavedState_]);
10049 int savedIndex = [[state objectForKey:@"InterfaceIndex"] intValue];
10050 NSArray *saved = [[[state objectForKey:@"InterfaceState"] mutableCopy] autorelease];
10051 int standardIndex = 0;
10052 NSArray *standard = [self defaultStartPages];
10059 NSDate *closed = [state objectForKey:@"LastClosed"];
10060 if (valid && closed != nil) {
10061 NSTimeInterval interval([closed timeIntervalSinceNow]);
10062 if (interval <= -(30*60))
10066 if (valid && [saved count] != [standard count])
10070 for (unsigned int i = 0; i < [standard count]; i++) {
10071 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
10072 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
10073 // but it's good enough for now.
10074 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
10081 NSArray *items = nil;
10083 [tabbar_ setSelectedIndex:savedIndex];
10086 [tabbar_ setSelectedIndex:standardIndex];
10090 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
10091 NSArray *stack = [items objectAtIndex:tab];
10092 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
10093 NSMutableArray *current = [NSMutableArray array];
10095 for (unsigned int nav = 0; nav < [stack count]; nav++) {
10096 NSString *addr = [stack objectAtIndex:nav];
10097 NSURL *url = [NSURL URLWithString:addr];
10098 CyteViewController *page = [self pageForURL:url forExternal:NO withReferrer:nil];
10100 [current addObject:page];
10103 [navigation setViewControllers:current];
10106 // (Try to) show the startup URL.
10107 if (starturl_ != nil) {
10108 [self openCydiaURL:starturl_ forExternal:YES];
10113 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
10115 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
10116 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
10119 if (item != nil && IsWildcat_) {
10120 [sheet showFromBarButtonItem:item animated:YES];
10122 [sheet showInView:window_];
10126 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
10127 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
10128 [progress setTitle:task];
10129 [progress addProgressEvent:event];
10132 - (void) addProgressEventForTask:(NSArray *)data {
10133 CydiaProgressEvent *event([data objectAtIndex:0]);
10134 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
10135 [self addProgressEvent:event forTask:task];
10138 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
10139 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
10145 id Alloc_(id self, SEL selector) {
10146 id object = alloc_(self, selector);
10147 lprintf("[%s]A-%p\n", self->isa->name, object);
10152 id Dealloc_(id self, SEL selector) {
10153 id object = dealloc_(self, selector);
10154 lprintf("[%s]D-%p\n", self->isa->name, object);
10158 Class $NSURLConnection;
10160 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
10161 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
10163 NSURL *url([copy URL]);
10165 NSString *host([url host]);
10166 NSString *scheme([[url scheme] lowercaseString]);
10168 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
10170 @synchronized (HostConfig_) {
10171 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
10172 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
10173 [copy setHTTPShouldUsePipelining:YES];
10175 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
10176 if ([control isEqualToString:@"max-age=0"])
10177 if ([CachedURLs_ containsObject:url]) {
10179 NSLog(@"~~~: %@", url);
10182 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
10184 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
10185 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
10186 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
10190 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
10196 static CGSize $WAKWindow$screenSize(WAKWindow *self, SEL _cmd) {
10197 CGSize size([[UIScreen mainScreen] bounds].size);
10198 /*if ([$WAKWindow respondsToSelector:@selector(hasLandscapeOrientation)])
10199 if ([$WAKWindow hasLandscapeOrientation])
10200 std::swap(size.width, size.height);*/
10204 Class $NSUserDefaults;
10206 MSHook(id, NSUserDefaults$objectForKey$, NSUserDefaults *self, SEL _cmd, NSString *key) {
10207 if ([key respondsToSelector:@selector(isEqualToString:)] && [key isEqualToString:@"WebKitLocalStorageDatabasePathPreferenceKey"])
10208 return Cache("LocalStorage");
10209 return _NSUserDefaults$objectForKey$(self, _cmd, key);
10212 static NSMutableDictionary *AutoreleaseDeepMutableCopyOfDictionary(CFTypeRef type) {
10215 if (CFGetTypeID(type) != CFDictionaryGetTypeID())
10217 CFTypeRef copy(CFPropertyListCreateDeepCopy(kCFAllocatorDefault, type, kCFPropertyListMutableContainers));
10219 return [(NSMutableDictionary *) copy autorelease];
10222 int main_store(int, char *argv[]);
10224 int main(int argc, char *argv[]) {
10226 const char *argv0(argv[0]);
10227 if (const char *slash = strrchr(argv0, '/'))
10230 else if (!strcmp(argv0, "store"))
10231 return main_store(argc, argv);
10234 int fd(open("/tmp/cydia.log", O_WRONLY | O_APPEND | O_CREAT, 0644));
10238 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10242 UpdateExternalStatus(0);
10244 UIScreen *screen([UIScreen mainScreen]);
10245 if ([screen respondsToSelector:@selector(scale)])
10246 ScreenScale_ = [screen scale];
10250 UIDevice *device([UIDevice currentDevice]);
10251 if ([device respondsToSelector:@selector(userInterfaceIdiom)]) {
10252 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10253 if (idiom == UIUserInterfaceIdiomPad)
10257 Idiom_ = IsWildcat_ ? @"ipad" : @"iphone";
10259 RegEx pattern("([0-9]+\\.[0-9]+).*");
10261 if (pattern([device systemVersion]))
10262 Firmware_ = pattern[1];
10263 if (pattern(Cydia_))
10264 Major_ = pattern[1];
10266 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
10268 HostConfig_ = [[[NSObject alloc] init] autorelease];
10269 @synchronized (HostConfig_) {
10270 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10271 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
10272 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
10273 CachedURLs_ = [NSMutableSet setWithCapacity:32];
10276 NSString *ui(@"ui/ios");
10278 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
10279 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"/%@", Major_]];
10280 UI_ = CydiaURL(ui);
10282 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10284 /* Library Hacks {{{ */
10285 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10287 $WAKWindow = objc_getClass("WAKWindow");
10288 if ($WAKWindow != NULL)
10289 if (Method method = class_getInstanceMethod($WAKWindow, @selector(screenSize)))
10290 method_setImplementation(method, (IMP) &$WAKWindow$screenSize);
10292 $NSURLConnection = objc_getClass("NSURLConnection");
10293 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10294 if (NSURLConnection$init$ != NULL) {
10295 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10296 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10299 $NSUserDefaults = objc_getClass("NSUserDefaults");
10300 Method NSUserDefaults$objectForKey$(class_getInstanceMethod($NSUserDefaults, @selector(objectForKey:)));
10301 if (NSUserDefaults$objectForKey$ != NULL) {
10302 _NSUserDefaults$objectForKey$ = reinterpret_cast<id (*)(NSUserDefaults *, SEL, NSString *)>(method_getImplementation(NSUserDefaults$objectForKey$));
10303 method_setImplementation(NSUserDefaults$objectForKey$, reinterpret_cast<IMP>(&$NSUserDefaults$objectForKey$));
10306 /* Set Locale {{{ */
10307 Locale_ = CFLocaleCopyCurrent();
10308 Languages_ = [NSLocale preferredLanguages];
10310 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10311 //NSLog(@"%@", [Languages_ description]);
10314 if (Locale_ != NULL)
10315 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10316 else if (Languages_ != nil && [Languages_ count] != 0)
10317 lang = [[Languages_ objectAtIndex:0] UTF8String];
10319 // XXX: consider just setting to C and then falling through?
10322 if (lang != NULL) {
10323 RegEx pattern("([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?");
10324 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10327 NSLog(@"Setting Language: %s", lang);
10329 if (lang != NULL) {
10330 setenv("LANG", lang, true);
10331 setlocale(LC_ALL, lang);
10334 /* Index Collation {{{ */
10335 if (Class $UILocalizedIndexedCollation = objc_getClass("UILocalizedIndexedCollation")) { @try {
10336 NSBundle *bundle([NSBundle bundleForClass:$UILocalizedIndexedCollation]);
10337 NSString *path([bundle pathForResource:@"UITableViewLocalizedSectionIndex" ofType:@"plist"]);
10338 //path = @"/System/Library/Frameworks/UIKit.framework/.lproj/UITableViewLocalizedSectionIndex.plist";
10339 NSDictionary *dictionary([NSDictionary dictionaryWithContentsOfFile:path]);
10340 _H<UILocalizedIndexedCollation> collation([[[$UILocalizedIndexedCollation alloc] initWithDictionary:dictionary] autorelease]);
10342 CollationLocale_ = MSHookIvar<NSLocale *>(collation, "_locale");
10344 if (kCFCoreFoundationVersionNumber >= 800 && [[CollationLocale_ localeIdentifier] isEqualToString:@"zh@collation=stroke"]) {
10345 CollationThumbs_ = [NSArray arrayWithObjects:@"1",@"•",@"4",@"•",@"7",@"•",@"10",@"•",@"13",@"•",@"16",@"•",@"19",@"A",@"•",@"E",@"•",@"I",@"•",@"M",@"•",@"R",@"•",@"V",@"•",@"Z",@"#",nil];
10346 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})
10347 CollationOffset_.push_back(offset);
10348 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];
10349 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];
10352 CollationThumbs_ = [collation sectionIndexTitles];
10353 for (size_t index(0), end([CollationThumbs_ count]); index != end; ++index)
10354 CollationOffset_.push_back([collation sectionForSectionIndexTitleAtIndex:index]);
10356 CollationTitles_ = [collation sectionTitles];
10357 CollationStarts_ = MSHookIvar<NSArray *>(collation, "_sectionStartStrings");
10359 NSString *&transform(MSHookIvar<NSString *>(collation, "_transform"));
10360 if (&transform != NULL && transform != nil) {
10361 /*if ([collation respondsToSelector:@selector(transformedCollationStringForString:)])
10362 CollationModify_ = [=](NSString *value) { return [collation transformedCollationStringForString:value]; };*/
10363 const UChar *uid(reinterpret_cast<const UChar *>([transform cStringUsingEncoding:NSUnicodeStringEncoding]));
10364 UErrorCode code(U_ZERO_ERROR);
10365 CollationTransl_ = utrans_openU(uid, -1, UTRANS_FORWARD, NULL, 0, NULL, &code);
10366 if (!U_SUCCESS(code))
10367 NSLog(@"%s", u_errorName(code));
10371 } @catch (NSException *e) {
10375 CollationLocale_ = [[[NSLocale alloc] initWithLocaleIdentifier:@"en@collation=dictionary"] autorelease];
10377 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];
10378 for (NSInteger offset(0); offset != 28; ++offset)
10379 CollationOffset_.push_back(offset);
10381 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];
10382 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];
10385 /* Parse Arguments {{{ */
10386 bool substrate(false);
10392 for (int argi(1); argi != argc; ++argi)
10393 if (strcmp(argv[argi], "--") == 0) {
10395 argv[argi] = argv[0];
10401 for (int argi(1); argi != arge; ++argi)
10402 if (strcmp(args[argi], "--substrate") == 0)
10405 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10409 App_ = [[NSBundle mainBundle] bundlePath];
10412 Cache_ = [[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia", @"/var/mobile"] retain];
10413 mkdir([Cache_ UTF8String], 0755);
10415 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10416 alloc_ = alloc->method_imp;
10417 alloc->method_imp = (IMP) &Alloc_;*/
10419 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10420 dealloc_ = dealloc->method_imp;
10421 dealloc->method_imp = (IMP) &Dealloc_;*/
10423 void *gestalt(dlopen("/usr/lib/libMobileGestalt.dylib", RTLD_GLOBAL | RTLD_LAZY));
10424 $MGCopyAnswer = reinterpret_cast<CFStringRef (*)(CFStringRef)>(dlsym(gestalt, "MGCopyAnswer"));
10426 /* System Information {{{ */
10430 size = sizeof(maxproc);
10431 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10432 perror("sysctlbyname(\"kern.maxproc\", ?)");
10433 else if (maxproc < 64) {
10435 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10436 perror("sysctlbyname(\"kern.maxproc\", #)");
10439 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10440 char *osversion = new char[size];
10441 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10442 perror("sysctlbyname(\"kern.osversion\", ?)");
10444 System_ = [NSString stringWithUTF8String:osversion];
10446 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10447 char *machine = new char[size];
10448 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10449 perror("sysctlbyname(\"hw.machine\", ?)");
10451 Machine_ = machine;
10453 int64_t usermem(0);
10454 size = sizeof(usermem);
10455 if (sysctlbyname("hw.usermem", &usermem, &size, NULL, 0) == -1)
10458 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10459 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10460 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10462 UniqueID_ = UniqueIdentifier(device);
10464 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10465 Product_ = [info objectForKey:@"SafariProductVersion"];
10466 Safari_ = [info objectForKey:@"CFBundleVersion"];
10469 NSString *agent([NSString stringWithFormat:@"Cydia/%@ CyF/%.2f", Cydia_, kCFCoreFoundationVersionNumber]);
10471 if (RegEx match = RegEx("([0-9]+(\\.[0-9]+)+).*", Safari_))
10472 agent = [NSString stringWithFormat:@"Safari/%@ %@", match[1], agent];
10473 if (RegEx match = RegEx("([0-9]+[A-Z][0-9]+[a-z]?).*", System_))
10474 agent = [NSString stringWithFormat:@"Mobile/%@ %@", match[1], agent];
10475 if (RegEx match = RegEx("([0-9]+(\\.[0-9]+)+).*", Product_))
10476 agent = [NSString stringWithFormat:@"Version/%@ %@", match[1], agent];
10478 UserAgent_ = agent;
10480 /* Load Database {{{ */
10481 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10484 mkdir("/var/mobile/Library/Cydia", 0755);
10485 MetaFile_.Open("/var/mobile/Library/Cydia/metadata.cb0");
10488 Values_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaValues"), CFSTR("com.saurik.Cydia")));
10489 Sections_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaSections"), CFSTR("com.saurik.Cydia")));
10490 Sources_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaSources"), CFSTR("com.saurik.Cydia")));
10491 Version_ = [(NSNumber *) CFPreferencesCopyAppValue(CFSTR("CydiaVersion"), CFSTR("com.saurik.Cydia")) autorelease];
10494 NSDictionary *metadata([[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease]);
10496 if (Values_ == nil)
10497 Values_ = [metadata objectForKey:@"Values"];
10498 if (Values_ == nil)
10499 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10501 if (Sections_ == nil)
10502 Sections_ = [metadata objectForKey:@"Sections"];
10503 if (Sections_ == nil)
10504 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10506 if (Sources_ == nil)
10507 Sources_ = [metadata objectForKey:@"Sources"];
10508 if (Sources_ == nil)
10509 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10511 // XXX: this wrong, but in a way that doesn't matter :/
10512 if (Version_ == nil)
10513 Version_ = [metadata objectForKey:@"Version"];
10514 if (Version_ == nil)
10515 Version_ = [NSNumber numberWithUnsignedInt:0];
10517 if (NSDictionary *packages = [metadata objectForKey:@"Packages"]) {
10519 CFDictionaryApplyFunction((CFDictionaryRef) packages, &PackageImport, &fail);
10522 NSLog(@"unable to import package preferences... from 2010? oh well :/");
10525 if ([Version_ unsignedIntValue] == 0) {
10526 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10527 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10528 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10529 CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./");
10531 Version_ = [NSNumber numberWithUnsignedInt:1];
10533 if (NSMutableDictionary *cache = [NSMutableDictionary dictionaryWithContentsOfFile:@ CacheState_]) {
10534 [cache removeObjectForKey:@"LastUpdate"];
10535 [cache writeToFile:@ CacheState_ atomically:YES];
10539 _H<NSMutableArray> broken([NSMutableArray array]);
10540 for (NSString *key in (id) Sources_)
10541 if ([key rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"# "]].location != NSNotFound || ![([[Sources_ objectForKey:key] objectForKey:@"URI"] ?: @"/") hasSuffix:@"/"])
10542 [broken addObject:key];
10543 if ([broken count] != 0)
10544 for (NSString *key in (id) broken)
10545 [Sources_ removeObjectForKey:key];
10549 system("/usr/libexec/cydia/cydo /bin/rm -f /var/lib/cydia/metadata.plist");
10552 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10554 if (kCFCoreFoundationVersionNumber > 1000)
10555 system("/usr/libexec/cydia/cydo /usr/libexec/cydia/setnsfpn /var/lib");
10557 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10559 if (access("/User", F_OK) != 0 || version != 6) {
10561 system("/usr/libexec/cydia/cydo /usr/libexec/cydia/firmware.sh");
10565 if (access("/tmp/cydia.chk", F_OK) == 0) {
10566 if (unlink([Cache("pkgcache.bin") UTF8String]) == -1)
10567 _assert(errno == ENOENT);
10568 if (unlink([Cache("srcpkgcache.bin") UTF8String]) == -1)
10569 _assert(errno == ENOENT);
10572 system("/usr/libexec/cydia/cydo /bin/ln -sf /var/mobile/Library/Caches/com.saurik.Cydia/sources.list /etc/apt/sources.list.d/cydia.list");
10574 /* APT Initialization {{{ */
10575 _assert(pkgInitConfig(*_config));
10576 _assert(pkgInitSystem(*_config, _system));
10578 _config->Set("Acquire::AllowInsecureRepositories", true);
10579 _config->Set("Acquire::Check-Valid-Until", false);
10580 _config->Set("Dir::Bin::Methods::store", "/Applications/Cydia.app/store");
10582 _config->Set("pkgCacheGen::ForceEssential", "");
10583 _config->Set("APT::Acquire::Translation", "environment");
10585 // XXX: this timeout might be important :(
10586 //_config->Set("Acquire::http::Timeout", 15);
10588 _config->Set("Acquire::http::MaxParallel", usermem >= 384 * 1024 * 1024 ? 16 : 3);
10590 mkdir([Cache("archives") UTF8String], 0755);
10591 mkdir([Cache("archives/partial") UTF8String], 0755);
10592 _config->Set("Dir::Cache", [Cache_ UTF8String]);
10594 symlink("/var/lib/apt/extended_states", [Cache("extended_states") UTF8String]);
10595 _config->Set("Dir::State", [Cache_ UTF8String]);
10597 mkdir([Cache("lists") UTF8String], 0755);
10598 mkdir([Cache("lists/partial") UTF8String], 0755);
10599 mkdir([Cache("periodic") UTF8String], 0755);
10600 _config->Set("Dir::State::Lists", [Cache("lists") UTF8String]);
10602 std::string logs("/var/mobile/Library/Logs/Cydia");
10603 mkdir(logs.c_str(), 0755);
10604 _config->Set("Dir::Log", logs);
10606 _config->Set("Dir::Bin::dpkg", "/usr/libexec/cydia/cydo");
10608 /* Color Choices {{{ */
10609 space_ = CGColorSpaceCreateDeviceRGB();
10611 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10612 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10613 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10614 Folder_.Set(space_, 0x8e/255.f, 0x8e/255.f, 0x93/255.f, 1.0);
10615 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10616 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10617 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10618 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10619 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10620 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10622 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10623 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10625 /* UIKit Configuration {{{ */
10626 // XXX: I have a feeling this was important
10627 //UIKeyboardDisableAutomaticAppearance();
10630 $SBSSetInterceptsMenuButtonForever = reinterpret_cast<void (*)(bool)>(dlsym(RTLD_DEFAULT, "SBSSetInterceptsMenuButtonForever"));
10631 $SBSCopyIconImagePNGDataForDisplayIdentifier = reinterpret_cast<NSData *(*)(NSString *)>(dlsym(RTLD_DEFAULT, "SBSCopyIconImagePNGDataForDisplayIdentifier"));
10633 const char *symbol(kCFCoreFoundationVersionNumber >= 800 ? "MGGetBoolAnswer" : "GSSystemHasCapability");
10634 BOOL (*GSSystemHasCapability)(CFStringRef) = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, symbol));
10635 bool fast = GSSystemHasCapability != NULL && GSSystemHasCapability(CFSTR("armv7"));
10637 PulseInterval_ = fast ? 50000 : 500000;
10639 Colon_ = UCLocalize("COLON_DELIMITED");
10640 Elision_ = UCLocalize("ELISION");
10641 Error_ = UCLocalize("ERROR");
10642 Warning_ = UCLocalize("WARNING");
10645 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10647 CGColorSpaceRelease(space_);
10648 CFRelease(Locale_);