1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2015 Jay Freeman (saurik)
5 /* GNU General Public License, Version 3 {{{ */
7 * Cydia is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published
9 * by the Free Software Foundation, either version 3 of the License,
10 * or (at your option) any later version.
12 * Cydia is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Cydia. If not, see <http://www.gnu.org/licenses/>.
22 // XXX: wtf/FastMalloc.h... wtf?
23 #define USE_SYSTEM_MALLOC 1
25 /* #include Directives {{{ */
26 #include "CyteKit/UCPlatform.h"
27 #include "CyteKit/Localize.h"
29 #include <unicode/ustring.h>
30 #include <unicode/utrans.h>
32 #include <objc/objc.h>
33 #include <objc/runtime.h>
35 #include <CoreGraphics/CoreGraphics.h>
36 #include <Foundation/Foundation.h>
39 #define DEPLOYMENT_TARGET_MACOSX 1
40 #define CF_BUILDING_CF 1
41 #include <CoreFoundation/CFInternal.h>
44 #include <CoreFoundation/CFUniChar.h>
46 #include <SystemConfiguration/SystemConfiguration.h>
48 #include <UIKit/UIKit.h>
49 #include "iPhonePrivate.h"
51 #include <IOKit/IOKitLib.h>
53 #include <QuartzCore/CALayer.h>
55 #include <WebCore/WebCoreThread.h>
64 #include "fdstream.hpp"
69 #include <apt-pkg/acquire.h>
70 #include <apt-pkg/acquire-item.h>
71 #include <apt-pkg/algorithms.h>
72 #include <apt-pkg/cachefile.h>
73 #include <apt-pkg/clean.h>
74 #include <apt-pkg/configuration.h>
75 #include <apt-pkg/debindexfile.h>
76 #include <apt-pkg/debmetaindex.h>
77 #include <apt-pkg/error.h>
78 #include <apt-pkg/init.h>
79 #include <apt-pkg/mmap.h>
80 #include <apt-pkg/pkgrecords.h>
81 #include <apt-pkg/sha1.h>
82 #include <apt-pkg/sourcelist.h>
83 #include <apt-pkg/sptr.h>
84 #include <apt-pkg/strutl.h>
85 #include <apt-pkg/tagfile.h>
87 #include <sys/types.h>
89 #include <sys/sysctl.h>
90 #include <sys/param.h>
91 #include <sys/mount.h>
92 #include <sys/reboot.h>
100 #include <mach-o/nlist.h>
109 #include <Cytore.hpp>
112 #include "Substrate.hpp"
113 #include "Menes/Menes.h"
115 #include "CyteKit/Application.h"
116 #include "CyteKit/NavigationController.h"
117 #include "CyteKit/RegEx.hpp"
118 #include "CyteKit/TableViewCell.h"
119 #include "CyteKit/TabBarController.h"
120 #include "CyteKit/WebScriptObject-Cyte.h"
121 #include "CyteKit/WebViewController.h"
122 #include "CyteKit/WebViewTableViewCell.h"
123 #include "CyteKit/stringWithUTF8Bytes.h"
125 #include "Cydia/MIMEAddress.h"
126 #include "Cydia/LoadingViewController.h"
127 #include "Cydia/ProgressEvent.h"
129 #include "SDURLCache/SDURLCache.h"
136 #define _timestamp ({ \
138 gettimeofday(&tv, NULL); \
139 tv.tv_sec * 1000000 + tv.tv_usec; \
142 typedef std::vector<class ProfileTime *> TimeList;
152 ProfileTime(const char *name) :
156 times_.push_back(this);
159 void AddTime(uint64_t time) {
166 std::cerr << std::setw(7) << count_ << ", " << std::setw(8) << total_ << " : " << name_ << std::endl;
178 ProfileTimer(ProfileTime &time) :
185 time_.AddTime(_timestamp - start_);
190 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
192 std::cerr << "========" << std::endl;
195 #define _profile(name) { \
196 static ProfileTime name(#name); \
197 ProfileTimer _ ## name(name);
202 // XXX: I hate clang. Apple: please get over your petty hatred of GPL and fix your gcc fork
203 #define synchronized(lock) \
204 synchronized(static_cast<NSObject *>(lock))
206 extern NSString *Cydia_;
208 #define lprintf(args...) fprintf(stderr, args)
211 #define TraceLogging (1 && !ForRelease)
212 #define HistogramInsertionSort (0 && !ForRelease)
213 #define ProfileTimes (0 && !ForRelease)
214 #define ForSaurik (0 && !ForRelease)
215 #define LogBrowser (0 && !ForRelease)
216 #define TrackResize (0 && !ForRelease)
217 #define ManualRefresh (1 && !ForRelease)
218 #define ShowInternals (0 && !ForRelease)
219 #define AlwaysReload (0 && !ForRelease)
223 #define _trace(args...)
228 #define _profile(name) {
231 #define PrintTimes() do {} while (false)
234 // Hash Functions/Structures {{{
235 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
243 @implementation NSDictionary (Cydia)
244 - (id) invokeUndefinedMethodFromWebScript:(NSString *)name withArguments:(NSArray *)arguments {
246 else if ([name isEqualToString:@"get"])
247 return [self objectForKey:[arguments objectAtIndex:0]];
248 else if ([name isEqualToString:@"keys"])
249 return [self allKeys];
253 static NSString *Colon_;
255 static NSString *Error_;
256 static NSString *Warning_;
258 static NSString *Cache_;
259 #define Cache(file) \
260 [NSString stringWithFormat:@"%@/%s", Cache_, file]
262 static void (*$SBSSetInterceptsMenuButtonForever)(bool);
263 static NSData *(*$SBSCopyIconImagePNGDataForDisplayIdentifier)(NSString *);
265 static CFStringRef (*$MGCopyAnswer)(CFStringRef);
267 static NSString *UniqueIdentifier(UIDevice *device = nil) {
268 if (kCFCoreFoundationVersionNumber < 800) // iOS 7.x
269 return [device ?: [UIDevice currentDevice] uniqueIdentifier];
271 return [(id)$MGCopyAnswer(CFSTR("UniqueDeviceID")) autorelease];
274 static bool IsReachable(const char *name) {
275 SCNetworkReachabilityFlags flags; {
276 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, name));
277 SCNetworkReachabilityGetFlags(reachability, &flags);
278 CFRelease(reachability);
281 // XXX: this elaborate mess is what Apple is using to determine this? :(
282 // XXX: do we care if the user has to intervene? maybe that's ok?
284 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
285 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
286 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
287 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
288 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
289 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
294 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
296 static _finline NSString *CydiaURL(NSString *path) {
298 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
299 page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
300 page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
301 page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
302 page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
304 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
307 static NSString *ShellEscape(NSString *value) {
308 return [NSString stringWithFormat:@"'%@'", [value stringByReplacingOccurrencesOfString:@"'" withString:@"'\\''"]];
311 static _finline void UpdateExternalStatus(uint64_t newStatus) {
313 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
314 notify_set_state(notify_token, newStatus);
315 notify_cancel(notify_token);
317 notify_post("com.saurik.Cydia.status");
320 static CGFloat CYStatusBarHeight() {
321 CGSize size([[UIApplication sharedApplication] statusBarFrame].size);
322 return UIInterfaceOrientationIsPortrait([[UIApplication sharedApplication] statusBarOrientation]) ? size.height : size.width;
325 /* NSForcedOrderingSearch doesn't work on the iPhone */
326 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
327 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
328 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
330 /* Insertion Sort {{{ */
332 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 _H<NSArray> 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;
1138 - (bool) hasPackages;
1140 - (void) _readCydia:(NSNumber *)fd;
1141 - (void) _readStatus:(NSNumber *)fd;
1142 - (void) _readOutput:(NSNumber *)fd;
1146 - (Package *) packageWithName:(NSString *)name;
1148 - (pkgCacheFile &) cache;
1149 - (pkgDepCache::Policy *) policy;
1150 - (pkgRecords *) records;
1151 - (pkgProblemResolver *) resolver;
1152 - (pkgAcquire &) fetcher;
1153 - (pkgSourceList &) list;
1154 - (NSArray *) packages;
1155 - (NSArray *) sources;
1156 - (Source *) sourceWithKey:(NSString *)key;
1157 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1165 - (void) updateWithStatus:(CancelStatus &)status;
1167 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1169 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1170 - (NSObject<ProgressDelegate> *) progressDelegate;
1172 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1173 - (void) setFetch:(bool)fetch forURI:(const char *)uri;
1174 - (void) resetFetch;
1176 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1180 /* SourceStatus {{{ */
1181 class SourceStatus :
1185 _transient NSObject<FetchDelegate> *delegate_;
1186 _transient Database *database_;
1187 std::set<std::string> fetches_;
1190 SourceStatus(NSObject<FetchDelegate> *delegate, Database *database) :
1191 delegate_(delegate),
1196 void Set(bool fetch, const std::string &uri) {
1198 if (!fetches_.insert(uri).second)
1201 if (fetches_.erase(uri) == 0)
1205 //printf("Set(%s, %s)\n", fetch ? "true" : "false", uri.c_str());
1206 [database_ setFetch:fetch forURI:uri.c_str()];
1209 _finline void Set(bool fetch, pkgAcquire::Item *item) {
1210 /*unsigned long ID(fetch ? 1 : 0);
1214 Set(fetch, item->DescURI());
1217 void Log(const char *tag, pkgAcquire::Item *item) {
1218 //printf("%s(%s) S:%u Q:%u\n", tag, item->DescURI().c_str(), item->Status, item->QueueCounter);
1221 virtual void Fetch(pkgAcquire::ItemDesc &desc) {
1222 Log("Fetch", desc.Owner);
1223 Set(true, desc.Owner);
1226 virtual void Done(pkgAcquire::ItemDesc &desc) {
1227 Log("Done", desc.Owner);
1228 Set(false, desc.Owner);
1231 virtual void Fail(pkgAcquire::ItemDesc &desc) {
1232 Log("Fail", desc.Owner);
1233 Set(false, desc.Owner);
1236 virtual bool Pulse_(pkgAcquire *Owner) {
1237 std::set<std::string> fetches;
1238 for (pkgAcquire::ItemCIterator item(Owner->ItemsBegin()); item != Owner->ItemsEnd(); ++item) {
1240 if ((*item)->QueueCounter == 0)
1242 else switch ((*item)->Status) {
1243 case pkgAcquire::Item::StatFetching:
1244 fetches.insert((*item)->DescURI());
1253 Log(fetch ? "Pulse<true>" : "Pulse<false>", *item);
1257 std::vector<std::string> stops;
1258 std::set_difference(fetches_.begin(), fetches_.end(), fetches.begin(), fetches.end(), std::back_insert_iterator<std::vector<std::string>>(stops));
1259 for (std::vector<std::string>::const_iterator stop(stops.begin()); stop != stops.end(); ++stop) {
1260 //printf("Stop(%s)\n", stop->c_str());
1264 return ![delegate_ isSourceCancelled];
1267 virtual void Stop() {
1268 pkgAcquireStatus::Stop();
1269 [database_ resetFetch];
1273 /* ProgressEvent Implementation {{{ */
1274 @implementation CydiaProgressEvent
1276 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1277 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1280 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1281 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1282 [event setPackage:package];
1286 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItemDesc:(pkgAcquire::ItemDesc &)desc {
1287 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1289 NSString *description([NSString stringWithUTF8String:desc.Description.c_str()]);
1290 NSArray *fields([description componentsSeparatedByString:@" "]);
1291 [event setItem:fields];
1293 if ([fields count] > 3) {
1294 [event setPackage:[fields objectAtIndex:2]];
1295 [event setVersion:[fields objectAtIndex:3]];
1298 [event setURL:[NSString stringWithUTF8String:desc.URI.c_str()]];
1303 + (NSArray *) _attributeKeys {
1304 return [NSArray arrayWithObjects:
1314 - (NSArray *) attributeKeys {
1315 return [[self class] _attributeKeys];
1318 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1319 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1322 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1323 if ((self = [super init]) != nil) {
1329 - (NSString *) message {
1333 - (NSString *) type {
1337 - (NSArray *) item {
1338 return (id) item_ ?: [NSNull null];
1341 - (void) setItem:(NSArray *)item {
1345 - (NSString *) package {
1346 return (id) package_ ?: [NSNull null];
1349 - (void) setPackage:(NSString *)package {
1353 - (NSString *) url {
1354 return (id) url_ ?: [NSNull null];
1357 - (void) setURL:(NSString *)url {
1361 - (void) setVersion:(NSString *)version {
1365 - (NSString *) version {
1366 return (id) version_ ?: [NSNull null];
1369 - (NSString *) compound:(NSString *)value {
1371 NSString *mode(nil); {
1372 NSString *type([self type]);
1373 if ([type isEqualToString:kCydiaProgressEventTypeError])
1374 mode = UCLocalize("ERROR");
1375 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1376 mode = UCLocalize("WARNING");
1380 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1386 - (NSString *) compoundMessage {
1387 return [self compound:[self message]];
1390 - (NSString *) compoundTitle {
1393 if (package_ == nil)
1395 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1396 title = [package name];
1400 return [self compound:title];
1406 // Cytore Definitions {{{
1407 struct PackageValue :
1410 Cytore::Offset<PackageValue> next_;
1412 uint32_t index_ : 23;
1413 uint32_t subscribed_ : 1;
1430 Cytore::Offset<PackageValue> packages_[1 << 16];
1433 static Cytore::File<MetaValue> MetaFile_;
1435 // Cytore Helper Functions {{{
1436 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1437 SplitHash nhash = { hashlittle(name, length) };
1439 PackageValue *metadata;
1441 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1442 for (;; offset = &metadata->next_) { if (offset->IsNull()) {
1443 *offset = MetaFile_.New<PackageValue>(length + 1);
1444 metadata = &MetaFile_.Get(*offset);
1446 if (metadata == NULL) {
1450 metadata = new PackageValue();
1451 memset(metadata, 0, sizeof(*metadata));
1454 memcpy(metadata->name_, name, length);
1455 metadata->name_[length] = '\0';
1456 metadata->nhash_ = nhash.u16[1];
1458 metadata = &MetaFile_.Get(*offset);
1459 if (metadata->nhash_ != nhash.u16[1])
1461 if (strncmp(metadata->name_, name, length) != 0)
1463 if (metadata->name_[length] != '\0')
1470 static void PackageImport(const void *key, const void *value, void *context) {
1471 bool &fail(*reinterpret_cast<bool *>(context));
1474 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1475 NSLog(@"failed to import package %@", key);
1479 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1480 NSDictionary *package((NSDictionary *) value);
1482 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1483 if ([subscribed boolValue] && !metadata->subscribed_)
1484 metadata->subscribed_ = true;
1486 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1487 time_t time([date timeIntervalSince1970]);
1488 if (metadata->first_ > time || metadata->first_ == 0)
1489 metadata->first_ = time;
1492 NSDate *date([package objectForKey:@"LastSeen"]);
1493 NSString *version([package objectForKey:@"LastVersion"]);
1495 if (date != nil && version != nil) {
1496 time_t time([date timeIntervalSince1970]);
1497 if (metadata->last_ < time || metadata->last_ == 0)
1498 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1499 size_t length(strlen(buffer));
1500 uint16_t vhash(hashlittle(buffer, length));
1502 size_t capped(std::min<size_t>(8, length));
1503 char *latest(buffer + length - capped);
1505 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1506 metadata->vhash_ = vhash;
1508 metadata->last_ = time;
1514 static NSDate *GetStatusDate() {
1515 return [[[NSFileManager defaultManager] attributesOfItemAtPath:@"/var/lib/dpkg/status" error:NULL] fileModificationDate];
1518 static void SaveConfig(NSObject *lock) {
1519 @synchronized (lock) {
1525 CFPreferencesSetMultiple((CFDictionaryRef) [NSDictionary dictionaryWithObjectsAndKeys:
1526 Values_, @"CydiaValues",
1527 Sections_, @"CydiaSections",
1528 (id) Sources_, @"CydiaSources",
1529 Version_, @"CydiaVersion",
1530 nil], NULL, CFSTR("com.saurik.Cydia"), kCFPreferencesCurrentUser, kCFPreferencesCurrentHost);
1532 if (!CFPreferencesAppSynchronize(CFSTR("com.saurik.Cydia")))
1533 NSLog(@"CFPreferencesAppSynchronize(com.saurik.Cydia) == false");
1535 CydiaWriteSources();
1538 /* Source Class {{{ */
1539 @interface Source : NSObject {
1541 Database *database_;
1544 CYString depiction_;
1545 CYString description_;
1551 CYString distribution_;
1557 _H<NSString> authority_;
1559 CYString defaultIcon_;
1561 _H<NSMutableDictionary> record_;
1564 std::set<std::string> fetches_;
1565 std::set<std::string> files_;
1566 _transient NSObject<SourceDelegate> *delegate_;
1569 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(CYPool *)pool;
1571 - (NSComparisonResult) compareByName:(Source *)source;
1573 - (NSString *) depictionForPackage:(NSString *)package;
1574 - (NSString *) supportForPackage:(NSString *)package;
1576 - (metaIndex *) metaIndex;
1577 - (NSDictionary *) record;
1580 - (NSString *) rooturi;
1581 - (NSString *) distribution;
1582 - (NSString *) type;
1585 - (NSString *) host;
1587 - (NSString *) name;
1588 - (NSString *) shortDescription;
1589 - (NSString *) label;
1590 - (NSString *) origin;
1591 - (NSString *) version;
1593 - (NSString *) defaultIcon;
1594 - (NSURL *) iconURL;
1596 - (void) setFetch:(bool)fetch forURI:(const char *)uri;
1597 - (void) resetFetch;
1601 @implementation Source
1603 + (NSString *) webScriptNameForSelector:(SEL)selector {
1605 else if (selector == @selector(addSection:))
1606 return @"addSection";
1607 else if (selector == @selector(getField:))
1609 else if (selector == @selector(removeSection:))
1610 return @"removeSection";
1611 else if (selector == @selector(remove))
1617 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1618 return [self webScriptNameForSelector:selector] == nil;
1621 + (NSArray *) _attributeKeys {
1622 return [NSArray arrayWithObjects:
1633 @"shortDescription",
1640 - (NSArray *) attributeKeys {
1641 return [[self class] _attributeKeys];
1644 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1645 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1648 - (metaIndex *) metaIndex {
1652 - (void) setMetaIndex:(metaIndex *)index inPool:(CYPool *)pool {
1653 trusted_ = index->IsTrusted();
1655 uri_.set(pool, index->GetURI());
1656 distribution_.set(pool, index->GetDist());
1657 type_.set(pool, index->GetType());
1659 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1660 if (dindex != NULL) {
1661 std::string file(dindex->MetaIndexURI(""));
1662 base_.set(pool, file);
1665 _profile(Source$setMetaIndex$GetIndexes)
1666 dindex->GetIndexes(&acquire, true);
1668 _profile(Source$setMetaIndex$DescURI)
1669 for (pkgAcquire::ItemIterator item(acquire.ItemsBegin()); item != acquire.ItemsEnd(); item++) {
1670 std::string file((*item)->DescURI());
1671 files_.insert(file);
1672 if (file.length() < sizeof("Packages.bz2") || file.substr(file.length() - sizeof("Packages.bz2")) != "/Packages.bz2")
1674 file = file.substr(0, file.length() - 4);
1675 files_.insert(file);
1676 files_.insert(file + ".gz");
1677 files_.insert(file + "Index");
1682 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1685 pkgTagFile tags(&fd);
1687 pkgTagSection section;
1694 {"default-icon", &defaultIcon_},
1695 {"depiction", &depiction_},
1696 {"description", &description_},
1698 {"origin", &origin_},
1699 {"support", &support_},
1700 {"version", &version_},
1703 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1704 const char *start, *end;
1706 if (section.Find(names[i].name_, start, end)) {
1707 CYString &value(*names[i].value_);
1708 value.set(pool, start, end - start);
1714 record_ = [Sources_ objectForKey:[self key]];
1716 NSURL *url([NSURL URLWithString:uri_]);
1720 host_ = [host_ lowercaseString];
1725 authority_ = [url path];
1728 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(CYPool *)pool {
1729 if ((self = [super init]) != nil) {
1730 era_ = [database era];
1731 database_ = database;
1734 _profile(Source$initWithMetaIndex$setMetaIndex)
1735 [self setMetaIndex:index inPool:pool];
1740 - (NSString *) getField:(NSString *)name {
1741 @synchronized (database_) {
1742 if ([database_ era] != era_ || index_ == NULL)
1745 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index_));
1750 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly)) {
1755 pkgTagFile tags(&fd);
1757 pkgTagSection section;
1760 const char *start, *end;
1761 if (!section.Find([name UTF8String], start, end))
1762 return (NSString *) [NSNull null];
1764 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
1767 - (NSComparisonResult) compareByName:(Source *)source {
1768 NSString *lhs = [self name];
1769 NSString *rhs = [source name];
1771 if ([lhs length] != 0 && [rhs length] != 0) {
1772 unichar lhc = [lhs characterAtIndex:0];
1773 unichar rhc = [rhs characterAtIndex:0];
1775 if (isalpha(lhc) && !isalpha(rhc))
1776 return NSOrderedAscending;
1777 else if (!isalpha(lhc) && isalpha(rhc))
1778 return NSOrderedDescending;
1781 return [lhs compare:rhs options:LaxCompareOptions_];
1784 - (NSString *) depictionForPackage:(NSString *)package {
1785 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1788 - (NSString *) supportForPackage:(NSString *)package {
1789 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1792 - (NSArray *) sections {
1793 return record_ == nil ? (id) [NSNull null] : [record_ objectForKey:@"Sections"] ?: [NSArray array];
1796 - (void) _addSection:(NSString *)section {
1799 else if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) {
1800 if (![sections containsObject:section])
1801 [sections addObject:section];
1803 [record_ setObject:[NSMutableArray arrayWithObject:section] forKey:@"Sections"];
1806 - (bool) addSection:(NSString *)section {
1810 [self performSelectorOnMainThread:@selector(_addSection:) withObject:section waitUntilDone:NO];
1814 - (void) _removeSection:(NSString *)section {
1818 if (NSMutableArray *sections = [record_ objectForKey:@"Sections"])
1819 if ([sections containsObject:section])
1820 [sections removeObject:section];
1823 - (bool) removeSection:(NSString *)section {
1827 [self performSelectorOnMainThread:@selector(_removeSection:) withObject:section waitUntilDone:NO];
1832 [Sources_ removeObjectForKey:[self key]];
1836 bool value(record_ != nil);
1837 [self performSelectorOnMainThread:@selector(_remove) withObject:nil waitUntilDone:NO];
1841 - (NSDictionary *) record {
1849 - (NSString *) rooturi {
1853 - (NSString *) distribution {
1854 return distribution_;
1857 - (NSString *) type {
1861 - (NSString *) baseuri {
1862 return base_.empty() ? nil : (id) base_;
1865 - (NSString *) iconuri {
1866 if (NSString *base = [self baseuri])
1867 return [base stringByAppendingString:@"CydiaIcon.png"];
1872 - (NSURL *) iconURL {
1873 if (NSString *uri = [self iconuri])
1874 return [NSURL URLWithString:uri];
1878 - (NSString *) key {
1879 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1882 - (NSString *) host {
1886 - (NSString *) name {
1887 return origin_.empty() ? (id) authority_ : origin_;
1890 - (NSString *) shortDescription {
1891 return description_;
1894 - (NSString *) label {
1895 return label_.empty() ? (id) authority_ : label_;
1898 - (NSString *) origin {
1902 - (NSString *) version {
1906 - (NSString *) defaultIcon {
1907 return defaultIcon_;
1910 - (void) setDelegate:(NSObject<SourceDelegate> *)delegate {
1911 delegate_ = delegate;
1915 return !fetches_.empty();
1918 - (void) setFetch:(bool)fetch forURI:(const char *)uri {
1920 if (fetches_.erase(uri) == 0)
1922 } else if (files_.find(uri) == files_.end())
1924 else if (!fetches_.insert(uri).second)
1927 [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:[self fetch]] waitUntilDone:NO];
1930 - (void) resetFetch {
1932 [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:NO];
1937 /* CydiaOperation Class {{{ */
1938 @interface CydiaOperation : NSObject {
1939 _H<NSString> operator_;
1940 _H<NSString> value_;
1943 - (NSString *) operator;
1944 - (NSString *) value;
1948 @implementation CydiaOperation
1950 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1951 if ((self = [super init]) != nil) {
1952 operator_ = [NSString stringWithUTF8String:_operator];
1953 value_ = [NSString stringWithUTF8String:value];
1957 + (NSArray *) _attributeKeys {
1958 return [NSArray arrayWithObjects:
1964 - (NSArray *) attributeKeys {
1965 return [[self class] _attributeKeys];
1968 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1969 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1972 - (NSString *) operator {
1976 - (NSString *) value {
1982 /* CydiaClause Class {{{ */
1983 @interface CydiaClause : NSObject {
1984 _H<NSString> package_;
1985 _H<CydiaOperation> version_;
1988 - (NSString *) package;
1989 - (CydiaOperation *) version;
1993 @implementation CydiaClause
1995 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1996 if ((self = [super init]) != nil) {
1997 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1999 if (const char *version = dep.TargetVer())
2000 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
2002 version_ = (id) [NSNull null];
2006 + (NSArray *) _attributeKeys {
2007 return [NSArray arrayWithObjects:
2013 - (NSArray *) attributeKeys {
2014 return [[self class] _attributeKeys];
2017 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2018 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2021 - (NSString *) package {
2025 - (CydiaOperation *) version {
2031 /* CydiaRelation Class {{{ */
2032 @interface CydiaRelation : NSObject {
2033 _H<NSString> relationship_;
2034 _H<NSMutableArray> clauses_;
2037 - (NSString *) relationship;
2038 - (NSArray *) clauses;
2042 @implementation CydiaRelation
2044 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
2045 if ((self = [super init]) != nil) {
2046 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
2047 clauses_ = [NSMutableArray arrayWithCapacity:8];
2049 pkgCache::DepIterator start;
2050 pkgCache::DepIterator end;
2051 dep.GlobOr(start, end); // ++dep
2054 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
2056 // yes, seriously. (wtf?)
2064 + (NSArray *) _attributeKeys {
2065 return [NSArray arrayWithObjects:
2071 - (NSArray *) attributeKeys {
2072 return [[self class] _attributeKeys];
2075 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2076 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2079 - (NSString *) relationship {
2080 return relationship_;
2083 - (NSArray *) clauses {
2087 - (void) addClause:(CydiaClause *)clause {
2088 [clauses_ addObject:clause];
2093 /* Package Class {{{ */
2094 struct ParsedPackage {
2098 CYString architecture_;
2101 CYString depiction_;
2108 @interface Package : NSObject {
2110 @public uint32_t role_ : 3;
2111 uint32_t essential_ : 1;
2112 uint32_t obsolete_ : 1;
2113 uint32_t ignored_ : 1;
2114 uint32_t pooled_ : 1;
2120 _transient Database *database_;
2122 pkgCache::VerIterator version_;
2123 pkgCache::PkgIterator iterator_;
2124 pkgCache::VerFileIterator file_;
2128 CYString transform_;
2131 CYString installed_;
2134 const char *section_;
2135 _transient NSString *section$_;
2139 PackageValue *metadata_;
2140 ParsedPackage *parsed_;
2142 _H<NSMutableArray> tags_;
2145 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database;
2146 + (Package *) newPackageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database;
2148 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database;
2150 - (pkgCache::PkgIterator) iterator;
2153 - (NSString *) section;
2154 - (NSString *) simpleSection;
2156 - (NSString *) longSection;
2157 - (NSString *) shortSection;
2161 - (MIMEAddress *) maintainer;
2163 - (NSString *) longDescription;
2164 - (NSString *) shortDescription;
2167 - (PackageValue *) metadata;
2170 - (bool) subscribed;
2171 - (bool) setSubscribed:(bool)subscribed;
2175 - (NSString *) latest;
2176 - (NSString *) installed;
2177 - (BOOL) uninstalled;
2179 - (BOOL) upgradableAndEssential:(BOOL)essential;
2182 - (BOOL) unfiltered;
2186 - (BOOL) halfConfigured;
2187 - (BOOL) halfInstalled;
2189 - (NSString *) mode;
2192 - (NSString *) name;
2194 - (NSString *) homepage;
2195 - (NSString *) depiction;
2196 - (MIMEAddress *) author;
2198 - (NSString *) support;
2200 - (NSArray *) files;
2201 - (NSArray *) warnings;
2202 - (NSArray *) applications;
2204 - (Source *) source;
2207 - (BOOL) matches:(NSArray *)query;
2209 - (BOOL) hasTag:(NSString *)tag;
2210 - (NSString *) primaryPurpose;
2211 - (NSArray *) purposes;
2212 - (bool) isCommercial;
2214 - (void) setIndex:(size_t)index;
2216 - (CYString &) cyname;
2218 - (uint32_t) compareBySection:(NSArray *)sections;
2225 uint32_t PackageChangesRadix(Package *self, void *) {
2230 uint32_t timestamp : 30;
2231 uint32_t ignored : 1;
2232 uint32_t upgradable : 1;
2236 bool upgradable([self upgradableAndEssential:YES]);
2237 value.bits.upgradable = upgradable ? 1 : 0;
2240 value.bits.timestamp = 0;
2241 value.bits.ignored = [self ignored] ? 0 : 1;
2242 value.bits.upgradable = 1;
2244 value.bits.timestamp = [self seen] >> 2;
2245 value.bits.ignored = 0;
2246 value.bits.upgradable = 0;
2249 return _not(uint32_t) - value.key;
2252 CYString &(*PackageName)(Package *self, SEL sel);
2254 uint32_t PackagePrefixRadix(Package *self, void *context) {
2255 size_t offset(reinterpret_cast<size_t>(context));
2256 CYString &name(PackageName(self, @selector(cyname)));
2258 size_t size(name.size());
2261 char *text(name.data());
2264 if (!isdigit(text[0]))
2268 while (size != digits && isdigit(text[digits]))
2276 if (offset == 0 && zeros != 0) {
2277 memset(data, '0', zeros);
2278 memcpy(data + zeros, text, 4 - zeros);
2280 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2281 if (size <= offset - zeros)
2284 text += offset - zeros;
2285 size -= offset - zeros;
2288 memcpy(data, text, 4);
2290 memcpy(data, text, size);
2291 memset(data + size, 0, 4 - size);
2294 for (size_t i(0); i != 4; ++i)
2295 if (isalpha(data[i]))
2303 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2305 /* XXX: ntohl may be more honest */
2306 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2309 CFComparisonResult StringNameCompare(CFStringRef lhn, CFStringRef rhn, size_t length) {
2310 _profile(PackageNameCompare)
2312 return rhn == NULL ? kCFCompareEqualTo : kCFCompareLessThan;
2313 else if (rhn == NULL)
2314 return kCFCompareGreaterThan;
2316 CFIndex length(CFStringGetLength(lhn));
2318 _profile(PackageNameCompare$NumbersLast)
2319 if (length != 0 && CFStringGetLength(rhn) != 0) {
2320 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2321 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2322 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2323 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2324 return lha ? kCFCompareLessThan : kCFCompareGreaterThan;
2328 _profile(PackageNameCompare$Compare)
2329 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, (CFLocaleRef) (id) CollationLocale_);
2334 _finline CFComparisonResult StringNameCompare(NSString *lhn, NSString*rhn, size_t length) {
2335 return StringNameCompare((CFStringRef) lhn, (CFStringRef) rhn, length);
2338 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2339 CYString &lhn(PackageName(lhs, @selector(cyname)));
2340 NSString *rhn(PackageName(rhs, @selector(cyname)));
2341 return StringNameCompare(lhn, rhn, lhn.size());
2344 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *arg) {
2345 return PackageNameCompare(*lhs, *rhs, arg);
2348 struct PackageNameOrdering :
2349 std::binary_function<Package *, Package *, bool>
2351 _finline bool operator ()(Package *lhs, Package *rhs) const {
2352 return PackageNameCompare(lhs, rhs, NULL) == kCFCompareLessThan;
2356 @implementation Package
2358 - (NSString *) description {
2359 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2365 if (parsed_ != NULL)
2370 + (NSString *) webScriptNameForSelector:(SEL)selector {
2372 else if (selector == @selector(clear))
2374 else if (selector == @selector(getField:))
2376 else if (selector == @selector(getRecord))
2377 return @"getRecord";
2378 else if (selector == @selector(hasTag:))
2380 else if (selector == @selector(install))
2382 else if (selector == @selector(remove))
2388 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2389 return [self webScriptNameForSelector:selector] == nil;
2392 + (NSArray *) _attributeKeys {
2393 return [NSArray arrayWithObjects:
2414 @"shortDescription",
2427 - (NSArray *) attributeKeys {
2428 return [[self class] _attributeKeys];
2431 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2432 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2435 - (NSArray *) relations {
2436 @synchronized (database_) {
2437 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2438 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2439 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2443 - (NSString *) architecture {
2445 @synchronized (database_) {
2446 return parsed_->architecture_.empty() ? [NSNull null] : (id) parsed_->architecture_;
2449 - (NSString *) getField:(NSString *)name {
2450 @synchronized (database_) {
2451 if ([database_ era] != era_ || file_.end())
2454 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2456 const char *start, *end;
2457 if (!parser.Find([name UTF8String], start, end))
2458 return (NSString *) [NSNull null];
2460 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2463 - (NSString *) getRecord {
2464 @synchronized (database_) {
2465 if ([database_ era] != era_ || file_.end())
2468 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2470 const char *start, *end;
2471 parser.GetRec(start, end);
2473 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2477 if (parsed_ != NULL)
2479 @synchronized (database_) {
2480 if ([database_ era] != era_ || file_.end())
2483 ParsedPackage *parsed(new ParsedPackage);
2486 _profile(Package$parse)
2487 pkgRecords::Parser *parser;
2489 _profile(Package$parse$Lookup)
2490 parser = &[database_ records]->Lookup(file_);
2496 _profile(Package$parse$Find)
2501 {"architecture", &parsed->architecture_},
2502 {"icon", &parsed->icon_},
2503 {"depiction", &parsed->depiction_},
2504 {"homepage", &parsed->homepage_},
2505 {"website", &website},
2507 {"support", &parsed->support_},
2508 {"author", &parsed->author_},
2509 {"md5sum", &parsed->md5sum_},
2512 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2513 const char *start, *end;
2515 if (parser->Find(names[i].name_, start, end)) {
2516 CYString &value(*names[i].value_);
2517 _profile(Package$parse$Value)
2518 value.set(pool_, start, end - start);
2524 _profile(Package$parse$Tagline)
2525 parsed->tagline_.set(pool_, parser->ShortDesc());
2528 _profile(Package$parse$Retain)
2529 if (parsed->homepage_.empty())
2530 parsed->homepage_ = website;
2531 if (parsed->homepage_ == parsed->depiction_)
2532 parsed->homepage_.clear();
2533 if (parsed->support_.empty())
2534 parsed->support_ = bugs;
2539 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database {
2540 if ((self = [super init]) != nil) {
2541 _profile(Package$initWithVersion)
2543 pool_ = new CYPool();
2549 database_ = database;
2550 era_ = [database era];
2554 pkgCache::PkgIterator iterator(version_.ParentPkg());
2555 iterator_ = iterator;
2557 _profile(Package$initWithVersion$Version)
2558 file_ = version_.FileList();
2561 _profile(Package$initWithVersion$Cache)
2562 name_.set(NULL, version_.Display());
2564 latest_.set(NULL, StripVersion_(version_.VerStr()));
2566 pkgCache::VerIterator current(iterator.CurrentVer());
2568 installed_.set(NULL, StripVersion_(current.VerStr()));
2571 _profile(Package$initWithVersion$Transliterate) do {
2572 if (CollationTransl_ == NULL)
2577 _profile(Package$initWithVersion$Transliterate$utf8)
2578 const uint8_t *data(reinterpret_cast<const uint8_t *>(name_.data()));
2579 for (size_t i(0), e(name_.size()); i != e; ++i)
2580 if (data[i] >= 0x80)
2585 UErrorCode code(U_ZERO_ERROR);
2588 _profile(Package$initWithVersion$Transliterate$u_strFromUTF8WithSub)
2589 CollationString_.resize(name_.size());
2590 u_strFromUTF8WithSub(&CollationString_[0], CollationString_.size(), &length, name_.data(), name_.size(), 0xfffd, NULL, &code);
2591 if (!U_SUCCESS(code))
2593 CollationString_.resize(length);
2596 _profile(Package$initWithVersion$Transliterate$utrans_trans)
2597 length = CollationString_.size();
2598 utrans_trans(CollationTransl_, reinterpret_cast<UReplaceable *>(&CollationString_), &CollationUCalls_, 0, &length, &code);
2599 if (!U_SUCCESS(code))
2601 _assert(CollationString_.size() == length);
2604 _profile(Package$initWithVersion$Transliterate$u_strToUTF8WithSub$preflight)
2605 u_strToUTF8WithSub(NULL, 0, &length, CollationString_.data(), CollationString_.size(), 0xfffd, NULL, &code);
2606 if (code == U_BUFFER_OVERFLOW_ERROR)
2607 code = U_ZERO_ERROR;
2608 else if (!U_SUCCESS(code))
2613 _profile(Package$initWithVersion$Transliterate$apr_palloc)
2614 transform = pool_->malloc<char>(length);
2616 _profile(Package$initWithVersion$Transliterate$u_strToUTF8WithSub$transform)
2617 u_strToUTF8WithSub(transform, length, NULL, CollationString_.data(), CollationString_.size(), 0xfffd, NULL, &code);
2618 if (!U_SUCCESS(code))
2622 transform_.set(NULL, transform, length);
2623 } while (false); _end
2625 _profile(Package$initWithVersion$Tags)
2627 pkgCache::TagIterator tag(version_.TagList());
2629 pkgCache::TagIterator tag(iterator.TagList());
2632 tags_ = [NSMutableArray arrayWithCapacity:8];
2634 goto tag; for (; !tag.end(); ++tag) tag: {
2635 const char *name(tag.Name());
2636 NSString *string((NSString *) CYStringCreate(name));
2640 [tags_ addObject:[string autorelease]];
2642 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2643 if (strcmp(name + 6, "enduser") == 0)
2645 else if (strcmp(name + 6, "hacker") == 0)
2647 else if (strcmp(name + 6, "developer") == 0)
2649 else if (strcmp(name + 6, "cydia") == 0)
2655 if (strncmp(name, "cydia::", 7) == 0) {
2656 if (strcmp(name + 7, "essential") == 0)
2658 else if (strcmp(name + 7, "obsolete") == 0)
2665 _profile(Package$initWithVersion$Metadata)
2666 const char *mixed(iterator.Name());
2667 size_t size(strlen(mixed));
2668 static const size_t prefix(sizeof("/var/lib/dpkg/info/") - 1);
2669 char lower[prefix + size + 5 + 1];
2671 for (size_t i(0); i != size; ++i)
2672 lower[prefix + i] = mixed[i] | 0x20;
2674 if (!installed_.empty()) {
2675 memcpy(lower, "/var/lib/dpkg/info/", prefix);
2676 memcpy(lower + prefix + size, ".list", 6);
2678 if (stat(lower, &info) != -1)
2679 upgraded_ = info.st_birthtime;
2682 PackageValue *metadata(PackageFind(lower + prefix, size));
2683 metadata_ = metadata;
2685 id_.set(NULL, metadata->name_, size);
2687 const char *latest(version_.VerStr());
2688 size_t length(strlen(latest));
2690 uint16_t vhash(hashlittle(latest, length));
2692 size_t capped(std::min<size_t>(8, length));
2693 latest = latest + length - capped;
2695 if (metadata->first_ == 0)
2696 metadata->first_ = now_;
2698 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2699 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2700 metadata->vhash_ = vhash;
2701 metadata->last_ = now_;
2702 } else if (metadata->last_ == 0)
2703 metadata->last_ = metadata->first_;
2706 _profile(Package$initWithVersion$Section)
2707 section_ = version_.Section();
2710 _profile(Package$initWithVersion$Flags)
2711 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2712 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2717 + (Package *) newPackageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database {
2718 pkgCache::VerIterator version;
2720 _profile(Package$packageWithIterator$GetCandidateVer)
2721 version = [database policy]->GetCandidateVer(iterator);
2729 _profile(Package$packageWithIterator$Allocate)
2730 package = [Package allocWithZone:zone];
2733 _profile(Package$packageWithIterator$Initialize)
2735 initWithVersion:version
2745 // XXX: just in case a Cydia extension is using this (I bet this is unlikely, though, due to CYPool?)
2746 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database {
2747 return [[self newPackageWithIterator:iterator withZone:zone inPool:pool database:database] autorelease];
2750 - (pkgCache::PkgIterator) iterator {
2754 - (NSArray *) downgrades {
2755 NSMutableArray *versions([NSMutableArray arrayWithCapacity:4]);
2757 for (auto version(iterator_.VersionList()); !version.end(); ++version) {
2758 if (version == version_)
2760 Package *package([[[Package allocWithZone:NULL] initWithVersion:version withZone:NULL inPool:NULL database:database_] autorelease]);
2761 if ([package source] == nil)
2763 [versions addObject:package];
2769 - (NSString *) section {
2770 if (section$_ == nil) {
2771 if (section_ == NULL)
2774 _profile(Package$section$mappedSectionForPointer)
2775 section$_ = [database_ mappedSectionForPointer:section_];
2780 - (NSString *) simpleSection {
2781 if (NSString *section = [self section])
2782 return Simplify(section);
2787 - (NSString *) longSection {
2788 if (NSString *section = [self section])
2789 return LocalizeSection(section);
2794 - (NSString *) shortSection {
2795 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2798 - (NSString *) uri {
2801 pkgIndexFile *index;
2802 pkgCache::PkgFileIterator file(file_.File());
2803 if (![database_ list].FindIndex(file, index))
2805 return [NSString stringWithUTF8String:iterator_->Path];
2806 //return [NSString stringWithUTF8String:file.Site()];
2807 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2811 - (MIMEAddress *) maintainer {
2812 @synchronized (database_) {
2813 if ([database_ era] != era_ || file_.end())
2816 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2817 const std::string &maintainer(parser->Maintainer());
2818 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2821 - (NSString *) md5sum {
2822 return parsed_ == NULL ? nil : (id) parsed_->md5sum_;
2826 @synchronized (database_) {
2827 if ([database_ era] != era_ || version_.end())
2830 return version_->InstalledSize;
2833 - (NSString *) longDescription {
2834 @synchronized (database_) {
2835 if ([database_ era] != era_ || file_.end())
2838 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2839 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2841 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2842 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2843 if ([lines count] < 2)
2846 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2847 for (size_t i(1), e([lines count]); i != e; ++i) {
2848 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2849 [trimmed addObject:trim];
2852 return [trimmed componentsJoinedByString:@"\n"];
2855 - (NSString *) shortDescription {
2856 if (parsed_ != NULL)
2857 return static_cast<NSString *>(parsed_->tagline_);
2859 @synchronized (database_) {
2860 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2861 std::string value(parser.ShortDesc());
2864 if (value.size() > 200)
2866 return [(id) CYStringCreate(value) autorelease];
2870 _profile(Package$index)
2871 CFStringRef name((CFStringRef) [self name]);
2872 if (CFStringGetLength(name) == 0)
2874 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2875 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2877 return toupper(character);
2881 - (PackageValue *) metadata {
2886 PackageValue *metadata([self metadata]);
2887 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2890 - (bool) subscribed {
2891 return [self metadata]->subscribed_;
2894 - (bool) setSubscribed:(bool)subscribed {
2895 PackageValue *metadata([self metadata]);
2896 if (metadata->subscribed_ == subscribed)
2898 metadata->subscribed_ = subscribed;
2906 - (NSString *) latest {
2910 - (NSString *) installed {
2914 - (BOOL) uninstalled {
2915 return installed_.empty();
2918 - (BOOL) upgradableAndEssential:(BOOL)essential {
2919 _profile(Package$upgradableAndEssential)
2920 pkgCache::VerIterator current(iterator_.CurrentVer());
2922 return essential && essential_;
2924 return version_ != current;
2928 - (BOOL) essential {
2933 return [database_ cache][iterator_].InstBroken();
2936 - (BOOL) unfiltered {
2937 _profile(Package$unfiltered$obsolete)
2938 if (_unlikely(obsolete_))
2942 _profile(Package$unfiltered$role)
2943 if (_unlikely(role_ > 3))
2951 if (![self unfiltered])
2956 _profile(Package$visible$section)
2957 section = [self section];
2960 _profile(Package$visible$isSectionVisible)
2961 if (!isSectionVisible(section))
2969 unsigned char current(iterator_->CurrentState);
2970 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2973 - (BOOL) halfConfigured {
2974 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2977 - (BOOL) halfInstalled {
2978 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2982 @synchronized (database_) {
2983 if ([database_ era] != era_ || iterator_.end())
2986 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2987 return state.Mode != pkgDepCache::ModeKeep;
2990 - (NSString *) mode {
2991 @synchronized (database_) {
2992 if ([database_ era] != era_ || iterator_.end())
2995 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2997 switch (state.Mode) {
2998 case pkgDepCache::ModeDelete:
2999 if ((state.iFlags & pkgDepCache::Purge) != 0)
3003 case pkgDepCache::ModeKeep:
3004 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
3005 return @"REINSTALL";
3006 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
3010 case pkgDepCache::ModeInstall:
3011 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
3012 return @"REINSTALL";
3013 else*/ switch (state.Status) {
3015 return @"DOWNGRADE";
3021 return @"NEW_INSTALL";
3032 - (NSString *) name {
3033 return name_.empty() ? id_ : name_;
3036 - (UIImage *) icon {
3037 NSString *section = [self simpleSection];
3040 if (parsed_ != NULL)
3041 if (NSString *href = parsed_->icon_)
3042 if ([href hasPrefix:@"file:///"])
3043 icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
3044 if (icon == nil) if (section != nil)
3045 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]];
3046 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
3047 if ([dicon hasPrefix:@"file:///"])
3048 icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
3050 icon = [UIImage imageNamed:@"unknown.png"];
3054 - (NSString *) homepage {
3055 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
3058 - (NSString *) depiction {
3059 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
3062 - (MIMEAddress *) author {
3063 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
3066 - (NSString *) support {
3067 return parsed_ != NULL && !parsed_->support_.empty() ? parsed_->support_ : [[self source] supportForPackage:id_];
3070 - (NSArray *) files {
3071 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
3072 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
3075 fin.open([path UTF8String]);
3080 while (std::getline(fin, line))
3081 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
3086 - (NSString *) state {
3087 @synchronized (database_) {
3088 if ([database_ era] != era_ || file_.end())
3091 switch (iterator_->CurrentState) {
3092 case pkgCache::State::NotInstalled:
3093 return @"NotInstalled";
3094 case pkgCache::State::UnPacked:
3096 case pkgCache::State::HalfConfigured:
3097 return @"HalfConfigured";
3098 case pkgCache::State::HalfInstalled:
3099 return @"HalfInstalled";
3100 case pkgCache::State::ConfigFiles:
3101 return @"ConfigFiles";
3102 case pkgCache::State::Installed:
3103 return @"Installed";
3104 case pkgCache::State::TriggersAwaited:
3105 return @"TriggersAwaited";
3106 case pkgCache::State::TriggersPending:
3107 return @"TriggersPending";
3110 return (NSString *) [NSNull null];
3113 - (NSString *) selection {
3114 @synchronized (database_) {
3115 if ([database_ era] != era_ || file_.end())
3118 switch (iterator_->SelectedState) {
3119 case pkgCache::State::Unknown:
3121 case pkgCache::State::Install:
3123 case pkgCache::State::Hold:
3125 case pkgCache::State::DeInstall:
3126 return @"DeInstall";
3127 case pkgCache::State::Purge:
3131 return (NSString *) [NSNull null];
3134 - (NSArray *) warnings {
3135 @synchronized (database_) {
3136 if ([database_ era] != era_ || file_.end())
3139 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
3140 const char *name(iterator_.Name());
3142 size_t length(strlen(name));
3143 if (length < 2) invalid:
3144 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
3145 else for (size_t i(0); i != length; ++i)
3147 /* XXX: technically this is not allowed */
3148 (name[i] < 'A' || name[i] > 'Z') &&
3149 (name[i] < 'a' || name[i] > 'z') &&
3150 (name[i] < '0' || name[i] > '9') &&
3151 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
3154 if (strcmp(name, "cydia") != 0) {
3157 bool _private = false;
3159 bool dbstash = false;
3160 bool dsstore = false;
3162 bool repository = [[self section] isEqualToString:@"Repositories"];
3164 if (NSArray *files = [self files])
3165 for (NSString *file in files)
3166 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
3168 else if (!user && [file isEqualToString:@"/User"])
3170 else if (!_private && [file isEqualToString:@"/private"])
3172 else if (!stash && [file isEqualToString:@"/var/stash"])
3174 else if (!dbstash && [file isEqualToString:@"/var/db/stash"])
3176 else if (!dsstore && [file hasSuffix:@"/.DS_Store"])
3179 /* XXX: this is not sensitive enough. only some folders are valid. */
3180 if (cydia && !repository)
3181 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
3183 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
3185 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
3187 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
3189 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/db/stash"]];
3191 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @".DS_Store"]];
3194 return [warnings count] == 0 ? nil : warnings;
3197 - (NSArray *) applications {
3198 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
3200 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
3202 static RegEx application_r("/Applications/(.*)\\.app/Info.plist");
3203 if (NSArray *files = [self files])
3204 for (NSString *file in files)
3205 if (application_r(file)) {
3206 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
3209 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
3210 if (id == nil || [id isEqualToString:me])
3213 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
3215 display = application_r[1];
3217 NSString *bundle([file stringByDeletingLastPathComponent]);
3218 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
3219 // XXX: maybe this should check if this is really a string, not just for length
3220 if (icon == nil || ![icon respondsToSelector:@selector(length)] || [icon length] == 0)
3222 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
3224 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
3225 [applications addObject:application];
3227 [application addObject:id];
3228 [application addObject:display];
3229 [application addObject:url];
3232 return [applications count] == 0 ? nil : applications;
3235 - (Source *) source {
3236 if (source_ == nil) {
3237 @synchronized (database_) {
3238 if ([database_ era] != era_ || file_.end())
3239 source_ = (Source *) [NSNull null];
3241 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
3245 return source_ == (Source *) [NSNull null] ? nil : source_;
3248 - (time_t) upgraded {
3252 - (uint32_t) recent {
3253 return std::numeric_limits<uint32_t>::max() - upgraded_;
3260 - (BOOL) matches:(NSArray *)query {
3261 if (query == nil || [query count] == 0)
3270 string = [self name];
3271 length = [string length];
3274 for (NSString *term in query) {
3275 range = [string rangeOfString:term options:MatchCompareOptions_];
3276 if (range.location != NSNotFound)
3277 rank_ -= 6 * 1000000 / length;
3282 length = [string length];
3285 for (NSString *term in query) {
3286 range = [string rangeOfString:term options:MatchCompareOptions_];
3287 if (range.location != NSNotFound)
3288 rank_ -= 6 * 1000000 / length;
3292 string = [self shortDescription];
3293 length = [string length];
3294 NSUInteger stop(std::min<NSUInteger>(length, 200));
3297 for (NSString *term in query) {
3298 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
3299 if (range.location != NSNotFound)
3300 rank_ -= 2 * 100000;
3306 - (NSArray *) tags {
3310 - (BOOL) hasTag:(NSString *)tag {
3311 return tags_ == nil ? NO : [tags_ containsObject:tag];
3314 - (NSString *) primaryPurpose {
3315 for (NSString *tag in (NSArray *) tags_)
3316 if ([tag hasPrefix:@"purpose::"])
3317 return [tag substringFromIndex:9];
3321 - (NSArray *) purposes {
3322 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
3323 for (NSString *tag in (NSArray *) tags_)
3324 if ([tag hasPrefix:@"purpose::"])
3325 [purposes addObject:[tag substringFromIndex:9]];
3326 return [purposes count] == 0 ? nil : purposes;
3329 - (bool) isCommercial {
3330 return [self hasTag:@"cydia::commercial"];
3333 - (void) setIndex:(size_t)index {
3334 if (metadata_->index_ != index + 1)
3335 metadata_->index_ = index + 1;
3338 - (CYString &) cyname {
3339 return !transform_.empty() ? transform_ : !name_.empty() ? name_ : id_;
3342 - (uint32_t) compareBySection:(NSArray *)sections {
3343 NSString *section([self section]);
3344 for (size_t i(0), e([sections count]); i != e; ++i) {
3345 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3349 return _not(uint32_t);
3353 @synchronized (database_) {
3354 if ([database_ era] != era_ || file_.end())
3357 pkgProblemResolver *resolver = [database_ resolver];
3358 resolver->Clear(iterator_);
3360 pkgCacheFile &cache([database_ cache]);
3361 cache->SetReInstall(iterator_, false);
3362 cache->MarkKeep(iterator_, false);
3366 @synchronized (database_) {
3367 if ([database_ era] != era_ || file_.end())
3370 pkgProblemResolver *resolver = [database_ resolver];
3371 resolver->Clear(iterator_);
3372 resolver->Protect(iterator_);
3374 pkgCacheFile &cache([database_ cache]);
3375 cache->SetCandidateVersion(version_);
3376 cache->SetReInstall(iterator_, false);
3377 cache->MarkInstall(iterator_, false);
3379 pkgDepCache::StateCache &state((*cache)[iterator_]);
3380 if (!state.Install())
3381 cache->SetReInstall(iterator_, true);
3385 @synchronized (database_) {
3386 if ([database_ era] != era_ || file_.end())
3389 pkgProblemResolver *resolver = [database_ resolver];
3390 resolver->Clear(iterator_);
3391 resolver->Remove(iterator_);
3392 resolver->Protect(iterator_);
3394 pkgCacheFile &cache([database_ cache]);
3395 cache->SetReInstall(iterator_, false);
3396 cache->MarkDelete(iterator_, true);
3401 /* Section Class {{{ */
3402 @interface Section : NSObject {
3406 _H<NSString> localized_;
3409 - (NSComparisonResult) compareByLocalized:(Section *)section;
3410 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3411 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3412 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3414 - (NSString *) name;
3415 - (void) setName:(NSString *)name;
3421 - (void) addToCount;
3423 - (void) setCount:(size_t)count;
3424 - (NSString *) localized;
3428 @implementation Section
3430 - (NSComparisonResult) compareByLocalized:(Section *)section {
3431 NSString *lhs(localized_);
3432 NSString *rhs([section localized]);
3434 /*if ([lhs length] != 0 && [rhs length] != 0) {
3435 unichar lhc = [lhs characterAtIndex:0];
3436 unichar rhc = [rhs characterAtIndex:0];
3438 if (isalpha(lhc) && !isalpha(rhc))
3439 return NSOrderedAscending;
3440 else if (!isalpha(lhc) && isalpha(rhc))
3441 return NSOrderedDescending;
3444 return [lhs compare:rhs options:LaxCompareOptions_];
3447 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3448 if ((self = [self initWithName:name localize:NO]) != nil) {
3449 if (localized != nil)
3450 localized_ = localized;
3454 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3455 return [self initWithName:name row:0 localize:localize];
3458 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3459 if ((self = [super init]) != nil) {
3463 localized_ = LocalizeSection(name_);
3467 - (NSString *) name {
3471 - (void) setName:(NSString *)name {
3487 - (void) addToCount {
3491 - (void) setCount:(size_t)count {
3495 - (NSString *) localized {
3502 class CydiaLogCleaner :
3503 public pkgArchiveCleaner
3506 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3511 /* Database Implementation {{{ */
3512 @implementation Database
3514 + (Database *) sharedInstance {
3515 static _H<Database> instance;
3516 if (instance == nil)
3517 instance = [[[Database alloc] init] autorelease];
3525 - (void) releasePackages {
3529 - (bool) hasPackages {
3530 return [packages_ count] != 0;
3534 // XXX: actually implement this thing
3536 [self releasePackages];
3537 NSRecycleZone(zone_);
3541 - (void) _readCydia:(NSNumber *)fd {
3542 boost::fdistream is([fd intValue]);
3545 static RegEx finish_r("finish:([^:]*)");
3547 while (std::getline(is, line)) {
3548 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3550 const char *data(line.c_str());
3551 size_t size = line.size();
3552 lprintf("C:%s\n", data);
3554 if (finish_r(data, size)) {
3555 NSString *finish = finish_r[1];
3556 int index = [Finishes_ indexOfObject:finish];
3557 if (index != INT_MAX && index > Finish_)
3567 - (void) _readStatus:(NSNumber *)fd {
3568 boost::fdistream is([fd intValue]);
3571 static RegEx conffile_r("status: [^ ]* : conffile-prompt : (.*?) *");
3572 static RegEx pmstatus_r("([^:]*):([^:]*):([^:]*):(.*)");
3574 while (std::getline(is, line)) {
3575 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3577 const char *data(line.c_str());
3578 size_t size(line.size());
3579 lprintf("S:%s\n", data);
3581 if (conffile_r(data, size)) {
3582 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3583 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3584 } else if (strncmp(data, "status: ", 8) == 0) {
3585 // status: <package>: {unpacked,half-configured,installed}
3586 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3587 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3588 } else if (strncmp(data, "processing: ", 12) == 0) {
3589 // processing: configure: config-test
3590 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3591 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3592 } else if (pmstatus_r(data, size)) {
3593 std::string type([pmstatus_r[1] UTF8String]);
3595 NSString *package = pmstatus_r[2];
3596 if ([package isEqualToString:@"dpkg-exec"])
3599 float percent([pmstatus_r[3] floatValue]);
3600 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3602 NSString *string = pmstatus_r[4];
3604 if (type == "pmerror") {
3605 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3606 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3607 } else if (type == "pmstatus") {
3608 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3609 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3610 } else if (type == "pmconffile")
3611 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3613 lprintf("E:unknown pmstatus\n");
3615 lprintf("E:unknown status\n");
3623 - (void) _readOutput:(NSNumber *)fd {
3624 boost::fdistream is([fd intValue]);
3627 while (std::getline(is, line)) {
3628 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3630 lprintf("O:%s\n", line.c_str());
3632 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3633 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3645 - (Package *) packageWithName:(NSString *)name {
3648 @synchronized (self) {
3649 if (static_cast<pkgDepCache *>(cache_) == NULL)
3651 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]
3656 return iterator.end() ? nil : [[Package newPackageWithIterator:iterator withZone:NULL inPool:NULL database:self] autorelease];
3660 if ((self = [super init]) != nil) {
3667 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
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 {
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: this block should probably be merged with popError: in some way
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];
3900 } else if ([self popErrorWithTitle:title forOperation:true])
3904 unlink("/tmp/cydia.chk");
3906 now_ = [[NSDate date] timeIntervalSince1970];
3908 policy_ = new pkgDepCache::Policy();
3909 records_ = new pkgRecords(cache_);
3910 resolver_ = new pkgProblemResolver(cache_);
3911 fetcher_ = new pkgAcquire(&status_);
3914 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3915 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3919 _profile(reloadDataWithInvocation$pkgApplyStatus)
3920 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3924 if (cache_->BrokenCount() != 0) {
3925 _profile(pkgApplyStatus$pkgFixBroken)
3926 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3930 if (cache_->BrokenCount() != 0) {
3931 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3935 _profile(pkgApplyStatus$pkgMinimizeUpgrade)
3936 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3941 for (Source *object in (id) sourceList_) {
3942 metaIndex *source([object metaIndex]);
3943 std::vector<pkgIndexFile *> *indices = source->GetIndexFiles();
3944 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3945 // XXX: this could be more intelligent
3946 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3947 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3949 sourceMap_[cached->ID] = object;
3954 size_t capacity(MetaFile_->active_);
3956 capacity = 128*1024;
3960 std::vector<Package *> packages;
3961 packages.reserve(capacity);
3965 _profile(reloadDataWithInvocation$packageWithIterator)
3966 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3967 if (Package *package = [Package newPackageWithIterator:iterator withZone:zone_ inPool:&pool_ database:self]) {
3968 if (unsigned index = package.metadata->index_) {
3970 if (packages.size() == index) {
3971 packages.push_back(package);
3972 } else if (packages.size() <= index) {
3973 packages.resize(index + 1, nil);
3974 packages[index] = package;
3977 std::swap(package, packages[index]);
3985 if (last == packages.size()) {
3986 packages.push_back(package);
3989 packages[last] = package;
3994 for (; last != packages.size(); ++last)
3995 if (packages[last] == nil)
4000 for (size_t next(last + 1); last != packages.size(); ++last, ++next) {
4002 if (next == packages.size())
4004 if (packages[next] != nil)
4009 std::swap(packages[last], packages[next]);
4012 packages.resize(last);
4014 packages_ = [[[NSMutableArray alloc] initWithObjects:packages.data() count:packages.size()] autorelease];
4017 NSLog(@"lost = %zu", lost);
4019 _profile(reloadDataWithInvocation$radix$8)
4020 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(8)];
4023 _profile(reloadDataWithInvocation$radix$4)
4024 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
4027 _profile(reloadDataWithInvocation$radix$0)
4028 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
4032 _profile(reloadDataWithInvocation$insertion)
4033 CFArrayInsertionSortValues((CFMutableArrayRef) (NSArray *) packages_, CFRangeMake(0, packages.size()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
4036 /*_profile(reloadDataWithInvocation$CFQSortArray)
4037 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);
4040 /*_profile(reloadDataWithInvocation$stdsort)
4041 std::sort(packages.begin(), packages.end(), PackageNameOrdering());
4044 /*_profile(reloadDataWithInvocation$CFArraySortValues)
4045 CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
4048 /*_profile(reloadDataWithInvocation$sortUsingFunction)
4049 [packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
4052 MetaFile_->active_ = packages.size();
4053 for (size_t index(0), count(packages.size()); index != count; ++index) {
4054 auto package((Package *) [packages_ objectAtIndex:index]);
4055 [package setIndex:index];
4062 @synchronized (self) {
4064 resolver_ = new pkgProblemResolver(cache_);
4066 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
4067 if (!cache_[iterator].Keep())
4068 cache_->MarkKeep(iterator, false);
4069 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
4070 cache_->SetReInstall(iterator, false);
4073 - (void) configure {
4074 NSString *dpkg = [NSString stringWithFormat:@"/usr/libexec/cydo --configure -a --status-fd %u", statusfd_];
4076 system([dpkg UTF8String]);
4081 @synchronized (self) {
4082 // XXX: I don't remember this condition
4087 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
4089 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
4091 if ([self popErrorWithTitle:title])
4095 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
4097 CydiaLogCleaner cleaner;
4098 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
4105 fetcher_->Shutdown();
4107 pkgRecords records(cache_);
4109 lock_ = new FileFd();
4110 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
4112 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
4114 if ([self popErrorWithTitle:title])
4118 if ([self popErrorWithTitle:title forReadList:list])
4121 manager_ = (_system->CreatePM(cache_));
4122 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
4129 bool substrate(RestartSubstrate_);
4130 RestartSubstrate_ = false;
4132 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
4134 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
4136 if ([self popErrorWithTitle:title forReadList:list])
4138 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
4139 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
4142 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4144 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
4146 [self popErrorWithTitle:title];
4150 bool failed = false;
4151 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
4152 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
4154 if ((*item)->Status == pkgAcquire::Item::StatIdle)
4157 std::string uri = (*item)->DescURI();
4158 std::string error = (*item)->ErrorText;
4160 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
4163 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError]);
4164 [delegate_ addProgressEventOnMainThread:event forTask:title];
4167 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4175 RestartSubstrate_ = true;
4177 if (![delock_ isEqual:GetStatusDate()]) {
4178 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("DPKG_LOCKED") ofType:kCydiaProgressEventTypeError] forTask:title];
4184 pkgPackageManager::OrderResult result(manager_->DoInstall(statusfd_));
4186 NSString *oextended(@"/var/lib/apt/extended_states");
4187 NSString *nextended(Cache("extended_states"));
4190 if (stat([nextended UTF8String], &info) != -1 && (info.st_mode & S_IFMT) == S_IFREG)
4191 system([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /bin/cp --remove-destination %@ %@", ShellEscape(nextended), ShellEscape(oextended)] UTF8String]);
4193 unlink([nextended UTF8String]);
4194 symlink([oextended UTF8String], [nextended UTF8String]);
4196 if ([self popErrorWithTitle:title])
4199 if (result == pkgPackageManager::Failed) {
4204 if (result != pkgPackageManager::Completed) {
4209 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
4211 if ([self popErrorWithTitle:title forReadList:list])
4213 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
4214 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
4217 if (![before isEqualToArray:after])
4222 return ![delock_ isEqual:GetStatusDate()];
4226 NSString *title(UCLocalize("UPGRADE"));
4227 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
4233 [self updateWithStatus:status_];
4236 - (void) updateWithStatus:(CancelStatus &)status {
4237 NSString *title(UCLocalize("REFRESHING_DATA"));
4240 if ([self popErrorWithTitle:title forReadList:list])
4244 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
4245 if ([self popErrorWithTitle:title])
4248 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4250 bool success(ListUpdate(status, list, PulseInterval_));
4251 if (status.WasCancelled())
4254 [self popErrorWithTitle:title forOperation:success];
4256 [[NSDictionary dictionaryWithObjectsAndKeys:
4257 [NSDate date], @"LastUpdate",
4258 nil] writeToFile:@ CacheState_ atomically:YES];
4261 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4264 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
4265 delegate_ = delegate;
4268 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
4269 progress_ = delegate;
4270 status_.setDelegate(delegate);
4273 - (NSObject<ProgressDelegate> *) progressDelegate {
4277 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
4278 SourceMap::const_iterator i(sourceMap_.find(file->ID));
4279 return i == sourceMap_.end() ? nil : i->second;
4282 - (void) setFetch:(bool)fetch forURI:(const char *)uri {
4283 for (Source *source in (id) sourceList_)
4284 [source setFetch:fetch forURI:uri];
4287 - (void) resetFetch {
4288 for (Source *source in (id) sourceList_)
4289 [source resetFetch];
4292 - (NSString *) mappedSectionForPointer:(const char *)section {
4293 _H<NSString> *mapped;
4295 _profile(Database$mappedSectionForPointer$Cache)
4296 mapped = §ions_[section];
4299 if (*mapped == NULL) {
4300 size_t length(strlen(section));
4301 char spaced[length + 1];
4303 _profile(Database$mappedSectionForPointer$Replace)
4304 for (size_t index(0); index != length; ++index)
4305 spaced[index] = section[index] == '_' ? ' ' : section[index];
4306 spaced[length] = '\0';
4311 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
4312 string = [NSString stringWithUTF8String:spaced];
4315 _profile(Database$mappedSectionForPointer$Map)
4316 string = [SectionMap_ objectForKey:string] ?: string;
4326 static _H<NSMutableSet> Diversions_;
4328 @interface Diversion : NSObject {
4331 _H<NSString> format_;
4336 @implementation Diversion
4338 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
4339 if ((self = [super init]) != nil) {
4340 pattern_ = [from UTF8String];
4346 - (NSString *) divert:(NSString *)url {
4347 return !pattern_(url) ? nil : pattern_->*format_;
4350 + (NSURL *) divertURL:(NSURL *)url {
4352 NSString *href([url absoluteString]);
4354 for (Diversion *diversion in (id) Diversions_)
4355 if (NSString *diverted = [diversion divert:href]) {
4357 NSLog(@"div: %@", diverted);
4359 url = [NSURL URLWithString:diverted];
4366 - (NSString *) key {
4370 - (NSUInteger) hash {
4374 - (BOOL) isEqual:(Diversion *)object {
4375 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
4380 @interface CydiaObject : NSObject {
4381 _H<CyteWebViewController> indirect_;
4382 _transient id delegate_;
4385 - (id) initWithDelegate:(CyteWebViewController *)indirect;
4391 @interface CydiaWebViewController : CyteWebViewController {
4392 _H<CydiaObject> cydia_;
4395 + (void) addDiversion:(Diversion *)diversion;
4396 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request;
4397 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia;
4398 - (void) setDelegate:(id)delegate;
4402 /* Web Scripting {{{ */
4403 @implementation CydiaObject
4405 - (id) initWithDelegate:(CyteWebViewController *)indirect {
4406 if ((self = [super init]) != nil) {
4407 indirect_ = indirect;
4411 - (void) setDelegate:(id)delegate {
4412 delegate_ = delegate;
4415 + (NSArray *) _attributeKeys {
4416 return [NSArray arrayWithObjects:
4421 @"coreFoundationVersionNumber",
4437 - (NSArray *) attributeKeys {
4438 return [[self class] _attributeKeys];
4441 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4442 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4445 - (NSString *) version {
4449 - (unsigned) bittage {
4451 #elif defined(__arm64__)
4453 #elif defined(__arm__)
4460 - (NSString *) build {
4464 - (NSString *) coreFoundationVersionNumber {
4465 return [NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber];
4468 - (NSString *) device {
4469 return UniqueIdentifier();
4472 - (NSString *) firmware {
4473 return [[UIDevice currentDevice] systemVersion];
4476 - (NSString *) hostname {
4477 return [[UIDevice currentDevice] name];
4480 - (NSString *) idiom {
4481 return (id) Idiom_ ?: [NSNull null];
4484 - (NSArray *) cells {
4485 auto *$_CTServerConnectionCreate(reinterpret_cast<id (*)(void *, void *, void *)>(dlsym(RTLD_DEFAULT, "_CTServerConnectionCreate")));
4486 if ($_CTServerConnectionCreate == NULL)
4489 struct CTResult { int flag; int error; };
4490 auto *$_CTServerConnectionCellMonitorCopyCellInfo(reinterpret_cast<CTResult (*)(CFTypeRef, void *, CFArrayRef *)>(dlsym(RTLD_DEFAULT, "_CTServerConnectionCellMonitorCopyCellInfo")));
4491 if ($_CTServerConnectionCellMonitorCopyCellInfo == NULL)
4494 _H<const void> connection($_CTServerConnectionCreate(NULL, NULL, NULL), true);
4495 if (connection == nil)
4499 CFArrayRef cells(NULL);
4500 auto result($_CTServerConnectionCellMonitorCopyCellInfo(connection, &count, &cells));
4501 if (result.flag != 0)
4504 return [(NSArray *) cells autorelease];
4507 - (NSString *) mcc {
4508 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode")))
4509 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault) autorelease];
4513 - (NSString *) mnc {
4514 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberNetworkCode")))
4515 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault) autorelease];
4519 - (NSString *) operator {
4520 if (CFStringRef (*$CTRegistrationCopyOperatorName)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTRegistrationCopyOperatorName")))
4521 return [(NSString *) (*$CTRegistrationCopyOperatorName)(kCFAllocatorDefault) autorelease];
4525 - (NSString *) bbsnum {
4526 return (id) BBSNum_ ?: [NSNull null];
4529 - (NSString *) ecid {
4530 return (id) ChipID_ ?: [NSNull null];
4533 - (NSString *) serial {
4534 return SerialNumber_;
4537 - (NSString *) role {
4538 return (id) [NSNull null];
4541 - (NSString *) model {
4542 return [NSString stringWithUTF8String:Machine_];
4545 + (NSString *) webScriptNameForSelector:(SEL)selector {
4547 else if (selector == @selector(addBridgedHost:))
4548 return @"addBridgedHost";
4549 else if (selector == @selector(addInsecureHost:))
4550 return @"addInsecureHost";
4551 else if (selector == @selector(addInternalRedirect::))
4552 return @"addInternalRedirect";
4553 else if (selector == @selector(addPipelinedHost:scheme:))
4554 return @"addPipelinedHost";
4555 else if (selector == @selector(addSource:::))
4556 return @"addSource";
4557 else if (selector == @selector(addTrivialSource:))
4558 return @"addTrivialSource";
4559 else if (selector == @selector(close))
4561 else if (selector == @selector(du:))
4563 else if (selector == @selector(stringWithFormat:arguments:))
4565 else if (selector == @selector(getAllSources))
4566 return @"getAllSources";
4567 else if (selector == @selector(getApplicationInfo:value:))
4568 return @"getApplicationInfoValue";
4569 else if (selector == @selector(getDisplayIdentifiers))
4570 return @"getDisplayIdentifiers";
4571 else if (selector == @selector(getLocalizedNameForDisplayIdentifier:))
4572 return @"getLocalizedNameForDisplayIdentifier";
4573 else if (selector == @selector(getKernelNumber:))
4574 return @"getKernelNumber";
4575 else if (selector == @selector(getKernelString:))
4576 return @"getKernelString";
4577 else if (selector == @selector(getInstalledPackages))
4578 return @"getInstalledPackages";
4579 else if (selector == @selector(getIORegistryEntry::))
4580 return @"getIORegistryEntry";
4581 else if (selector == @selector(getLocaleIdentifier))
4582 return @"getLocaleIdentifier";
4583 else if (selector == @selector(getPreferredLanguages))
4584 return @"getPreferredLanguages";
4585 else if (selector == @selector(getPackageById:))
4586 return @"getPackageById";
4587 else if (selector == @selector(getMetadataKeys))
4588 return @"getMetadataKeys";
4589 else if (selector == @selector(getMetadataValue:))
4590 return @"getMetadataValue";
4591 else if (selector == @selector(getSessionValue:))
4592 return @"getSessionValue";
4593 else if (selector == @selector(installPackages:))
4594 return @"installPackages";
4595 else if (selector == @selector(isReachable:))
4596 return @"isReachable";
4597 else if (selector == @selector(localizedStringForKey:value:table:))
4599 else if (selector == @selector(popViewController:))
4600 return @"popViewController";
4601 else if (selector == @selector(refreshSources))
4602 return @"refreshSources";
4603 else if (selector == @selector(registerFrame:))
4604 return @"registerFrame";
4605 else if (selector == @selector(removeButton))
4606 return @"removeButton";
4607 else if (selector == @selector(saveConfig))
4608 return @"saveConfig";
4609 else if (selector == @selector(setMetadataValue::))
4610 return @"setMetadataValue";
4611 else if (selector == @selector(setSessionValue::))
4612 return @"setSessionValue";
4613 else if (selector == @selector(substitutePackageNames:))
4614 return @"substitutePackageNames";
4615 else if (selector == @selector(scrollToBottom:))
4616 return @"scrollToBottom";
4617 else if (selector == @selector(setAllowsNavigationAction:))
4618 return @"setAllowsNavigationAction";
4619 else if (selector == @selector(setBadgeValue:))
4620 return @"setBadgeValue";
4621 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4622 return @"setButtonImage";
4623 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4624 return @"setButtonTitle";
4625 else if (selector == @selector(setHidesBackButton:))
4626 return @"setHidesBackButton";
4627 else if (selector == @selector(setHidesNavigationBar:))
4628 return @"setHidesNavigationBar";
4629 else if (selector == @selector(setNavigationBarStyle:))
4630 return @"setNavigationBarStyle";
4631 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4632 return @"setNavigationBarTintColor";
4633 else if (selector == @selector(setPasteboardString:))
4634 return @"setPasteboardString";
4635 else if (selector == @selector(setPasteboardURL:))
4636 return @"setPasteboardURL";
4637 else if (selector == @selector(setScrollAlwaysBounceVertical:))
4638 return @"setScrollAlwaysBounceVertical";
4639 else if (selector == @selector(setScrollIndicatorStyle:))
4640 return @"setScrollIndicatorStyle";
4641 else if (selector == @selector(setToken:))
4643 else if (selector == @selector(setViewportWidth:))
4644 return @"setViewportWidth";
4645 else if (selector == @selector(statfs:))
4647 else if (selector == @selector(supports:))
4649 else if (selector == @selector(unload))
4655 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4656 return [self webScriptNameForSelector:selector] == nil;
4659 - (BOOL) supports:(NSString *)feature {
4660 return [feature isEqualToString:@"window.open"];
4664 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4667 - (void) setScrollAlwaysBounceVertical:(NSNumber *)value {
4668 [indirect_ performSelectorOnMainThread:@selector(setScrollAlwaysBounceVerticalNumber:) withObject:value waitUntilDone:NO];
4671 - (void) setScrollIndicatorStyle:(NSString *)style {
4672 [indirect_ performSelectorOnMainThread:@selector(setScrollIndicatorStyleWithName:) withObject:style waitUntilDone:NO];
4675 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4676 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4679 - (NSDictionary *) getApplicationInfo:(NSString *)display value:(NSString *)key {
4681 if (SBBundlePathForDisplayIdentifier(SBSSpringBoardServerPort(), [display UTF8String], path) != 0)
4682 return (id) [NSNull null];
4683 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:[[NSString stringWithUTF8String:path] stringByAppendingString:@"/Info.plist"]]);
4685 return (id) [NSNull null];
4686 return [info objectForKey:key];
4689 - (NSArray *) getDisplayIdentifiers {
4690 return SBSCopyApplicationDisplayIdentifiers(false, false);
4693 - (NSString *) getLocalizedNameForDisplayIdentifier:(NSString *)identifier {
4694 return [SBSCopyLocalizedApplicationNameForDisplayIdentifier(identifier) autorelease] ?: (id) [NSNull null];
4697 - (NSNumber *) getKernelNumber:(NSString *)name {
4698 const char *string([name UTF8String]);
4701 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4702 return (id) [NSNull null];
4704 if (size != sizeof(int))
4705 return (id) [NSNull null];
4708 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4709 return (id) [NSNull null];
4711 return [NSNumber numberWithInt:value];
4714 - (NSString *) getKernelString:(NSString *)name {
4715 const char *string([name UTF8String]);
4718 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4719 return (id) [NSNull null];
4721 char value[size + 1];
4722 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4723 return (id) [NSNull null];
4725 // XXX: just in case you request something ludicrous
4728 return [NSString stringWithCString:value];
4731 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4732 NSObject *value(CYIOGetValue([path UTF8String], entry));
4735 if ([value isKindOfClass:[NSData class]])
4736 value = CYHex((NSData *) value);
4741 - (NSArray *) getMetadataKeys {
4742 @synchronized (Values_) {
4743 return [Values_ allKeys];
4746 - (void) registerFrame:(DOMHTMLIFrameElement *)iframe {
4747 WebFrame *frame([iframe contentFrame]);
4748 [indirect_ registerFrame:frame];
4751 - (id) getMetadataValue:(NSString *)key {
4752 @synchronized (Values_) {
4753 return [Values_ objectForKey:key];
4756 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4757 @synchronized (Values_) {
4758 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4759 [Values_ removeObjectForKey:key];
4761 [Values_ setObject:value forKey:key];
4764 - (id) getSessionValue:(NSString *)key {
4765 @synchronized (SessionData_) {
4766 return [SessionData_ objectForKey:key];
4769 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4770 @synchronized (SessionData_) {
4771 if (value == (id) [WebUndefined undefined])
4772 [SessionData_ removeObjectForKey:key];
4774 [SessionData_ setObject:value forKey:key];
4777 - (void) addBridgedHost:(NSString *)host {
4778 @synchronized (HostConfig_) {
4779 [BridgedHosts_ addObject:host];
4782 - (void) addInsecureHost:(NSString *)host {
4783 @synchronized (HostConfig_) {
4784 [InsecureHosts_ addObject:host];
4787 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4788 @synchronized (HostConfig_) {
4789 if (scheme != (id) [WebUndefined undefined])
4790 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4792 [PipelinedHosts_ addObject:host];
4795 - (void) popViewController:(NSNumber *)value {
4796 if (value == (id) [WebUndefined undefined])
4797 value = [NSNumber numberWithBool:YES];
4798 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4801 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4802 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4804 for (NSString *section in sections)
4805 [array addObject:section];
4807 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4810 distribution, @"Distribution",
4812 nil] waitUntilDone:NO];
4815 - (BOOL) addTrivialSource:(NSString *)href {
4816 href = VerifySource(href);
4819 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4823 - (void) refreshSources {
4824 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4827 - (void) saveConfig {
4828 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4831 - (NSArray *) getAllSources {
4832 return [[Database sharedInstance] sources];
4835 - (NSArray *) getInstalledPackages {
4836 Database *database([Database sharedInstance]);
4837 @synchronized (database) {
4838 NSArray *packages([database packages]);
4839 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4840 for (Package *package in packages)
4841 if (![package uninstalled])
4842 [installed addObject:package];
4846 - (Package *) getPackageById:(NSString *)id {
4847 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4851 return (Package *) [NSNull null];
4854 - (NSString *) getLocaleIdentifier {
4855 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4858 - (NSArray *) getPreferredLanguages {
4862 - (NSArray *) statfs:(NSString *)path {
4865 if (path == nil || statfs([path UTF8String], &stat) == -1)
4868 return [NSArray arrayWithObjects:
4869 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4870 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4871 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4875 - (NSNumber *) du:(NSString *)path {
4876 NSNumber *value(nil);
4878 FILE *du(popen([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /usr/libexec/cydia/du -ks %@", ShellEscape(path)] UTF8String], "r"));
4881 while (fgets(line, sizeof(line), du) != NULL) {
4882 size_t length(strlen(line));
4883 while (length != 0 && line[length - 1] == '\n')
4884 line[--length] = '\0';
4885 if (char *tab = strchr(line, '\t')) {
4887 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4897 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4900 - (NSNumber *) isReachable:(NSString *)name {
4901 return [NSNumber numberWithBool:IsReachable([name UTF8String])];
4904 - (void) installPackages:(NSArray *)packages {
4905 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4908 - (NSString *) substitutePackageNames:(NSString *)message {
4909 auto database([Database sharedInstance]);
4911 // XXX: this check is less racy than you'd expect, but this entire concept is a little awkward
4912 if (![database hasPackages])
4915 NSMutableArray *words([[[message componentsSeparatedByString:@" "] mutableCopy] autorelease]);
4916 for (size_t i(0), e([words count]); i != e; ++i) {
4917 NSString *word([words objectAtIndex:i]);
4918 if (Package *package = [database packageWithName:word])
4919 [words replaceObjectAtIndex:i withObject:[package name]];
4922 return [words componentsJoinedByString:@" "];
4925 - (void) removeButton {
4926 [indirect_ removeButton];
4929 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4930 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4933 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4934 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4937 - (void) setBadgeValue:(id)value {
4938 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4941 - (void) setAllowsNavigationAction:(NSString *)value {
4942 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4945 - (void) setHidesBackButton:(NSString *)value {
4946 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4949 - (void) setHidesNavigationBar:(NSString *)value {
4950 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4953 - (void) setNavigationBarStyle:(NSString *)value {
4954 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4957 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4958 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4959 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4960 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4963 - (void) setPasteboardString:(NSString *)value {
4964 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4967 - (void) setPasteboardURL:(NSString *)value {
4968 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4971 - (void) setToken:(NSString *)token {
4972 // XXX: the website expects this :/
4975 - (void) scrollToBottom:(NSNumber *)animated {
4976 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4979 - (void) setViewportWidth:(float)width {
4980 [indirect_ setViewportWidthOnMainThread:width];
4983 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4984 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4985 unsigned count([arguments count]);
4987 for (unsigned i(0); i != count; ++i)
4988 values[i] = [arguments objectAtIndex:i];
4989 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4992 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4993 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4995 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4997 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
5003 @interface NSURL (CydiaSecure)
5006 @implementation NSURL (CydiaSecure)
5008 - (bool) isCydiaSecure {
5009 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
5012 @synchronized (HostConfig_) {
5013 if ([InsecureHosts_ containsObject:[self host]])
5022 /* Cydia Browser Controller {{{ */
5023 @implementation CydiaWebViewController
5025 - (NSURL *) navigationURL {
5026 if (NSURLRequest *request = self.request)
5027 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request URL] absoluteString]]];
5032 + (void) _initialize {
5033 [super _initialize];
5035 Diversions_ = [NSMutableSet setWithCapacity:0];
5038 + (void) addDiversion:(Diversion *)diversion {
5039 [Diversions_ addObject:diversion];
5042 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5043 [super webView:view didClearWindowObject:window forFrame:frame];
5044 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
5047 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia {
5048 WebDataSource *source([frame dataSource]);
5049 NSURLResponse *response([source response]);
5050 NSURL *url([response URL]);
5051 NSString *scheme([[url scheme] lowercaseString]);
5053 bool bridged(false);
5055 @synchronized (HostConfig_) {
5056 if ([scheme isEqualToString:@"file"])
5058 else if ([scheme isEqualToString:@"https"])
5059 if ([BridgedHosts_ containsObject:[url host]])
5064 [window setValue:cydia forKey:@"cydia"];
5067 - (void) _setupMail:(MFMailComposeViewController *)controller {
5068 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
5070 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
5071 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
5074 - (NSURL *) URLWithURL:(NSURL *)url {
5075 return [Diversion divertURL:url];
5078 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
5079 return [CydiaWebViewController requestWithHeaders:[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
5082 - (NSURLRequest *) webThreadWebView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
5083 return [CydiaWebViewController requestWithHeaders:[super webThreadWebView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
5086 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request {
5087 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
5089 NSURL *url([copy URL]);
5090 NSString *href([url absoluteString]);
5091 NSString *host([url host]);
5093 if ([href hasPrefix:@"https://cydia.saurik.com/TSS/"]) {
5094 if (NSString *agent = [copy valueForHTTPHeaderField:@"X-User-Agent"]) {
5095 [copy setValue:agent forHTTPHeaderField:@"User-Agent"];
5096 [copy setValue:nil forHTTPHeaderField:@"X-User-Agent"];
5099 [copy setValue:nil forHTTPHeaderField:@"Referer"];
5100 [copy setValue:nil forHTTPHeaderField:@"Origin"];
5102 [copy setURL:[NSURL URLWithString:[@"http://gs.apple.com/TSS/" stringByAppendingString:[href substringFromIndex:29]]]];
5106 if ([copy valueForHTTPHeaderField:@"X-Cydia-Cf"] == nil)
5107 [copy setValue:[NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber] forHTTPHeaderField:@"X-Cydia-Cf"];
5108 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
5109 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
5111 bool bridged; @synchronized (HostConfig_) {
5112 bridged = [BridgedHosts_ containsObject:host];
5115 if ([url isCydiaSecure] && bridged && UniqueID_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Id"] == nil)
5116 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
5121 - (void) setDelegate:(id)delegate {
5122 [super setDelegate:delegate];
5123 [cydia_ setDelegate:delegate];
5126 - (NSString *) applicationNameForUserAgent {
5131 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
5132 cydia_ = [[[CydiaObject alloc] initWithDelegate:self.indirect] autorelease];
5138 @interface AppCacheController : CydiaWebViewController {
5143 @implementation AppCacheController
5145 - (void) didReceiveMemoryWarning {
5146 // XXX: this doesn't work
5149 - (bool) retainsNetworkActivityIndicator {
5157 @interface NSObject (CydiaScript)
5158 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
5161 @implementation NSObject (CydiaScript)
5163 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5169 @implementation NSArray (CydiaScript)
5171 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5172 WebScriptObject *object([context evaluateWebScript:@"[]"]);
5173 for (size_t i(0), e([self count]); i != e; ++i)
5174 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
5180 @implementation NSDictionary (CydiaScript)
5182 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5183 WebScriptObject *object([context evaluateWebScript:@"({})"]);
5185 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
5192 /* Confirmation Controller {{{ */
5193 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
5194 if (!iterator.end())
5195 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
5196 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
5198 pkgCache::PkgIterator package(dep.TargetPkg());
5201 if (strcmp(package.Name(), "mobilesubstrate") == 0)
5208 @protocol ConfirmationControllerDelegate
5209 - (void) cancelAndClear:(bool)clear;
5210 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
5214 @interface ConfirmationController : CydiaWebViewController {
5215 _transient Database *database_;
5217 _H<UIAlertView> essential_;
5219 _H<NSDictionary> changes_;
5220 _H<NSMutableArray> issues_;
5221 _H<NSDictionary> sizes_;
5226 - (id) initWithDatabase:(Database *)database;
5230 @implementation ConfirmationController
5234 RestartSubstrate_ = true;
5235 [self.delegate confirmWithNavigationController:[self navigationController]];
5238 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
5239 NSString *context([alert context]);
5241 if ([context isEqualToString:@"remove"]) {
5242 if (button == [alert cancelButtonIndex])
5244 else if (button == [alert firstOtherButtonIndex]) {
5245 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
5248 [alert dismissWithClickedButtonIndex:-1 animated:YES];
5249 } else if ([context isEqualToString:@"unable"]) {
5250 [self dismissModalViewControllerAnimated:YES];
5251 [alert dismissWithClickedButtonIndex:-1 animated:YES];
5253 [super alertView:alert clickedButtonAtIndex:button];
5257 - (void) _doContinue {
5258 [self.delegate cancelAndClear:NO];
5259 [self dismissModalViewControllerAnimated:YES];
5262 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
5263 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
5267 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5268 [super webView:view didClearWindowObject:window forFrame:frame];
5270 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
5271 (id) changes_, @"changes",
5272 (id) issues_, @"issues",
5273 (id) sizes_, @"sizes",
5275 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
5278 - (id) initWithDatabase:(Database *)database {
5279 if ((self = [super init]) != nil) {
5280 database_ = database;
5282 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
5283 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
5284 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
5285 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
5286 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
5290 pkgCacheFile &cache([database_ cache]);
5291 NSArray *packages([database_ packages]);
5292 pkgDepCache::Policy *policy([database_ policy]);
5294 issues_ = [NSMutableArray arrayWithCapacity:4];
5296 for (Package *package in packages) {
5297 pkgCache::PkgIterator iterator([package iterator]);
5298 NSString *name([package id]);
5300 if ([package broken]) {
5301 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
5303 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5305 reasons, @"reasons",
5308 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
5312 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
5313 pkgCache::DepIterator start;
5314 pkgCache::DepIterator end;
5315 dep.GlobOr(start, end); // ++dep
5317 if (!cache->IsImportantDep(end))
5319 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
5322 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
5324 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5325 [NSString stringWithUTF8String:start.DepType()], @"relationship",
5326 clauses, @"clauses",
5330 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
5332 pkgCache::PkgIterator target(start.TargetPkg());
5333 if (target->ProvidesList != 0)
5334 reason = @"missing";
5336 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
5338 reason = @"installed";
5339 installed = [NSString stringWithUTF8String:ver.VerStr()];
5340 } else if (!cache[target].CandidateVerIter(cache).end())
5341 reason = @"uninstalled";
5342 else if (target->ProvidesList == 0)
5343 reason = @"uninstallable";
5345 reason = @"virtual";
5348 NSDictionary *version(start.TargetVer() == 0 ? (NSDictionary *) [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
5349 [NSString stringWithUTF8String:start.CompType()], @"operator",
5350 [NSString stringWithUTF8String:start.TargetVer()], @"value",
5353 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5354 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
5355 version, @"version",
5357 installed, @"installed",
5360 // yes, seriously. (wtf?)
5368 pkgDepCache::StateCache &state(cache[iterator]);
5370 static RegEx special_r("(firmware|gsc\\..*|cy\\+.*)");
5372 if (state.NewInstall())
5373 [installs addObject:name];
5374 // XXX: else if (state.Install())
5375 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
5376 [reinstalls addObject:name];
5377 // XXX: move before previous if
5378 else if (state.Upgrade())
5379 [upgrades addObject:name];
5380 else if (state.Downgrade())
5381 [downgrades addObject:name];
5382 else if (!state.Delete())
5383 // XXX: _assert(state.Keep());
5385 else if (special_r(name))
5386 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5387 [NSNull null], @"package",
5388 [NSArray arrayWithObjects:
5389 [NSDictionary dictionaryWithObjectsAndKeys:
5390 @"Conflicts", @"relationship",
5391 [NSArray arrayWithObjects:
5392 [NSDictionary dictionaryWithObjectsAndKeys:
5394 [NSNull null], @"version",
5395 @"installed", @"reason",
5402 if ([package essential])
5404 [removes addObject:name];
5407 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
5408 substrate_ |= DepSubstrate(iterator.CurrentVer());
5413 else if (Advanced_) {
5414 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
5416 essential_ = [[[UIAlertView alloc]
5417 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
5418 message:UCLocalize("REMOVING_ESSENTIALS_EX")
5420 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
5422 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
5426 [essential_ setContext:@"remove"];
5427 [essential_ setNumberOfRows:2];
5429 essential_ = [[[UIAlertView alloc]
5430 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
5431 message:UCLocalize("UNABLE_TO_COMPLY_EX")
5433 cancelButtonTitle:UCLocalize("OKAY")
5434 otherButtonTitles:nil
5437 [essential_ setContext:@"unable"];
5440 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5441 installs, @"installs",
5442 reinstalls, @"reinstalls",
5443 upgrades, @"upgrades",
5444 downgrades, @"downgrades",
5445 removes, @"removes",
5448 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5449 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
5450 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
5453 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
5457 - (UIBarButtonItem *) leftButton {
5458 return [[[UIBarButtonItem alloc]
5459 initWithTitle:UCLocalize("CANCEL")
5460 style:UIBarButtonItemStylePlain
5462 action:@selector(cancelButtonClicked)
5467 - (void) applyRightButton {
5468 if ([issues_ count] == 0 && ![self isLoading])
5469 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
5470 initWithTitle:UCLocalize("CONFIRM")
5471 style:UIBarButtonItemStyleDone
5473 action:@selector(confirmButtonClicked)
5476 [[self navigationItem] setRightBarButtonItem:nil];
5480 - (void) cancelButtonClicked {
5481 [self.delegate cancelAndClear:YES];
5482 [self dismissModalViewControllerAnimated:YES];
5486 - (void) confirmButtonClicked {
5487 if (essential_ != nil)
5497 /* Progress Data {{{ */
5498 @interface CydiaProgressData : NSObject {
5499 _transient id delegate_;
5508 _H<NSMutableArray> events_;
5509 _H<NSString> title_;
5511 _H<NSString> status_;
5512 _H<NSString> finish_;
5517 @implementation CydiaProgressData
5519 + (NSArray *) _attributeKeys {
5520 return [NSArray arrayWithObjects:
5532 - (NSArray *) attributeKeys {
5533 return [[self class] _attributeKeys];
5536 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5537 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5541 if ((self = [super init]) != nil) {
5542 events_ = [NSMutableArray arrayWithCapacity:32];
5550 - (void) setDelegate:(id)delegate {
5551 delegate_ = delegate;
5554 - (void) setPercent:(float)value {
5558 - (NSNumber *) percent {
5559 return [NSNumber numberWithFloat:percent_];
5562 - (void) setCurrent:(float)value {
5566 - (NSNumber *) current {
5567 return [NSNumber numberWithFloat:current_];
5570 - (void) setTotal:(float)value {
5574 - (NSNumber *) total {
5575 return [NSNumber numberWithFloat:total_];
5578 - (void) setSpeed:(float)value {
5582 - (NSNumber *) speed {
5583 return [NSNumber numberWithFloat:speed_];
5586 - (NSArray *) events {
5590 - (void) removeAllEvents {
5591 [events_ removeAllObjects];
5594 - (void) addEvent:(CydiaProgressEvent *)event {
5595 [events_ addObject:event];
5598 - (void) setTitle:(NSString *)text {
5602 - (NSString *) title {
5606 - (void) setFinish:(NSString *)text {
5610 - (NSString *) finish {
5611 return (id) finish_ ?: [NSNull null];
5614 - (void) setRunning:(bool)running {
5618 - (NSNumber *) running {
5619 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5624 /* Progress Controller {{{ */
5625 @interface ProgressController : CydiaWebViewController <
5628 _transient Database *database_;
5629 _H<CydiaProgressData, 1> progress_;
5633 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5635 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5637 - (void) setTitle:(NSString *)title;
5638 - (void) setCancellable:(bool)cancellable;
5642 @implementation ProgressController
5645 [database_ setProgressDelegate:nil];
5649 - (UIBarButtonItem *) leftButton {
5650 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5651 initWithTitle:UCLocalize("CANCEL")
5652 style:UIBarButtonItemStylePlain
5654 action:@selector(cancel)
5655 ] autorelease] : nil;
5658 - (void) updateCancel {
5659 [super applyLeftButton];
5662 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5663 if ((self = [super init]) != nil) {
5664 database_ = database;
5665 self.delegate = delegate;
5667 [database_ setProgressDelegate:self];
5669 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5670 [progress_ setDelegate:self];
5672 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5674 [self setPageColor:[UIColor blackColor]];
5676 [[self navigationItem] setHidesBackButton:YES];
5678 [self updateCancel];
5682 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5683 [super webView:view didClearWindowObject:window forFrame:frame];
5684 [window setValue:progress_ forKey:@"cydiaProgress"];
5687 - (void) updateProgress {
5688 [self dispatchEvent:@"CydiaProgressUpdate"];
5691 - (void) viewWillAppear:(BOOL)animated {
5692 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5693 [super viewWillAppear:animated];
5697 UpdateExternalStatus(0);
5700 [self.delegate saveState];
5704 [self.delegate returnToCydia];
5708 [self.delegate terminateWithSuccess];
5709 /*if ([self.delegate respondsToSelector:@selector(suspendWithAnimation:)])
5710 [self.delegate suspendWithAnimation:YES];
5712 [self.delegate suspend];*/
5724 UIProgressHUD *hud([self.delegate addProgressHUD]);
5725 [hud setText:UCLocalize("LOADING")];
5726 [self.delegate performSelector:@selector(reloadSpringBoard) withObject:nil afterDelay:0.5];
5732 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5733 SBReboot(SBSSpringBoardServerPort());
5735 reboot2(RB_AUTOBOOT);
5742 - (void) setTitle:(NSString *)title {
5743 [progress_ setTitle:title];
5744 [self updateProgress];
5747 - (UIBarButtonItem *) rightButton {
5748 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5749 initWithTitle:UCLocalize("CLOSE")
5750 style:UIBarButtonItemStylePlain
5752 action:@selector(close)
5756 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5757 UpdateExternalStatus(1);
5759 [progress_ setRunning:true];
5760 [self setTitle:title];
5761 // implicit updateProgress
5763 SHA1SumValue notifyconf; {
5765 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5768 MMap mmap(file, MMap::ReadOnly);
5770 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5771 notifyconf = sha1.Result();
5775 SHA1SumValue springlist; {
5777 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5780 MMap mmap(file, MMap::ReadOnly);
5782 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5783 springlist = sha1.Result();
5787 if (invocation != nil) {
5788 [invocation yieldToSelector:@selector(invoke)];
5789 [self setTitle:@"COMPLETE"];
5794 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5797 MMap mmap(file, MMap::ReadOnly);
5799 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5800 if (!(notifyconf == sha1.Result()))
5807 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5810 MMap mmap(file, MMap::ReadOnly);
5812 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5813 if (!(springlist == sha1.Result()))
5819 if (RestartSubstrate_)
5823 RestartSubstrate_ = false;
5826 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5827 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5828 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5829 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5830 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5833 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5835 [progress_ setRunning:false];
5836 [self updateProgress];
5838 [self applyRightButton];
5841 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5842 [progress_ addEvent:event];
5843 [self updateProgress];
5846 - (bool) isProgressCancelled {
5847 return cancel_ == 2;
5852 [self updateCancel];
5855 - (void) setCancellable:(bool)cancellable {
5856 unsigned cancel(cancel_);
5860 else if (cancel_ == 0)
5863 if (cancel != cancel_)
5864 [self updateCancel];
5867 - (void) setProgressCancellable:(NSNumber *)cancellable {
5868 [self setCancellable:[cancellable boolValue]];
5871 - (void) setProgressPercent:(NSNumber *)percent {
5872 [progress_ setPercent:[percent floatValue]];
5873 [self updateProgress];
5876 - (void) setProgressStatus:(NSDictionary *)status {
5877 if (status == nil) {
5878 [progress_ setCurrent:0];
5879 [progress_ setTotal:0];
5880 [progress_ setSpeed:0];
5882 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5884 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5885 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5886 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5889 [self updateProgress];
5895 /* Package Cell {{{ */
5896 @interface PackageCell : CyteTableViewCell <
5897 CyteTableViewCellDelegate
5901 _H<NSString> description_;
5903 _H<NSString> source_;
5905 _H<UIImage> placard_;
5909 - (PackageCell *) init;
5910 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5912 - (void) drawContentRect:(CGRect)rect;
5916 @implementation PackageCell
5918 - (PackageCell *) init {
5919 CGRect frame(CGRectMake(0, 0, 320, 74));
5920 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5921 UIView *content([self contentView]);
5922 CGRect bounds([content bounds]);
5924 self.content = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5925 [self.content setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5926 [content addSubview:self.content];
5928 [self.content setDelegate:self];
5929 [self.content setOpaque:YES];
5933 - (NSString *) accessibilityLabel {
5937 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5938 summarized_ = summary;
5948 [self.content setBackgroundColor:[UIColor whiteColor]];
5952 Source *source = [package source];
5954 icon_ = [package icon];
5956 if (NSString *name = [package name])
5957 name_ = [NSString stringWithString:name];
5959 if (NSString *description = [package shortDescription])
5960 description_ = [NSString stringWithString:description];
5962 commercial_ = [package isCommercial];
5964 NSString *label = nil;
5965 bool trusted = false;
5967 if (source != nil) {
5968 label = [source label];
5969 trusted = [source trusted];
5970 } else if ([[package id] isEqualToString:@"firmware"])
5971 label = UCLocalize("APPLE");
5973 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5975 NSString *from(label);
5977 NSString *section = [package simpleSection];
5978 if (section != nil && ![section isEqualToString:label]) {
5979 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5980 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5983 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5985 if (NSString *purpose = [package primaryPurpose])
5986 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5991 if (NSString *mode = [package mode]) {
5992 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5993 color = RemovingColor_;
5994 placard = @"removing";
5996 color = InstallingColor_;
5997 placard = @"installing";
6000 color = [UIColor whiteColor];
6002 if ([package installed] != nil)
6003 placard = @"installed";
6008 [self.content setBackgroundColor:color];
6011 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
6014 [self setNeedsDisplay];
6015 [self.content setNeedsDisplay];
6018 - (void) drawSummaryContentRect:(CGRect)rect {
6019 bool highlighted(self.highlighted);
6020 float width([self bounds].size.width);
6024 rect.size = [(UIImage *) icon_ size];
6026 while (rect.size.width > 16 || rect.size.height > 16) {
6027 rect.size.width /= 2;
6028 rect.size.height /= 2;
6031 rect.origin.x = 19 - rect.size.width / 2;
6032 rect.origin.y = 19 - rect.size.height / 2;
6034 [icon_ drawInRect:Retina(rect)];
6037 if (badge_ != nil) {
6039 rect.size = [(UIImage *) badge_ size];
6041 rect.size.width /= 4;
6042 rect.size.height /= 4;
6044 rect.origin.x = 25 - rect.size.width / 2;
6045 rect.origin.y = 25 - rect.size.height / 2;
6047 [badge_ drawInRect:Retina(rect)];
6050 if (highlighted && kCFCoreFoundationVersionNumber < 800)
6054 UISetColor(commercial_ ? Purple_ : Black_);
6055 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
6057 if (placard_ != nil)
6058 [placard_ drawAtPoint:CGPointMake(width - 52, 11)];
6061 - (void) drawNormalContentRect:(CGRect)rect {
6062 bool highlighted(self.highlighted);
6063 float width([self bounds].size.width);
6067 rect.size = [(UIImage *) icon_ size];
6069 while (rect.size.width > 32 || rect.size.height > 32) {
6070 rect.size.width /= 2;
6071 rect.size.height /= 2;
6074 rect.origin.x = 25 - rect.size.width / 2;
6075 rect.origin.y = 25 - rect.size.height / 2;
6077 [icon_ drawInRect:Retina(rect)];
6080 if (badge_ != nil) {
6082 rect.size = [(UIImage *) badge_ size];
6084 rect.size.width /= 2;
6085 rect.size.height /= 2;
6087 rect.origin.x = 36 - rect.size.width / 2;
6088 rect.origin.y = 36 - rect.size.height / 2;
6090 [badge_ drawInRect:Retina(rect)];
6093 if (highlighted && kCFCoreFoundationVersionNumber < 800)
6097 UISetColor(commercial_ ? Purple_ : Black_);
6098 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
6099 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
6102 UISetColor(commercial_ ? Purplish_ : Gray_);
6103 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:NSLineBreakByTruncatingTail];
6105 if (placard_ != nil)
6106 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
6109 - (void) drawContentRect:(CGRect)rect {
6111 [self drawSummaryContentRect:rect];
6113 [self drawNormalContentRect:rect];
6118 /* Section Cell {{{ */
6119 @interface SectionCell : CyteTableViewCell <
6120 CyteTableViewCellDelegate
6122 _H<NSString> basic_;
6123 _H<NSString> section_;
6125 _H<NSString> count_;
6127 _H<UISwitch> switch_;
6131 - (void) setSection:(Section *)section editing:(BOOL)editing;
6135 @implementation SectionCell
6137 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
6138 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
6139 icon_ = [UIImage imageNamed:@"folder.png"];
6140 // XXX: this initial frame is wrong, but is fixed later
6141 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
6142 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
6144 UIView *content([self contentView]);
6145 CGRect bounds([content bounds]);
6147 self.content = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
6148 [self.content setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6149 [content addSubview:self.content];
6150 [self.content setBackgroundColor:[UIColor whiteColor]];
6152 [self.content setDelegate:self];
6156 - (void) onSwitch:(id)sender {
6157 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
6158 if (metadata == nil) {
6159 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
6160 [Sections_ setObject:metadata forKey:basic_];
6163 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
6166 - (void) setSection:(Section *)section editing:(BOOL)editing {
6167 if (editing != editing_) {
6169 [switch_ removeFromSuperview];
6171 [self addSubview:switch_];
6180 if (section == nil) {
6181 name_ = UCLocalize("ALL_PACKAGES");
6184 basic_ = [section name];
6185 section_ = [section localized];
6187 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
6188 count_ = [NSString stringWithFormat:@"%zd", [section count]];
6191 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
6194 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
6195 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
6197 [self.content setNeedsDisplay];
6200 - (void) setFrame:(CGRect)frame {
6201 [super setFrame:frame];
6203 CGRect rect([switch_ frame]);
6204 [switch_ setFrame:CGRectMake(frame.size.width - rect.size.width - 9, 9, rect.size.width, rect.size.height)];
6207 - (NSString *) accessibilityLabel {
6211 - (void) drawContentRect:(CGRect)rect {
6212 bool highlighted(self.highlighted && !editing_);
6214 [icon_ drawInRect:CGRectMake(7, 7, 32, 32)];
6216 if (highlighted && kCFCoreFoundationVersionNumber < 800)
6219 float width(rect.size.width);
6221 width -= 9 + [switch_ frame].size.width;
6225 [name_ drawAtPoint:CGPointMake(48, 12) forWidth:(width - 58) withFont:Font18_ lineBreakMode:NSLineBreakByTruncatingTail];
6227 CGSize size = [count_ sizeWithFont:Font14_];
6229 UISetColor(Folder_);
6231 [count_ drawAtPoint:CGPointMake(Retina(10 + (30 - size.width) / 2), 18) withFont:Font12Bold_];
6237 /* File Table {{{ */
6238 @interface FileTable : CyteViewController <
6239 UITableViewDataSource,
6242 _transient Database *database_;
6243 _H<Package> package_;
6245 _H<NSMutableArray> files_;
6246 _H<UITableView, 2> list_;
6249 - (id) initWithDatabase:(Database *)database;
6250 - (void) setPackage:(Package *)package;
6254 @implementation FileTable
6256 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6257 return files_ == nil ? 0 : [files_ count];
6260 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6264 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6265 static NSString *reuseIdentifier = @"Cell";
6267 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6269 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6270 [cell setFont:[UIFont systemFontOfSize:16]];
6272 [cell setText:[files_ objectAtIndex:indexPath.row]];
6273 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
6278 - (NSURL *) navigationURL {
6279 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
6283 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
6284 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6285 [list_ setRowHeight:24.0f];
6286 [(UITableView *) list_ setDataSource:self];
6287 [list_ setDelegate:self];
6288 [self setView:list_];
6291 - (void) viewDidLoad {
6292 [super viewDidLoad];
6294 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
6297 - (void) releaseSubviews {
6303 [super releaseSubviews];
6306 - (id) initWithDatabase:(Database *)database {
6307 if ((self = [super init]) != nil) {
6308 database_ = database;
6312 - (void) setPackage:(Package *)package {
6316 files_ = [NSMutableArray arrayWithCapacity:32];
6318 if (package != nil) {
6320 name_ = [package id];
6322 if (NSArray *files = [package files])
6323 [files_ addObjectsFromArray:files];
6325 if ([files_ count] != 0) {
6326 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
6327 [files_ removeObjectAtIndex:0];
6328 [files_ sortUsingSelector:@selector(compareByPath:)];
6330 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
6331 [stack addObject:@"/"];
6333 for (int i(0), e([files_ count]); i != e; ++i) {
6334 NSString *file = [files_ objectAtIndex:i];
6335 while (![file hasPrefix:[stack lastObject]])
6336 [stack removeLastObject];
6337 NSString *directory = [stack lastObject];
6338 [stack addObject:[file stringByAppendingString:@"/"]];
6339 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
6340 int(([stack count] - 2) * 3), "",
6341 [file substringFromIndex:[directory length]]
6350 - (void) reloadData {
6353 [self setPackage:[database_ packageWithName:name_]];
6358 /* Package Controller {{{ */
6359 @interface CYPackageController : CydiaWebViewController <
6360 UIActionSheetDelegate
6362 _transient Database *database_;
6363 _H<Package> package_;
6366 std::vector<std::pair<_H<NSString>, _H<NSString>>> buttons_;
6367 _H<UIActionSheet> sheet_;
6368 _H<UIBarButtonItem> button_;
6369 _H<NSArray> versions_;
6372 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer;
6376 @implementation CYPackageController
6378 - (NSURL *) navigationURL {
6379 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
6382 - (void) _clickButtonWithPackage:(Package *)package {
6383 [self.delegate installPackage:package];
6386 - (void) _clickButtonWithName:(NSString *)name {
6387 if ([name isEqualToString:@"CLEAR"])
6388 return [self.delegate clearPackage:package_];
6389 else if ([name isEqualToString:@"REMOVE"])
6390 return [self.delegate removePackage:package_];
6391 else if ([name isEqualToString:@"DOWNGRADE"]) {
6392 sheet_ = [[[UIActionSheet alloc]
6395 cancelButtonTitle:nil
6396 destructiveButtonTitle:nil
6397 otherButtonTitles:nil
6400 for (Package *version in (id) versions_)
6401 [sheet_ addButtonWithTitle:[version latest]];
6402 [sheet_ setContext:@"version"];
6404 [self.delegate showActionSheet:sheet_ fromItem:[[self navigationItem] rightBarButtonItem]];
6408 else if ([name isEqualToString:@"INSTALL"]);
6409 else if ([name isEqualToString:@"REINSTALL"]);
6410 else if ([name isEqualToString:@"UPGRADE"]);
6411 else _assert(false);
6413 [self.delegate installPackage:package_];
6416 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
6417 NSString *context([sheet context]);
6418 if (sheet_ == sheet)
6421 if ([context isEqualToString:@"modify"]) {
6422 if (button != [sheet cancelButtonIndex]) {
6424 [self performSelector:@selector(_clickButtonWithName:) withObject:buttons_[button].first afterDelay:0];
6426 [self _clickButtonWithName:buttons_[button].first];
6429 [sheet dismissWithClickedButtonIndex:button animated:YES];
6430 } else if ([context isEqualToString:@"version"]) {
6431 if (button != [sheet cancelButtonIndex]) {
6432 Package *version([versions_ objectAtIndex:button]);
6434 [self performSelector:@selector(_clickButtonWithPackage:) withObject:version afterDelay:0];
6436 [self _clickButtonWithPackage:version];
6439 [sheet dismissWithClickedButtonIndex:button animated:YES];
6443 - (bool) _allowJavaScriptPanel {
6448 - (void) _customButtonClicked {
6449 if (commercial_ && [package_ uninstalled])
6450 return [self reloadURLWithCache:NO];
6452 size_t count(buttons_.size());
6457 [self _clickButtonWithName:buttons_[0].first];
6459 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
6460 for (const auto &button : buttons_)
6461 [buttons addObject:button.second];
6463 sheet_ = [[[UIActionSheet alloc]
6466 cancelButtonTitle:nil
6467 destructiveButtonTitle:nil
6468 otherButtonTitles:nil
6471 for (NSString *button in buttons)
6472 [sheet_ addButtonWithTitle:button];
6473 [sheet_ setContext:@"modify"];
6475 [self.delegate showActionSheet:sheet_ fromItem:[[self navigationItem] rightBarButtonItem]];
6479 - (void) applyLoadingTitle {
6480 // Don't show "Loading" as the title. Ever.
6483 - (UIBarButtonItem *) rightButton {
6488 - (void) setPageColor:(UIColor *)color {
6489 return [super setPageColor:nil];
6492 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer {
6493 if ((self = [super init]) != nil) {
6494 database_ = database;
6495 name_ = name == nil ? @"" : [NSString stringWithString:name];
6496 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]] withReferrer:referrer];
6500 - (void) reloadData {
6503 [sheet_ dismissWithClickedButtonIndex:[sheet_ cancelButtonIndex] animated:YES];
6506 package_ = [database_ packageWithName:name_];
6507 versions_ = [package_ downgrades];
6511 if (package_ != nil) {
6512 [(Package *) package_ parse];
6514 commercial_ = [package_ isCommercial];
6516 if ([package_ mode] != nil)
6517 buttons_.push_back(std::make_pair(@"CLEAR", UCLocalize("CLEAR")));
6518 if ([package_ source] == nil);
6519 else if ([package_ upgradableAndEssential:NO])
6520 buttons_.push_back(std::make_pair(@"UPGRADE", UCLocalize("UPGRADE")));
6521 else if ([package_ uninstalled])
6522 buttons_.push_back(std::make_pair(@"INSTALL", UCLocalize("INSTALL")));
6524 buttons_.push_back(std::make_pair(@"REINSTALL", UCLocalize("REINSTALL")));
6525 if (![package_ uninstalled])
6526 buttons_.push_back(std::make_pair(@"REMOVE", UCLocalize("REMOVE")));
6527 if ([versions_ count] != 0)
6528 buttons_.push_back(std::make_pair(@"DOWNGRADE", UCLocalize("DOWNGRADE")));
6532 switch (buttons_.size()) {
6533 case 0: title = nil; break;
6534 case 1: title = buttons_[0].second; break;
6535 default: title = UCLocalize("MODIFY"); break;
6538 button_ = [[[UIBarButtonItem alloc]
6540 style:UIBarButtonItemStylePlain
6542 action:@selector(customButtonClicked)
6546 - (bool) isLoading {
6547 return commercial_ ? [super isLoading] : false;
6553 /* Package List Controller {{{ */
6554 @interface PackageListController : CyteViewController <
6555 UITableViewDataSource,
6558 _transient Database *database_;
6560 _H<NSArray> packages_;
6561 _H<NSArray> sections_;
6562 _H<UITableView, 2> list_;
6564 _H<NSArray> thumbs_;
6565 std::vector<NSInteger> offset_;
6567 _H<NSString> title_;
6568 unsigned reloading_;
6571 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6572 - (void) resetCursor;
6575 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages;
6579 @implementation PackageListController
6581 - (NSURL *) referrerURL {
6582 return [self navigationURL];
6585 - (bool) isSummarized {
6589 - (bool) showsSections {
6593 - (void) deselectWithAnimation:(BOOL)animated {
6594 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6597 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6598 CGRect base = [[self view] bounds];
6599 base.size.height -= bounds.size.height;
6600 base.origin = [list_ frame].origin;
6602 [UIView beginAnimations:nil context:NULL];
6603 [UIView setAnimationBeginsFromCurrentState:YES];
6604 [UIView setAnimationCurve:curve];
6605 [UIView setAnimationDuration:duration];
6606 [list_ setFrame:base];
6607 [UIView commitAnimations];
6610 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6611 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6614 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6615 [self resizeForKeyboardBounds:bounds duration:0];
6618 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6619 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6620 *curve = UIViewAnimationCurveEaseInOut;
6622 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6624 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6627 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6630 - (void) keyboardWillShow:(NSNotification *)notification {
6633 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6634 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6636 NSTimeInterval duration;
6637 UIViewAnimationCurve curve;
6638 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6640 CGRect kbframe = CGRectMake(Retina(center.x - bounds.size.width / 2), Retina(center.y - bounds.size.height / 2), bounds.size.width, bounds.size.height);
6641 UIViewController *base = self;
6642 while ([base parentOrPresentingViewController] != nil)
6643 base = [base parentOrPresentingViewController];
6644 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6645 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6647 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6648 intersection.size.height += CYStatusBarHeight();
6650 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6653 - (void) keyboardWillHide:(NSNotification *)notification {
6654 NSTimeInterval duration;
6655 UIViewAnimationCurve curve;
6656 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6658 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6661 - (void) viewWillAppear:(BOOL)animated {
6662 [super viewWillAppear:animated];
6664 [self resizeForKeyboardBounds:CGRectZero];
6665 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6666 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6669 - (void) viewWillDisappear:(BOOL)animated {
6670 [super viewWillDisappear:animated];
6672 [self resizeForKeyboardBounds:CGRectZero];
6673 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6674 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6677 - (void) viewDidAppear:(BOOL)animated {
6678 [super viewDidAppear:animated];
6679 [self deselectWithAnimation:animated];
6682 - (void) didSelectPackage:(Package *)package {
6683 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[[self referrerURL] absoluteString]] autorelease]);
6684 [view setDelegate:self.delegate];
6685 [[self navigationController] pushViewController:view animated:YES];
6688 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6689 NSInteger count([sections_ count]);
6690 return count == 0 ? 1 : count;
6693 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6694 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6696 return [[sections_ objectAtIndex:section] name];
6699 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6700 if ([sections_ count] == 0)
6702 return [[sections_ objectAtIndex:section] count];
6705 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6706 @synchronized (database_) {
6707 if ([database_ era] != era_)
6710 Section *section([sections_ objectAtIndex:[path section]]);
6711 NSInteger row([path row]);
6712 Package *package([packages_ objectAtIndex:([section row] + row)]);
6713 return [[package retain] autorelease];
6716 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6717 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6719 cell = [[[PackageCell alloc] init] autorelease];
6721 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6722 [cell setPackage:package asSummary:[self isSummarized]];
6726 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6727 Package *package([self packageAtIndexPath:path]);
6728 package = [database_ packageWithName:[package id]];
6729 [self didSelectPackage:package];
6732 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6736 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6737 return offset_[index];
6740 - (void) updateHeight {
6741 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6744 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6745 if ((self = [super init]) != nil) {
6746 database_ = database;
6747 title_ = [title copy];
6748 [[self navigationItem] setTitle:title_];
6753 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
6754 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
6755 [self setView:view];
6757 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6758 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6759 [view addSubview:list_];
6761 // XXX: is 20 the most optimal number here?
6762 [list_ setSectionIndexMinimumDisplayRowCount:20];
6764 [(UITableView *) list_ setDataSource:self];
6765 [list_ setDelegate:self];
6767 [self updateHeight];
6770 - (void) releaseSubviews {
6779 [super releaseSubviews];
6782 - (bool) shouldYield {
6786 - (bool) shouldBlock {
6790 - (NSMutableArray *) _reloadPackages {
6791 @synchronized (database_) {
6792 era_ = [database_ era];
6793 NSArray *packages([database_ packages]);
6795 return [NSMutableArray arrayWithArray:packages];
6798 - (void) _reloadData {
6799 if (reloading_ != 0) {
6804 NSMutableArray *packages;
6807 if ([self shouldYield]) {
6811 if (![self shouldBlock])
6814 hud = [self.delegate addProgressHUD];
6815 [hud setText:UCLocalize("LOADING")];
6819 packages = [self yieldToSelector:@selector(_reloadPackages)];
6822 [self.delegate removeProgressHUD:hud];
6823 } while (reloading_ == 2);
6825 packages = [self _reloadPackages];
6828 @synchronized (database_) {
6829 if (era_ != [database_ era])
6836 packages_ = packages;
6838 if ([self showsSections])
6839 sections_ = [self sectionsForPackages:packages];
6841 Section *section([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6842 [section setCount:[packages_ count]];
6843 sections_ = [NSArray arrayWithObject:section];
6846 [self updateHeight];
6848 _profile(PackageTable$reloadData$List)
6849 [(UITableView *) list_ setDataSource:self];
6857 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
6858 Section *prefix([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6859 size_t end([packages count]);
6861 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
6862 Section *section(prefix);
6864 thumbs_ = CollationThumbs_;
6865 offset_ = CollationOffset_;
6868 size_t offsets([CollationStarts_ count]);
6870 NSString *start([CollationStarts_ objectAtIndex:offset]);
6871 size_t length([start length]);
6873 for (size_t index(0); index != end; ++index) {
6875 Package *package([packages objectAtIndex:index]);
6876 NSString *name(PackageName(package, @selector(cyname)));
6878 //while ([start compare:name options:NSNumericSearch range:NSMakeRange(0, length) locale:CollationLocale_] != NSOrderedDescending) {
6879 while (StringNameCompare(start, name, length) != kCFCompareGreaterThan) {
6880 NSString *title([CollationTitles_ objectAtIndex:offset]);
6881 section = [[[Section alloc] initWithName:title row:index localize:NO] autorelease];
6882 [sections addObject:section];
6884 start = ++offset == offsets ? nil : [CollationStarts_ objectAtIndex:offset];
6887 length = [start length];
6891 [section addToCount];
6894 for (; offset != offsets; ++offset) {
6895 NSString *title([CollationTitles_ objectAtIndex:offset]);
6896 Section *section([[[Section alloc] initWithName:title row:end localize:NO] autorelease]);
6897 [sections addObject:section];
6900 if ([prefix count] != 0) {
6901 Section *suffix([sections lastObject]);
6902 [prefix setName:[suffix name]];
6903 [suffix setName:nil];
6904 [sections insertObject:prefix atIndex:(offsets - 1)];
6910 - (void) reloadData {
6913 if ([self shouldYield])
6914 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6919 - (void) resetCursor {
6920 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6923 - (void) clearData {
6924 [self updateHeight];
6926 [list_ setDataSource:nil];
6934 /* Filtered Package List Controller {{{ */
6935 typedef Function<bool, Package *> PackageFilter;
6936 typedef Function<void, NSMutableArray *> PackageSorter;
6937 @interface FilteredPackageListController : PackageListController {
6938 PackageFilter filter_;
6939 PackageSorter sorter_;
6942 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter;
6944 - (void) setFilter:(PackageFilter)filter;
6945 - (void) setSorter:(PackageSorter)sorter;
6949 @implementation FilteredPackageListController
6951 - (void) setFilter:(PackageFilter)filter {
6952 @synchronized (self) {
6956 - (void) setSorter:(PackageSorter)sorter {
6957 @synchronized (self) {
6961 - (NSMutableArray *) _reloadPackages {
6962 @synchronized (database_) {
6963 era_ = [database_ era];
6965 NSArray *packages([database_ packages]);
6966 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6968 PackageFilter filter;
6969 PackageSorter sorter;
6971 @synchronized (self) {
6976 _profile(PackageTable$reloadData$Filter)
6977 for (Package *package in packages)
6978 if (filter(package))
6979 [filtered addObject:package];
6987 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter {
6988 if ((self = [super initWithDatabase:database title:title]) != nil) {
6989 [self setFilter:filter];
6996 /* Home Controller {{{ */
6997 @interface HomeController : CydiaWebViewController {
6998 CFRunLoopRef runloop_;
6999 SCNetworkReachabilityRef reachability_;
7004 @implementation HomeController
7006 static void HomeControllerReachabilityCallback(SCNetworkReachabilityRef reachability, SCNetworkReachabilityFlags flags, void *info) {
7007 [(HomeController *) info dispatchEvent:@"CydiaReachabilityCallback"];
7011 if ((self = [super init]) != nil) {
7012 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
7015 reachability_ = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "cydia.saurik.com");
7016 if (reachability_ != NULL) {
7017 SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
7018 SCNetworkReachabilitySetCallback(reachability_, HomeControllerReachabilityCallback, &context);
7020 CFRunLoopRef runloop(CFRunLoopGetCurrent());
7021 if (SCNetworkReachabilityScheduleWithRunLoop(reachability_, runloop, kCFRunLoopDefaultMode))
7028 if (reachability_ != NULL && runloop_ != NULL)
7029 SCNetworkReachabilityUnscheduleFromRunLoop(reachability_, runloop_, kCFRunLoopDefaultMode);
7033 - (NSURL *) navigationURL {
7034 return [NSURL URLWithString:@"cydia://home"];
7037 - (void) aboutButtonClicked {
7038 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
7040 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
7041 [alert addButtonWithTitle:UCLocalize("CLOSE")];
7042 [alert setCancelButtonIndex:0];
7045 @"Copyright \u00a9 2008-2015\n"
7048 "Jay Freeman (saurik)\n"
7049 "saurik@saurik.com\n"
7050 "http://www.saurik.com/"
7056 - (UIBarButtonItem *) leftButton {
7057 return [[[UIBarButtonItem alloc]
7058 initWithTitle:UCLocalize("ABOUT")
7059 style:UIBarButtonItemStylePlain
7061 action:@selector(aboutButtonClicked)
7068 /* Cydia Tab Bar Controller {{{ */
7069 @interface CydiaTabBarController : CyteTabBarController <
7070 UITabBarControllerDelegate,
7073 _transient Database *database_;
7075 _H<UIActivityIndicatorView> indicator_;
7078 // XXX: ok, "updatedelegate_"?...
7079 _transient NSObject<CydiaDelegate> *updatedelegate_;
7082 - (void) beginUpdate;
7087 @implementation CydiaTabBarController
7089 - (id) initWithDatabase:(Database *)database {
7090 if ((self = [super init]) != nil) {
7091 database_ = database;
7092 [self setDelegate:self];
7094 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteTiny] autorelease];
7095 [indicator_ setOrigin:CGPointMake(kCFCoreFoundationVersionNumber >= 800 ? 2 : 4, 2)];
7097 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7101 - (void) beginUpdate {
7105 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
7106 UITabBarItem *item([controller tabBarItem]);
7108 [item setBadgeValue:@""];
7109 UIView *badge(MSHookIvar<UIView *>([item view], "_badge"));
7111 [indicator_ startAnimating];
7112 [badge addSubview:indicator_];
7114 [updatedelegate_ retainNetworkActivityIndicator];
7118 detachNewThreadSelector:@selector(performUpdate)
7124 - (void) performUpdate {
7125 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
7127 SourceStatus status(self, database_);
7128 [database_ updateWithStatus:status];
7131 performSelectorOnMainThread:@selector(completeUpdate)
7139 - (void) stopUpdateWithSelector:(SEL)selector {
7141 [updatedelegate_ releaseNetworkActivityIndicator];
7143 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
7144 [[controller tabBarItem] setBadgeValue:nil];
7146 [indicator_ removeFromSuperview];
7147 [indicator_ stopAnimating];
7149 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
7152 - (void) completeUpdate {
7155 [self stopUpdateWithSelector:@selector(reloadData)];
7158 - (void) cancelUpdate {
7159 [self stopUpdateWithSelector:@selector(updateDataAndLoad)];
7162 - (void) cancelPressed {
7163 [self cancelUpdate];
7170 - (bool) isSourceCancelled {
7174 - (void) startSourceFetch:(NSString *)uri {
7177 - (void) stopSourceFetch:(NSString *)uri {
7180 - (void) setUpdateDelegate:(id)delegate {
7181 updatedelegate_ = delegate;
7187 /* Cydia:// Protocol {{{ */
7188 @interface CydiaURLProtocol : NSURLProtocol {
7193 @implementation CydiaURLProtocol
7195 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7196 NSURL *url([request URL]);
7200 NSString *scheme([[url scheme] lowercaseString]);
7201 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7203 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7209 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7213 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7214 id<NSURLProtocolClient> client([self client]);
7216 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7218 NSData *data(UIImagePNGRepresentation(icon));
7220 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7221 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7222 [client URLProtocol:self didLoadData:data];
7223 [client URLProtocolDidFinishLoading:self];
7227 - (void) startLoading {
7228 id<NSURLProtocolClient> client([self client]);
7229 NSURLRequest *request([self request]);
7231 NSURL *url([request URL]);
7232 NSString *href([url absoluteString]);
7233 NSString *scheme([[url scheme] lowercaseString]);
7237 if ([scheme isEqualToString:@"cydia"])
7238 path = [href substringFromIndex:8];
7239 else if ([scheme isEqualToString:@"about"])
7240 path = [href substringFromIndex:12];
7241 else _assert(false);
7243 NSRange slash([path rangeOfString:@"/"]);
7246 if (slash.location == NSNotFound) {
7250 command = [path substringToIndex:slash.location];
7251 path = [path substringFromIndex:(slash.location + 1)];
7254 Database *database([Database sharedInstance]);
7257 else if ([command isEqualToString:@"application-icon"]) {
7260 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7264 if (icon == nil && $SBSCopyIconImagePNGDataForDisplayIdentifier != NULL) {
7265 NSData *data([$SBSCopyIconImagePNGDataForDisplayIdentifier(path) autorelease]);
7266 icon = [UIImage imageWithData:data];
7270 if (NSString *file = SBSCopyIconImagePathForDisplayIdentifier(path))
7271 icon = [UIImage imageAtPath:file];
7274 icon = [UIImage imageNamed:@"unknown.png"];
7276 [self _returnPNGWithImage:icon forRequest:request];
7277 } else if ([command isEqualToString:@"package-icon"]) {
7280 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7281 Package *package([database packageWithName:path]);
7285 UIImage *icon([package icon]);
7286 [self _returnPNGWithImage:icon forRequest:request];
7287 } else if ([command isEqualToString:@"uikit-image"]) {
7290 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7291 UIImage *icon(_UIImageWithName(path));
7292 [self _returnPNGWithImage:icon forRequest:request];
7293 } else if ([command isEqualToString:@"section-icon"]) {
7296 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7297 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7299 icon = [UIImage imageNamed:@"unknown.png"];
7300 [self _returnPNGWithImage:icon forRequest:request];
7302 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7306 - (void) stopLoading {
7312 /* Section Controller {{{ */
7313 @interface SectionController : FilteredPackageListController {
7315 _H<NSString> section_;
7318 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section;
7322 @implementation SectionController
7324 - (NSURL *) referrerURL {
7325 NSString *name(section_);
7326 name = name ?: @"*";
7327 NSString *key(key_);
7329 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sections/%@/%@", UI_, [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7332 - (NSURL *) navigationURL {
7333 NSString *name(section_);
7334 name = name ?: @"*";
7335 NSString *key(key_);
7337 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@/%@", [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7340 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section {
7343 title = UCLocalize("ALL_PACKAGES");
7344 else if (![section isEqual:@""])
7345 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(section) value:nil table:@"Sections"];
7347 title = UCLocalize("NO_SECTION");
7349 if ((self = [super initWithDatabase:database title:title]) != nil) {
7350 key_ = [source key];
7355 - (void) reloadData {
7356 Source *source([database_ sourceWithKey:key_]);
7357 _H<NSString> name(section_);
7359 [self setFilter:[=](Package *package) {
7360 NSString *section([package section]);
7364 section == nil && [name length] == 0 ||
7365 [name isEqualToString:section]
7368 [package source] == source
7369 ) && [package visible];
7377 /* Sections Controller {{{ */
7378 @interface SectionsController : CyteViewController <
7379 UITableViewDataSource,
7382 _transient Database *database_;
7384 _H<NSMutableArray> sections_;
7385 _H<NSMutableArray> filtered_;
7386 _H<UITableView, 2> list_;
7389 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7390 - (void) editButtonClicked;
7394 @implementation SectionsController
7396 - (NSURL *) navigationURL {
7397 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
7400 - (Source *) source {
7403 return [database_ sourceWithKey:key_];
7406 - (void) updateNavigationItem {
7407 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7408 if ([sections_ count] == 0) {
7409 [[self navigationItem] setRightBarButtonItem:nil];
7411 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7412 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7414 action:@selector(editButtonClicked)
7415 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7419 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7420 [super setEditing:editing animated:animated];
7425 [self.delegate updateData];
7427 [self updateNavigationItem];
7430 - (void) viewDidAppear:(BOOL)animated {
7431 [super viewDidAppear:animated];
7432 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7435 - (void) viewWillDisappear:(BOOL)animated {
7436 [super viewWillDisappear:animated];
7437 [self setEditing:NO];
7440 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7441 Section *section = nil;
7442 int index = [indexPath row];
7443 if (![self isEditing]) {
7446 section = [filtered_ objectAtIndex:index];
7448 section = [sections_ objectAtIndex:index];
7453 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7454 if ([self isEditing])
7455 return [sections_ count];
7457 return [filtered_ count] + 1;
7460 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7464 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7465 static NSString *reuseIdentifier = @"SectionCell";
7467 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7469 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7471 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7476 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7477 if ([self isEditing])
7480 Section *section = [self sectionAtIndexPath:indexPath];
7482 SectionController *controller = [[[SectionController alloc]
7483 initWithDatabase:database_
7484 source:[self source]
7485 section:[section name]
7487 [controller setDelegate:self.delegate];
7489 [[self navigationController] pushViewController:controller animated:YES];
7493 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
7494 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7495 [list_ setRowHeight:46];
7496 [(UITableView *) list_ setDataSource:self];
7497 [list_ setDelegate:self];
7498 [self setView:list_];
7501 - (void) viewDidLoad {
7502 [super viewDidLoad];
7504 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7507 - (void) releaseSubviews {
7513 [super releaseSubviews];
7516 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7517 if ((self = [super init]) != nil) {
7518 database_ = database;
7519 key_ = [source key];
7523 - (void) reloadData {
7526 NSArray *packages = [database_ packages];
7528 sections_ = [NSMutableArray arrayWithCapacity:16];
7529 filtered_ = [NSMutableArray arrayWithCapacity:16];
7531 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7533 Source *source([self source]);
7536 for (Package *package in packages) {
7537 if (source != nil && [package source] != source)
7540 NSString *name([package section]);
7541 NSString *key(name == nil ? @"" : name);
7545 _profile(SectionsView$reloadData$Section)
7546 section = [sections objectForKey:key];
7547 if (section == nil) {
7548 _profile(SectionsView$reloadData$Section$Allocate)
7549 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7550 [sections setObject:section forKey:key];
7555 [section addToCount];
7557 _profile(SectionsView$reloadData$Filter)
7558 if (![package visible])
7566 [sections_ addObjectsFromArray:[sections allValues]];
7568 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7570 for (Section *section in (id) sections_) {
7571 size_t count([section row]);
7575 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7576 [section setCount:count];
7577 [filtered_ addObject:section];
7580 [self updateNavigationItem];
7585 - (void) editButtonClicked {
7586 [self setEditing:![self isEditing] animated:YES];
7592 /* Changes Controller {{{ */
7593 @interface ChangesController : FilteredPackageListController {
7597 - (id) initWithDatabase:(Database *)database;
7601 @implementation ChangesController
7603 - (NSURL *) referrerURL {
7604 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/changes/", UI_]];
7607 - (NSURL *) navigationURL {
7608 return [NSURL URLWithString:@"cydia://changes"];
7611 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7612 @synchronized (database_) {
7613 if ([database_ era] != era_)
7616 NSUInteger sectionIndex([path section]);
7617 if (sectionIndex >= [sections_ count])
7619 Section *section([sections_ objectAtIndex:sectionIndex]);
7620 NSInteger row([path row]);
7621 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7624 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7625 NSString *context([alert context]);
7627 if ([context isEqualToString:@"norefresh"])
7628 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7631 - (void) setLeftBarButtonItem {
7632 if ([self.delegate updating])
7633 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7634 initWithTitle:UCLocalize("CANCEL")
7635 style:UIBarButtonItemStyleDone
7637 action:@selector(cancelButtonClicked)
7638 ] autorelease] animated:YES];
7640 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7641 initWithTitle:UCLocalize("REFRESH")
7642 style:UIBarButtonItemStylePlain
7644 action:@selector(refreshButtonClicked)
7645 ] autorelease] animated:YES];
7648 - (void) refreshButtonClicked {
7649 if ([self.delegate requestUpdate])
7650 [self setLeftBarButtonItem];
7653 - (void) cancelButtonClicked {
7654 [self.delegate cancelUpdate];
7657 - (void) upgradeButtonClicked {
7658 [self.delegate distUpgrade];
7659 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7662 - (bool) shouldYield {
7666 - (bool) shouldBlock {
7670 - (void) useFilter {
7671 @synchronized (self) {
7672 [self setFilter:[](Package *package) {
7673 return [package upgradableAndEssential:YES] || [package visible];
7676 [self setSorter:[](NSMutableArray *packages) {
7677 [packages radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7681 - (id) initWithDatabase:(Database *)database {
7682 if ((self = [super initWithDatabase:database title:UCLocalize("CHANGES")]) != nil) {
7687 - (void) viewDidLoad {
7688 [super viewDidLoad];
7689 [self setLeftBarButtonItem];
7692 - (void) viewWillAppear:(BOOL)animated {
7693 [super viewWillAppear:animated];
7694 [self setLeftBarButtonItem];
7697 - (void) reloadData {
7698 [self setLeftBarButtonItem];
7702 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
7703 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
7705 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7706 Section *ignored = nil;
7707 Section *section = nil;
7711 bool unseens = false;
7713 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7715 for (size_t offset = 0, count = [packages count]; offset != count; ++offset) {
7716 Package *package = [packages objectAtIndex:offset];
7718 BOOL uae = [package upgradableAndEssential:YES];
7722 time_t seen([package seen]);
7724 if (section == nil || last != seen) {
7728 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7731 _profile(ChangesController$reloadData$Allocate)
7732 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7733 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7734 [sections addObject:section];
7738 [section addToCount];
7739 } else if ([package ignored]) {
7740 if (ignored == nil) {
7741 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7743 [ignored addToCount];
7746 [upgradable addToCount];
7751 CFRelease(formatter);
7754 Section *last = [sections lastObject];
7755 size_t count = [last count];
7756 [packages removeObjectsInRange:NSMakeRange([packages count] - count, count)];
7757 [sections removeLastObject];
7760 if ([ignored count] != 0)
7761 [sections insertObject:ignored atIndex:0];
7763 [sections insertObject:upgradable atIndex:0];
7767 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7768 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7769 style:UIBarButtonItemStylePlain
7771 action:@selector(upgradeButtonClicked)
7772 ] autorelease]) animated:YES];
7779 /* Search Controller {{{ */
7780 @interface SearchController : FilteredPackageListController <
7783 _H<UISearchBar, 1> search_;
7788 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7789 - (void) reloadData;
7793 @implementation SearchController
7795 - (NSURL *) referrerURL {
7796 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/search?q=%@", UI_, [([search_ text] ?: @"") stringByAddingPercentEscapesIncludingReserved]]];
7799 - (NSURL *) navigationURL {
7800 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7801 return [NSURL URLWithString:@"cydia://search"];
7803 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [[search_ text] stringByAddingPercentEscapesIncludingReserved]]];
7806 - (NSArray *) termsForQuery:(NSString *)query {
7807 NSMutableArray *terms([NSMutableArray arrayWithCapacity:2]);
7808 for (NSString *component in [query componentsSeparatedByString:@" "])
7809 if ([component length] != 0)
7810 [terms addObject:component];
7815 - (void) useSearch {
7816 _H<NSArray> query([self termsForQuery:[search_ text]]);
7819 @synchronized (self) {
7820 [self setFilter:[=](Package *package) {
7821 if (![package unfiltered])
7823 if (![package matches:query])
7828 [self setSorter:[](NSMutableArray *packages) {
7829 [packages radixSortUsingSelector:@selector(rank)];
7837 - (void) usePrefix:(NSString *)prefix {
7838 _H<NSString> query(prefix);
7841 @synchronized (self) {
7842 [self setFilter:[=](Package *package) {
7843 if ([query length] == 0)
7845 if (![package unfiltered])
7847 if ([[package name] compare:query options:MatchCompareOptions_ range:NSMakeRange(0, [query length])] != NSOrderedSame)
7852 [self setSorter:nullptr];
7858 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7860 [self usePrefix:[search_ text]];
7863 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7864 [search_ resignFirstResponder];
7868 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7869 [search_ setText:@""];
7870 [self searchBarButtonClicked:searchBar];
7873 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7874 [self searchBarButtonClicked:searchBar];
7877 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7878 [self usePrefix:text];
7881 - (bool) shouldYield {
7885 - (bool) shouldBlock {
7889 - (bool) isSummarized {
7893 - (bool) showsSections {
7897 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7898 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH")])) {
7899 search_ = [[[UISearchBar alloc] init] autorelease];
7900 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7901 [search_ setDelegate:self];
7903 UITextField *textField;
7904 if ([search_ respondsToSelector:@selector(searchField)])
7905 textField = [search_ searchField];
7907 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7909 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7910 [textField setEnablesReturnKeyAutomatically:NO];
7911 [[self navigationItem] setTitleView:textField];
7914 [search_ setText:query];
7919 - (void) viewDidAppear:(BOOL)animated {
7920 [super viewDidAppear:animated];
7922 if (!searchloaded_) {
7923 searchloaded_ = YES;
7924 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7925 [search_ layoutSubviews];
7928 if ([self isSummarized])
7929 [search_ becomeFirstResponder];
7932 - (void) reloadData {
7937 - (void) didSelectPackage:(Package *)package {
7938 [search_ resignFirstResponder];
7939 [super didSelectPackage:package];
7944 /* Package Settings Controller {{{ */
7945 @interface PackageSettingsController : CyteViewController <
7946 UITableViewDataSource,
7949 _transient Database *database_;
7951 _H<Package> package_;
7952 _H<UITableView, 2> table_;
7953 _H<UISwitch> subscribedSwitch_;
7954 _H<UISwitch> ignoredSwitch_;
7955 _H<UITableViewCell> subscribedCell_;
7956 _H<UITableViewCell> ignoredCell_;
7959 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7963 @implementation PackageSettingsController
7965 - (NSURL *) navigationURL {
7966 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
7969 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7970 if (package_ == nil)
7973 if ([package_ installed] == nil)
7979 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7980 if (package_ == nil)
7983 // both sections contain just one item right now.
7987 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7991 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7993 return UCLocalize("SHOW_ALL_CHANGES_EX");
7995 return UCLocalize("IGNORE_UPGRADES_EX");
7998 - (void) onSubscribed:(id)control {
7999 bool value([control isOn]);
8000 if (package_ == nil)
8002 if ([package_ setSubscribed:value])
8003 [self.delegate updateData];
8006 - (void) _updateIgnored {
8007 const char *package([name_ UTF8String]);
8008 bool on([ignoredSwitch_ isOn]);
8010 FILE *dpkg(popen("/usr/libexec/cydia/cydo --set-selections", "w"));
8011 fwrite(package, strlen(package), 1, dpkg);
8014 fwrite(" hold\n", 6, 1, dpkg);
8016 fwrite(" install\n", 9, 1, dpkg);
8021 - (void) onIgnored:(id)control {
8022 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
8023 [invocation setTarget:self];
8024 [invocation setSelector:@selector(_updateIgnored)];
8026 [self.delegate reloadDataWithInvocation:invocation];
8029 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8030 if (package_ == nil)
8033 switch ([indexPath section]) {
8034 case 0: return subscribedCell_;
8035 case 1: return ignoredCell_;
8044 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8045 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8046 [self setView:view];
8048 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
8049 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8050 [(UITableView *) table_ setDataSource:self];
8051 [table_ setDelegate:self];
8052 [view addSubview:table_];
8054 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
8055 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
8056 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
8058 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
8059 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
8060 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
8062 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
8063 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
8064 [subscribedCell_ setAccessoryView:subscribedSwitch_];
8065 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
8067 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
8068 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
8069 [ignoredCell_ setAccessoryView:ignoredSwitch_];
8070 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
8073 - (void) viewDidLoad {
8074 [super viewDidLoad];
8076 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
8079 - (void) releaseSubviews {
8081 subscribedCell_ = nil;
8083 ignoredSwitch_ = nil;
8084 subscribedSwitch_ = nil;
8086 [super releaseSubviews];
8089 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
8090 if ((self = [super init]) != nil) {
8091 database_ = database;
8096 - (void) reloadData {
8099 package_ = [database_ packageWithName:name_];
8101 if (package_ != nil) {
8102 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
8103 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
8104 } // XXX: what now, G?
8106 [table_ reloadData];
8112 /* Installed Controller {{{ */
8113 @interface InstalledController : FilteredPackageListController {
8117 - (id) initWithDatabase:(Database *)database;
8118 - (void) queueStatusDidChange;
8122 @implementation InstalledController
8124 - (NSURL *) referrerURL {
8125 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/installed/", UI_]];
8128 - (NSURL *) navigationURL {
8129 return [NSURL URLWithString:@"cydia://installed"];
8132 - (void) useRecent {
8135 @synchronized (self) {
8136 [self setFilter:[](Package *package) {
8137 return ![package uninstalled] && package->role_ < 7;
8140 [self setSorter:[](NSMutableArray *packages) {
8141 [packages radixSortUsingSelector:@selector(recent)];
8145 - (void) useFilter:(UISegmentedControl *)segmented {
8146 NSInteger selected([segmented selectedSegmentIndex]);
8148 return [self useRecent];
8149 bool simple(selected == 0);
8152 @synchronized (self) {
8153 [self setFilter:[=](Package *package) {
8154 return ![package uninstalled] && package->role_ <= (simple ? 1 : 3);
8157 [self setSorter:nullptr];
8160 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
8162 return [super sectionsForPackages:packages];
8164 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterLongStyle, kCFDateFormatterNoStyle));
8166 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
8167 Section *section(nil);
8170 for (size_t offset(0), count([packages count]); offset != count; ++offset) {
8171 Package *package([packages objectAtIndex:offset]);
8173 time_t upgraded([package upgraded]);
8174 if (upgraded < 1168364520)
8177 upgraded -= upgraded % (60 * 60 * 24);
8179 if (section == nil || upgraded != last) {
8184 continue; // XXX: name = UCLocalize("...");
8186 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:upgraded]);
8190 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
8191 [sections addObject:section];
8194 [section addToCount];
8197 CFRelease(formatter);
8201 - (id) initWithDatabase:(Database *)database {
8202 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED")]) != nil) {
8203 UISegmentedControl *segmented([[[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:UCLocalize("USER"), UCLocalize("EXPERT"), UCLocalize("RECENT"), nil]] autorelease]);
8204 [segmented setSelectedSegmentIndex:0];
8205 [segmented setSegmentedControlStyle:UISegmentedControlStyleBar];
8206 [[self navigationItem] setTitleView:segmented];
8208 [segmented addTarget:self action:@selector(modeChanged:) forEvents:UIControlEventValueChanged];
8209 [self useFilter:segmented];
8211 [self queueStatusDidChange];
8216 - (void) queueButtonClicked {
8217 [self.delegate queue];
8221 - (void) queueStatusDidChange {
8224 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8225 initWithTitle:UCLocalize("QUEUE")
8226 style:UIBarButtonItemStyleDone
8228 action:@selector(queueButtonClicked)
8231 [[self navigationItem] setRightBarButtonItem:nil];
8236 - (void) modeChanged:(UISegmentedControl *)segmented {
8237 [self useFilter:segmented];
8244 /* Source Cell {{{ */
8245 @interface SourceCell : CyteTableViewCell <
8246 CyteTableViewCellDelegate,
8249 _H<Source, 1> source_;
8252 _H<NSString> origin_;
8253 _H<NSString> label_;
8254 _H<UIActivityIndicatorView> indicator_;
8257 - (void) setSource:(Source *)source;
8258 - (void) setFetch:(NSNumber *)fetch;
8262 @implementation SourceCell
8264 - (void) _setImage:(NSArray *)data {
8265 if ([url_ isEqual:[data objectAtIndex:0]]) {
8266 icon_ = [data objectAtIndex:1];
8267 [self.content setNeedsDisplay];
8271 - (void) _setSource:(NSURL *) url {
8272 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8274 if (NSData *data = [NSURLConnection
8275 sendSynchronousRequest:[NSURLRequest
8277 cachePolicy:NSURLRequestUseProtocolCachePolicy
8281 returningResponse:NULL
8284 if (UIImage *image = [UIImage imageWithData:data])
8285 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
8290 - (void) setSource:(Source *)source {
8292 [source_ setDelegate:self];
8294 [self setFetch:[NSNumber numberWithBool:[source_ fetch]]];
8296 icon_ = [UIImage imageNamed:@"unknown.png"];
8298 origin_ = [source name];
8299 label_ = [source rooturi];
8301 [self.content setNeedsDisplay];
8303 url_ = [source iconURL];
8304 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
8307 - (void) setAllSource {
8309 [indicator_ stopAnimating];
8311 icon_ = [UIImage imageNamed:@"folder.png"];
8312 origin_ = UCLocalize("ALL_SOURCES");
8313 label_ = UCLocalize("ALL_SOURCES_EX");
8314 [self.content setNeedsDisplay];
8317 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8318 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8319 UIView *content([self contentView]);
8320 CGRect bounds([content bounds]);
8322 self.content = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8323 [self.content setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8324 [self.content setBackgroundColor:[UIColor whiteColor]];
8325 [content addSubview:self.content];
8327 [self.content setDelegate:self];
8328 [self.content setOpaque:YES];
8330 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGraySmall] autorelease];
8331 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin];// | UIViewAutoresizingFlexibleBottomMargin];
8332 [content addSubview:indicator_];
8334 [[self.content layer] setContentsGravity:kCAGravityTopLeft];
8338 - (void) layoutSubviews {
8339 [super layoutSubviews];
8341 UIView *content([self contentView]);
8342 CGRect bounds([content bounds]);
8344 CGRect frame([indicator_ frame]);
8345 frame.origin.x = bounds.size.width - frame.size.width;
8346 frame.origin.y = Retina((bounds.size.height - frame.size.height) / 2);
8348 if (kCFCoreFoundationVersionNumber < 800)
8349 frame.origin.x -= 8;
8350 [indicator_ setFrame:frame];
8353 - (NSString *) accessibilityLabel {
8357 - (void) drawContentRect:(CGRect)rect {
8358 bool highlighted(self.highlighted);
8359 float width(rect.size.width);
8363 rect.size = [(UIImage *) icon_ size];
8365 while (rect.size.width > 32 || rect.size.height > 32) {
8366 rect.size.width /= 2;
8367 rect.size.height /= 2;
8370 rect.origin.x = 26 - rect.size.width / 2;
8371 rect.origin.y = 26 - rect.size.height / 2;
8373 [icon_ drawInRect:Retina(rect)];
8376 if (highlighted && kCFCoreFoundationVersionNumber < 800)
8381 [origin_ drawAtPoint:CGPointMake(52, 8) forWidth:(width - 49) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
8385 [label_ drawAtPoint:CGPointMake(52, 29) forWidth:(width - 49) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
8388 - (void) setFetch:(NSNumber *)fetch {
8389 if ([fetch boolValue])
8390 [indicator_ startAnimating];
8392 [indicator_ stopAnimating];
8397 /* Sources Controller {{{ */
8398 @interface SourcesController : CyteViewController <
8399 UITableViewDataSource,
8402 _transient Database *database_;
8405 _H<UITableView, 2> list_;
8406 _H<NSMutableArray> sources_;
8410 _H<UIProgressHUD> hud_;
8413 NSURLConnection *trivial_bz2_;
8414 NSURLConnection *trivial_gz_;
8419 - (id) initWithDatabase:(Database *)database;
8420 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated;
8424 @implementation SourcesController
8426 - (void) _releaseConnection:(NSURLConnection *)connection {
8427 if (connection != nil) {
8428 [connection cancel];
8429 //[connection setDelegate:nil];
8430 [connection release];
8435 [self _releaseConnection:trivial_gz_];
8436 [self _releaseConnection:trivial_bz2_];
8441 - (NSURL *) navigationURL {
8442 return [NSURL URLWithString:@"cydia://sources"];
8445 - (void) viewDidAppear:(BOOL)animated {
8446 [super viewDidAppear:animated];
8447 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8450 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8454 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8456 return UCLocalize("INDIVIDUAL_SOURCES");
8460 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8463 case 1: return [sources_ count];
8468 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8469 @synchronized (database_) {
8470 if ([database_ era] != era_)
8472 if ([indexPath section] != 1)
8474 NSUInteger index([indexPath row]);
8475 if (index >= [sources_ count])
8477 return [sources_ objectAtIndex:index];
8480 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8481 static NSString *cellIdentifier = @"SourceCell";
8483 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8484 if (cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8485 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8487 Source *source([self sourceAtIndexPath:indexPath]);
8489 [cell setAllSource];
8491 [cell setSource:source];
8496 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8497 SectionsController *controller([[[SectionsController alloc]
8498 initWithDatabase:database_
8499 source:[self sourceAtIndexPath:indexPath]
8502 [controller setDelegate:self.delegate];
8503 [[self navigationController] pushViewController:controller animated:YES];
8506 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8507 if ([indexPath section] != 1)
8509 Source *source = [self sourceAtIndexPath:indexPath];
8510 return [source record] != nil;
8513 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8514 _assert([indexPath section] == 1);
8515 if (editingStyle == UITableViewCellEditingStyleDelete) {
8516 Source *source = [self sourceAtIndexPath:indexPath];
8517 if (source == nil) return;
8519 [Sources_ removeObjectForKey:[source key]];
8521 [self.delegate syncData];
8525 - (void) tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath {
8526 [self updateButtonsForEditingStatusAnimated:YES];
8530 [self.delegate addTrivialSource:href_];
8533 [self.delegate syncData];
8536 - (NSString *) getWarning {
8537 NSString *href(href_);
8538 NSRange colon([href rangeOfString:@"://"]);
8539 if (colon.location != NSNotFound)
8540 href = [href substringFromIndex:(colon.location + 3)];
8541 href = [href stringByAddingPercentEscapes];
8542 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8544 NSURL *url([NSURL URLWithString:href]);
8546 NSStringEncoding encoding;
8547 NSError *error(nil);
8549 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8550 return [warning length] == 0 ? nil : warning;
8554 - (void) _endConnection:(NSURLConnection *)connection {
8555 // XXX: the memory management in this method is horribly awkward
8557 NSURLConnection **field = NULL;
8558 if (connection == trivial_bz2_)
8559 field = &trivial_bz2_;
8560 else if (connection == trivial_gz_)
8561 field = &trivial_gz_;
8562 _assert(field != NULL);
8563 [connection release];
8567 trivial_bz2_ == nil &&
8570 NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil);
8572 [self.delegate releaseNetworkActivityIndicator];
8574 [self.delegate removeProgressHUD:hud_];
8578 if (warning != nil) {
8579 UIAlertView *alert = [[[UIAlertView alloc]
8580 initWithTitle:UCLocalize("SOURCE_WARNING")
8583 cancelButtonTitle:UCLocalize("CANCEL")
8585 UCLocalize("ADD_ANYWAY"),
8589 [alert setContext:@"warning"];
8590 [alert setNumberOfRows:1];
8593 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
8599 } else if (error_ != nil) {
8600 UIAlertView *alert = [[[UIAlertView alloc]
8601 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8602 message:[error_ localizedDescription]
8604 cancelButtonTitle:UCLocalize("OK")
8605 otherButtonTitles:nil
8608 [alert setContext:@"urlerror"];
8613 UIAlertView *alert = [[[UIAlertView alloc]
8614 initWithTitle:UCLocalize("NOT_REPOSITORY")
8615 message:UCLocalize("NOT_REPOSITORY_EX")
8617 cancelButtonTitle:UCLocalize("OK")
8618 otherButtonTitles:nil
8621 [alert setContext:@"trivial"];
8631 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8632 switch ([response statusCode]) {
8638 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8639 lprintf("connection:\"%s\" didFailWithError:\"%s\"\n", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8641 [self _endConnection:connection];
8644 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8645 [self _endConnection:connection];
8648 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8649 NSURL *url([NSURL URLWithString:href]);
8651 NSMutableURLRequest *request = [NSMutableURLRequest
8653 cachePolicy:NSURLRequestUseProtocolCachePolicy
8657 [request setHTTPMethod:method];
8659 if (Machine_ != NULL)
8660 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8662 if (UniqueID_ != nil)
8663 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8665 if ([url isCydiaSecure]) {
8666 if (UniqueID_ != nil)
8667 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
8670 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8673 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8674 NSString *context([alert context]);
8676 if ([context isEqualToString:@"source"]) {
8679 NSString *href = [[alert textField] text];
8680 href = VerifySource(href);
8685 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8686 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8690 // XXX: this is stupid
8691 hud_ = [self.delegate addProgressHUD];
8692 [hud_ setText:UCLocalize("VERIFYING_URL")];
8693 [self.delegate retainNetworkActivityIndicator];
8702 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8703 } else if ([context isEqualToString:@"trivial"])
8704 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8705 else if ([context isEqualToString:@"urlerror"])
8706 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8707 else if ([context isEqualToString:@"warning"]) {
8710 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
8719 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8723 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated {
8724 BOOL editing([list_ isEditing]);
8727 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8728 initWithTitle:UCLocalize("ADD")
8729 style:UIBarButtonItemStylePlain
8731 action:@selector(addButtonClicked)
8732 ] autorelease] animated:animated];
8733 else if ([self.delegate updating])
8734 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8735 initWithTitle:UCLocalize("CANCEL")
8736 style:UIBarButtonItemStyleDone
8738 action:@selector(cancelButtonClicked)
8739 ] autorelease] animated:animated];
8741 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8742 initWithTitle:UCLocalize("REFRESH")
8743 style:UIBarButtonItemStylePlain
8745 action:@selector(refreshButtonClicked)
8746 ] autorelease] animated:animated];
8748 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8749 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8750 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8752 action:@selector(editButtonClicked)
8753 ] autorelease] animated:animated];
8757 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease];
8758 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8759 [list_ setRowHeight:53];
8760 [(UITableView *) list_ setDataSource:self];
8761 [list_ setDelegate:self];
8762 [self setView:list_];
8765 - (void) viewDidLoad {
8766 [super viewDidLoad];
8768 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8769 [self updateButtonsForEditingStatusAnimated:NO];
8772 - (void) viewWillAppear:(BOOL)animated {
8773 [super viewWillAppear:animated];
8775 [list_ setEditing:NO];
8776 [self updateButtonsForEditingStatusAnimated:NO];
8779 - (void) releaseSubviews {
8784 [super releaseSubviews];
8787 - (id) initWithDatabase:(Database *)database {
8788 if ((self = [super init]) != nil) {
8789 database_ = database;
8793 - (void) reloadData {
8795 [self updateButtonsForEditingStatusAnimated:YES];
8797 @synchronized (database_) {
8798 era_ = [database_ era];
8800 sources_ = [NSMutableArray arrayWithCapacity:16];
8801 [sources_ addObjectsFromArray:[database_ sources]];
8803 [sources_ sortUsingSelector:@selector(compareByName:)];
8806 int count([sources_ count]);
8808 for (int i = 0; i != count; i++) {
8809 if ([[sources_ objectAtIndex:i] record] == nil)
8817 - (void) showAddSourcePrompt {
8818 UIAlertView *alert = [[[UIAlertView alloc]
8819 initWithTitle:UCLocalize("ENTER_APT_URL")
8822 cancelButtonTitle:UCLocalize("CANCEL")
8824 UCLocalize("ADD_SOURCE"),
8828 [alert setContext:@"source"];
8830 [alert setNumberOfRows:1];
8831 [alert addTextFieldWithValue:@"http://" label:@""];
8833 NSObject<UITextInputTraits> *traits = [[alert textField] textInputTraits];
8834 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8835 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8836 [traits setKeyboardType:UIKeyboardTypeURL];
8837 // XXX: UIReturnKeyDone
8838 [traits setReturnKeyType:UIReturnKeyNext];
8843 - (void) addButtonClicked {
8844 [self showAddSourcePrompt];
8847 - (void) refreshButtonClicked {
8848 if ([self.delegate requestUpdate])
8849 [self updateButtonsForEditingStatusAnimated:YES];
8852 - (void) cancelButtonClicked {
8853 [self.delegate cancelUpdate];
8856 - (void) editButtonClicked {
8857 [list_ setEditing:![list_ isEditing] animated:YES];
8858 [self updateButtonsForEditingStatusAnimated:YES];
8864 /* Stash Controller {{{ */
8865 @interface StashController : CyteViewController {
8866 _H<UIActivityIndicatorView> spinner_;
8867 _H<UILabel> status_;
8868 _H<UILabel> caption_;
8873 @implementation StashController
8876 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8877 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8878 [self setView:view];
8880 [view setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8882 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8883 CGRect spinrect = [spinner_ frame];
8884 spinrect.origin.x = Retina([[self view] frame].size.width / 2 - spinrect.size.width / 2);
8885 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8886 [spinner_ setFrame:spinrect];
8887 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8888 [view addSubview:spinner_];
8889 [spinner_ startAnimating];
8892 captrect.size.width = [[self view] frame].size.width;
8893 captrect.size.height = 40.0f;
8894 captrect.origin.x = 0;
8895 captrect.origin.y = Retina([[self view] frame].size.height / 2 - captrect.size.height * 2);
8896 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8897 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8898 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8899 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8900 [caption_ setTextColor:[UIColor whiteColor]];
8901 [caption_ setBackgroundColor:[UIColor clearColor]];
8902 [caption_ setShadowColor:[UIColor blackColor]];
8903 [caption_ setTextAlignment:NSTextAlignmentCenter];
8904 [view addSubview:caption_];
8907 statusrect.size.width = [[self view] frame].size.width;
8908 statusrect.size.height = 30.0f;
8909 statusrect.origin.x = 0;
8910 statusrect.origin.y = Retina([[self view] frame].size.height / 2 - statusrect.size.height);
8911 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8912 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8913 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8914 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8915 [status_ setTextColor:[UIColor whiteColor]];
8916 [status_ setBackgroundColor:[UIColor clearColor]];
8917 [status_ setShadowColor:[UIColor blackColor]];
8918 [status_ setTextAlignment:NSTextAlignmentCenter];
8919 [view addSubview:status_];
8922 - (void) releaseSubviews {
8927 [super releaseSubviews];
8933 @interface CYURLCache : SDURLCache {
8938 @implementation CYURLCache
8940 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8943 else if ([event isEqualToString:@"no-cache"])
8945 else if ([event isEqualToString:@"store"])
8947 else if ([event isEqualToString:@"invalid"])
8949 else if ([event isEqualToString:@"memory"])
8951 else if ([event isEqualToString:@"disk"])
8953 else if ([event isEqualToString:@"miss"])
8956 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8960 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
8961 if (NSURLResponse *response = [cached response])
8962 if (NSString *mime = [response MIMEType])
8963 if ([mime isEqualToString:@"text/cache-manifest"]) {
8964 NSURL *url([response URL]);
8967 NSLog(@"###: %@", [url absoluteString]);
8970 @synchronized (HostConfig_) {
8971 [CachedURLs_ addObject:url];
8975 [super storeCachedResponse:cached forRequest:request];
8978 - (void) createDiskCachePath {
8979 [super createDiskCachePath];
8984 @interface Cydia : CyteApplication <
8985 ConfirmationControllerDelegate,
8989 _H<UIWindow> window_;
8990 _H<CydiaTabBarController> tabbar_;
8991 _H<CyteTabBarController> emulated_;
8992 _H<AppCacheController> appcache_;
8994 _H<NSMutableArray> essential_;
8995 _H<NSMutableArray> broken_;
8997 Database *database_;
8999 _H<NSURL> starturl_;
9004 _H<StashController> stash_;
9013 @implementation Cydia
9015 - (void) lockSuspend {
9016 if (locked_++ == 0) {
9017 if ($SBSSetInterceptsMenuButtonForever != NULL)
9018 (*$SBSSetInterceptsMenuButtonForever)(true);
9020 [self setIdleTimerDisabled:YES];
9024 - (void) unlockSuspend {
9025 if (--locked_ == 0) {
9026 [self setIdleTimerDisabled:NO];
9028 if ($SBSSetInterceptsMenuButtonForever != NULL)
9029 (*$SBSSetInterceptsMenuButtonForever)(false);
9033 - (void) beginUpdate {
9034 [tabbar_ beginUpdate];
9037 - (void) cancelUpdate {
9038 [tabbar_ cancelUpdate];
9041 - (bool) requestUpdate {
9042 if (IsReachable("cydia.saurik.com")) {
9046 UIAlertView *alert = [[[UIAlertView alloc]
9047 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("REFRESH")]
9048 message:@"Host Unreachable" // XXX: Localize
9050 cancelButtonTitle:UCLocalize("OK")
9051 otherButtonTitles:nil
9054 [alert setContext:@"norefresh"];
9062 return [tabbar_ updating];
9066 if ([broken_ count] != 0) {
9067 int count = [broken_ count];
9069 UIAlertView *alert = [[[UIAlertView alloc]
9070 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
9071 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
9073 cancelButtonTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("FORCIBLY_CLEAR"), UCLocalize("UNSAFE")]
9075 UCLocalize("TEMPORARY_IGNORE"),
9079 [alert setContext:@"fixhalf"];
9080 [alert setNumberOfRows:2];
9082 } else if (!Ignored_ && [essential_ count] != 0) {
9083 int count = [essential_ count];
9085 UIAlertView *alert = [[[UIAlertView alloc]
9086 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
9087 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
9089 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
9091 UCLocalize("UPGRADE_ESSENTIAL"),
9092 UCLocalize("COMPLETE_UPGRADE"),
9096 [alert setContext:@"upgrade"];
9101 - (void) returnToCydia {
9105 - (void) reloadSpringBoard {
9106 if (kCFCoreFoundationVersionNumber >= 700) // XXX: iOS 6.x
9107 system("/usr/libexec/cydia/cydo /bin/launchctl stop com.apple.backboardd");
9109 system("/usr/libexec/cydia/cydo /bin/launchctl stop com.apple.SpringBoard");
9111 system("/usr/bin/killall backboardd SpringBoard");
9114 - (void) _saveConfig {
9115 SaveConfig(database_);
9118 // Navigation controller for the queuing badge.
9119 - (UINavigationController *) queueNavigationController {
9120 NSArray *controllers = [tabbar_ viewControllers];
9121 return [controllers objectAtIndex:3];
9124 - (void) unloadData {
9125 [tabbar_ unloadData];
9128 - (void) _updateData {
9132 UINavigationController *navigation = [self queueNavigationController];
9134 id queuedelegate = nil;
9135 if ([[navigation viewControllers] count] > 0)
9136 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9138 [queuedelegate queueStatusDidChange];
9139 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9142 - (void) _refreshIfPossible {
9143 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9145 NSDate *update([[NSDictionary dictionaryWithContentsOfFile:@ CacheState_] objectForKey:@"LastUpdate"]);
9147 bool recently = false;
9148 if (update != nil) {
9149 NSTimeInterval interval([update timeIntervalSinceNow]);
9150 if (interval > -(15*60))
9154 // Don't automatic refresh if:
9155 // - We already refreshed recently.
9156 // - We already auto-refreshed this launch.
9157 // - Auto-refresh is disabled.
9158 // - Cydia's server is not reachable
9159 if (recently || loaded_ || ManualRefresh || !IsReachable("cydia.saurik.com")) {
9160 // If we are cancelling, we need to make sure it knows it's already loaded.
9163 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9165 // We are going to load, so remember that.
9168 [tabbar_ performSelectorOnMainThread:@selector(beginUpdate) withObject:nil waitUntilDone:NO];
9174 - (void) refreshIfPossible {
9175 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
9178 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9179 _profile(reloadDataWithInvocation)
9180 @synchronized (self) {
9181 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9183 [hud setText:UCLocalize("RELOADING_DATA")];
9185 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9189 [essential_ removeAllObjects];
9190 [broken_ removeAllObjects];
9192 _profile(reloadDataWithInvocation$Essential)
9193 NSArray *packages([database_ packages]);
9194 for (Package *package in packages) {
9196 [broken_ addObject:package];
9197 if ([package upgradableAndEssential:YES] && ![package ignored]) {
9198 if ([package essential] && [package installed] != nil)
9199 [essential_ addObject:package];
9205 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9208 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9209 [changesItem setBadgeValue:badge];
9210 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9211 [self setApplicationIconBadgeNumber:changes];
9214 [changesItem setBadgeValue:nil];
9215 [changesItem setAnimatedBadge:NO];
9216 [self setApplicationIconBadgeNumber:0];
9223 [self removeProgressHUD:hud];
9230 - (void) updateData {
9234 - (void) updateDataAndLoad {
9236 if ([database_ progressDelegate] == nil)
9242 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9245 - (void) disemulate {
9246 if (emulated_ == nil)
9249 if ([window_ respondsToSelector:@selector(setRootViewController:)])
9250 [window_ setRootViewController:tabbar_];
9252 [window_ addSubview:[tabbar_ view]];
9253 [[emulated_ view] removeFromSuperview];
9257 [window_ setUserInteractionEnabled:YES];
9260 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9261 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9263 UIViewController *parent;
9264 if (emulated_ == nil)
9274 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9275 [parent presentModalViewController:navigation animated:YES];
9278 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9279 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9281 if (navigation != nil)
9282 [navigation pushViewController:progress animated:YES];
9284 [self presentModalViewController:progress force:YES];
9286 [progress invoke:invocation withTitle:title];
9290 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9291 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9294 - (void) repairWithInvocation:(NSInvocation *)invocation {
9296 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9300 - (void) repairWithSelector:(SEL)selector {
9301 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9304 - (void) reloadData {
9305 [self reloadDataWithInvocation:nil];
9306 if ([database_ progressDelegate] == nil)
9312 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9315 - (void) addSource:(NSDictionary *) source {
9316 CydiaAddSource(source);
9319 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9320 CydiaAddSource(href, distribution, sections);
9323 // XXX: this method should not return anything
9324 - (BOOL) addTrivialSource:(NSString *)href {
9325 CydiaAddSource(href, @"./");
9330 pkgProblemResolver *resolver = [database_ resolver];
9332 resolver->InstallProtect();
9333 if (!resolver->Resolve(true))
9338 // XXX: this is a really crappy way of doing this.
9339 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9340 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9341 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9342 if ([tabbar_ updating])
9343 [tabbar_ cancelUpdate];
9345 if (![database_ prepare])
9348 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9349 [page setDelegate:self];
9350 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9353 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9354 [tabbar_ presentModalViewController:confirm_ animated:YES];
9360 @synchronized (self) {
9365 - (void) clearPackage:(Package *)package {
9366 @synchronized (self) {
9373 - (void) installPackages:(NSArray *)packages {
9374 @synchronized (self) {
9375 for (Package *package in packages)
9382 - (void) installPackage:(Package *)package {
9383 @synchronized (self) {
9390 - (void) removePackage:(Package *)package {
9391 @synchronized (self) {
9398 - (void) distUpgrade {
9399 @synchronized (self) {
9400 if (![database_ upgrade])
9408 system("/usr/bin/uicache");
9413 UIProgressHUD *hud([self addProgressHUD]);
9414 [hud setText:UCLocalize("LOADING")];
9415 [self yieldToSelector:@selector(_uicache)];
9416 [self removeProgressHUD:hud];
9420 [database_ perform];
9421 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9422 [self performSelectorOnMainThread:@selector(uicache) withObject:nil waitUntilDone:YES];
9425 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9428 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9429 [self unlockSuspend];
9432 - (void) retainNetworkActivityIndicator {
9433 if (activity_++ == 0)
9434 [self setNetworkActivityIndicatorVisible:YES];
9437 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9441 - (void) releaseNetworkActivityIndicator {
9442 if (--activity_ == 0)
9443 [self setNetworkActivityIndicatorVisible:NO];
9446 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9451 - (void) cancelAndClear:(bool)clear {
9452 @synchronized (self) {
9464 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9465 NSString *context([alert context]);
9467 if ([context isEqualToString:@"conffile"]) {
9468 FILE *input = [database_ input];
9469 if (button == [alert cancelButtonIndex])
9470 fprintf(input, "N\n");
9471 else if (button == [alert firstOtherButtonIndex])
9472 fprintf(input, "Y\n");
9475 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9476 } else if ([context isEqualToString:@"fixhalf"]) {
9477 if (button == [alert cancelButtonIndex]) {
9478 @synchronized (self) {
9479 for (Package *broken in (id) broken_) {
9481 NSString *id(ShellEscape([broken id]));
9482 system([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /bin/rm -f"
9483 " /var/lib/dpkg/info/%@.prerm"
9484 " /var/lib/dpkg/info/%@.postrm"
9485 " /var/lib/dpkg/info/%@.preinst"
9486 " /var/lib/dpkg/info/%@.postinst"
9487 " /var/lib/dpkg/info/%@.extrainst_"
9488 "", id, id, id, id, id] UTF8String]);
9494 } else if (button == [alert firstOtherButtonIndex]) {
9495 [broken_ removeAllObjects];
9499 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9500 } else if ([context isEqualToString:@"upgrade"]) {
9501 if (button == [alert firstOtherButtonIndex]) {
9502 @synchronized (self) {
9503 for (Package *essential in (id) essential_)
9504 [essential install];
9509 } else if (button == [alert firstOtherButtonIndex] + 1) {
9511 } else if (button == [alert cancelButtonIndex]) {
9515 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9519 - (void) system:(NSString *)command {
9520 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9523 system([command UTF8String]);
9529 - (void) applicationWillSuspend {
9531 [super applicationWillSuspend];
9534 - (BOOL) isSafeToSuspend {
9537 NSLog(@"isSafeToSuspend: locked_ != 0");
9542 if ([tabbar_ modalViewController] != nil)
9545 // Use external process status API internally.
9546 // This is probably a really bad idea.
9547 // XXX: what is the point of this? does this solve anything at all?
9548 uint64_t status = 0;
9550 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9551 notify_get_state(notify_token, &status);
9552 notify_cancel(notify_token);
9557 NSLog(@"isSafeToSuspend: status != 0");
9563 NSLog(@"isSafeToSuspend: -> true");
9568 - (void) suspendReturningToLastApp:(BOOL)returning {
9569 if ([self isSafeToSuspend])
9570 [super suspendReturningToLastApp:returning];
9574 if ([self isSafeToSuspend])
9578 - (void) applicationSuspend {
9579 if ([self isSafeToSuspend])
9580 [super applicationSuspend];
9583 - (void) applicationSuspend:(GSEventRef)event {
9584 if ([self isSafeToSuspend])
9585 [super applicationSuspend:event];
9588 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9589 if ([self isSafeToSuspend])
9590 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9593 - (void) _setSuspended:(BOOL)value {
9594 if ([self isSafeToSuspend])
9595 [super _setSuspended:value];
9598 - (UIProgressHUD *) addProgressHUD {
9599 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9600 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9602 [window_ setUserInteractionEnabled:NO];
9604 UIViewController *target(tabbar_);
9605 if (UIViewController *modal = [target modalViewController])
9608 [hud showInView:[target view]];
9614 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9615 [self unlockSuspend];
9617 [hud removeFromSuperview];
9618 [window_ setUserInteractionEnabled:YES];
9621 - (CyteViewController *) pageForPackage:(NSString *)name withReferrer:(NSString *)referrer {
9622 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name withReferrer:referrer] autorelease];
9625 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external withReferrer:(NSString *)referrer {
9626 NSString *scheme([[url scheme] lowercaseString]);
9627 if ([[url absoluteString] length] <= [scheme length] + 3)
9629 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9630 NSArray *components([path componentsSeparatedByString:@"/"]);
9632 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"]) {
9633 CyteViewController *controller([self pageForPackage:[components objectAtIndex:1] withReferrer:referrer]);
9634 if (controller != nil)
9635 [controller setDelegate:self];
9639 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9642 NSString *base([components objectAtIndex:0]);
9644 CyteViewController *controller = nil;
9646 if ([base isEqualToString:@"url"]) {
9647 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9648 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9649 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9650 } else if (!external && [components count] == 1) {
9651 if ([base isEqualToString:@"sources"]) {
9652 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9655 if ([base isEqualToString:@"home"]) {
9656 controller = [[[HomeController alloc] init] autorelease];
9659 if ([base isEqualToString:@"sections"]) {
9660 controller = [[[SectionsController alloc] initWithDatabase:database_ source:nil] autorelease];
9663 if ([base isEqualToString:@"search"]) {
9664 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9667 if ([base isEqualToString:@"changes"]) {
9668 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9671 if ([base isEqualToString:@"installed"]) {
9672 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9674 } else if ([components count] == 2) {
9675 NSString *argument = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9677 if ([base isEqualToString:@"package"]) {
9678 controller = [self pageForPackage:argument withReferrer:referrer];
9681 if (!external && [base isEqualToString:@"search"]) {
9682 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9685 if (!external && [base isEqualToString:@"sections"]) {
9686 if ([argument isEqualToString:@"all"] || [argument isEqualToString:@"*"])
9688 controller = [[[SectionController alloc] initWithDatabase:database_ source:nil section:argument] autorelease];
9691 if ([base isEqualToString:@"sources"]) {
9692 if ([argument isEqualToString:@"add"]) {
9693 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9694 [(SourcesController *)controller showAddSourcePrompt];
9696 Source *source([database_ sourceWithKey:argument]);
9697 controller = [[[SectionsController alloc] initWithDatabase:database_ source:source] autorelease];
9701 if (!external && [base isEqualToString:@"launch"]) {
9702 [self launchApplicationWithIdentifier:argument suspended:NO];
9705 } else if (!external && [components count] == 3) {
9706 NSString *arg1 = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9707 NSString *arg2 = [[components objectAtIndex:2] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9709 if ([base isEqualToString:@"package"]) {
9710 if ([arg2 isEqualToString:@"settings"]) {
9711 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9712 } else if ([arg2 isEqualToString:@"files"]) {
9713 if (Package *package = [database_ packageWithName:arg1]) {
9714 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9715 [(FileTable *)controller setPackage:package];
9720 if ([base isEqualToString:@"sections"]) {
9721 Source *source([arg1 isEqualToString:@"*"] ? nil : [database_ sourceWithKey:arg1]);
9722 NSString *section([arg2 isEqualToString:@"*"] ? nil : arg2);
9723 controller = [[[SectionController alloc] initWithDatabase:database_ source:source section:section] autorelease];
9727 [controller setDelegate:self];
9731 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9732 CyteViewController *page([self pageForURL:url forExternal:external withReferrer:nil]);
9735 [tabbar_ setUnselectedViewController:page];
9740 - (void) applicationOpenURL:(NSURL *)url {
9741 [super applicationOpenURL:url];
9746 [self openCydiaURL:url forExternal:YES];
9749 - (void) applicationWillResignActive:(UIApplication *)application {
9750 // Stop refreshing if you get a phone call or lock the device.
9751 if ([tabbar_ updating])
9752 [tabbar_ cancelUpdate];
9754 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9755 [super applicationWillResignActive:application];
9758 - (void) saveState {
9759 [[NSDictionary dictionaryWithObjectsAndKeys:
9760 @"InterfaceState", [tabbar_ navigationURLCollection],
9761 @"LastClosed", [NSDate date],
9762 @"InterfaceIndex", [NSNumber numberWithInt:[tabbar_ selectedIndex]],
9763 nil] writeToFile:@ SavedState_ atomically:YES];
9768 - (void) applicationWillTerminate:(UIApplication *)application {
9772 - (void) applicationDidEnterBackground:(UIApplication *)application {
9773 if (kCFCoreFoundationVersionNumber < 1000 && [self isSafeToSuspend])
9774 return [self terminateWithSuccess];
9775 Backgrounded_ = [NSDate date];
9779 - (void) applicationWillEnterForeground:(UIApplication *)application {
9780 if (Backgrounded_ == nil)
9783 NSTimeInterval interval([Backgrounded_ timeIntervalSinceNow]);
9785 if (interval <= -(30*60)) {
9786 [tabbar_ setSelectedIndex:0];
9787 [[[tabbar_ viewControllers] objectAtIndex:0] popToRootViewControllerAnimated:NO];
9790 if (interval <= -(15*60)) {
9791 if (IsReachable("cydia.saurik.com")) {
9792 [tabbar_ beginUpdate];
9793 [appcache_ reloadURLWithCache:YES];
9797 if ([database_ delocked])
9801 - (void) setConfigurationData:(NSString *)data {
9802 static RegEx conffile_r("'(.*)' '(.*)' ([01]) ([01])");
9804 if (!conffile_r(data)) {
9805 lprintf("E:invalid conffile\n");
9809 NSString *ofile = conffile_r[1];
9810 //NSString *nfile = conffile_r[2];
9812 UIAlertView *alert = [[[UIAlertView alloc]
9813 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9814 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9816 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9818 UCLocalize("ACCEPT_NEW_COPY"),
9819 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9823 [alert setContext:@"conffile"];
9824 [alert setNumberOfRows:2];
9828 - (void) addStashController {
9830 stash_ = [[[StashController alloc] init] autorelease];
9831 [window_ addSubview:[stash_ view]];
9834 - (void) removeStashController {
9835 [[stash_ view] removeFromSuperview];
9837 [self unlockSuspend];
9841 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9842 UpdateExternalStatus(1);
9843 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/cydo /usr/libexec/cydia/free.sh"];
9844 UpdateExternalStatus(0);
9846 [self removeStashController];
9847 [self reloadSpringBoard];
9850 - (void) setupViewControllers {
9851 tabbar_ = [[[CydiaTabBarController alloc] initWithDatabase:database_] autorelease];
9853 NSMutableArray *items;
9854 if (kCFCoreFoundationVersionNumber < 800) {
9855 items = [NSMutableArray arrayWithObjects:
9856 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage imageNamed:@"home.png"] tag:0] autorelease],
9857 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage imageNamed:@"install.png"] tag:0] autorelease],
9858 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage imageNamed:@"changes.png"] tag:0] autorelease],
9859 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage imageNamed:@"manage.png"] tag:0] autorelease],
9860 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage imageNamed:@"search.png"] tag:0] autorelease],
9863 items = [NSMutableArray arrayWithObjects:
9864 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage imageNamed:@"home7.png"] selectedImage:[UIImage imageNamed:@"home7s.png"]] autorelease],
9865 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage imageNamed:@"install7.png"] selectedImage:[UIImage imageNamed:@"install7s.png"]] autorelease],
9866 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage imageNamed:@"changes7.png"] selectedImage:[UIImage imageNamed:@"changes7s.png"]] autorelease],
9867 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage imageNamed:@"manage7.png"] selectedImage:[UIImage imageNamed:@"manage7s.png"]] autorelease],
9868 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage imageNamed:@"search7.png"] selectedImage:[UIImage imageNamed:@"search7s.png"]] autorelease],
9872 NSMutableArray *controllers([NSMutableArray array]);
9873 for (UITabBarItem *item in items) {
9874 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9875 [controller setTabBarItem:item];
9876 [controllers addObject:controller];
9878 [tabbar_ setViewControllers:controllers];
9880 [tabbar_ setUpdateDelegate:self];
9883 - (void) applicationDidFinishLaunching:(id)unused {
9884 [super applicationDidFinishLaunching:unused];
9887 @synchronized (HostConfig_) {
9888 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9891 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9892 initWithMemoryCapacity:524288
9893 diskCapacity:10485760
9894 diskPath:Cache("SDURLCache")
9897 [CydiaWebViewController _initialize];
9899 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9901 // this would disallow http{,s} URLs from accessing this data
9902 //[WebView registerURLSchemeAsLocal:@"cydia"];
9904 Font12_ = [UIFont systemFontOfSize:12];
9905 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9906 Font14_ = [UIFont systemFontOfSize:14];
9907 Font18_ = [UIFont systemFontOfSize:18];
9908 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9909 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9911 essential_ = [NSMutableArray arrayWithCapacity:4];
9912 broken_ = [NSMutableArray arrayWithCapacity:4];
9914 // XXX: I really need this thing... like, seriously... I'm sorry
9915 appcache_ = [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] autorelease];
9916 [appcache_ reloadData];
9918 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9919 [window_ orderFront:self];
9920 [window_ makeKey:self];
9921 [window_ setHidden:NO];
9923 if (access("/.cydia_no_stash", F_OK) == 0);
9927 [self addStashController];
9928 // XXX: this would be much cleaner as a yieldToSelector:
9929 // that way the removeStashController could happen right here inline
9930 // we also could no longer require the useless stash_ field anymore
9931 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9936 int error(stat("/", &root));
9937 _assert(error != -1);
9939 #define Stash_(path) do { \
9940 struct stat folder; \
9941 int error(lstat((path), &folder)); \
9942 if (error != -1 && ( \
9943 folder.st_dev == root.st_dev && \
9944 S_ISDIR(folder.st_mode) \
9945 ) || error == -1 && ( \
9946 errno == ENOENT || \
9951 Stash_("/Applications");
9952 Stash_("/Library/Ringtones");
9953 Stash_("/Library/Wallpaper");
9954 //Stash_("/usr/bin");
9955 Stash_("/usr/include");
9956 Stash_("/usr/share");
9957 //Stash_("/var/lib");
9961 database_ = [Database sharedInstance];
9962 [database_ setDelegate:self];
9964 [window_ setUserInteractionEnabled:NO];
9965 [self setupViewControllers];
9967 CydiaLoadingViewController *loading([[[CydiaLoadingViewController alloc] init] autorelease]);
9968 UINavigationController *navigation([[[UINavigationController alloc] init] autorelease]);
9969 [navigation setViewControllers:[NSArray arrayWithObject:loading]];
9971 emulated_ = [[[CyteTabBarController alloc] init] autorelease];
9972 [emulated_ setViewControllers:[NSArray arrayWithObject:navigation]];
9973 [emulated_ setSelectedIndex:0];
9975 if ([emulated_ respondsToSelector:@selector(concealTabBarSelection)])
9976 [emulated_ concealTabBarSelection];
9978 if ([window_ respondsToSelector:@selector(setRootViewController:)])
9979 [window_ setRootViewController:emulated_];
9981 [window_ addSubview:[emulated_ view]];
9983 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9987 - (NSArray *) defaultStartPages {
9988 NSMutableArray *standard = [NSMutableArray array];
9989 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9990 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9991 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9992 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9993 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9999 if ([emulated_ modalViewController] != nil)
10000 [emulated_ dismissModalViewControllerAnimated:YES];
10001 [window_ setUserInteractionEnabled:NO];
10003 [self reloadDataWithInvocation:nil];
10004 [self refreshIfPossible];
10007 NSDictionary *state([NSDictionary dictionaryWithContentsOfFile:@ SavedState_]);
10009 int savedIndex = [[state objectForKey:@"InterfaceIndex"] intValue];
10010 NSArray *saved = [[[state objectForKey:@"InterfaceState"] mutableCopy] autorelease];
10011 int standardIndex = 0;
10012 NSArray *standard = [self defaultStartPages];
10019 NSDate *closed = [state objectForKey:@"LastClosed"];
10020 if (valid && closed != nil) {
10021 NSTimeInterval interval([closed timeIntervalSinceNow]);
10022 if (interval <= -(30*60))
10026 if (valid && [saved count] != [standard count])
10030 for (unsigned int i = 0; i < [standard count]; i++) {
10031 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
10032 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
10033 // but it's good enough for now.
10034 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
10041 NSArray *items = nil;
10043 [tabbar_ setSelectedIndex:savedIndex];
10046 [tabbar_ setSelectedIndex:standardIndex];
10050 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
10051 NSArray *stack = [items objectAtIndex:tab];
10052 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
10053 NSMutableArray *current = [NSMutableArray array];
10055 for (unsigned int nav = 0; nav < [stack count]; nav++) {
10056 NSString *addr = [stack objectAtIndex:nav];
10057 NSURL *url = [NSURL URLWithString:addr];
10058 CyteViewController *page = [self pageForURL:url forExternal:NO withReferrer:nil];
10060 [current addObject:page];
10063 [navigation setViewControllers:current];
10066 // (Try to) show the startup URL.
10067 if (starturl_ != nil) {
10068 [self openCydiaURL:starturl_ forExternal:YES];
10073 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
10075 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
10076 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
10079 if (item != nil && IsWildcat_) {
10080 [sheet showFromBarButtonItem:item animated:YES];
10082 [sheet showInView:window_];
10086 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
10087 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
10088 [progress setTitle:task];
10089 [progress addProgressEvent:event];
10092 - (void) addProgressEventForTask:(NSArray *)data {
10093 CydiaProgressEvent *event([data objectAtIndex:0]);
10094 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
10095 [self addProgressEvent:event forTask:task];
10098 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
10099 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
10105 id Alloc_(id self, SEL selector) {
10106 id object = alloc_(self, selector);
10107 lprintf("[%s]A-%p\n", self->isa->name, object);
10112 id Dealloc_(id self, SEL selector) {
10113 id object = dealloc_(self, selector);
10114 lprintf("[%s]D-%p\n", self->isa->name, object);
10118 Class $NSURLConnection;
10120 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
10121 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
10123 NSURL *url([copy URL]);
10125 NSString *host([url host]);
10126 NSString *scheme([[url scheme] lowercaseString]);
10128 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
10130 @synchronized (HostConfig_) {
10131 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
10132 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
10133 [copy setHTTPShouldUsePipelining:YES];
10135 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
10136 if ([control isEqualToString:@"max-age=0"])
10137 if ([CachedURLs_ containsObject:url]) {
10139 NSLog(@"~~~: %@", url);
10142 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
10144 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
10145 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
10146 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
10150 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
10156 static CGSize $WAKWindow$screenSize(WAKWindow *self, SEL _cmd) {
10157 CGSize size([[UIScreen mainScreen] bounds].size);
10158 /*if ([$WAKWindow respondsToSelector:@selector(hasLandscapeOrientation)])
10159 if ([$WAKWindow hasLandscapeOrientation])
10160 std::swap(size.width, size.height);*/
10164 Class $NSUserDefaults;
10166 MSHook(id, NSUserDefaults$objectForKey$, NSUserDefaults *self, SEL _cmd, NSString *key) {
10167 if ([key respondsToSelector:@selector(isEqualToString:)] && [key isEqualToString:@"WebKitLocalStorageDatabasePathPreferenceKey"])
10168 return Cache("LocalStorage");
10169 return _NSUserDefaults$objectForKey$(self, _cmd, key);
10172 static NSMutableDictionary *AutoreleaseDeepMutableCopyOfDictionary(CFTypeRef type) {
10175 if (CFGetTypeID(type) != CFDictionaryGetTypeID())
10177 CFTypeRef copy(CFPropertyListCreateDeepCopy(kCFAllocatorDefault, type, kCFPropertyListMutableContainers));
10179 return [(NSMutableDictionary *) copy autorelease];
10182 int main_store(int, char *argv[]);
10184 int main(int argc, char *argv[]) {
10186 const char *argv0(argv[0]);
10187 if (const char *slash = strrchr(argv0, '/'))
10190 else if (!strcmp(argv0, "store"))
10191 return main_store(argc, argv);
10194 int fd(open("/tmp/cydia.log", O_WRONLY | O_APPEND | O_CREAT, 0644));
10198 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10202 UpdateExternalStatus(0);
10204 UIScreen *screen([UIScreen mainScreen]);
10205 if ([screen respondsToSelector:@selector(scale)])
10206 ScreenScale_ = [screen scale];
10210 UIDevice *device([UIDevice currentDevice]);
10211 if ([device respondsToSelector:@selector(userInterfaceIdiom)]) {
10212 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10213 if (idiom == UIUserInterfaceIdiomPad)
10217 Idiom_ = IsWildcat_ ? @"ipad" : @"iphone";
10219 RegEx pattern("([0-9]+\\.[0-9]+).*");
10221 if (pattern([device systemVersion]))
10222 Firmware_ = pattern[1];
10223 if (pattern(Cydia_))
10224 Major_ = pattern[1];
10226 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
10228 HostConfig_ = [[[NSObject alloc] init] autorelease];
10229 @synchronized (HostConfig_) {
10230 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10231 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
10232 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
10233 CachedURLs_ = [NSMutableSet setWithCapacity:32];
10236 NSString *ui(@"ui/ios");
10238 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
10239 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"/%@", Major_]];
10240 UI_ = CydiaURL(ui);
10242 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10244 /* Library Hacks {{{ */
10245 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10247 $WAKWindow = objc_getClass("WAKWindow");
10248 if ($WAKWindow != NULL)
10249 if (Method method = class_getInstanceMethod($WAKWindow, @selector(screenSize)))
10250 method_setImplementation(method, (IMP) &$WAKWindow$screenSize);
10252 $NSURLConnection = objc_getClass("NSURLConnection");
10253 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10254 if (NSURLConnection$init$ != NULL) {
10255 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10256 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10259 $NSUserDefaults = objc_getClass("NSUserDefaults");
10260 Method NSUserDefaults$objectForKey$(class_getInstanceMethod($NSUserDefaults, @selector(objectForKey:)));
10261 if (NSUserDefaults$objectForKey$ != NULL) {
10262 _NSUserDefaults$objectForKey$ = reinterpret_cast<id (*)(NSUserDefaults *, SEL, NSString *)>(method_getImplementation(NSUserDefaults$objectForKey$));
10263 method_setImplementation(NSUserDefaults$objectForKey$, reinterpret_cast<IMP>(&$NSUserDefaults$objectForKey$));
10266 /* Set Locale {{{ */
10267 Locale_ = CFLocaleCopyCurrent();
10268 Languages_ = [NSLocale preferredLanguages];
10270 std::string languages;
10271 const char *translation(NULL);
10273 // XXX: this isn't really a language, but this is compatible with older Cydia builds
10274 if (Locale_ != NULL)
10275 if (const char *language = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String]) {
10276 RegEx pattern("([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?");
10277 if (pattern(language)) {
10278 translation = strdup([pattern->*@"%1$@%2$@" UTF8String]);
10279 languages += translation;
10284 if (Languages_ != nil)
10285 for (NSString *language : Languages_) {
10286 languages += [language UTF8String];
10291 NSLog(@"Setting Language: [%s] %s", translation, languages.c_str());
10293 /* Index Collation {{{ */
10294 if (Class $UILocalizedIndexedCollation = objc_getClass("UILocalizedIndexedCollation")) { @try {
10295 NSBundle *bundle([NSBundle bundleForClass:$UILocalizedIndexedCollation]);
10296 NSString *path([bundle pathForResource:@"UITableViewLocalizedSectionIndex" ofType:@"plist"]);
10297 //path = @"/System/Library/Frameworks/UIKit.framework/.lproj/UITableViewLocalizedSectionIndex.plist";
10298 NSDictionary *dictionary([NSDictionary dictionaryWithContentsOfFile:path]);
10299 _H<UILocalizedIndexedCollation> collation([[[$UILocalizedIndexedCollation alloc] initWithDictionary:dictionary] autorelease]);
10301 CollationLocale_ = MSHookIvar<NSLocale *>(collation, "_locale");
10303 if (kCFCoreFoundationVersionNumber >= 800 && [[CollationLocale_ localeIdentifier] isEqualToString:@"zh@collation=stroke"]) {
10304 CollationThumbs_ = [NSArray arrayWithObjects:@"1",@"•",@"4",@"•",@"7",@"•",@"10",@"•",@"13",@"•",@"16",@"•",@"19",@"A",@"•",@"E",@"•",@"I",@"•",@"M",@"•",@"R",@"•",@"V",@"•",@"Z",@"#",nil];
10305 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})
10306 CollationOffset_.push_back(offset);
10307 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];
10308 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];
10311 CollationThumbs_ = [collation sectionIndexTitles];
10312 for (size_t index(0), end([CollationThumbs_ count]); index != end; ++index)
10313 CollationOffset_.push_back([collation sectionForSectionIndexTitleAtIndex:index]);
10315 CollationTitles_ = [collation sectionTitles];
10316 CollationStarts_ = MSHookIvar<NSArray *>(collation, "_sectionStartStrings");
10318 NSString *&transform(MSHookIvar<NSString *>(collation, "_transform"));
10319 if (&transform != NULL && transform != nil) {
10320 /*if ([collation respondsToSelector:@selector(transformedCollationStringForString:)])
10321 CollationModify_ = [=](NSString *value) { return [collation transformedCollationStringForString:value]; };*/
10322 const UChar *uid(reinterpret_cast<const UChar *>([transform cStringUsingEncoding:NSUnicodeStringEncoding]));
10323 UErrorCode code(U_ZERO_ERROR);
10324 CollationTransl_ = utrans_openU(uid, -1, UTRANS_FORWARD, NULL, 0, NULL, &code);
10325 if (!U_SUCCESS(code))
10326 NSLog(@"%s", u_errorName(code));
10330 } @catch (NSException *e) {
10334 CollationLocale_ = [[[NSLocale alloc] initWithLocaleIdentifier:@"en@collation=dictionary"] autorelease];
10336 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];
10337 for (NSInteger offset(0); offset != 28; ++offset)
10338 CollationOffset_.push_back(offset);
10340 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];
10341 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];
10344 /* Parse Arguments {{{ */
10345 bool substrate(false);
10351 for (int argi(1); argi != argc; ++argi)
10352 if (strcmp(argv[argi], "--") == 0) {
10354 argv[argi] = argv[0];
10360 for (int argi(1); argi != arge; ++argi)
10361 if (strcmp(args[argi], "--substrate") == 0)
10364 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10368 App_ = [[NSBundle mainBundle] bundlePath];
10371 Cache_ = [[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia", @"/var/mobile"] retain];
10372 mkdir([Cache_ UTF8String], 0755);
10374 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10375 alloc_ = alloc->method_imp;
10376 alloc->method_imp = (IMP) &Alloc_;*/
10378 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10379 dealloc_ = dealloc->method_imp;
10380 dealloc->method_imp = (IMP) &Dealloc_;*/
10382 void *gestalt(dlopen("/usr/lib/libMobileGestalt.dylib", RTLD_GLOBAL | RTLD_LAZY));
10383 $MGCopyAnswer = reinterpret_cast<CFStringRef (*)(CFStringRef)>(dlsym(gestalt, "MGCopyAnswer"));
10385 /* System Information {{{ */
10389 size = sizeof(maxproc);
10390 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10391 perror("sysctlbyname(\"kern.maxproc\", ?)");
10392 else if (maxproc < 64) {
10394 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10395 perror("sysctlbyname(\"kern.maxproc\", #)");
10398 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10399 char *osversion = new char[size];
10400 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10401 perror("sysctlbyname(\"kern.osversion\", ?)");
10403 System_ = [NSString stringWithUTF8String:osversion];
10405 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10406 char *machine = new char[size];
10407 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10408 perror("sysctlbyname(\"hw.machine\", ?)");
10410 Machine_ = machine;
10412 int64_t usermem(0);
10413 size = sizeof(usermem);
10414 if (sysctlbyname("hw.usermem", &usermem, &size, NULL, 0) == -1)
10417 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10418 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10419 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10421 UniqueID_ = UniqueIdentifier(device);
10423 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10424 Product_ = [info objectForKey:@"SafariProductVersion"];
10425 Safari_ = [info objectForKey:@"CFBundleVersion"];
10428 NSString *agent([NSString stringWithFormat:@"Cydia/%@ CyF/%.2f", Cydia_, kCFCoreFoundationVersionNumber]);
10430 if (RegEx match = RegEx("([0-9]+(\\.[0-9]+)+).*", Safari_))
10431 agent = [NSString stringWithFormat:@"Safari/%@ %@", match[1], agent];
10432 if (RegEx match = RegEx("([0-9]+[A-Z][0-9]+[a-z]?).*", System_))
10433 agent = [NSString stringWithFormat:@"Mobile/%@ %@", match[1], agent];
10434 if (RegEx match = RegEx("([0-9]+(\\.[0-9]+)+).*", Product_))
10435 agent = [NSString stringWithFormat:@"Version/%@ %@", match[1], agent];
10437 UserAgent_ = agent;
10439 /* Load Database {{{ */
10440 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10443 mkdir("/var/mobile/Library/Cydia", 0755);
10444 MetaFile_.Open("/var/mobile/Library/Cydia/metadata.cb0");
10447 Values_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaValues"), CFSTR("com.saurik.Cydia")));
10448 Sections_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaSections"), CFSTR("com.saurik.Cydia")));
10449 Sources_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaSources"), CFSTR("com.saurik.Cydia")));
10450 Version_ = [(NSNumber *) CFPreferencesCopyAppValue(CFSTR("CydiaVersion"), CFSTR("com.saurik.Cydia")) autorelease];
10453 NSDictionary *metadata([[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease]);
10455 if (Values_ == nil)
10456 Values_ = [metadata objectForKey:@"Values"];
10457 if (Values_ == nil)
10458 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10460 if (Sections_ == nil)
10461 Sections_ = [metadata objectForKey:@"Sections"];
10462 if (Sections_ == nil)
10463 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10465 if (Sources_ == nil)
10466 Sources_ = [metadata objectForKey:@"Sources"];
10467 if (Sources_ == nil)
10468 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10470 // XXX: this wrong, but in a way that doesn't matter :/
10471 if (Version_ == nil)
10472 Version_ = [metadata objectForKey:@"Version"];
10473 if (Version_ == nil)
10474 Version_ = [NSNumber numberWithUnsignedInt:0];
10476 if (NSDictionary *packages = [metadata objectForKey:@"Packages"]) {
10478 CFDictionaryApplyFunction((CFDictionaryRef) packages, &PackageImport, &fail);
10481 NSLog(@"unable to import package preferences... from 2010? oh well :/");
10484 if ([Version_ unsignedIntValue] == 0) {
10485 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10486 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10487 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10488 CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./");
10490 Version_ = [NSNumber numberWithUnsignedInt:1];
10492 if (NSMutableDictionary *cache = [NSMutableDictionary dictionaryWithContentsOfFile:@ CacheState_]) {
10493 [cache removeObjectForKey:@"LastUpdate"];
10494 [cache writeToFile:@ CacheState_ atomically:YES];
10498 _H<NSMutableArray> broken([NSMutableArray array]);
10499 for (NSString *key in (id) Sources_)
10500 if ([key rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"# "]].location != NSNotFound || ![([[Sources_ objectForKey:key] objectForKey:@"URI"] ?: @"/") hasSuffix:@"/"])
10501 [broken addObject:key];
10502 if ([broken count] != 0)
10503 for (NSString *key in (id) broken)
10504 [Sources_ removeObjectForKey:key];
10508 system("/usr/libexec/cydia/cydo /bin/rm -f /var/lib/cydia/metadata.plist");
10511 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10513 if (kCFCoreFoundationVersionNumber > 1000)
10514 system("/usr/libexec/cydia/cydo /usr/libexec/cydia/setnsfpn /var/lib");
10516 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10518 if (access("/User", F_OK) != 0 || version != 6) {
10520 system("/usr/libexec/cydia/cydo /usr/libexec/cydia/firmware.sh");
10524 if (access("/tmp/cydia.chk", F_OK) == 0) {
10525 if (unlink([Cache("pkgcache.bin") UTF8String]) == -1)
10526 _assert(errno == ENOENT);
10527 if (unlink([Cache("srcpkgcache.bin") UTF8String]) == -1)
10528 _assert(errno == ENOENT);
10531 system("/usr/libexec/cydia/cydo /bin/ln -sf /var/mobile/Library/Caches/com.saurik.Cydia/sources.list /etc/apt/sources.list.d/cydia.list");
10533 /* APT Initialization {{{ */
10534 _assert(pkgInitConfig(*_config));
10535 _assert(pkgInitSystem(*_config, _system));
10537 _config->Set("Acquire::AllowInsecureRepositories", true);
10538 _config->Set("Acquire::Check-Valid-Until", false);
10539 _config->Set("Dir::Bin::Methods::store", "/Applications/Cydia.app/store");
10541 _config->Set("pkgCacheGen::ForceEssential", "");
10543 if (translation != NULL)
10544 _config->Set("APT::Acquire::Translation", translation);
10545 _config->Set("Acquire::Languages", languages);
10547 // XXX: this timeout might be important :(
10548 //_config->Set("Acquire::http::Timeout", 15);
10550 _config->Set("Acquire::http::MaxParallel", usermem >= 384 * 1024 * 1024 ? 16 : 3);
10552 mkdir([Cache("archives") UTF8String], 0755);
10553 mkdir([Cache("archives/partial") UTF8String], 0755);
10554 _config->Set("Dir::Cache", [Cache_ UTF8String]);
10556 symlink("/var/lib/apt/extended_states", [Cache("extended_states") UTF8String]);
10557 _config->Set("Dir::State", [Cache_ UTF8String]);
10559 mkdir([Cache("lists") UTF8String], 0755);
10560 mkdir([Cache("lists/partial") UTF8String], 0755);
10561 mkdir([Cache("periodic") UTF8String], 0755);
10562 _config->Set("Dir::State::Lists", [Cache("lists") UTF8String]);
10564 std::string logs("/var/mobile/Library/Logs/Cydia");
10565 mkdir(logs.c_str(), 0755);
10566 _config->Set("Dir::Log", logs);
10568 _config->Set("Dir::Bin::dpkg", "/usr/libexec/cydia/cydo");
10570 /* Color Choices {{{ */
10571 space_ = CGColorSpaceCreateDeviceRGB();
10573 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10574 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10575 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10576 Folder_.Set(space_, 0x8e/255.f, 0x8e/255.f, 0x93/255.f, 1.0);
10577 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10578 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10579 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10580 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10581 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10582 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10584 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10585 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10587 /* UIKit Configuration {{{ */
10588 // XXX: I have a feeling this was important
10589 //UIKeyboardDisableAutomaticAppearance();
10592 $SBSSetInterceptsMenuButtonForever = reinterpret_cast<void (*)(bool)>(dlsym(RTLD_DEFAULT, "SBSSetInterceptsMenuButtonForever"));
10593 $SBSCopyIconImagePNGDataForDisplayIdentifier = reinterpret_cast<NSData *(*)(NSString *)>(dlsym(RTLD_DEFAULT, "SBSCopyIconImagePNGDataForDisplayIdentifier"));
10595 const char *symbol(kCFCoreFoundationVersionNumber >= 800 ? "MGGetBoolAnswer" : "GSSystemHasCapability");
10596 BOOL (*GSSystemHasCapability)(CFStringRef) = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, symbol));
10597 bool fast = GSSystemHasCapability != NULL && GSSystemHasCapability(CFSTR("armv7"));
10599 PulseInterval_ = fast ? 50000 : 500000;
10601 Colon_ = UCLocalize("COLON_DELIMITED");
10602 Elision_ = UCLocalize("ELISION");
10603 Error_ = UCLocalize("ERROR");
10604 Warning_ = UCLocalize("WARNING");
10607 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10609 CGColorSpaceRelease(space_);
10610 CFRelease(Locale_);