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/URLCache.h"
121 #include "CyteKit/WebScriptObject-Cyte.h"
122 #include "CyteKit/WebViewController.h"
123 #include "CyteKit/WebViewTableViewCell.h"
124 #include "CyteKit/stringWithUTF8Bytes.h"
126 #include "Cydia/MIMEAddress.h"
127 #include "Cydia/LoadingViewController.h"
128 #include "Cydia/ProgressEvent.h"
135 #define _timestamp ({ \
137 gettimeofday(&tv, NULL); \
138 tv.tv_sec * 1000000 + tv.tv_usec; \
141 typedef std::vector<class ProfileTime *> TimeList;
151 ProfileTime(const char *name) :
155 times_.push_back(this);
158 void AddTime(uint64_t time) {
165 std::cerr << std::setw(7) << count_ << ", " << std::setw(8) << total_ << " : " << name_ << std::endl;
177 ProfileTimer(ProfileTime &time) :
184 time_.AddTime(_timestamp - start_);
189 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
191 std::cerr << "========" << std::endl;
194 #define _profile(name) { \
195 static ProfileTime name(#name); \
196 ProfileTimer _ ## name(name);
201 extern NSString *Cydia_;
203 #define lprintf(args...) fprintf(stderr, args)
206 #define TraceLogging (1 && !ForRelease)
207 #define HistogramInsertionSort (0 && !ForRelease)
208 #define ProfileTimes (0 && !ForRelease)
209 #define ForSaurik (0 && !ForRelease)
210 #define LogBrowser (0 && !ForRelease)
211 #define TrackResize (0 && !ForRelease)
212 #define ManualRefresh (1 && !ForRelease)
213 #define ShowInternals (0 && !ForRelease)
214 #define AlwaysReload (0 && !ForRelease)
218 #define _trace(args...)
223 #define _profile(name) {
226 #define PrintTimes() do {} while (false)
229 // Hash Functions/Structures {{{
230 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
238 @implementation NSDictionary (Cydia)
239 - (id) invokeUndefinedMethodFromWebScript:(NSString *)name withArguments:(NSArray *)arguments {
241 else if ([name isEqualToString:@"get"])
242 return [self objectForKey:[arguments objectAtIndex:0]];
243 else if ([name isEqualToString:@"keys"])
244 return [self allKeys];
248 static NSString *Colon_;
250 static NSString *Error_;
251 static NSString *Warning_;
253 static NSString *Cache_;
254 #define Cache(file) \
255 [NSString stringWithFormat:@"%@/%s", Cache_, file]
257 static void (*$SBSSetInterceptsMenuButtonForever)(bool);
258 static NSData *(*$SBSCopyIconImagePNGDataForDisplayIdentifier)(NSString *);
260 static CFStringRef (*$MGCopyAnswer)(CFStringRef);
262 static NSString *UniqueIdentifier(UIDevice *device = nil) {
263 if (kCFCoreFoundationVersionNumber < 800) // iOS 7.x
264 return [device ?: [UIDevice currentDevice] uniqueIdentifier];
266 return [(id)$MGCopyAnswer(CFSTR("UniqueDeviceID")) autorelease];
269 static bool IsReachable(const char *name) {
270 SCNetworkReachabilityFlags flags; {
271 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, name));
272 SCNetworkReachabilityGetFlags(reachability, &flags);
273 CFRelease(reachability);
276 // XXX: this elaborate mess is what Apple is using to determine this? :(
277 // XXX: do we care if the user has to intervene? maybe that's ok?
279 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
280 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
281 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
282 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
283 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
284 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
289 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
291 static _finline NSString *CydiaURL(NSString *path) {
293 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
294 page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
295 page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
296 page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
297 page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
299 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
302 static NSString *ShellEscape(NSString *value) {
303 return [NSString stringWithFormat:@"'%@'", [value stringByReplacingOccurrencesOfString:@"'" withString:@"'\\''"]];
306 static _finline void UpdateExternalStatus(uint64_t newStatus) {
308 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
309 notify_set_state(notify_token, newStatus);
310 notify_cancel(notify_token);
312 notify_post("com.saurik.Cydia.status");
315 static CGFloat CYStatusBarHeight() {
316 CGSize size([[UIApplication sharedApplication] statusBarFrame].size);
317 return UIInterfaceOrientationIsPortrait([[UIApplication sharedApplication] statusBarOrientation]) ? size.height : size.width;
320 /* NSForcedOrderingSearch doesn't work on the iPhone */
321 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
322 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
323 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
325 /* Insertion Sort {{{ */
327 template <typename Type_>
328 size_t CFBSearch_(const Type_ &element, const void *list, size_t count, CFComparisonResult (*comparator)(Type_, Type_, void *), void *context) {
329 const char *ptr = (const char *)list;
331 size_t half = count / 2;
332 const char *probe = ptr + sizeof(Type_) * half;
333 CFComparisonResult cr = comparator(element, * (const Type_ *) probe, context);
334 if (0 == cr) return (probe - (const char *)list) / sizeof(Type_);
335 ptr = (cr < 0) ? ptr : probe + sizeof(Type_);
336 count = (cr < 0) ? half : (half + (count & 1) - 1);
338 return (ptr - (const char *)list) / sizeof(Type_);
341 template <typename Type_>
342 void CYArrayInsertionSortValues(Type_ *values, size_t length, CFComparisonResult (*comparator)(Type_, Type_, void *), void *context) {
346 #if HistogramInsertionSort > 0
347 uint32_t total(0), *offsets(new uint32_t[length]);
350 for (size_t index(1); index != length; ++index) {
351 Type_ value(values[index]);
353 size_t correct(CFBSearch_(value, values, index, comparator, context));
355 size_t correct(index);
356 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
357 #if HistogramInsertionSort > 1
358 NSLog(@"%@ < %@", value, values[correct - 1]);
362 if (index - correct >= 8) {
363 correct = CFBSearch_(value, values, correct, comparator, context);
368 if (correct != index) {
369 size_t offset(index - correct);
370 #if HistogramInsertionSort
374 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
376 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
377 values[correct] = value;
381 #if HistogramInsertionSort > 0
382 for (size_t index(0); index != range.length; ++index)
383 if (offsets[index] != 0)
384 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
385 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
392 /* Apple Bug Fixes {{{ */
393 @implementation UIWebDocumentView (Cydia)
395 - (void) _setScrollerOffset:(CGPoint)offset {
396 UIScroller *scroller([self _scroller]);
398 CGSize size([scroller contentSize]);
399 CGSize bounds([scroller bounds].size);
402 max.x = size.width - bounds.width;
403 max.y = size.height - bounds.height;
411 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
412 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
414 [scroller setOffset:offset];
420 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
421 size_t length([self length] - state->state);
424 else if (length > count)
426 for (size_t i(0); i != length; ++i)
427 objects[i] = [self item:state->state++];
428 state->itemsPtr = objects;
429 state->mutationsPtr = (unsigned long *) self;
433 /* Cydia NSString Additions {{{ */
434 @interface NSString (Cydia)
435 - (NSComparisonResult) compareByPath:(NSString *)other;
436 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
439 @implementation NSString (Cydia)
441 - (NSComparisonResult) compareByPath:(NSString *)other {
442 NSString *prefix = [self commonPrefixWithString:other options:0];
443 size_t length = [prefix length];
445 NSRange lrange = NSMakeRange(length, [self length] - length);
446 NSRange rrange = NSMakeRange(length, [other length] - length);
448 lrange = [self rangeOfString:@"/" options:0 range:lrange];
449 rrange = [other rangeOfString:@"/" options:0 range:rrange];
451 NSComparisonResult value;
453 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
454 value = NSOrderedSame;
455 else if (lrange.location == NSNotFound)
456 value = NSOrderedAscending;
457 else if (rrange.location == NSNotFound)
458 value = NSOrderedDescending;
460 value = NSOrderedSame;
462 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
463 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
464 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
465 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
467 NSComparisonResult result = [lpath compare:rpath];
468 return result == NSOrderedSame ? value : result;
471 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
472 return [(id)CFURLCreateStringByAddingPercentEscapes(
477 kCFStringEncodingUTF8
484 /* C++ NSString Wrapper Cache {{{ */
485 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
486 return size == 0 ? NULL :
487 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
488 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
491 static _finline CFStringRef CYStringCreate(const std::string &data) {
492 return CYStringCreate(data.data(), data.size());
495 static _finline CFStringRef CYStringCreate(const char *data) {
496 return CYStringCreate(data, strlen(data));
505 _finline void clear_() {
506 if (cache_ != NULL) {
513 _finline bool empty() const {
517 _finline size_t size() const {
521 _finline char *data() const {
525 _finline void clear() {
530 _finline CYString() :
537 _finline ~CYString() {
541 void operator =(const CYString &rhs) {
545 if (rhs.cache_ == nil)
548 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
551 void copy(CYPool *pool) {
552 char *temp(pool->malloc<char>(size_ + 1));
553 memcpy(temp, data_, size_);
558 void set(CYPool *pool, const char *data, size_t size) {
564 data_ = const_cast<char *>(data);
572 _finline void set(CYPool *pool, const char *data) {
573 set(pool, data, data == NULL ? 0 : strlen(data));
576 _finline void set(CYPool *pool, const std::string &rhs) {
577 set(pool, rhs.data(), rhs.size());
580 bool operator ==(const CYString &rhs) const {
581 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
584 _finline operator CFStringRef() {
586 cache_ = CYStringCreate(data_, size_);
590 _finline operator id() {
591 return (NSString *) static_cast<CFStringRef>(*this);
594 _finline operator const char *() {
595 return reinterpret_cast<const char *>(data_);
599 /* C++ NSString Algorithm Adapters {{{ */
601 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
604 struct NSStringMapHash :
605 std::unary_function<NSString *, size_t>
607 _finline size_t operator ()(NSString *value) const {
608 return CFStringHashNSString((CFStringRef) value);
612 struct NSStringMapLess :
613 std::binary_function<NSString *, NSString *, bool>
615 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
616 return [lhs compare:rhs] == NSOrderedAscending;
620 struct NSStringMapEqual :
621 std::binary_function<NSString *, NSString *, bool>
623 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
624 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
625 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
626 //[lhs isEqualToString:rhs];
631 /* CoreGraphics Primitives {{{ */
636 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
637 CGFloat color[] = {red, green, blue, alpha};
638 return CGColorCreate(space, color);
647 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
648 color_(Create_(space, red, green, blue, alpha))
650 Set(space, red, green, blue, alpha);
655 CGColorRelease(color_);
662 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
664 color_ = Create_(space, red, green, blue, alpha);
667 operator CGColorRef() {
673 /* Random Global Variables {{{ */
674 static int PulseInterval_ = 500000;
676 static const NSString *UI_;
679 static bool RestartSubstrate_;
680 static NSArray *Finishes_;
682 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
683 #define NotifyConfig_ "/etc/notify.conf"
685 static bool Queuing_;
687 static CYColor Blue_;
688 static CYColor Blueish_;
689 static CYColor Black_;
690 static CYColor Folder_;
692 static CYColor White_;
693 static CYColor Gray_;
694 static CYColor Green_;
695 static CYColor Purple_;
696 static CYColor Purplish_;
698 static UIColor *InstallingColor_;
699 static UIColor *RemovingColor_;
701 static NSString *App_;
703 static BOOL Advanced_;
704 static BOOL Ignored_;
706 static _H<UIFont> Font12_;
707 static _H<UIFont> Font12Bold_;
708 static _H<UIFont> Font14_;
709 static _H<UIFont> Font18_;
710 static _H<UIFont> Font18Bold_;
711 static _H<UIFont> Font22Bold_;
713 static const char *Machine_ = NULL;
714 static _H<NSString> System_;
715 static NSString *SerialNumber_ = nil;
716 static NSString *ChipID_ = nil;
717 static NSString *BBSNum_ = nil;
718 static _H<NSString> UniqueID_;
719 static _H<NSString> UserAgent_;
720 static _H<NSString> Product_;
721 static _H<NSString> Safari_;
723 static _H<NSLocale> CollationLocale_;
724 static _H<NSArray> CollationThumbs_;
725 static std::vector<NSInteger> CollationOffset_;
726 static _H<NSArray> CollationTitles_;
727 static _H<NSArray> CollationStarts_;
728 static UTransliterator *CollationTransl_;
729 //static Function<NSString *, NSString *> CollationModify_;
731 typedef std::basic_string<UChar> ustring;
732 static ustring CollationString_;
734 #define CUC const ustring &str(*reinterpret_cast<const ustring *>(rep))
735 #define UC ustring &str(*reinterpret_cast<ustring *>(rep))
736 static struct UReplaceableCallbacks CollationUCalls_ = {
737 .length = [](const UReplaceable *rep) -> int32_t { CUC;
741 .charAt = [](const UReplaceable *rep, int32_t offset) -> UChar { CUC;
742 //fprintf(stderr, "charAt(%d) : %d\n", offset, str.size());
743 if (offset >= str.size())
748 .char32At = [](const UReplaceable *rep, int32_t offset) -> UChar32 { CUC;
749 //fprintf(stderr, "char32At(%d) : %d\n", offset, str.size());
750 if (offset >= str.size())
753 U16_GET(str.data(), 0, offset, str.size(), c);
757 .replace = [](UReplaceable *rep, int32_t start, int32_t limit, const UChar *text, int32_t length) -> void { UC;
758 //fprintf(stderr, "replace(%d, %d, %d) : %d\n", start, limit, length, str.size());
759 str.replace(start, limit - start, text, length);
762 .extract = [](UReplaceable *rep, int32_t start, int32_t limit, UChar *dst) -> void { UC;
763 //fprintf(stderr, "extract(%d, %d) : %d\n", start, limit, str.size());
764 str.copy(dst, limit - start, start);
767 .copy = [](UReplaceable *rep, int32_t start, int32_t limit, int32_t dest) -> void { UC;
768 //fprintf(stderr, "copy(%d, %d, %d) : %d\n", start, limit, dest, str.size());
769 str.replace(dest, 0, str, start, limit - start);
773 static CFLocaleRef Locale_;
774 static NSArray *Languages_;
775 static CGColorSpaceRef space_;
777 #define CacheState_ "/var/mobile/Library/Caches/com.saurik.Cydia/CacheState.plist"
778 #define SavedState_ "/var/mobile/Library/Caches/com.saurik.Cydia/SavedState.plist"
780 static NSDictionary *SectionMap_;
781 static _H<NSDate> Backgrounded_;
782 static _transient NSMutableDictionary *Values_;
783 static _transient NSMutableDictionary *Sections_;
784 _H<NSMutableDictionary> Sources_;
785 static _transient NSNumber *Version_;
789 CGFloat ScreenScale_;
790 static NSString *Idiom_;
791 static _H<NSString> Firmware_;
792 static NSString *Major_;
794 static _H<NSMutableDictionary> SessionData_;
795 static _H<NSObject> HostConfig_;
796 static _H<NSMutableSet> BridgedHosts_;
797 static _H<NSMutableSet> InsecureHosts_;
799 static NSString *kCydiaProgressEventTypeError = @"Error";
800 static NSString *kCydiaProgressEventTypeInformation = @"Information";
801 static NSString *kCydiaProgressEventTypeStatus = @"Status";
802 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
805 /* Display Helpers {{{ */
806 inline float Interpolate(float begin, float end, float fraction) {
807 return (end - begin) * fraction + begin;
810 static inline double Retina(double value) {
811 value *= ScreenScale_;
812 value = round(value);
813 value /= ScreenScale_;
817 static inline CGRect Retina(CGRect value) {
818 value.origin.x *= ScreenScale_;
819 value.origin.y *= ScreenScale_;
820 value.size.width *= ScreenScale_;
821 value.size.height *= ScreenScale_;
822 value = CGRectIntegral(value);
823 value.origin.x /= ScreenScale_;
824 value.origin.y /= ScreenScale_;
825 value.size.width /= ScreenScale_;
826 value.size.height /= ScreenScale_;
830 static _finline const char *StripVersion_(const char *version) {
831 const char *colon(strchr(version, ':'));
832 return colon == NULL ? version : colon + 1;
835 NSString *LocalizeSection(NSString *section) {
836 static RegEx title_r("(.*?) \\((.*)\\)");
837 if (title_r(section)) {
838 NSString *parent(title_r[1]);
839 NSString *child(title_r[2]);
841 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
842 LocalizeSection(parent),
843 LocalizeSection(child)
847 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
850 NSString *Simplify(NSString *title) {
851 const char *data = [title UTF8String];
852 size_t size = [title lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
854 static RegEx square_r("\\[(.*)\\]");
855 if (square_r(data, size))
856 return Simplify(square_r[1]);
858 static RegEx paren_r("\\((.*)\\)");
859 if (paren_r(data, size))
860 return Simplify(paren_r[1]);
862 static RegEx title_r("(.*?) \\((.*)\\)");
863 if (title_r(data, size))
864 return Simplify(title_r[1]);
870 bool isSectionVisible(NSString *section) {
871 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
872 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
873 return hidden == nil || ![hidden boolValue];
876 static NSObject *CYIOGetValue(const char *path, NSString *property) {
877 io_registry_entry_t entry(IORegistryEntryFromPath(kIOMasterPortDefault, path));
878 if (entry == MACH_PORT_NULL)
881 CFTypeRef value(IORegistryEntryCreateCFProperty(entry, (CFStringRef) property, kCFAllocatorDefault, 0));
882 IOObjectRelease(entry);
886 return [(id) value autorelease];
889 static NSString *CYHex(NSData *data, bool reverse = false) {
893 size_t length([data length]);
894 uint8_t bytes[length];
895 [data getBytes:bytes];
897 char string[length * 2 + 1];
898 for (size_t i(0); i != length; ++i)
899 sprintf(string + i * 2, "%.2x", bytes[reverse ? length - i - 1 : i]);
901 return [NSString stringWithUTF8String:string];
904 static NSString *VerifySource(NSString *href) {
905 static RegEx href_r("(http(s?)://|file:///)[^# ]*");
907 [[[[UIAlertView alloc]
908 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("INVALID_URL")]
909 message:UCLocalize("INVALID_URL_EX")
911 cancelButtonTitle:UCLocalize("OK")
912 otherButtonTitles:nil
913 ] autorelease] show];
918 if (![href hasSuffix:@"/"])
919 href = [href stringByAppendingString:@"/"];
925 /* Delegate Prototypes {{{ */
928 @class CydiaProgressEvent;
930 @protocol DatabaseDelegate
931 - (void) repairWithSelector:(SEL)selector;
932 - (void) setConfigurationData:(NSString *)data;
933 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
936 @class CYPackageController;
938 @protocol SourceDelegate
939 - (void) setFetch:(NSNumber *)fetch;
942 @protocol FetchDelegate
943 - (bool) isSourceCancelled;
944 - (void) startSourceFetch:(NSString *)uri;
945 - (void) stopSourceFetch:(NSString *)uri;
948 @protocol CydiaDelegate
949 - (void) returnToCydia;
951 - (void) retainNetworkActivityIndicator;
952 - (void) releaseNetworkActivityIndicator;
953 - (void) clearPackage:(Package *)package;
954 - (void) installPackage:(Package *)package;
955 - (void) installPackages:(NSArray *)packages;
956 - (void) removePackage:(Package *)package;
957 - (void) beginUpdate;
959 - (bool) requestUpdate;
960 - (void) distUpgrade;
963 - (void) _saveConfig;
965 - (void) addSource:(NSDictionary *)source;
966 - (BOOL) addTrivialSource:(NSString *)href;
967 - (UIProgressHUD *) addProgressHUD;
968 - (void) removeProgressHUD:(UIProgressHUD *)hud;
969 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
970 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
974 /* CancelStatus {{{ */
976 public pkgAcquireStatus
987 virtual bool MediaChange(std::string media, std::string drive) {
991 virtual void IMSHit(pkgAcquire::ItemDesc &desc) {
995 virtual bool Pulse_(pkgAcquire *Owner) = 0;
997 virtual bool Pulse(pkgAcquire *Owner) {
998 if (pkgAcquireStatus::Pulse(Owner) && Pulse_(Owner))
1006 _finline bool WasCancelled() const {
1011 /* DelegateStatus {{{ */
1016 _transient NSObject<ProgressDelegate> *delegate_;
1024 void setDelegate(NSObject<ProgressDelegate> *delegate) {
1025 delegate_ = delegate;
1028 virtual void Fetch(pkgAcquire::ItemDesc &desc) {
1029 NSString *name([NSString stringWithUTF8String:desc.ShortDesc.c_str()]);
1030 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItemDesc:desc]);
1031 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1034 virtual void Done(pkgAcquire::ItemDesc &desc) {
1035 NSString *name([NSString stringWithUTF8String:desc.ShortDesc.c_str()]);
1036 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:Colon_, UCLocalize("DONE"), name] ofType:kCydiaProgressEventTypeStatus forItemDesc:desc]);
1037 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1040 virtual void Fail(pkgAcquire::ItemDesc &desc) {
1042 desc.Owner->Status == pkgAcquire::Item::StatIdle ||
1043 desc.Owner->Status == pkgAcquire::Item::StatDone
1047 std::string &error(desc.Owner->ErrorText);
1051 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItemDesc:desc]);
1052 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1055 virtual bool Pulse_(pkgAcquire *Owner) {
1057 double(CurrentBytes + CurrentItems) /
1058 double(TotalBytes + TotalItems)
1061 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
1062 [NSNumber numberWithDouble:percent], @"Percent",
1064 [NSNumber numberWithDouble:CurrentBytes], @"Current",
1065 [NSNumber numberWithDouble:TotalBytes], @"Total",
1066 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
1067 nil] waitUntilDone:YES];
1069 return ![delegate_ isProgressCancelled];
1072 virtual void Start() {
1073 pkgAcquireStatus::Start();
1074 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
1077 virtual void Stop() {
1078 pkgAcquireStatus::Stop();
1079 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
1080 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
1084 /* Database Interface {{{ */
1085 typedef std::map< unsigned long, _H<Source> > SourceMap;
1087 @interface Database : NSObject {
1094 pkgCacheFile cache_;
1095 pkgDepCache::Policy *policy_;
1096 pkgRecords *records_;
1097 pkgProblemResolver *resolver_;
1098 pkgAcquire *fetcher_;
1100 SPtr<pkgPackageManager> manager_;
1101 pkgSourceList *list_;
1103 SourceMap sourceMap_;
1104 _H<NSMutableArray> sourceList_;
1106 _H<NSArray> packages_;
1108 _transient NSObject<DatabaseDelegate> *delegate_;
1109 _transient NSObject<ProgressDelegate> *progress_;
1111 CydiaStatus status_;
1117 std::map<const char *, _H<NSString> > sections_;
1120 + (Database *) sharedInstance;
1122 - (bool) hasPackages;
1124 - (void) _readCydia:(NSNumber *)fd;
1125 - (void) _readStatus:(NSNumber *)fd;
1126 - (void) _readOutput:(NSNumber *)fd;
1130 - (Package *) packageWithName:(NSString *)name;
1132 - (pkgCacheFile &) cache;
1133 - (pkgDepCache::Policy *) policy;
1134 - (pkgRecords *) records;
1135 - (pkgProblemResolver *) resolver;
1136 - (pkgAcquire &) fetcher;
1137 - (pkgSourceList &) list;
1138 - (NSArray *) packages;
1139 - (NSArray *) sources;
1140 - (Source *) sourceWithKey:(NSString *)key;
1141 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1149 - (void) updateWithStatus:(CancelStatus &)status;
1151 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1153 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1154 - (NSObject<ProgressDelegate> *) progressDelegate;
1156 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1157 - (void) setFetch:(bool)fetch forURI:(const char *)uri;
1158 - (void) resetFetch;
1160 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1164 /* SourceStatus {{{ */
1165 class SourceStatus :
1169 _transient NSObject<FetchDelegate> *delegate_;
1170 _transient Database *database_;
1171 std::set<std::string> fetches_;
1174 SourceStatus(NSObject<FetchDelegate> *delegate, Database *database) :
1175 delegate_(delegate),
1180 void Set(bool fetch, const std::string &uri) {
1182 if (!fetches_.insert(uri).second)
1185 if (fetches_.erase(uri) == 0)
1189 //printf("Set(%s, %s)\n", fetch ? "true" : "false", uri.c_str());
1191 auto slash(uri.rfind('/'));
1192 if (slash != std::string::npos)
1193 [database_ setFetch:fetch forURI:uri.substr(0, slash).c_str()];
1196 _finline void Set(bool fetch, pkgAcquire::Item *item) {
1197 /*unsigned long ID(fetch ? 1 : 0);
1201 Set(fetch, item->DescURI());
1204 void Log(const char *tag, pkgAcquire::Item *item) {
1205 //printf("%s(%s) S:%u Q:%u\n", tag, item->DescURI().c_str(), item->Status, item->QueueCounter);
1208 virtual void Fetch(pkgAcquire::ItemDesc &desc) {
1209 Log("Fetch", desc.Owner);
1210 Set(true, desc.Owner);
1213 virtual void Done(pkgAcquire::ItemDesc &desc) {
1214 Log("Done", desc.Owner);
1215 Set(false, desc.Owner);
1218 virtual void Fail(pkgAcquire::ItemDesc &desc) {
1219 Log("Fail", desc.Owner);
1220 Set(false, desc.Owner);
1223 virtual bool Pulse_(pkgAcquire *Owner) {
1224 std::set<std::string> fetches;
1225 for (pkgAcquire::ItemCIterator item(Owner->ItemsBegin()); item != Owner->ItemsEnd(); ++item) {
1227 if ((*item)->QueueCounter == 0)
1229 else switch ((*item)->Status) {
1230 case pkgAcquire::Item::StatFetching:
1231 fetches.insert((*item)->DescURI());
1240 Log(fetch ? "Pulse<true>" : "Pulse<false>", *item);
1244 std::vector<std::string> stops;
1245 std::set_difference(fetches_.begin(), fetches_.end(), fetches.begin(), fetches.end(), std::back_insert_iterator<std::vector<std::string>>(stops));
1246 for (std::vector<std::string>::const_iterator stop(stops.begin()); stop != stops.end(); ++stop) {
1247 //printf("Stop(%s)\n", stop->c_str());
1251 return ![delegate_ isSourceCancelled];
1254 virtual void Stop() {
1255 pkgAcquireStatus::Stop();
1256 [database_ resetFetch];
1260 /* ProgressEvent Implementation {{{ */
1261 @implementation CydiaProgressEvent
1263 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1264 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1267 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1268 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1269 [event setPackage:package];
1273 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItemDesc:(pkgAcquire::ItemDesc &)desc {
1274 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1276 NSString *description([NSString stringWithUTF8String:desc.Description.c_str()]);
1277 NSArray *fields([description componentsSeparatedByString:@" "]);
1278 [event setItem:fields];
1280 if ([fields count] > 3) {
1281 [event setPackage:[fields objectAtIndex:2]];
1282 [event setVersion:[fields objectAtIndex:3]];
1285 [event setURL:[NSString stringWithUTF8String:desc.URI.c_str()]];
1290 + (NSArray *) _attributeKeys {
1291 return [NSArray arrayWithObjects:
1301 - (NSArray *) attributeKeys {
1302 return [[self class] _attributeKeys];
1305 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1306 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1309 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1310 if ((self = [super init]) != nil) {
1316 - (NSString *) message {
1320 - (NSString *) type {
1324 - (NSArray *) item {
1325 return (id) item_ ?: [NSNull null];
1328 - (void) setItem:(NSArray *)item {
1332 - (NSString *) package {
1333 return (id) package_ ?: [NSNull null];
1336 - (void) setPackage:(NSString *)package {
1340 - (NSString *) url {
1341 return (id) url_ ?: [NSNull null];
1344 - (void) setURL:(NSString *)url {
1348 - (void) setVersion:(NSString *)version {
1352 - (NSString *) version {
1353 return (id) version_ ?: [NSNull null];
1356 - (NSString *) compound:(NSString *)value {
1358 NSString *mode(nil); {
1359 NSString *type([self type]);
1360 if ([type isEqualToString:kCydiaProgressEventTypeError])
1361 mode = UCLocalize("ERROR");
1362 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1363 mode = UCLocalize("WARNING");
1367 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1373 - (NSString *) compoundMessage {
1374 return [self compound:[self message]];
1377 - (NSString *) compoundTitle {
1380 if (package_ == nil)
1382 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1383 title = [package name];
1387 return [self compound:title];
1393 // Cytore Definitions {{{
1394 struct PackageValue :
1397 Cytore::Offset<PackageValue> next_;
1399 uint32_t index_ : 23;
1400 uint32_t subscribed_ : 1;
1417 Cytore::Offset<PackageValue> packages_[1 << 16];
1420 static Cytore::File<MetaValue> MetaFile_;
1422 // Cytore Helper Functions {{{
1423 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1424 SplitHash nhash = { hashlittle(name, length) };
1426 PackageValue *metadata;
1428 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1429 for (;; offset = &metadata->next_) { if (offset->IsNull()) {
1430 *offset = MetaFile_.New<PackageValue>(length + 1);
1431 metadata = &MetaFile_.Get(*offset);
1433 if (metadata == NULL) {
1437 metadata = new PackageValue();
1438 memset(metadata, 0, sizeof(*metadata));
1441 memcpy(metadata->name_, name, length);
1442 metadata->name_[length] = '\0';
1443 metadata->nhash_ = nhash.u16[1];
1445 metadata = &MetaFile_.Get(*offset);
1446 if (metadata->nhash_ != nhash.u16[1])
1448 if (strncmp(metadata->name_, name, length) != 0)
1450 if (metadata->name_[length] != '\0')
1457 static void PackageImport(const void *key, const void *value, void *context) {
1458 bool &fail(*reinterpret_cast<bool *>(context));
1461 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1462 NSLog(@"failed to import package %@", key);
1466 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1467 NSDictionary *package((NSDictionary *) value);
1469 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1470 if ([subscribed boolValue] && !metadata->subscribed_)
1471 metadata->subscribed_ = true;
1473 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1474 time_t time([date timeIntervalSince1970]);
1475 if (metadata->first_ > time || metadata->first_ == 0)
1476 metadata->first_ = time;
1479 NSDate *date([package objectForKey:@"LastSeen"]);
1480 NSString *version([package objectForKey:@"LastVersion"]);
1482 if (date != nil && version != nil) {
1483 time_t time([date timeIntervalSince1970]);
1484 if (metadata->last_ < time || metadata->last_ == 0)
1485 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1486 size_t length(strlen(buffer));
1487 uint16_t vhash(hashlittle(buffer, length));
1489 size_t capped(std::min<size_t>(8, length));
1490 char *latest(buffer + length - capped);
1492 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1493 metadata->vhash_ = vhash;
1495 metadata->last_ = time;
1501 static NSDate *GetStatusDate() {
1502 return [[[NSFileManager defaultManager] attributesOfItemAtPath:@"/var/lib/dpkg/status" error:NULL] fileModificationDate];
1505 static void SaveConfig(NSObject *lock) {
1506 @synchronized (lock) {
1512 CFPreferencesSetMultiple((CFDictionaryRef) [NSDictionary dictionaryWithObjectsAndKeys:
1513 Values_, @"CydiaValues",
1514 Sections_, @"CydiaSections",
1515 (id) Sources_, @"CydiaSources",
1516 Version_, @"CydiaVersion",
1517 nil], NULL, CFSTR("com.saurik.Cydia"), kCFPreferencesCurrentUser, kCFPreferencesCurrentHost);
1519 if (!CFPreferencesAppSynchronize(CFSTR("com.saurik.Cydia")))
1520 NSLog(@"CFPreferencesAppSynchronize(com.saurik.Cydia) == false");
1522 CydiaWriteSources();
1525 /* Source Class {{{ */
1526 @interface Source : NSObject {
1528 Database *database_;
1531 CYString depiction_;
1532 CYString description_;
1538 CYString distribution_;
1544 _H<NSString> authority_;
1546 CYString defaultIcon_;
1548 _H<NSMutableDictionary> record_;
1551 std::set<std::string> fetches_;
1552 std::set<std::string> files_;
1553 _transient NSObject<SourceDelegate> *delegate_;
1556 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(CYPool *)pool;
1558 - (NSComparisonResult) compareByName:(Source *)source;
1560 - (NSString *) depictionForPackage:(NSString *)package;
1561 - (NSString *) supportForPackage:(NSString *)package;
1563 - (metaIndex *) metaIndex;
1564 - (NSDictionary *) record;
1567 - (NSString *) rooturi;
1568 - (NSString *) distribution;
1569 - (NSString *) type;
1572 - (NSString *) host;
1574 - (NSString *) name;
1575 - (NSString *) shortDescription;
1576 - (NSString *) label;
1577 - (NSString *) origin;
1578 - (NSString *) version;
1580 - (NSString *) defaultIcon;
1581 - (NSURL *) iconURL;
1583 - (void) setFetch:(bool)fetch forURI:(const char *)uri;
1584 - (void) resetFetch;
1588 @implementation Source
1590 + (NSString *) webScriptNameForSelector:(SEL)selector {
1592 else if (selector == @selector(addSection:))
1593 return @"addSection";
1594 else if (selector == @selector(getField:))
1596 else if (selector == @selector(removeSection:))
1597 return @"removeSection";
1598 else if (selector == @selector(remove))
1604 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1605 return [self webScriptNameForSelector:selector] == nil;
1608 + (NSArray *) _attributeKeys {
1609 return [NSArray arrayWithObjects:
1620 @"shortDescription",
1627 - (NSArray *) attributeKeys {
1628 return [[self class] _attributeKeys];
1631 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1632 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1635 - (metaIndex *) metaIndex {
1639 - (void) setMetaIndex:(metaIndex *)index inPool:(CYPool *)pool {
1640 trusted_ = index->IsTrusted();
1642 uri_.set(pool, index->GetURI());
1643 distribution_.set(pool, index->GetDist());
1644 type_.set(pool, index->GetType());
1646 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1647 if (dindex != NULL) {
1648 std::string file(dindex->MetaIndexURI(""));
1649 base_.set(pool, file);
1652 _profile(Source$setMetaIndex$GetIndexes)
1653 dindex->GetIndexes(&acquire, true);
1655 _profile(Source$setMetaIndex$DescURI)
1656 for (pkgAcquire::ItemIterator item(acquire.ItemsBegin()); item != acquire.ItemsEnd(); item++) {
1657 std::string file((*item)->DescURI());
1658 auto slash(file.rfind('/'));
1659 if (slash == std::string::npos)
1661 files_.insert(file.substr(0, slash));
1666 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1669 pkgTagFile tags(&fd);
1671 pkgTagSection section;
1678 {"default-icon", &defaultIcon_},
1679 {"depiction", &depiction_},
1680 {"description", &description_},
1682 {"origin", &origin_},
1683 {"support", &support_},
1684 {"version", &version_},
1687 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1688 const char *start, *end;
1690 if (section.Find(names[i].name_, start, end)) {
1691 CYString &value(*names[i].value_);
1692 value.set(pool, start, end - start);
1698 record_ = [Sources_ objectForKey:[self key]];
1700 NSURL *url([NSURL URLWithString:uri_]);
1704 host_ = [host_ lowercaseString];
1709 authority_ = [url path];
1712 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(CYPool *)pool {
1713 if ((self = [super init]) != nil) {
1714 era_ = [database era];
1715 database_ = database;
1718 _profile(Source$initWithMetaIndex$setMetaIndex)
1719 [self setMetaIndex:index inPool:pool];
1724 - (NSString *) getField:(NSString *)name {
1725 @synchronized (database_) {
1726 if ([database_ era] != era_ || index_ == NULL)
1729 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index_));
1734 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly)) {
1739 pkgTagFile tags(&fd);
1741 pkgTagSection section;
1744 const char *start, *end;
1745 if (!section.Find([name UTF8String], start, end))
1746 return (NSString *) [NSNull null];
1748 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
1751 - (NSComparisonResult) compareByName:(Source *)source {
1752 NSString *lhs = [self name];
1753 NSString *rhs = [source name];
1755 if ([lhs length] != 0 && [rhs length] != 0) {
1756 unichar lhc = [lhs characterAtIndex:0];
1757 unichar rhc = [rhs characterAtIndex:0];
1759 if (isalpha(lhc) && !isalpha(rhc))
1760 return NSOrderedAscending;
1761 else if (!isalpha(lhc) && isalpha(rhc))
1762 return NSOrderedDescending;
1765 return [lhs compare:rhs options:LaxCompareOptions_];
1768 - (NSString *) depictionForPackage:(NSString *)package {
1769 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1772 - (NSString *) supportForPackage:(NSString *)package {
1773 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1776 - (NSArray *) sections {
1777 return record_ == nil ? (id) [NSNull null] : [record_ objectForKey:@"Sections"] ?: [NSArray array];
1780 - (void) _addSection:(NSString *)section {
1783 else if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) {
1784 if (![sections containsObject:section])
1785 [sections addObject:section];
1787 [record_ setObject:[NSMutableArray arrayWithObject:section] forKey:@"Sections"];
1790 - (bool) addSection:(NSString *)section {
1794 [self performSelectorOnMainThread:@selector(_addSection:) withObject:section waitUntilDone:NO];
1798 - (void) _removeSection:(NSString *)section {
1802 if (NSMutableArray *sections = [record_ objectForKey:@"Sections"])
1803 if ([sections containsObject:section])
1804 [sections removeObject:section];
1807 - (bool) removeSection:(NSString *)section {
1811 [self performSelectorOnMainThread:@selector(_removeSection:) withObject:section waitUntilDone:NO];
1816 [Sources_ removeObjectForKey:[self key]];
1820 bool value(record_ != nil);
1821 [self performSelectorOnMainThread:@selector(_remove) withObject:nil waitUntilDone:NO];
1825 - (NSDictionary *) record {
1833 - (NSString *) rooturi {
1837 - (NSString *) distribution {
1838 return distribution_;
1841 - (NSString *) type {
1845 - (NSString *) baseuri {
1846 return base_.empty() ? nil : (id) base_;
1849 - (NSString *) iconuri {
1850 if (NSString *base = [self baseuri])
1851 return [base stringByAppendingString:@"CydiaIcon.png"];
1856 - (NSURL *) iconURL {
1857 if (NSString *uri = [self iconuri])
1858 return [NSURL URLWithString:uri];
1862 - (NSString *) key {
1863 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1866 - (NSString *) host {
1870 - (NSString *) name {
1871 return origin_.empty() ? (id) authority_ : origin_;
1874 - (NSString *) shortDescription {
1875 return description_;
1878 - (NSString *) label {
1879 return label_.empty() ? (id) authority_ : label_;
1882 - (NSString *) origin {
1886 - (NSString *) version {
1890 - (NSString *) defaultIcon {
1891 return defaultIcon_;
1894 - (void) setDelegate:(NSObject<SourceDelegate> *)delegate {
1895 delegate_ = delegate;
1899 return !fetches_.empty();
1902 - (void) setFetch:(bool)fetch forURI:(const char *)uri {
1904 if (fetches_.erase(uri) == 0)
1906 } else if (files_.find(uri) == files_.end())
1908 else if (!fetches_.insert(uri).second)
1911 [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:[self fetch]] waitUntilDone:NO];
1914 - (void) resetFetch {
1916 [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:NO];
1921 /* CydiaOperation Class {{{ */
1922 @interface CydiaOperation : NSObject {
1923 _H<NSString> operator_;
1924 _H<NSString> value_;
1927 - (NSString *) operator;
1928 - (NSString *) value;
1932 @implementation CydiaOperation
1934 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1935 if ((self = [super init]) != nil) {
1936 operator_ = [NSString stringWithUTF8String:_operator];
1937 value_ = [NSString stringWithUTF8String:value];
1941 + (NSArray *) _attributeKeys {
1942 return [NSArray arrayWithObjects:
1948 - (NSArray *) attributeKeys {
1949 return [[self class] _attributeKeys];
1952 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1953 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1956 - (NSString *) operator {
1960 - (NSString *) value {
1966 /* CydiaClause Class {{{ */
1967 @interface CydiaClause : NSObject {
1968 _H<NSString> package_;
1969 _H<CydiaOperation> version_;
1972 - (NSString *) package;
1973 - (CydiaOperation *) version;
1977 @implementation CydiaClause
1979 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1980 if ((self = [super init]) != nil) {
1981 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1983 if (const char *version = dep.TargetVer())
1984 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1986 version_ = (id) [NSNull null];
1990 + (NSArray *) _attributeKeys {
1991 return [NSArray arrayWithObjects:
1997 - (NSArray *) attributeKeys {
1998 return [[self class] _attributeKeys];
2001 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2002 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2005 - (NSString *) package {
2009 - (CydiaOperation *) version {
2015 /* CydiaRelation Class {{{ */
2016 @interface CydiaRelation : NSObject {
2017 _H<NSString> relationship_;
2018 _H<NSMutableArray> clauses_;
2021 - (NSString *) relationship;
2022 - (NSArray *) clauses;
2026 @implementation CydiaRelation
2028 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
2029 if ((self = [super init]) != nil) {
2030 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
2031 clauses_ = [NSMutableArray arrayWithCapacity:8];
2033 pkgCache::DepIterator start;
2034 pkgCache::DepIterator end;
2035 dep.GlobOr(start, end); // ++dep
2038 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
2040 // yes, seriously. (wtf?)
2048 + (NSArray *) _attributeKeys {
2049 return [NSArray arrayWithObjects:
2055 - (NSArray *) attributeKeys {
2056 return [[self class] _attributeKeys];
2059 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2060 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2063 - (NSString *) relationship {
2064 return relationship_;
2067 - (NSArray *) clauses {
2071 - (void) addClause:(CydiaClause *)clause {
2072 [clauses_ addObject:clause];
2077 /* Package Class {{{ */
2078 struct ParsedPackage {
2082 CYString architecture_;
2085 CYString depiction_;
2092 @interface Package : NSObject {
2094 @public uint32_t role_ : 3;
2095 uint32_t essential_ : 1;
2096 uint32_t obsolete_ : 1;
2097 uint32_t ignored_ : 1;
2098 uint32_t pooled_ : 1;
2104 _transient Database *database_;
2106 pkgCache::VerIterator version_;
2107 pkgCache::PkgIterator iterator_;
2108 pkgCache::VerFileIterator file_;
2112 CYString transform_;
2115 CYString installed_;
2118 const char *section_;
2119 _transient NSString *section$_;
2123 PackageValue *metadata_;
2124 ParsedPackage *parsed_;
2126 _H<NSMutableArray> tags_;
2129 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database;
2130 + (Package *) newPackageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database;
2132 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database;
2134 - (pkgCache::PkgIterator) iterator;
2137 - (NSString *) section;
2138 - (NSString *) simpleSection;
2140 - (NSString *) longSection;
2141 - (NSString *) shortSection;
2145 - (MIMEAddress *) maintainer;
2147 - (NSString *) longDescription;
2148 - (NSString *) shortDescription;
2151 - (PackageValue *) metadata;
2154 - (bool) subscribed;
2155 - (bool) setSubscribed:(bool)subscribed;
2159 - (NSString *) latest;
2160 - (NSString *) installed;
2161 - (BOOL) uninstalled;
2163 - (BOOL) upgradableAndEssential:(BOOL)essential;
2166 - (BOOL) unfiltered;
2170 - (BOOL) halfConfigured;
2171 - (BOOL) halfInstalled;
2173 - (NSString *) mode;
2176 - (NSString *) name;
2178 - (NSString *) homepage;
2179 - (NSString *) depiction;
2180 - (MIMEAddress *) author;
2182 - (NSString *) support;
2184 - (NSArray *) files;
2185 - (NSArray *) warnings;
2186 - (NSArray *) applications;
2188 - (Source *) source;
2191 - (BOOL) matches:(NSArray *)query;
2193 - (BOOL) hasTag:(NSString *)tag;
2194 - (NSString *) primaryPurpose;
2195 - (NSArray *) purposes;
2196 - (bool) isCommercial;
2198 - (void) setIndex:(size_t)index;
2200 - (CYString &) cyname;
2202 - (uint32_t) compareBySection:(NSArray *)sections;
2209 uint32_t PackageChangesRadix(Package *self, void *) {
2214 uint32_t timestamp : 30;
2215 uint32_t ignored : 1;
2216 uint32_t upgradable : 1;
2220 bool upgradable([self upgradableAndEssential:YES]);
2221 value.bits.upgradable = upgradable ? 1 : 0;
2224 value.bits.timestamp = 0;
2225 value.bits.ignored = [self ignored] ? 0 : 1;
2226 value.bits.upgradable = 1;
2228 value.bits.timestamp = [self seen] >> 2;
2229 value.bits.ignored = 0;
2230 value.bits.upgradable = 0;
2233 return _not(uint32_t) - value.key;
2236 CYString &(*PackageName)(Package *self, SEL sel);
2238 uint32_t PackagePrefixRadix(Package *self, void *context) {
2239 size_t offset(reinterpret_cast<size_t>(context));
2240 CYString &name(PackageName(self, @selector(cyname)));
2242 size_t size(name.size());
2245 char *text(name.data());
2248 if (!isdigit(text[0]))
2252 while (size != digits && isdigit(text[digits]))
2260 if (offset == 0 && zeros != 0) {
2261 memset(data, '0', zeros);
2262 memcpy(data + zeros, text, 4 - zeros);
2264 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2265 if (size <= offset - zeros)
2268 text += offset - zeros;
2269 size -= offset - zeros;
2272 memcpy(data, text, 4);
2274 memcpy(data, text, size);
2275 memset(data + size, 0, 4 - size);
2278 for (size_t i(0); i != 4; ++i)
2279 if (isalpha(data[i]))
2287 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2289 /* XXX: ntohl may be more honest */
2290 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2293 CFComparisonResult StringNameCompare(CFStringRef lhn, CFStringRef rhn, size_t length) {
2294 _profile(PackageNameCompare)
2296 return rhn == NULL ? kCFCompareEqualTo : kCFCompareLessThan;
2297 else if (rhn == NULL)
2298 return kCFCompareGreaterThan;
2300 CFIndex length(CFStringGetLength(lhn));
2302 _profile(PackageNameCompare$NumbersLast)
2303 if (length != 0 && CFStringGetLength(rhn) != 0) {
2304 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2305 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2306 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2307 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2308 return lha ? kCFCompareLessThan : kCFCompareGreaterThan;
2312 _profile(PackageNameCompare$Compare)
2313 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, (CFLocaleRef) (id) CollationLocale_);
2318 _finline CFComparisonResult StringNameCompare(NSString *lhn, NSString*rhn, size_t length) {
2319 return StringNameCompare((CFStringRef) lhn, (CFStringRef) rhn, length);
2322 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2323 CYString &lhn(PackageName(lhs, @selector(cyname)));
2324 NSString *rhn(PackageName(rhs, @selector(cyname)));
2325 return StringNameCompare(lhn, rhn, lhn.size());
2328 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *arg) {
2329 return PackageNameCompare(*lhs, *rhs, arg);
2332 struct PackageNameOrdering :
2333 std::binary_function<Package *, Package *, bool>
2335 _finline bool operator ()(Package *lhs, Package *rhs) const {
2336 return PackageNameCompare(lhs, rhs, NULL) == kCFCompareLessThan;
2340 @implementation Package
2342 - (NSString *) description {
2343 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2349 if (parsed_ != NULL)
2354 + (NSString *) webScriptNameForSelector:(SEL)selector {
2356 else if (selector == @selector(clear))
2358 else if (selector == @selector(getField:))
2360 else if (selector == @selector(getRecord))
2361 return @"getRecord";
2362 else if (selector == @selector(hasTag:))
2364 else if (selector == @selector(install))
2366 else if (selector == @selector(remove))
2372 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2373 return [self webScriptNameForSelector:selector] == nil;
2376 + (NSArray *) _attributeKeys {
2377 return [NSArray arrayWithObjects:
2398 @"shortDescription",
2411 - (NSArray *) attributeKeys {
2412 return [[self class] _attributeKeys];
2415 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2416 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2419 - (NSArray *) relations {
2420 @synchronized (database_) {
2421 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2422 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2423 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2427 - (NSString *) architecture {
2429 @synchronized (database_) {
2430 return parsed_->architecture_.empty() ? [NSNull null] : (id) parsed_->architecture_;
2433 - (NSString *) getField:(NSString *)name {
2434 @synchronized (database_) {
2435 if ([database_ era] != era_ || file_.end())
2438 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2440 const char *start, *end;
2441 if (!parser.Find([name UTF8String], start, end))
2442 return (NSString *) [NSNull null];
2444 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2447 - (NSString *) getRecord {
2448 @synchronized (database_) {
2449 if ([database_ era] != era_ || file_.end())
2452 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2454 const char *start, *end;
2455 parser.GetRec(start, end);
2457 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2461 if (parsed_ != NULL)
2463 @synchronized (database_) {
2464 if ([database_ era] != era_ || file_.end())
2467 ParsedPackage *parsed(new ParsedPackage);
2470 _profile(Package$parse)
2471 pkgRecords::Parser *parser;
2473 _profile(Package$parse$Lookup)
2474 parser = &[database_ records]->Lookup(file_);
2480 _profile(Package$parse$Find)
2485 {"architecture", &parsed->architecture_},
2486 {"icon", &parsed->icon_},
2487 {"depiction", &parsed->depiction_},
2488 {"homepage", &parsed->homepage_},
2489 {"website", &website},
2491 {"support", &parsed->support_},
2492 {"author", &parsed->author_},
2493 {"md5sum", &parsed->md5sum_},
2496 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2497 const char *start, *end;
2499 if (parser->Find(names[i].name_, start, end)) {
2500 CYString &value(*names[i].value_);
2501 _profile(Package$parse$Value)
2502 value.set(pool_, start, end - start);
2508 _profile(Package$parse$Tagline)
2509 parsed->tagline_.set(pool_, parser->ShortDesc());
2512 _profile(Package$parse$Retain)
2513 if (parsed->homepage_.empty())
2514 parsed->homepage_ = website;
2515 if (parsed->homepage_ == parsed->depiction_)
2516 parsed->homepage_.clear();
2517 if (parsed->support_.empty())
2518 parsed->support_ = bugs;
2523 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database {
2524 if ((self = [super init]) != nil) {
2525 _profile(Package$initWithVersion)
2527 pool_ = new CYPool();
2533 database_ = database;
2534 era_ = [database era];
2538 pkgCache::PkgIterator iterator(version_.ParentPkg());
2539 iterator_ = iterator;
2541 _profile(Package$initWithVersion$Version)
2542 file_ = version_.FileList();
2545 _profile(Package$initWithVersion$Cache)
2546 name_.set(NULL, version_.Display());
2548 latest_.set(NULL, StripVersion_(version_.VerStr()));
2550 pkgCache::VerIterator current(iterator.CurrentVer());
2552 installed_.set(NULL, StripVersion_(current.VerStr()));
2555 _profile(Package$initWithVersion$Transliterate) do {
2556 if (CollationTransl_ == NULL)
2561 _profile(Package$initWithVersion$Transliterate$utf8)
2562 const uint8_t *data(reinterpret_cast<const uint8_t *>(name_.data()));
2563 for (size_t i(0), e(name_.size()); i != e; ++i)
2564 if (data[i] >= 0x80)
2569 UErrorCode code(U_ZERO_ERROR);
2572 _profile(Package$initWithVersion$Transliterate$u_strFromUTF8WithSub)
2573 CollationString_.resize(name_.size());
2574 u_strFromUTF8WithSub(&CollationString_[0], CollationString_.size(), &length, name_.data(), name_.size(), 0xfffd, NULL, &code);
2575 if (!U_SUCCESS(code))
2577 CollationString_.resize(length);
2580 _profile(Package$initWithVersion$Transliterate$utrans_trans)
2581 length = CollationString_.size();
2582 utrans_trans(CollationTransl_, reinterpret_cast<UReplaceable *>(&CollationString_), &CollationUCalls_, 0, &length, &code);
2583 if (!U_SUCCESS(code))
2585 _assert(CollationString_.size() == length);
2588 _profile(Package$initWithVersion$Transliterate$u_strToUTF8WithSub$preflight)
2589 u_strToUTF8WithSub(NULL, 0, &length, CollationString_.data(), CollationString_.size(), 0xfffd, NULL, &code);
2590 if (code == U_BUFFER_OVERFLOW_ERROR)
2591 code = U_ZERO_ERROR;
2592 else if (!U_SUCCESS(code))
2597 _profile(Package$initWithVersion$Transliterate$apr_palloc)
2598 transform = pool_->malloc<char>(length);
2600 _profile(Package$initWithVersion$Transliterate$u_strToUTF8WithSub$transform)
2601 u_strToUTF8WithSub(transform, length, NULL, CollationString_.data(), CollationString_.size(), 0xfffd, NULL, &code);
2602 if (!U_SUCCESS(code))
2606 transform_.set(NULL, transform, length);
2607 } while (false); _end
2609 _profile(Package$initWithVersion$Tags)
2611 pkgCache::TagIterator tag(version_.TagList());
2613 pkgCache::TagIterator tag(iterator.TagList());
2616 tags_ = [NSMutableArray arrayWithCapacity:8];
2618 goto tag; for (; !tag.end(); ++tag) tag: {
2619 const char *name(tag.Name());
2620 NSString *string((NSString *) CYStringCreate(name));
2624 [tags_ addObject:[string autorelease]];
2626 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2627 if (strcmp(name + 6, "enduser") == 0)
2629 else if (strcmp(name + 6, "hacker") == 0)
2631 else if (strcmp(name + 6, "developer") == 0)
2633 else if (strcmp(name + 6, "cydia") == 0)
2639 if (strncmp(name, "cydia::", 7) == 0) {
2640 if (strcmp(name + 7, "essential") == 0)
2642 else if (strcmp(name + 7, "obsolete") == 0)
2649 _profile(Package$initWithVersion$Metadata)
2650 const char *mixed(iterator.Name());
2651 size_t size(strlen(mixed));
2652 static const size_t prefix(sizeof("/var/lib/dpkg/info/") - 1);
2653 char lower[prefix + size + 5 + 1];
2655 for (size_t i(0); i != size; ++i)
2656 lower[prefix + i] = mixed[i] | 0x20;
2658 if (!installed_.empty()) {
2659 memcpy(lower, "/var/lib/dpkg/info/", prefix);
2660 memcpy(lower + prefix + size, ".list", 6);
2662 if (stat(lower, &info) != -1)
2663 upgraded_ = info.st_birthtime;
2666 PackageValue *metadata(PackageFind(lower + prefix, size));
2667 metadata_ = metadata;
2669 id_.set(NULL, metadata->name_, size);
2671 const char *latest(version_.VerStr());
2672 size_t length(strlen(latest));
2674 uint16_t vhash(hashlittle(latest, length));
2676 size_t capped(std::min<size_t>(8, length));
2677 latest = latest + length - capped;
2679 if (metadata->first_ == 0)
2680 metadata->first_ = now_;
2682 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2683 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2684 metadata->vhash_ = vhash;
2685 metadata->last_ = now_;
2686 } else if (metadata->last_ == 0)
2687 metadata->last_ = metadata->first_;
2690 _profile(Package$initWithVersion$Section)
2691 section_ = version_.Section();
2694 _profile(Package$initWithVersion$Flags)
2695 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2696 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2701 + (Package *) newPackageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database {
2702 pkgCache::VerIterator version;
2704 _profile(Package$packageWithIterator$GetCandidateVer)
2705 version = [database policy]->GetCandidateVer(iterator);
2713 _profile(Package$packageWithIterator$Allocate)
2714 package = [Package allocWithZone:zone];
2717 _profile(Package$packageWithIterator$Initialize)
2719 initWithVersion:version
2729 // XXX: just in case a Cydia extension is using this (I bet this is unlikely, though, due to CYPool?)
2730 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database {
2731 return [[self newPackageWithIterator:iterator withZone:zone inPool:pool database:database] autorelease];
2734 - (pkgCache::PkgIterator) iterator {
2738 - (NSArray *) downgrades {
2739 NSMutableArray *versions([NSMutableArray arrayWithCapacity:4]);
2741 for (auto version(iterator_.VersionList()); !version.end(); ++version) {
2742 if (version == version_)
2744 Package *package([[[Package allocWithZone:NULL] initWithVersion:version withZone:NULL inPool:NULL database:database_] autorelease]);
2745 if ([package source] == nil)
2747 [versions addObject:package];
2753 - (NSString *) section {
2754 if (section$_ == nil) {
2755 if (section_ == NULL)
2758 _profile(Package$section$mappedSectionForPointer)
2759 section$_ = [database_ mappedSectionForPointer:section_];
2764 - (NSString *) simpleSection {
2765 if (NSString *section = [self section])
2766 return Simplify(section);
2771 - (NSString *) longSection {
2772 if (NSString *section = [self section])
2773 return LocalizeSection(section);
2778 - (NSString *) shortSection {
2779 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2782 - (NSString *) uri {
2785 pkgIndexFile *index;
2786 pkgCache::PkgFileIterator file(file_.File());
2787 if (![database_ list].FindIndex(file, index))
2789 return [NSString stringWithUTF8String:iterator_->Path];
2790 //return [NSString stringWithUTF8String:file.Site()];
2791 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2795 - (MIMEAddress *) maintainer {
2796 @synchronized (database_) {
2797 if ([database_ era] != era_ || file_.end())
2800 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2801 const std::string &maintainer(parser->Maintainer());
2802 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2805 - (NSString *) md5sum {
2806 return parsed_ == NULL ? nil : (id) parsed_->md5sum_;
2810 @synchronized (database_) {
2811 if ([database_ era] != era_ || version_.end())
2814 return version_->InstalledSize;
2817 - (NSString *) longDescription {
2818 @synchronized (database_) {
2819 if ([database_ era] != era_ || file_.end())
2822 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2823 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2825 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2826 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2827 if ([lines count] < 2)
2830 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2831 for (size_t i(1), e([lines count]); i != e; ++i) {
2832 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2833 [trimmed addObject:trim];
2836 return [trimmed componentsJoinedByString:@"\n"];
2839 - (NSString *) shortDescription {
2840 if (parsed_ != NULL)
2841 return static_cast<NSString *>(parsed_->tagline_);
2843 @synchronized (database_) {
2844 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2845 std::string value(parser.ShortDesc());
2848 if (value.size() > 200)
2850 return [(id) CYStringCreate(value) autorelease];
2854 _profile(Package$index)
2855 CFStringRef name((CFStringRef) [self name]);
2856 if (CFStringGetLength(name) == 0)
2858 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2859 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2861 return toupper(character);
2865 - (PackageValue *) metadata {
2870 PackageValue *metadata([self metadata]);
2871 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2874 - (bool) subscribed {
2875 return [self metadata]->subscribed_;
2878 - (bool) setSubscribed:(bool)subscribed {
2879 PackageValue *metadata([self metadata]);
2880 if (metadata->subscribed_ == subscribed)
2882 metadata->subscribed_ = subscribed;
2890 - (NSString *) latest {
2894 - (NSString *) installed {
2898 - (BOOL) uninstalled {
2899 return installed_.empty();
2902 - (BOOL) upgradableAndEssential:(BOOL)essential {
2903 _profile(Package$upgradableAndEssential)
2904 pkgCache::VerIterator current(iterator_.CurrentVer());
2906 return essential && essential_;
2908 return version_ != current;
2912 - (BOOL) essential {
2917 return [database_ cache][iterator_].InstBroken();
2920 - (BOOL) unfiltered {
2921 _profile(Package$unfiltered$obsolete)
2922 if (_unlikely(obsolete_))
2926 _profile(Package$unfiltered$role)
2927 if (_unlikely(role_ > 3))
2935 if (![self unfiltered])
2940 _profile(Package$visible$section)
2941 section = [self section];
2944 _profile(Package$visible$isSectionVisible)
2945 if (!isSectionVisible(section))
2953 unsigned char current(iterator_->CurrentState);
2954 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2957 - (BOOL) halfConfigured {
2958 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2961 - (BOOL) halfInstalled {
2962 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2966 @synchronized (database_) {
2967 if ([database_ era] != era_ || iterator_.end())
2970 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2971 return state.Mode != pkgDepCache::ModeKeep;
2974 - (NSString *) mode {
2975 @synchronized (database_) {
2976 if ([database_ era] != era_ || iterator_.end())
2979 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2981 switch (state.Mode) {
2982 case pkgDepCache::ModeDelete:
2983 if ((state.iFlags & pkgDepCache::Purge) != 0)
2987 case pkgDepCache::ModeKeep:
2988 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2989 return @"REINSTALL";
2990 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2994 case pkgDepCache::ModeInstall:
2995 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2996 return @"REINSTALL";
2997 else*/ switch (state.Status) {
2999 return @"DOWNGRADE";
3005 return @"NEW_INSTALL";
3016 - (NSString *) name {
3017 return name_.empty() ? id_ : name_;
3020 - (UIImage *) icon {
3021 NSString *section = [self simpleSection];
3024 if (parsed_ != NULL)
3025 if (NSString *href = parsed_->icon_)
3026 if ([href hasPrefix:@"file:///"])
3027 icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
3028 if (icon == nil) if (section != nil)
3029 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]];
3030 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
3031 if ([dicon hasPrefix:@"file:///"])
3032 icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
3034 icon = [UIImage imageNamed:@"unknown.png"];
3038 - (NSString *) homepage {
3039 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
3042 - (NSString *) depiction {
3043 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
3046 - (MIMEAddress *) author {
3047 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
3050 - (NSString *) support {
3051 return parsed_ != NULL && !parsed_->support_.empty() ? parsed_->support_ : [[self source] supportForPackage:id_];
3054 - (NSArray *) files {
3055 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
3056 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
3059 fin.open([path UTF8String]);
3064 while (std::getline(fin, line))
3065 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
3070 - (NSString *) state {
3071 @synchronized (database_) {
3072 if ([database_ era] != era_ || file_.end())
3075 switch (iterator_->CurrentState) {
3076 case pkgCache::State::NotInstalled:
3077 return @"NotInstalled";
3078 case pkgCache::State::UnPacked:
3080 case pkgCache::State::HalfConfigured:
3081 return @"HalfConfigured";
3082 case pkgCache::State::HalfInstalled:
3083 return @"HalfInstalled";
3084 case pkgCache::State::ConfigFiles:
3085 return @"ConfigFiles";
3086 case pkgCache::State::Installed:
3087 return @"Installed";
3088 case pkgCache::State::TriggersAwaited:
3089 return @"TriggersAwaited";
3090 case pkgCache::State::TriggersPending:
3091 return @"TriggersPending";
3094 return (NSString *) [NSNull null];
3097 - (NSString *) selection {
3098 @synchronized (database_) {
3099 if ([database_ era] != era_ || file_.end())
3102 switch (iterator_->SelectedState) {
3103 case pkgCache::State::Unknown:
3105 case pkgCache::State::Install:
3107 case pkgCache::State::Hold:
3109 case pkgCache::State::DeInstall:
3110 return @"DeInstall";
3111 case pkgCache::State::Purge:
3115 return (NSString *) [NSNull null];
3118 - (NSArray *) warnings {
3119 @synchronized (database_) {
3120 if ([database_ era] != era_ || file_.end())
3123 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
3124 const char *name(iterator_.Name());
3126 size_t length(strlen(name));
3127 if (length < 2) invalid:
3128 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
3129 else for (size_t i(0); i != length; ++i)
3131 /* XXX: technically this is not allowed */
3132 (name[i] < 'A' || name[i] > 'Z') &&
3133 (name[i] < 'a' || name[i] > 'z') &&
3134 (name[i] < '0' || name[i] > '9') &&
3135 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
3138 if (strcmp(name, "cydia") != 0) {
3141 bool _private = false;
3143 bool dbstash = false;
3144 bool dsstore = false;
3146 bool repository = [[self section] isEqualToString:@"Repositories"];
3148 if (NSArray *files = [self files])
3149 for (NSString *file in files)
3150 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
3152 else if (!user && [file isEqualToString:@"/User"])
3154 else if (!_private && [file isEqualToString:@"/private"])
3156 else if (!stash && [file isEqualToString:@"/var/stash"])
3158 else if (!dbstash && [file isEqualToString:@"/var/db/stash"])
3160 else if (!dsstore && [file hasSuffix:@"/.DS_Store"])
3163 /* XXX: this is not sensitive enough. only some folders are valid. */
3164 if (cydia && !repository)
3165 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
3167 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
3169 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
3171 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
3173 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/db/stash"]];
3175 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @".DS_Store"]];
3178 return [warnings count] == 0 ? nil : warnings;
3181 - (NSArray *) applications {
3182 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
3184 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
3186 static RegEx application_r("/Applications/(.*)\\.app/Info.plist");
3187 if (NSArray *files = [self files])
3188 for (NSString *file in files)
3189 if (application_r(file)) {
3190 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
3193 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
3194 if (id == nil || [id isEqualToString:me])
3197 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
3199 display = application_r[1];
3201 NSString *bundle([file stringByDeletingLastPathComponent]);
3202 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
3203 // XXX: maybe this should check if this is really a string, not just for length
3204 if (icon == nil || ![icon respondsToSelector:@selector(length)] || [icon length] == 0)
3206 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
3208 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
3209 [applications addObject:application];
3211 [application addObject:id];
3212 [application addObject:display];
3213 [application addObject:url];
3216 return [applications count] == 0 ? nil : applications;
3219 - (Source *) source {
3220 if (source_ == nil) {
3221 @synchronized (database_) {
3222 if ([database_ era] != era_ || file_.end())
3223 source_ = (Source *) [NSNull null];
3225 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
3229 return source_ == (Source *) [NSNull null] ? nil : source_;
3232 - (time_t) upgraded {
3236 - (uint32_t) recent {
3237 return std::numeric_limits<uint32_t>::max() - upgraded_;
3244 - (BOOL) matches:(NSArray *)query {
3245 if (query == nil || [query count] == 0)
3254 string = [self name];
3255 length = [string length];
3258 for (NSString *term in query) {
3259 range = [string rangeOfString:term options:MatchCompareOptions_];
3260 if (range.location != NSNotFound)
3261 rank_ -= 6 * 1000000 / length;
3266 length = [string length];
3269 for (NSString *term in query) {
3270 range = [string rangeOfString:term options:MatchCompareOptions_];
3271 if (range.location != NSNotFound)
3272 rank_ -= 6 * 1000000 / length;
3276 string = [self shortDescription];
3277 length = [string length];
3278 NSUInteger stop(std::min<NSUInteger>(length, 200));
3281 for (NSString *term in query) {
3282 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
3283 if (range.location != NSNotFound)
3284 rank_ -= 2 * 100000;
3290 - (NSArray *) tags {
3294 - (BOOL) hasTag:(NSString *)tag {
3295 return tags_ == nil ? NO : [tags_ containsObject:tag];
3298 - (NSString *) primaryPurpose {
3299 for (NSString *tag in (NSArray *) tags_)
3300 if ([tag hasPrefix:@"purpose::"])
3301 return [tag substringFromIndex:9];
3305 - (NSArray *) purposes {
3306 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
3307 for (NSString *tag in (NSArray *) tags_)
3308 if ([tag hasPrefix:@"purpose::"])
3309 [purposes addObject:[tag substringFromIndex:9]];
3310 return [purposes count] == 0 ? nil : purposes;
3313 - (bool) isCommercial {
3314 return [self hasTag:@"cydia::commercial"];
3317 - (void) setIndex:(size_t)index {
3318 if (metadata_->index_ != index + 1)
3319 metadata_->index_ = index + 1;
3322 - (CYString &) cyname {
3323 return !transform_.empty() ? transform_ : !name_.empty() ? name_ : id_;
3326 - (uint32_t) compareBySection:(NSArray *)sections {
3327 NSString *section([self section]);
3328 for (size_t i(0), e([sections count]); i != e; ++i) {
3329 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3333 return _not(uint32_t);
3337 @synchronized (database_) {
3338 if ([database_ era] != era_ || file_.end())
3341 pkgProblemResolver *resolver = [database_ resolver];
3342 resolver->Clear(iterator_);
3344 pkgCacheFile &cache([database_ cache]);
3345 cache->SetReInstall(iterator_, false);
3346 cache->MarkKeep(iterator_, false);
3350 @synchronized (database_) {
3351 if ([database_ era] != era_ || file_.end())
3354 pkgProblemResolver *resolver = [database_ resolver];
3355 resolver->Clear(iterator_);
3356 resolver->Protect(iterator_);
3358 pkgCacheFile &cache([database_ cache]);
3359 cache->SetCandidateVersion(version_);
3360 cache->SetReInstall(iterator_, false);
3361 cache->MarkInstall(iterator_, false);
3363 pkgDepCache::StateCache &state((*cache)[iterator_]);
3364 if (!state.Install())
3365 cache->SetReInstall(iterator_, true);
3369 @synchronized (database_) {
3370 if ([database_ era] != era_ || file_.end())
3373 pkgProblemResolver *resolver = [database_ resolver];
3374 resolver->Clear(iterator_);
3375 resolver->Remove(iterator_);
3376 resolver->Protect(iterator_);
3378 pkgCacheFile &cache([database_ cache]);
3379 cache->SetReInstall(iterator_, false);
3380 cache->MarkDelete(iterator_, true);
3385 /* Section Class {{{ */
3386 @interface Section : NSObject {
3390 _H<NSString> localized_;
3393 - (NSComparisonResult) compareByLocalized:(Section *)section;
3394 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3395 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3396 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3398 - (NSString *) name;
3399 - (void) setName:(NSString *)name;
3405 - (void) addToCount;
3407 - (void) setCount:(size_t)count;
3408 - (NSString *) localized;
3412 @implementation Section
3414 - (NSComparisonResult) compareByLocalized:(Section *)section {
3415 NSString *lhs(localized_);
3416 NSString *rhs([section localized]);
3418 /*if ([lhs length] != 0 && [rhs length] != 0) {
3419 unichar lhc = [lhs characterAtIndex:0];
3420 unichar rhc = [rhs characterAtIndex:0];
3422 if (isalpha(lhc) && !isalpha(rhc))
3423 return NSOrderedAscending;
3424 else if (!isalpha(lhc) && isalpha(rhc))
3425 return NSOrderedDescending;
3428 return [lhs compare:rhs options:LaxCompareOptions_];
3431 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3432 if ((self = [self initWithName:name localize:NO]) != nil) {
3433 if (localized != nil)
3434 localized_ = localized;
3438 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3439 return [self initWithName:name row:0 localize:localize];
3442 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3443 if ((self = [super init]) != nil) {
3447 localized_ = LocalizeSection(name_);
3451 - (NSString *) name {
3455 - (void) setName:(NSString *)name {
3471 - (void) addToCount {
3475 - (void) setCount:(size_t)count {
3479 - (NSString *) localized {
3486 class CydiaLogCleaner :
3487 public pkgArchiveCleaner
3490 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3495 /* Database Implementation {{{ */
3496 @implementation Database
3498 + (Database *) sharedInstance {
3499 static _H<Database> instance;
3500 if (instance == nil)
3501 instance = [[[Database alloc] init] autorelease];
3509 - (void) releasePackages {
3513 - (bool) hasPackages {
3514 return [packages_ count] != 0;
3518 // XXX: actually implement this thing
3520 [self releasePackages];
3521 NSRecycleZone(zone_);
3525 - (void) _readCydia:(NSNumber *)fd {
3526 boost::fdistream is([fd intValue]);
3529 static RegEx finish_r("finish:([^:]*)");
3531 while (std::getline(is, line)) {
3532 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3534 const char *data(line.c_str());
3535 size_t size = line.size();
3536 lprintf("C:%s\n", data);
3538 if (finish_r(data, size)) {
3539 NSString *finish = finish_r[1];
3540 int index = [Finishes_ indexOfObject:finish];
3541 if (index != INT_MAX && index > Finish_)
3551 - (void) _readStatus:(NSNumber *)fd {
3552 boost::fdistream is([fd intValue]);
3555 static RegEx conffile_r("status: [^ ]* : conffile-prompt : (.*?) *");
3556 static RegEx pmstatus_r("([^:]*):([^:]*):([^:]*):(.*)");
3558 while (std::getline(is, line)) {
3559 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3561 const char *data(line.c_str());
3562 size_t size(line.size());
3563 lprintf("S:%s\n", data);
3565 if (conffile_r(data, size)) {
3566 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3567 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3568 } else if (strncmp(data, "status: ", 8) == 0) {
3569 // status: <package>: {unpacked,half-configured,installed}
3570 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3571 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3572 } else if (strncmp(data, "processing: ", 12) == 0) {
3573 // processing: configure: config-test
3574 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3575 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3576 } else if (pmstatus_r(data, size)) {
3577 std::string type([pmstatus_r[1] UTF8String]);
3579 NSString *package = pmstatus_r[2];
3580 if ([package isEqualToString:@"dpkg-exec"])
3583 float percent([pmstatus_r[3] floatValue]);
3584 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3586 NSString *string = pmstatus_r[4];
3588 if (type == "pmerror") {
3589 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3590 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3591 } else if (type == "pmstatus") {
3592 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3593 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3594 } else if (type == "pmconffile")
3595 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3597 lprintf("E:unknown pmstatus\n");
3599 lprintf("E:unknown status\n");
3607 - (void) _readOutput:(NSNumber *)fd {
3608 boost::fdistream is([fd intValue]);
3611 while (std::getline(is, line)) {
3612 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3614 lprintf("O:%s\n", line.c_str());
3616 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3617 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3629 - (Package *) packageWithName:(NSString *)name {
3632 @synchronized (self) {
3633 if (static_cast<pkgDepCache *>(cache_) == NULL)
3635 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]
3640 return iterator.end() ? nil : [[Package newPackageWithIterator:iterator withZone:NULL inPool:NULL database:self] autorelease];
3644 if ((self = [super init]) != nil) {
3651 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3653 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3657 _assert(pipe(fds) != -1);
3660 _config->Set("APT::Keep-Fds::", cydiafd_);
3661 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3664 detachNewThreadSelector:@selector(_readCydia:)
3666 withObject:[NSNumber numberWithInt:fds[0]]
3669 _assert(pipe(fds) != -1);
3673 detachNewThreadSelector:@selector(_readStatus:)
3675 withObject:[NSNumber numberWithInt:fds[0]]
3678 _assert(pipe(fds) != -1);
3679 _assert(dup2(fds[0], 0) != -1);
3680 _assert(close(fds[0]) != -1);
3682 input_ = fdopen(fds[1], "a");
3684 _assert(pipe(fds) != -1);
3685 _assert(dup2(fds[1], 1) != -1);
3686 _assert(close(fds[1]) != -1);
3689 detachNewThreadSelector:@selector(_readOutput:)
3691 withObject:[NSNumber numberWithInt:fds[0]]
3696 - (pkgCacheFile &) cache {
3700 - (pkgDepCache::Policy *) policy {
3704 - (pkgRecords *) records {
3708 - (pkgProblemResolver *) resolver {
3712 - (pkgAcquire &) fetcher {
3716 - (pkgSourceList &) list {
3720 - (NSArray *) packages {
3724 - (NSArray *) sources {
3728 - (Source *) sourceWithKey:(NSString *)key {
3729 for (Source *source in [self sources]) {
3730 if ([[source key] isEqualToString:key])
3735 - (bool) popErrorWithTitle:(NSString *)title {
3738 while (!_error->empty()) {
3740 bool warning(!_error->PopMessage(error));
3745 size_t size(error.size());
3746 if (size == 0 || error[size - 1] != '\n')
3748 error.resize(size - 1);
3751 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3753 static RegEx no_pubkey("GPG error:.* NO_PUBKEY .*");
3754 if (warning && no_pubkey(error.c_str()))
3757 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3763 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3764 return [self popErrorWithTitle:title] || !success;
3767 - (bool) popErrorWithTitle:(NSString *)title forReadList:(pkgSourceList &)list {
3768 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3776 if (access("/etc/apt/sources.list", F_OK) == 0)
3777 error |= [self popErrorWithTitle:title forOperation:list.ReadAppend("/etc/apt/sources.list")];
3779 std::string base("/etc/apt/sources.list.d");
3780 if (DIR *sources = opendir(base.c_str())) {
3781 while (dirent *source = readdir(sources))
3782 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)
3783 error |= [self popErrorWithTitle:title forOperation:list.ReadAppend((base + "/" + source->d_name).c_str())];
3787 error |= [self popErrorWithTitle:title forOperation:list.ReadAppend(SOURCES_LIST)];
3792 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3793 @synchronized (self) {
3796 [self releasePackages];
3799 [sourceList_ removeAllObjects];
3820 new (&pool_) CYPool();
3822 NSRecycleZone(zone_);
3823 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3825 int chk(creat("/tmp/cydia.chk", 0644));
3829 if (invocation != nil)
3830 [invocation invoke];
3832 NSString *title(UCLocalize("DATABASE"));
3834 list_ = new pkgSourceList();
3835 _profile(reloadDataWithInvocation$ReadMainList)
3836 if ([self popErrorWithTitle:title forReadList:*list_])
3840 _profile(reloadDataWithInvocation$Source$initWithMetaIndex)
3841 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3842 Source *object([[[Source alloc] initWithMetaIndex:*source forDatabase:self inPool:&pool_] autorelease]);
3843 [sourceList_ addObject:object];
3848 OpProgress progress;
3851 delock_ = GetStatusDate();
3852 _profile(reloadDataWithInvocation$pkgCacheFile)
3853 opened = cache_.Open(progress, false);
3856 // XXX: this block should probably be merged with popError: in some way
3857 while (!_error->empty()) {
3859 bool warning(!_error->PopMessage(error));
3861 lprintf("cache_.Open():[%s]\n", error.c_str());
3863 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3867 else if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3868 repair = @selector(configure);
3869 //else if (error == "The package lists or status file could not be parsed or opened.")
3870 // repair = @selector(update);
3871 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3872 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3873 // else if (error == "Malformed Status line")
3874 // else if (error == "The list of sources could not be read.")
3876 if (repair != NULL) {
3878 [delegate_ repairWithSelector:repair];
3884 } else if ([self popErrorWithTitle:title forOperation:true])
3888 unlink("/tmp/cydia.chk");
3890 now_ = [[NSDate date] timeIntervalSince1970];
3892 policy_ = new pkgDepCache::Policy();
3893 records_ = new pkgRecords(cache_);
3894 resolver_ = new pkgProblemResolver(cache_);
3895 fetcher_ = new pkgAcquire(&status_);
3898 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3899 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3903 _profile(reloadDataWithInvocation$pkgApplyStatus)
3904 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3908 if (cache_->BrokenCount() != 0) {
3909 _profile(pkgApplyStatus$pkgFixBroken)
3910 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3914 if (cache_->BrokenCount() != 0) {
3915 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3919 _profile(pkgApplyStatus$pkgMinimizeUpgrade)
3920 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3925 for (Source *object in (id) sourceList_) {
3926 metaIndex *source([object metaIndex]);
3927 std::vector<pkgIndexFile *> *indices = source->GetIndexFiles();
3928 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3929 // XXX: this could be more intelligent
3930 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3931 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3933 sourceMap_[cached->ID] = object;
3938 size_t capacity(MetaFile_->active_);
3940 capacity = 128*1024;
3944 std::vector<Package *> packages;
3945 packages.reserve(capacity);
3949 _profile(reloadDataWithInvocation$packageWithIterator)
3950 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3951 if (Package *package = [Package newPackageWithIterator:iterator withZone:zone_ inPool:&pool_ database:self]) {
3952 if (unsigned index = package.metadata->index_) {
3954 if (packages.size() == index) {
3955 packages.push_back(package);
3956 } else if (packages.size() <= index) {
3957 packages.resize(index + 1, nil);
3958 packages[index] = package;
3961 std::swap(package, packages[index]);
3969 if (last == packages.size()) {
3970 packages.push_back(package);
3973 packages[last] = package;
3978 for (; last != packages.size(); ++last)
3979 if (packages[last] == nil)
3984 for (size_t next(last + 1); last != packages.size(); ++last, ++next) {
3986 if (next == packages.size())
3988 if (packages[next] != nil)
3993 std::swap(packages[last], packages[next]);
3996 packages.resize(last);
3999 NSLog(@"lost = %zu", lost);
4001 _profile(reloadDataWithInvocation$radix$8)
4002 CYRadixSortUsingFunction(packages.data(), packages.size(), reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix), reinterpret_cast<void *>(8));
4005 _profile(reloadDataWithInvocation$radix$4)
4006 CYRadixSortUsingFunction(packages.data(), packages.size(), reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix), reinterpret_cast<void *>(4));
4009 _profile(reloadDataWithInvocation$radix$0)
4010 CYRadixSortUsingFunction(packages.data(), packages.size(), reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix), reinterpret_cast<void *>(0));
4014 _profile(reloadDataWithInvocation$insertion)
4015 CYArrayInsertionSortValues(packages.data(), packages.size(), &PackageNameCompare, NULL);
4018 packages_ = [[[NSArray alloc] initWithObjects:packages.data() count:packages.size()] autorelease];
4020 /*_profile(reloadDataWithInvocation$CFQSortArray)
4021 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);
4024 /*_profile(reloadDataWithInvocation$stdsort)
4025 std::sort(packages.begin(), packages.end(), PackageNameOrdering());
4028 /*_profile(reloadDataWithInvocation$CFArraySortValues)
4029 CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
4032 /*_profile(reloadDataWithInvocation$sortUsingFunction)
4033 [packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
4036 MetaFile_->active_ = packages.size();
4037 for (size_t index(0), count(packages.size()); index != count; ++index) {
4038 auto package(packages[index]);
4039 [package setIndex:index];
4046 @synchronized (self) {
4048 resolver_ = new pkgProblemResolver(cache_);
4050 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
4051 if (!cache_[iterator].Keep())
4052 cache_->MarkKeep(iterator, false);
4053 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
4054 cache_->SetReInstall(iterator, false);
4057 - (void) configure {
4058 NSString *dpkg = [NSString stringWithFormat:@"/usr/libexec/cydo --configure -a --status-fd %u", statusfd_];
4060 system([dpkg UTF8String]);
4065 @synchronized (self) {
4066 // XXX: I don't remember this condition
4071 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
4073 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
4075 if ([self popErrorWithTitle:title])
4079 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
4081 CydiaLogCleaner cleaner;
4082 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
4089 fetcher_->Shutdown();
4091 pkgRecords records(cache_);
4093 lock_ = new FileFd();
4094 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
4096 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
4098 if ([self popErrorWithTitle:title])
4102 if ([self popErrorWithTitle:title forReadList:list])
4105 manager_ = (_system->CreatePM(cache_));
4106 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
4113 bool substrate(RestartSubstrate_);
4114 RestartSubstrate_ = false;
4116 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
4118 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
4120 if ([self popErrorWithTitle:title forReadList:list])
4122 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
4123 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
4126 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4128 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
4130 [self popErrorWithTitle:title];
4134 bool failed = false;
4135 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
4136 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
4138 if ((*item)->Status == pkgAcquire::Item::StatIdle)
4141 std::string uri = (*item)->DescURI();
4142 std::string error = (*item)->ErrorText;
4144 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
4147 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError]);
4148 [delegate_ addProgressEventOnMainThread:event forTask:title];
4151 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4159 RestartSubstrate_ = true;
4161 if (![delock_ isEqual:GetStatusDate()]) {
4162 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("DPKG_LOCKED") ofType:kCydiaProgressEventTypeError] forTask:title];
4168 pkgPackageManager::OrderResult result(manager_->DoInstall(statusfd_));
4170 NSString *oextended(@"/var/lib/apt/extended_states");
4171 NSString *nextended(Cache("extended_states"));
4174 if (stat([nextended UTF8String], &info) != -1 && (info.st_mode & S_IFMT) == S_IFREG)
4175 system([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /bin/cp --remove-destination %@ %@", ShellEscape(nextended), ShellEscape(oextended)] UTF8String]);
4177 unlink([nextended UTF8String]);
4178 symlink([oextended UTF8String], [nextended UTF8String]);
4180 if ([self popErrorWithTitle:title])
4183 if (result == pkgPackageManager::Failed) {
4188 if (result != pkgPackageManager::Completed) {
4193 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
4195 if ([self popErrorWithTitle:title forReadList:list])
4197 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
4198 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
4201 if (![before isEqualToArray:after])
4206 return ![delock_ isEqual:GetStatusDate()];
4210 NSString *title(UCLocalize("UPGRADE"));
4211 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
4217 [self updateWithStatus:status_];
4220 - (void) updateWithStatus:(CancelStatus &)status {
4221 NSString *title(UCLocalize("REFRESHING_DATA"));
4224 if ([self popErrorWithTitle:title forReadList:list])
4228 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
4229 if ([self popErrorWithTitle:title])
4232 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4234 bool success(ListUpdate(status, list, PulseInterval_));
4235 if (status.WasCancelled())
4238 [self popErrorWithTitle:title forOperation:success];
4240 [[NSDictionary dictionaryWithObjectsAndKeys:
4241 [NSDate date], @"LastUpdate",
4242 nil] writeToFile:@ CacheState_ atomically:YES];
4245 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4248 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
4249 delegate_ = delegate;
4252 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
4253 progress_ = delegate;
4254 status_.setDelegate(delegate);
4257 - (NSObject<ProgressDelegate> *) progressDelegate {
4261 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
4262 SourceMap::const_iterator i(sourceMap_.find(file->ID));
4263 return i == sourceMap_.end() ? nil : i->second;
4266 - (void) setFetch:(bool)fetch forURI:(const char *)uri {
4267 for (Source *source in (id) sourceList_)
4268 [source setFetch:fetch forURI:uri];
4271 - (void) resetFetch {
4272 for (Source *source in (id) sourceList_)
4273 [source resetFetch];
4276 - (NSString *) mappedSectionForPointer:(const char *)section {
4277 _H<NSString> *mapped;
4279 _profile(Database$mappedSectionForPointer$Cache)
4280 mapped = §ions_[section];
4283 if (*mapped == NULL) {
4284 size_t length(strlen(section));
4285 char spaced[length + 1];
4287 _profile(Database$mappedSectionForPointer$Replace)
4288 for (size_t index(0); index != length; ++index)
4289 spaced[index] = section[index] == '_' ? ' ' : section[index];
4290 spaced[length] = '\0';
4295 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
4296 string = [NSString stringWithUTF8String:spaced];
4299 _profile(Database$mappedSectionForPointer$Map)
4300 string = [SectionMap_ objectForKey:string] ?: string;
4310 static _H<NSMutableSet> Diversions_;
4312 @interface Diversion : NSObject {
4315 _H<NSString> format_;
4320 @implementation Diversion
4322 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
4323 if ((self = [super init]) != nil) {
4324 pattern_ = [from UTF8String];
4330 - (NSString *) divert:(NSString *)url {
4331 return !pattern_(url) ? nil : pattern_->*format_;
4334 + (NSURL *) divertURL:(NSURL *)url {
4336 NSString *href([url absoluteString]);
4338 for (Diversion *diversion in (id) Diversions_)
4339 if (NSString *diverted = [diversion divert:href]) {
4341 NSLog(@"div: %@", diverted);
4343 url = [NSURL URLWithString:diverted];
4350 - (NSString *) key {
4354 - (NSUInteger) hash {
4358 - (BOOL) isEqual:(Diversion *)object {
4359 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
4364 @interface CydiaObject : NSObject {
4365 _H<CyteWebViewController> indirect_;
4366 _transient id delegate_;
4369 - (id) initWithDelegate:(CyteWebViewController *)indirect;
4375 @interface CydiaWebViewController : CyteWebViewController {
4376 _H<CydiaObject> cydia_;
4379 + (void) addDiversion:(Diversion *)diversion;
4380 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request;
4381 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia;
4382 - (void) setDelegate:(id)delegate;
4386 /* Web Scripting {{{ */
4387 @implementation CydiaObject
4389 - (id) initWithDelegate:(CyteWebViewController *)indirect {
4390 if ((self = [super init]) != nil) {
4391 indirect_ = indirect;
4395 - (void) setDelegate:(id)delegate {
4396 delegate_ = delegate;
4399 + (NSArray *) _attributeKeys {
4400 return [NSArray arrayWithObjects:
4405 @"coreFoundationVersionNumber",
4421 - (NSArray *) attributeKeys {
4422 return [[self class] _attributeKeys];
4425 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4426 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4429 - (NSString *) version {
4433 - (unsigned) bittage {
4435 #elif defined(__arm64__)
4437 #elif defined(__arm__)
4444 - (NSString *) build {
4448 - (NSString *) coreFoundationVersionNumber {
4449 return [NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber];
4452 - (NSString *) device {
4453 return UniqueIdentifier();
4456 - (NSString *) firmware {
4457 return [[UIDevice currentDevice] systemVersion];
4460 - (NSString *) hostname {
4461 return [[UIDevice currentDevice] name];
4464 - (NSString *) idiom {
4465 return (id) Idiom_ ?: [NSNull null];
4468 - (NSArray *) cells {
4469 auto *$_CTServerConnectionCreate(reinterpret_cast<id (*)(void *, void *, void *)>(dlsym(RTLD_DEFAULT, "_CTServerConnectionCreate")));
4470 if ($_CTServerConnectionCreate == NULL)
4473 struct CTResult { int flag; int error; };
4474 auto *$_CTServerConnectionCellMonitorCopyCellInfo(reinterpret_cast<CTResult (*)(CFTypeRef, void *, CFArrayRef *)>(dlsym(RTLD_DEFAULT, "_CTServerConnectionCellMonitorCopyCellInfo")));
4475 if ($_CTServerConnectionCellMonitorCopyCellInfo == NULL)
4478 _H<const void> connection($_CTServerConnectionCreate(NULL, NULL, NULL), true);
4479 if (connection == nil)
4483 CFArrayRef cells(NULL);
4484 auto result($_CTServerConnectionCellMonitorCopyCellInfo(connection, &count, &cells));
4485 if (result.flag != 0)
4488 return [(NSArray *) cells autorelease];
4491 - (NSString *) mcc {
4492 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode")))
4493 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault) autorelease];
4497 - (NSString *) mnc {
4498 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberNetworkCode")))
4499 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault) autorelease];
4503 - (NSString *) operator {
4504 if (CFStringRef (*$CTRegistrationCopyOperatorName)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTRegistrationCopyOperatorName")))
4505 return [(NSString *) (*$CTRegistrationCopyOperatorName)(kCFAllocatorDefault) autorelease];
4509 - (NSString *) bbsnum {
4510 return (id) BBSNum_ ?: [NSNull null];
4513 - (NSString *) ecid {
4514 return (id) ChipID_ ?: [NSNull null];
4517 - (NSString *) serial {
4518 return SerialNumber_;
4521 - (NSString *) role {
4522 return (id) [NSNull null];
4525 - (NSString *) model {
4526 return [NSString stringWithUTF8String:Machine_];
4529 + (NSString *) webScriptNameForSelector:(SEL)selector {
4531 else if (selector == @selector(addBridgedHost:))
4532 return @"addBridgedHost";
4533 else if (selector == @selector(addInsecureHost:))
4534 return @"addInsecureHost";
4535 else if (selector == @selector(addInternalRedirect::))
4536 return @"addInternalRedirect";
4537 else if (selector == @selector(addSource:::))
4538 return @"addSource";
4539 else if (selector == @selector(addTrivialSource:))
4540 return @"addTrivialSource";
4541 else if (selector == @selector(close))
4543 else if (selector == @selector(du:))
4545 else if (selector == @selector(stringWithFormat:arguments:))
4547 else if (selector == @selector(getAllSources))
4548 return @"getAllSources";
4549 else if (selector == @selector(getApplicationInfo:value:))
4550 return @"getApplicationInfoValue";
4551 else if (selector == @selector(getDisplayIdentifiers))
4552 return @"getDisplayIdentifiers";
4553 else if (selector == @selector(getLocalizedNameForDisplayIdentifier:))
4554 return @"getLocalizedNameForDisplayIdentifier";
4555 else if (selector == @selector(getKernelNumber:))
4556 return @"getKernelNumber";
4557 else if (selector == @selector(getKernelString:))
4558 return @"getKernelString";
4559 else if (selector == @selector(getInstalledPackages))
4560 return @"getInstalledPackages";
4561 else if (selector == @selector(getIORegistryEntry::))
4562 return @"getIORegistryEntry";
4563 else if (selector == @selector(getLocaleIdentifier))
4564 return @"getLocaleIdentifier";
4565 else if (selector == @selector(getPreferredLanguages))
4566 return @"getPreferredLanguages";
4567 else if (selector == @selector(getPackageById:))
4568 return @"getPackageById";
4569 else if (selector == @selector(getMetadataKeys))
4570 return @"getMetadataKeys";
4571 else if (selector == @selector(getMetadataValue:))
4572 return @"getMetadataValue";
4573 else if (selector == @selector(getSessionValue:))
4574 return @"getSessionValue";
4575 else if (selector == @selector(installPackages:))
4576 return @"installPackages";
4577 else if (selector == @selector(isReachable:))
4578 return @"isReachable";
4579 else if (selector == @selector(localizedStringForKey:value:table:))
4581 else if (selector == @selector(popViewController:))
4582 return @"popViewController";
4583 else if (selector == @selector(refreshSources))
4584 return @"refreshSources";
4585 else if (selector == @selector(registerFrame:))
4586 return @"registerFrame";
4587 else if (selector == @selector(removeButton))
4588 return @"removeButton";
4589 else if (selector == @selector(saveConfig))
4590 return @"saveConfig";
4591 else if (selector == @selector(setMetadataValue::))
4592 return @"setMetadataValue";
4593 else if (selector == @selector(setSessionValue::))
4594 return @"setSessionValue";
4595 else if (selector == @selector(substitutePackageNames:))
4596 return @"substitutePackageNames";
4597 else if (selector == @selector(scrollToBottom:))
4598 return @"scrollToBottom";
4599 else if (selector == @selector(setAllowsNavigationAction:))
4600 return @"setAllowsNavigationAction";
4601 else if (selector == @selector(setBadgeValue:))
4602 return @"setBadgeValue";
4603 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4604 return @"setButtonImage";
4605 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4606 return @"setButtonTitle";
4607 else if (selector == @selector(setHidesBackButton:))
4608 return @"setHidesBackButton";
4609 else if (selector == @selector(setHidesNavigationBar:))
4610 return @"setHidesNavigationBar";
4611 else if (selector == @selector(setNavigationBarStyle:))
4612 return @"setNavigationBarStyle";
4613 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4614 return @"setNavigationBarTintColor";
4615 else if (selector == @selector(setPasteboardString:))
4616 return @"setPasteboardString";
4617 else if (selector == @selector(setPasteboardURL:))
4618 return @"setPasteboardURL";
4619 else if (selector == @selector(setScrollAlwaysBounceVertical:))
4620 return @"setScrollAlwaysBounceVertical";
4621 else if (selector == @selector(setScrollIndicatorStyle:))
4622 return @"setScrollIndicatorStyle";
4623 else if (selector == @selector(setToken:))
4625 else if (selector == @selector(setViewportWidth:))
4626 return @"setViewportWidth";
4627 else if (selector == @selector(statfs:))
4629 else if (selector == @selector(supports:))
4631 else if (selector == @selector(unload))
4637 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4638 return [self webScriptNameForSelector:selector] == nil;
4641 - (BOOL) supports:(NSString *)feature {
4642 return [feature isEqualToString:@"window.open"];
4646 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4649 - (void) setScrollAlwaysBounceVertical:(NSNumber *)value {
4650 [indirect_ performSelectorOnMainThread:@selector(setScrollAlwaysBounceVerticalNumber:) withObject:value waitUntilDone:NO];
4653 - (void) setScrollIndicatorStyle:(NSString *)style {
4654 [indirect_ performSelectorOnMainThread:@selector(setScrollIndicatorStyleWithName:) withObject:style waitUntilDone:NO];
4657 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4658 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4661 - (NSDictionary *) getApplicationInfo:(NSString *)display value:(NSString *)key {
4663 if (SBBundlePathForDisplayIdentifier(SBSSpringBoardServerPort(), [display UTF8String], path) != 0)
4664 return (id) [NSNull null];
4665 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:[[NSString stringWithUTF8String:path] stringByAppendingString:@"/Info.plist"]]);
4667 return (id) [NSNull null];
4668 return [info objectForKey:key];
4671 - (NSArray *) getDisplayIdentifiers {
4672 return SBSCopyApplicationDisplayIdentifiers(false, false);
4675 - (NSString *) getLocalizedNameForDisplayIdentifier:(NSString *)identifier {
4676 return [SBSCopyLocalizedApplicationNameForDisplayIdentifier(identifier) autorelease] ?: (id) [NSNull null];
4679 - (NSNumber *) getKernelNumber:(NSString *)name {
4680 const char *string([name UTF8String]);
4683 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4684 return (id) [NSNull null];
4686 if (size != sizeof(int))
4687 return (id) [NSNull null];
4690 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4691 return (id) [NSNull null];
4693 return [NSNumber numberWithInt:value];
4696 - (NSString *) getKernelString:(NSString *)name {
4697 const char *string([name UTF8String]);
4700 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4701 return (id) [NSNull null];
4703 char value[size + 1];
4704 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4705 return (id) [NSNull null];
4707 // XXX: just in case you request something ludicrous
4710 return [NSString stringWithCString:value];
4713 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4714 NSObject *value(CYIOGetValue([path UTF8String], entry));
4717 if ([value isKindOfClass:[NSData class]])
4718 value = CYHex((NSData *) value);
4723 - (NSArray *) getMetadataKeys {
4724 @synchronized (Values_) {
4725 return [Values_ allKeys];
4728 - (void) registerFrame:(DOMHTMLIFrameElement *)iframe {
4729 WebFrame *frame([iframe contentFrame]);
4730 [indirect_ registerFrame:frame];
4733 - (id) getMetadataValue:(NSString *)key {
4734 @synchronized (Values_) {
4735 return [Values_ objectForKey:key];
4738 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4739 @synchronized (Values_) {
4740 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4741 [Values_ removeObjectForKey:key];
4743 [Values_ setObject:value forKey:key];
4746 - (id) getSessionValue:(NSString *)key {
4747 @synchronized (SessionData_) {
4748 return [SessionData_ objectForKey:key];
4751 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4752 @synchronized (SessionData_) {
4753 if (value == (id) [WebUndefined undefined])
4754 [SessionData_ removeObjectForKey:key];
4756 [SessionData_ setObject:value forKey:key];
4759 - (void) addBridgedHost:(NSString *)host {
4760 @synchronized (HostConfig_) {
4761 [BridgedHosts_ addObject:host];
4764 - (void) addInsecureHost:(NSString *)host {
4765 @synchronized (HostConfig_) {
4766 [InsecureHosts_ addObject:host];
4769 - (void) popViewController:(NSNumber *)value {
4770 if (value == (id) [WebUndefined undefined])
4771 value = [NSNumber numberWithBool:YES];
4772 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4775 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4776 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4778 for (NSString *section in sections)
4779 [array addObject:section];
4781 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4784 distribution, @"Distribution",
4786 nil] waitUntilDone:NO];
4789 - (BOOL) addTrivialSource:(NSString *)href {
4790 href = VerifySource(href);
4793 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4797 - (void) refreshSources {
4798 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4801 - (void) saveConfig {
4802 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4805 - (NSArray *) getAllSources {
4806 return [[Database sharedInstance] sources];
4809 - (NSArray *) getInstalledPackages {
4810 Database *database([Database sharedInstance]);
4811 @synchronized (database) {
4812 NSArray *packages([database packages]);
4813 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4814 for (Package *package in packages)
4815 if (![package uninstalled])
4816 [installed addObject:package];
4820 - (Package *) getPackageById:(NSString *)id {
4821 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4825 return (Package *) [NSNull null];
4828 - (NSString *) getLocaleIdentifier {
4829 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4832 - (NSArray *) getPreferredLanguages {
4836 - (NSArray *) statfs:(NSString *)path {
4839 if (path == nil || statfs([path UTF8String], &stat) == -1)
4842 return [NSArray arrayWithObjects:
4843 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4844 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4845 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4849 - (NSNumber *) du:(NSString *)path {
4850 NSNumber *value(nil);
4852 FILE *du(popen([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /usr/libexec/cydia/du -ks %@", ShellEscape(path)] UTF8String], "r"));
4855 while (fgets(line, sizeof(line), du) != NULL) {
4856 size_t length(strlen(line));
4857 while (length != 0 && line[length - 1] == '\n')
4858 line[--length] = '\0';
4859 if (char *tab = strchr(line, '\t')) {
4861 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4871 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4874 - (NSNumber *) isReachable:(NSString *)name {
4875 return [NSNumber numberWithBool:IsReachable([name UTF8String])];
4878 - (void) installPackages:(NSArray *)packages {
4879 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4882 - (NSString *) substitutePackageNames:(NSString *)message {
4883 auto database([Database sharedInstance]);
4885 // XXX: this check is less racy than you'd expect, but this entire concept is a little awkward
4886 if (![database hasPackages])
4889 NSMutableArray *words([[[message componentsSeparatedByString:@" "] mutableCopy] autorelease]);
4890 for (size_t i(0), e([words count]); i != e; ++i) {
4891 NSString *word([words objectAtIndex:i]);
4892 if (Package *package = [database packageWithName:word])
4893 [words replaceObjectAtIndex:i withObject:[package name]];
4896 return [words componentsJoinedByString:@" "];
4899 - (void) removeButton {
4900 [indirect_ removeButton];
4903 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4904 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4907 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4908 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4911 - (void) setBadgeValue:(id)value {
4912 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4915 - (void) setAllowsNavigationAction:(NSString *)value {
4916 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4919 - (void) setHidesBackButton:(NSString *)value {
4920 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4923 - (void) setHidesNavigationBar:(NSString *)value {
4924 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4927 - (void) setNavigationBarStyle:(NSString *)value {
4928 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4931 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4932 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4933 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4934 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4937 - (void) setPasteboardString:(NSString *)value {
4938 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4941 - (void) setPasteboardURL:(NSString *)value {
4942 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4945 - (void) setToken:(NSString *)token {
4946 // XXX: the website expects this :/
4949 - (void) scrollToBottom:(NSNumber *)animated {
4950 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4953 - (void) setViewportWidth:(float)width {
4954 [indirect_ setViewportWidthOnMainThread:width];
4957 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4958 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4959 unsigned count([arguments count]);
4961 for (unsigned i(0); i != count; ++i)
4962 values[i] = [arguments objectAtIndex:i];
4963 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4966 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4967 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4969 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4971 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4977 @interface NSURL (CydiaSecure)
4980 @implementation NSURL (CydiaSecure)
4982 - (bool) isCydiaSecure {
4983 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4986 @synchronized (HostConfig_) {
4987 if ([InsecureHosts_ containsObject:[self host]])
4996 /* Cydia Browser Controller {{{ */
4997 @implementation CydiaWebViewController
4999 - (NSURL *) navigationURL {
5000 if (NSURLRequest *request = self.request)
5001 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request URL] absoluteString]]];
5006 + (void) _initialize {
5007 [super _initialize];
5009 Diversions_ = [NSMutableSet setWithCapacity:0];
5012 + (void) addDiversion:(Diversion *)diversion {
5013 [Diversions_ addObject:diversion];
5016 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5017 [super webView:view didClearWindowObject:window forFrame:frame];
5018 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
5021 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia {
5022 WebDataSource *source([frame dataSource]);
5023 NSURLResponse *response([source response]);
5024 NSURL *url([response URL]);
5025 NSString *scheme([[url scheme] lowercaseString]);
5027 bool bridged(false);
5029 @synchronized (HostConfig_) {
5030 if ([scheme isEqualToString:@"file"])
5032 else if ([scheme isEqualToString:@"https"])
5033 if ([BridgedHosts_ containsObject:[url host]])
5038 [window setValue:cydia forKey:@"cydia"];
5041 - (void) _setupMail:(MFMailComposeViewController *)controller {
5042 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
5044 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
5045 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
5048 - (NSURL *) URLWithURL:(NSURL *)url {
5049 return [Diversion divertURL:url];
5052 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
5053 return [CydiaWebViewController requestWithHeaders:[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
5056 - (NSURLRequest *) webThreadWebView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
5057 return [CydiaWebViewController requestWithHeaders:[super webThreadWebView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
5060 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request {
5061 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
5063 NSURL *url([copy URL]);
5064 NSString *href([url absoluteString]);
5065 NSString *host([url host]);
5067 if ([href hasPrefix:@"https://cydia.saurik.com/TSS/"]) {
5068 if (NSString *agent = [copy valueForHTTPHeaderField:@"X-User-Agent"]) {
5069 [copy setValue:agent forHTTPHeaderField:@"User-Agent"];
5070 [copy setValue:nil forHTTPHeaderField:@"X-User-Agent"];
5073 [copy setValue:nil forHTTPHeaderField:@"Referer"];
5074 [copy setValue:nil forHTTPHeaderField:@"Origin"];
5076 [copy setURL:[NSURL URLWithString:[@"http://gs.apple.com/TSS/" stringByAppendingString:[href substringFromIndex:29]]]];
5080 if ([copy valueForHTTPHeaderField:@"X-Cydia-Cf"] == nil)
5081 [copy setValue:[NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber] forHTTPHeaderField:@"X-Cydia-Cf"];
5082 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
5083 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
5085 bool bridged; @synchronized (HostConfig_) {
5086 bridged = [BridgedHosts_ containsObject:host];
5089 if ([url isCydiaSecure] && bridged && UniqueID_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Id"] == nil)
5090 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
5095 - (void) setDelegate:(id)delegate {
5096 [super setDelegate:delegate];
5097 [cydia_ setDelegate:delegate];
5100 - (NSString *) applicationNameForUserAgent {
5105 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
5106 cydia_ = [[[CydiaObject alloc] initWithDelegate:self.indirect] autorelease];
5112 @interface AppCacheController : CydiaWebViewController {
5117 @implementation AppCacheController
5119 - (void) didReceiveMemoryWarning {
5120 // XXX: this doesn't work
5123 - (bool) retainsNetworkActivityIndicator {
5131 @interface NSObject (CydiaScript)
5132 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
5135 @implementation NSObject (CydiaScript)
5137 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5143 @implementation NSArray (CydiaScript)
5145 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5146 WebScriptObject *object([context evaluateWebScript:@"[]"]);
5147 for (size_t i(0), e([self count]); i != e; ++i)
5148 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
5154 @implementation NSDictionary (CydiaScript)
5156 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5157 WebScriptObject *object([context evaluateWebScript:@"({})"]);
5159 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
5166 /* Confirmation Controller {{{ */
5167 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
5168 if (!iterator.end())
5169 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
5170 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
5172 pkgCache::PkgIterator package(dep.TargetPkg());
5175 if (strcmp(package.Name(), "mobilesubstrate") == 0)
5182 @protocol ConfirmationControllerDelegate
5183 - (void) cancelAndClear:(bool)clear;
5184 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
5188 @interface ConfirmationController : CydiaWebViewController {
5189 _transient Database *database_;
5191 _H<UIAlertView> essential_;
5193 _H<NSDictionary> changes_;
5194 _H<NSMutableArray> issues_;
5195 _H<NSDictionary> sizes_;
5200 - (id) initWithDatabase:(Database *)database;
5204 @implementation ConfirmationController
5208 RestartSubstrate_ = true;
5209 [self.delegate confirmWithNavigationController:[self navigationController]];
5212 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
5213 NSString *context([alert context]);
5215 if ([context isEqualToString:@"remove"]) {
5216 if (button == [alert cancelButtonIndex])
5218 else if (button == [alert firstOtherButtonIndex]) {
5219 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
5222 [alert dismissWithClickedButtonIndex:-1 animated:YES];
5223 } else if ([context isEqualToString:@"unable"]) {
5224 [self dismissModalViewControllerAnimated:YES];
5225 [alert dismissWithClickedButtonIndex:-1 animated:YES];
5227 [super alertView:alert clickedButtonAtIndex:button];
5231 - (void) _doContinue {
5232 [self.delegate cancelAndClear:NO];
5233 [self dismissModalViewControllerAnimated:YES];
5236 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
5237 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
5241 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5242 [super webView:view didClearWindowObject:window forFrame:frame];
5244 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
5245 (id) changes_, @"changes",
5246 (id) issues_, @"issues",
5247 (id) sizes_, @"sizes",
5249 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
5252 - (id) initWithDatabase:(Database *)database {
5253 if ((self = [super init]) != nil) {
5254 database_ = database;
5256 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
5257 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
5258 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
5259 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
5260 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
5264 pkgCacheFile &cache([database_ cache]);
5265 NSArray *packages([database_ packages]);
5266 pkgDepCache::Policy *policy([database_ policy]);
5268 issues_ = [NSMutableArray arrayWithCapacity:4];
5270 for (Package *package in packages) {
5271 pkgCache::PkgIterator iterator([package iterator]);
5272 NSString *name([package id]);
5274 if ([package broken]) {
5275 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
5277 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5279 reasons, @"reasons",
5282 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
5286 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
5287 pkgCache::DepIterator start;
5288 pkgCache::DepIterator end;
5289 dep.GlobOr(start, end); // ++dep
5291 if (!cache->IsImportantDep(end))
5293 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
5296 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
5298 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5299 [NSString stringWithUTF8String:start.DepType()], @"relationship",
5300 clauses, @"clauses",
5304 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
5306 pkgCache::PkgIterator target(start.TargetPkg());
5307 if (target->ProvidesList != 0)
5308 reason = @"missing";
5310 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
5312 reason = @"installed";
5313 installed = [NSString stringWithUTF8String:ver.VerStr()];
5314 } else if (!cache[target].CandidateVerIter(cache).end())
5315 reason = @"uninstalled";
5316 else if (target->ProvidesList == 0)
5317 reason = @"uninstallable";
5319 reason = @"virtual";
5322 NSDictionary *version(start.TargetVer() == 0 ? (NSDictionary *) [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
5323 [NSString stringWithUTF8String:start.CompType()], @"operator",
5324 [NSString stringWithUTF8String:start.TargetVer()], @"value",
5327 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5328 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
5329 version, @"version",
5331 installed, @"installed",
5334 // yes, seriously. (wtf?)
5342 pkgDepCache::StateCache &state(cache[iterator]);
5344 static RegEx special_r("(firmware|gsc\\..*|cy\\+.*)");
5346 if (state.NewInstall())
5347 [installs addObject:name];
5348 // XXX: else if (state.Install())
5349 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
5350 [reinstalls addObject:name];
5351 // XXX: move before previous if
5352 else if (state.Upgrade())
5353 [upgrades addObject:name];
5354 else if (state.Downgrade())
5355 [downgrades addObject:name];
5356 else if (!state.Delete())
5357 // XXX: _assert(state.Keep());
5359 else if (special_r(name))
5360 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5361 [NSNull null], @"package",
5362 [NSArray arrayWithObjects:
5363 [NSDictionary dictionaryWithObjectsAndKeys:
5364 @"Conflicts", @"relationship",
5365 [NSArray arrayWithObjects:
5366 [NSDictionary dictionaryWithObjectsAndKeys:
5368 [NSNull null], @"version",
5369 @"installed", @"reason",
5376 if ([package essential])
5378 [removes addObject:name];
5381 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
5382 substrate_ |= DepSubstrate(iterator.CurrentVer());
5387 else if (Advanced_) {
5388 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
5390 essential_ = [[[UIAlertView alloc]
5391 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
5392 message:UCLocalize("REMOVING_ESSENTIALS_EX")
5394 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
5396 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
5400 [essential_ setContext:@"remove"];
5401 [essential_ setNumberOfRows:2];
5403 essential_ = [[[UIAlertView alloc]
5404 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
5405 message:UCLocalize("UNABLE_TO_COMPLY_EX")
5407 cancelButtonTitle:UCLocalize("OKAY")
5408 otherButtonTitles:nil
5411 [essential_ setContext:@"unable"];
5414 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5415 installs, @"installs",
5416 reinstalls, @"reinstalls",
5417 upgrades, @"upgrades",
5418 downgrades, @"downgrades",
5419 removes, @"removes",
5422 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5423 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
5424 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
5427 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
5431 - (UIBarButtonItem *) leftButton {
5432 return [[[UIBarButtonItem alloc]
5433 initWithTitle:UCLocalize("CANCEL")
5434 style:UIBarButtonItemStylePlain
5436 action:@selector(cancelButtonClicked)
5441 - (void) applyRightButton {
5442 if ([issues_ count] == 0 && ![self isLoading])
5443 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
5444 initWithTitle:UCLocalize("CONFIRM")
5445 style:UIBarButtonItemStyleDone
5447 action:@selector(confirmButtonClicked)
5450 [[self navigationItem] setRightBarButtonItem:nil];
5454 - (void) cancelButtonClicked {
5455 [self.delegate cancelAndClear:YES];
5456 [self dismissModalViewControllerAnimated:YES];
5460 - (void) confirmButtonClicked {
5461 if (essential_ != nil)
5471 /* Progress Data {{{ */
5472 @interface CydiaProgressData : NSObject {
5473 _transient id delegate_;
5482 _H<NSMutableArray> events_;
5483 _H<NSString> title_;
5485 _H<NSString> status_;
5486 _H<NSString> finish_;
5491 @implementation CydiaProgressData
5493 + (NSArray *) _attributeKeys {
5494 return [NSArray arrayWithObjects:
5506 - (NSArray *) attributeKeys {
5507 return [[self class] _attributeKeys];
5510 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5511 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5515 if ((self = [super init]) != nil) {
5516 events_ = [NSMutableArray arrayWithCapacity:32];
5524 - (void) setDelegate:(id)delegate {
5525 delegate_ = delegate;
5528 - (void) setPercent:(float)value {
5532 - (NSNumber *) percent {
5533 return [NSNumber numberWithFloat:percent_];
5536 - (void) setCurrent:(float)value {
5540 - (NSNumber *) current {
5541 return [NSNumber numberWithFloat:current_];
5544 - (void) setTotal:(float)value {
5548 - (NSNumber *) total {
5549 return [NSNumber numberWithFloat:total_];
5552 - (void) setSpeed:(float)value {
5556 - (NSNumber *) speed {
5557 return [NSNumber numberWithFloat:speed_];
5560 - (NSArray *) events {
5564 - (void) removeAllEvents {
5565 [events_ removeAllObjects];
5568 - (void) addEvent:(CydiaProgressEvent *)event {
5569 [events_ addObject:event];
5572 - (void) setTitle:(NSString *)text {
5576 - (NSString *) title {
5580 - (void) setFinish:(NSString *)text {
5584 - (NSString *) finish {
5585 return (id) finish_ ?: [NSNull null];
5588 - (void) setRunning:(bool)running {
5592 - (NSNumber *) running {
5593 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5598 /* Progress Controller {{{ */
5599 @interface ProgressController : CydiaWebViewController <
5602 _transient Database *database_;
5603 _H<CydiaProgressData, 1> progress_;
5607 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5609 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5611 - (void) setTitle:(NSString *)title;
5612 - (void) setCancellable:(bool)cancellable;
5616 @implementation ProgressController
5619 [database_ setProgressDelegate:nil];
5623 - (UIBarButtonItem *) leftButton {
5624 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5625 initWithTitle:UCLocalize("CANCEL")
5626 style:UIBarButtonItemStylePlain
5628 action:@selector(cancel)
5629 ] autorelease] : nil;
5632 - (void) updateCancel {
5633 [super applyLeftButton];
5636 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5637 if ((self = [super init]) != nil) {
5638 database_ = database;
5639 self.delegate = delegate;
5641 [database_ setProgressDelegate:self];
5643 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5644 [progress_ setDelegate:self];
5646 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5648 [self setPageColor:[UIColor blackColor]];
5650 [[self navigationItem] setHidesBackButton:YES];
5652 [self updateCancel];
5656 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5657 [super webView:view didClearWindowObject:window forFrame:frame];
5658 [window setValue:progress_ forKey:@"cydiaProgress"];
5661 - (void) updateProgress {
5662 [self dispatchEvent:@"CydiaProgressUpdate"];
5665 - (void) viewWillAppear:(BOOL)animated {
5666 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5667 [super viewWillAppear:animated];
5671 UpdateExternalStatus(0);
5674 [self.delegate saveState];
5678 [self.delegate returnToCydia];
5682 [self.delegate terminateWithSuccess];
5683 /*if ([self.delegate respondsToSelector:@selector(suspendWithAnimation:)])
5684 [self.delegate suspendWithAnimation:YES];
5686 [self.delegate suspend];*/
5698 UIProgressHUD *hud([self.delegate addProgressHUD]);
5699 [hud setText:UCLocalize("LOADING")];
5700 [self.delegate performSelector:@selector(reloadSpringBoard) withObject:nil afterDelay:0.5];
5706 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5707 SBReboot(SBSSpringBoardServerPort());
5709 reboot2(RB_AUTOBOOT);
5716 - (void) setTitle:(NSString *)title {
5717 [progress_ setTitle:title];
5718 [self updateProgress];
5721 - (UIBarButtonItem *) rightButton {
5722 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5723 initWithTitle:UCLocalize("CLOSE")
5724 style:UIBarButtonItemStylePlain
5726 action:@selector(close)
5730 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5731 UpdateExternalStatus(1);
5733 [progress_ setRunning:true];
5734 [self setTitle:title];
5735 // implicit updateProgress
5737 SHA1SumValue notifyconf; {
5739 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5742 MMap mmap(file, MMap::ReadOnly);
5744 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5745 notifyconf = sha1.Result();
5749 SHA1SumValue springlist; {
5751 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5754 MMap mmap(file, MMap::ReadOnly);
5756 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5757 springlist = sha1.Result();
5761 if (invocation != nil) {
5762 [invocation yieldToSelector:@selector(invoke)];
5763 [self setTitle:@"COMPLETE"];
5768 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5771 MMap mmap(file, MMap::ReadOnly);
5773 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5774 if (!(notifyconf == sha1.Result()))
5781 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5784 MMap mmap(file, MMap::ReadOnly);
5786 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5787 if (!(springlist == sha1.Result()))
5793 if (RestartSubstrate_)
5797 RestartSubstrate_ = false;
5800 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5801 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5802 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5803 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5804 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5807 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5809 [progress_ setRunning:false];
5810 [self updateProgress];
5812 [self applyRightButton];
5815 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5816 [progress_ addEvent:event];
5817 [self updateProgress];
5820 - (bool) isProgressCancelled {
5821 return cancel_ == 2;
5826 [self updateCancel];
5829 - (void) setCancellable:(bool)cancellable {
5830 unsigned cancel(cancel_);
5834 else if (cancel_ == 0)
5837 if (cancel != cancel_)
5838 [self updateCancel];
5841 - (void) setProgressCancellable:(NSNumber *)cancellable {
5842 [self setCancellable:[cancellable boolValue]];
5845 - (void) setProgressPercent:(NSNumber *)percent {
5846 [progress_ setPercent:[percent floatValue]];
5847 [self updateProgress];
5850 - (void) setProgressStatus:(NSDictionary *)status {
5851 if (status == nil) {
5852 [progress_ setCurrent:0];
5853 [progress_ setTotal:0];
5854 [progress_ setSpeed:0];
5856 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5858 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5859 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5860 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5863 [self updateProgress];
5869 /* Package Cell {{{ */
5870 @interface PackageCell : CyteTableViewCell <
5871 CyteTableViewCellDelegate
5875 _H<NSString> description_;
5877 _H<NSString> source_;
5879 _H<UIImage> placard_;
5883 - (PackageCell *) init;
5884 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5886 - (void) drawContentRect:(CGRect)rect;
5890 @implementation PackageCell
5892 - (PackageCell *) init {
5893 CGRect frame(CGRectMake(0, 0, 320, 74));
5894 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5895 UIView *content([self contentView]);
5896 CGRect bounds([content bounds]);
5898 self.content = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5899 [self.content setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5900 [content addSubview:self.content];
5902 [self.content setDelegate:self];
5903 [self.content setOpaque:YES];
5907 - (NSString *) accessibilityLabel {
5911 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5912 summarized_ = summary;
5922 [self.content setBackgroundColor:[UIColor whiteColor]];
5926 Source *source = [package source];
5928 icon_ = [package icon];
5930 if (NSString *name = [package name])
5931 name_ = [NSString stringWithString:name];
5933 if (NSString *description = [package shortDescription])
5934 description_ = [NSString stringWithString:description];
5936 commercial_ = [package isCommercial];
5938 NSString *label = nil;
5939 bool trusted = false;
5941 if (source != nil) {
5942 label = [source label];
5943 trusted = [source trusted];
5944 } else if ([[package id] isEqualToString:@"firmware"])
5945 label = UCLocalize("APPLE");
5947 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5949 NSString *from(label);
5951 NSString *section = [package simpleSection];
5952 if (section != nil && ![section isEqualToString:label]) {
5953 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5954 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5957 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5959 if (NSString *purpose = [package primaryPurpose])
5960 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5965 if (NSString *mode = [package mode]) {
5966 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5967 color = RemovingColor_;
5968 placard = @"removing";
5970 color = InstallingColor_;
5971 placard = @"installing";
5974 color = [UIColor whiteColor];
5976 if ([package installed] != nil)
5977 placard = @"installed";
5982 [self.content setBackgroundColor:color];
5985 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5988 [self setNeedsDisplay];
5989 [self.content setNeedsDisplay];
5992 - (void) drawSummaryContentRect:(CGRect)rect {
5993 bool highlighted(self.highlighted);
5994 float width([self bounds].size.width);
5998 rect.size = [(UIImage *) icon_ size];
6000 while (rect.size.width > 16 || rect.size.height > 16) {
6001 rect.size.width /= 2;
6002 rect.size.height /= 2;
6005 rect.origin.x = 19 - rect.size.width / 2;
6006 rect.origin.y = 19 - rect.size.height / 2;
6008 [icon_ drawInRect:Retina(rect)];
6011 if (badge_ != nil) {
6013 rect.size = [(UIImage *) badge_ size];
6015 rect.size.width /= 4;
6016 rect.size.height /= 4;
6018 rect.origin.x = 25 - rect.size.width / 2;
6019 rect.origin.y = 25 - rect.size.height / 2;
6021 [badge_ drawInRect:Retina(rect)];
6024 if (highlighted && kCFCoreFoundationVersionNumber < 800)
6028 UISetColor(commercial_ ? Purple_ : Black_);
6029 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
6031 if (placard_ != nil)
6032 [placard_ drawAtPoint:CGPointMake(width - 52, 11)];
6035 - (void) drawNormalContentRect:(CGRect)rect {
6036 bool highlighted(self.highlighted);
6037 float width([self bounds].size.width);
6041 rect.size = [(UIImage *) icon_ size];
6043 while (rect.size.width > 32 || rect.size.height > 32) {
6044 rect.size.width /= 2;
6045 rect.size.height /= 2;
6048 rect.origin.x = 25 - rect.size.width / 2;
6049 rect.origin.y = 25 - rect.size.height / 2;
6051 [icon_ drawInRect:Retina(rect)];
6054 if (badge_ != nil) {
6056 rect.size = [(UIImage *) badge_ size];
6058 rect.size.width /= 2;
6059 rect.size.height /= 2;
6061 rect.origin.x = 36 - rect.size.width / 2;
6062 rect.origin.y = 36 - rect.size.height / 2;
6064 [badge_ drawInRect:Retina(rect)];
6067 if (highlighted && kCFCoreFoundationVersionNumber < 800)
6071 UISetColor(commercial_ ? Purple_ : Black_);
6072 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
6073 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
6076 UISetColor(commercial_ ? Purplish_ : Gray_);
6077 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:NSLineBreakByTruncatingTail];
6079 if (placard_ != nil)
6080 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
6083 - (void) drawContentRect:(CGRect)rect {
6085 [self drawSummaryContentRect:rect];
6087 [self drawNormalContentRect:rect];
6092 /* Section Cell {{{ */
6093 @interface SectionCell : CyteTableViewCell <
6094 CyteTableViewCellDelegate
6096 _H<NSString> basic_;
6097 _H<NSString> section_;
6099 _H<NSString> count_;
6101 _H<UISwitch> switch_;
6105 - (void) setSection:(Section *)section editing:(BOOL)editing;
6109 @implementation SectionCell
6111 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
6112 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
6113 icon_ = [UIImage imageNamed:@"folder.png"];
6114 // XXX: this initial frame is wrong, but is fixed later
6115 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
6116 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
6118 UIView *content([self contentView]);
6119 CGRect bounds([content bounds]);
6121 self.content = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
6122 [self.content setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6123 [content addSubview:self.content];
6124 [self.content setBackgroundColor:[UIColor whiteColor]];
6126 [self.content setDelegate:self];
6130 - (void) onSwitch:(id)sender {
6131 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
6132 if (metadata == nil) {
6133 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
6134 [Sections_ setObject:metadata forKey:basic_];
6137 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
6140 - (void) setSection:(Section *)section editing:(BOOL)editing {
6141 if (editing != editing_) {
6143 [switch_ removeFromSuperview];
6145 [self addSubview:switch_];
6154 if (section == nil) {
6155 name_ = UCLocalize("ALL_PACKAGES");
6158 basic_ = [section name];
6159 section_ = [section localized];
6161 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
6162 count_ = [NSString stringWithFormat:@"%zd", [section count]];
6165 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
6168 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
6169 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
6171 [self.content setNeedsDisplay];
6174 - (void) setFrame:(CGRect)frame {
6175 [super setFrame:frame];
6177 CGRect rect([switch_ frame]);
6178 [switch_ setFrame:CGRectMake(frame.size.width - rect.size.width - 9, 9, rect.size.width, rect.size.height)];
6181 - (NSString *) accessibilityLabel {
6185 - (void) drawContentRect:(CGRect)rect {
6186 bool highlighted(self.highlighted && !editing_);
6188 [icon_ drawInRect:CGRectMake(7, 7, 32, 32)];
6190 if (highlighted && kCFCoreFoundationVersionNumber < 800)
6193 float width(rect.size.width);
6195 width -= 9 + [switch_ frame].size.width;
6199 [name_ drawAtPoint:CGPointMake(48, 12) forWidth:(width - 58) withFont:Font18_ lineBreakMode:NSLineBreakByTruncatingTail];
6201 CGSize size = [count_ sizeWithFont:Font14_];
6203 UISetColor(Folder_);
6205 [count_ drawAtPoint:CGPointMake(Retina(10 + (30 - size.width) / 2), 18) withFont:Font12Bold_];
6211 /* File Table {{{ */
6212 @interface FileTable : CyteViewController <
6213 UITableViewDataSource,
6216 _transient Database *database_;
6217 _H<Package> package_;
6219 _H<NSMutableArray> files_;
6220 _H<UITableView, 2> list_;
6223 - (id) initWithDatabase:(Database *)database;
6224 - (void) setPackage:(Package *)package;
6228 @implementation FileTable
6230 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6231 return files_ == nil ? 0 : [files_ count];
6234 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6238 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6239 static NSString *reuseIdentifier = @"Cell";
6241 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6243 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6244 [cell setFont:[UIFont systemFontOfSize:16]];
6246 [cell setText:[files_ objectAtIndex:indexPath.row]];
6247 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
6252 - (NSURL *) navigationURL {
6253 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
6257 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
6258 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6259 [list_ setRowHeight:24.0f];
6260 [(UITableView *) list_ setDataSource:self];
6261 [list_ setDelegate:self];
6262 [self setView:list_];
6265 - (void) viewDidLoad {
6266 [super viewDidLoad];
6268 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
6271 - (void) releaseSubviews {
6277 [super releaseSubviews];
6280 - (id) initWithDatabase:(Database *)database {
6281 if ((self = [super init]) != nil) {
6282 database_ = database;
6286 - (void) setPackage:(Package *)package {
6290 files_ = [NSMutableArray arrayWithCapacity:32];
6292 if (package != nil) {
6294 name_ = [package id];
6296 if (NSArray *files = [package files])
6297 [files_ addObjectsFromArray:files];
6299 if ([files_ count] != 0) {
6300 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
6301 [files_ removeObjectAtIndex:0];
6302 [files_ sortUsingSelector:@selector(compareByPath:)];
6304 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
6305 [stack addObject:@"/"];
6307 for (int i(0), e([files_ count]); i != e; ++i) {
6308 NSString *file = [files_ objectAtIndex:i];
6309 while (![file hasPrefix:[stack lastObject]])
6310 [stack removeLastObject];
6311 NSString *directory = [stack lastObject];
6312 [stack addObject:[file stringByAppendingString:@"/"]];
6313 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
6314 int(([stack count] - 2) * 3), "",
6315 [file substringFromIndex:[directory length]]
6324 - (void) reloadData {
6327 [self setPackage:[database_ packageWithName:name_]];
6332 /* Package Controller {{{ */
6333 @interface CYPackageController : CydiaWebViewController <
6334 UIActionSheetDelegate
6336 _transient Database *database_;
6337 _H<Package> package_;
6340 std::vector<std::pair<_H<NSString>, _H<NSString>>> buttons_;
6341 _H<UIActionSheet> sheet_;
6342 _H<UIBarButtonItem> button_;
6343 _H<NSArray> versions_;
6346 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer;
6350 @implementation CYPackageController
6352 - (NSURL *) navigationURL {
6353 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
6356 - (void) _clickButtonWithPackage:(Package *)package {
6357 [self.delegate installPackage:package];
6360 - (void) _clickButtonWithName:(NSString *)name {
6361 if ([name isEqualToString:@"CLEAR"])
6362 return [self.delegate clearPackage:package_];
6363 else if ([name isEqualToString:@"REMOVE"])
6364 return [self.delegate removePackage:package_];
6365 else if ([name isEqualToString:@"DOWNGRADE"]) {
6366 sheet_ = [[[UIActionSheet alloc]
6369 cancelButtonTitle:nil
6370 destructiveButtonTitle:nil
6371 otherButtonTitles:nil
6374 for (Package *version in (id) versions_)
6375 [sheet_ addButtonWithTitle:[version latest]];
6376 [sheet_ setContext:@"version"];
6378 [self.delegate showActionSheet:sheet_ fromItem:[[self navigationItem] rightBarButtonItem]];
6382 else if ([name isEqualToString:@"INSTALL"]);
6383 else if ([name isEqualToString:@"REINSTALL"]);
6384 else if ([name isEqualToString:@"UPGRADE"]);
6385 else _assert(false);
6387 [self.delegate installPackage:package_];
6390 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
6391 NSString *context([sheet context]);
6392 if (sheet_ == sheet)
6395 if ([context isEqualToString:@"modify"]) {
6396 if (button != [sheet cancelButtonIndex]) {
6398 [self performSelector:@selector(_clickButtonWithName:) withObject:buttons_[button].first afterDelay:0];
6400 [self _clickButtonWithName:buttons_[button].first];
6403 [sheet dismissWithClickedButtonIndex:button animated:YES];
6404 } else if ([context isEqualToString:@"version"]) {
6405 if (button != [sheet cancelButtonIndex]) {
6406 Package *version([versions_ objectAtIndex:button]);
6408 [self performSelector:@selector(_clickButtonWithPackage:) withObject:version afterDelay:0];
6410 [self _clickButtonWithPackage:version];
6413 [sheet dismissWithClickedButtonIndex:button animated:YES];
6417 - (bool) _allowJavaScriptPanel {
6422 - (void) _customButtonClicked {
6423 if (commercial_ && self.isLoading && [package_ uninstalled])
6424 return [self reloadURLWithCache:NO];
6426 size_t count(buttons_.size());
6431 [self _clickButtonWithName:buttons_[0].first];
6433 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
6434 for (const auto &button : buttons_)
6435 [buttons addObject:button.second];
6437 sheet_ = [[[UIActionSheet alloc]
6440 cancelButtonTitle:nil
6441 destructiveButtonTitle:nil
6442 otherButtonTitles:nil
6445 for (NSString *button in buttons)
6446 [sheet_ addButtonWithTitle:button];
6447 [sheet_ setContext:@"modify"];
6449 [self.delegate showActionSheet:sheet_ fromItem:[[self navigationItem] rightBarButtonItem]];
6453 - (void) applyLoadingTitle {
6454 // Don't show "Loading" as the title. Ever.
6457 - (UIBarButtonItem *) rightButton {
6462 - (void) setPageColor:(UIColor *)color {
6463 return [super setPageColor:nil];
6466 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer {
6467 if ((self = [super init]) != nil) {
6468 database_ = database;
6469 name_ = name == nil ? @"" : [NSString stringWithString:name];
6470 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]] withReferrer:referrer];
6474 - (void) reloadData {
6477 [sheet_ dismissWithClickedButtonIndex:[sheet_ cancelButtonIndex] animated:YES];
6480 package_ = [database_ packageWithName:name_];
6481 versions_ = [package_ downgrades];
6485 if (package_ != nil) {
6486 [(Package *) package_ parse];
6488 commercial_ = [package_ isCommercial];
6490 if ([package_ mode] != nil)
6491 buttons_.push_back(std::make_pair(@"CLEAR", UCLocalize("CLEAR")));
6492 if ([package_ source] == nil);
6493 else if ([package_ upgradableAndEssential:NO])
6494 buttons_.push_back(std::make_pair(@"UPGRADE", UCLocalize("UPGRADE")));
6495 else if ([package_ uninstalled])
6496 buttons_.push_back(std::make_pair(@"INSTALL", UCLocalize("INSTALL")));
6498 buttons_.push_back(std::make_pair(@"REINSTALL", UCLocalize("REINSTALL")));
6499 if (![package_ uninstalled])
6500 buttons_.push_back(std::make_pair(@"REMOVE", UCLocalize("REMOVE")));
6501 if ([versions_ count] != 0)
6502 buttons_.push_back(std::make_pair(@"DOWNGRADE", UCLocalize("DOWNGRADE")));
6506 switch (buttons_.size()) {
6507 case 0: title = nil; break;
6508 case 1: title = buttons_[0].second; break;
6509 default: title = UCLocalize("MODIFY"); break;
6512 button_ = [[[UIBarButtonItem alloc]
6514 style:UIBarButtonItemStylePlain
6516 action:@selector(customButtonClicked)
6520 - (bool) isLoading {
6521 return commercial_ ? [super isLoading] : false;
6527 /* Package List Controller {{{ */
6528 @interface PackageListController : CyteViewController <
6529 UITableViewDataSource,
6532 _transient Database *database_;
6534 _H<NSArray> packages_;
6535 _H<NSArray> sections_;
6536 _H<UITableView, 2> list_;
6538 _H<NSArray> thumbs_;
6539 std::vector<NSInteger> offset_;
6541 _H<NSString> title_;
6542 unsigned reloading_;
6545 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6546 - (void) resetCursor;
6549 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages;
6553 @implementation PackageListController
6555 - (NSURL *) referrerURL {
6556 return [self navigationURL];
6559 - (bool) isSummarized {
6563 - (bool) showsSections {
6567 - (void) deselectWithAnimation:(BOOL)animated {
6568 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6571 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6572 CGRect base = [[self view] bounds];
6573 base.size.height -= bounds.size.height;
6574 base.origin = [list_ frame].origin;
6576 [UIView beginAnimations:nil context:NULL];
6577 [UIView setAnimationBeginsFromCurrentState:YES];
6578 [UIView setAnimationCurve:curve];
6579 [UIView setAnimationDuration:duration];
6580 [list_ setFrame:base];
6581 [UIView commitAnimations];
6584 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6585 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6588 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6589 [self resizeForKeyboardBounds:bounds duration:0];
6592 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6593 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6594 *curve = UIViewAnimationCurveEaseInOut;
6596 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6598 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6601 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6604 - (void) keyboardWillShow:(NSNotification *)notification {
6607 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6608 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6610 NSTimeInterval duration;
6611 UIViewAnimationCurve curve;
6612 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6614 CGRect kbframe = CGRectMake(Retina(center.x - bounds.size.width / 2), Retina(center.y - bounds.size.height / 2), bounds.size.width, bounds.size.height);
6615 UIViewController *base = self;
6616 while ([base parentOrPresentingViewController] != nil)
6617 base = [base parentOrPresentingViewController];
6618 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6619 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6621 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6622 intersection.size.height += CYStatusBarHeight();
6624 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6627 - (void) keyboardWillHide:(NSNotification *)notification {
6628 NSTimeInterval duration;
6629 UIViewAnimationCurve curve;
6630 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6632 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6635 - (void) viewWillAppear:(BOOL)animated {
6636 [super viewWillAppear:animated];
6638 [self resizeForKeyboardBounds:CGRectZero];
6639 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6640 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6643 - (void) viewWillDisappear:(BOOL)animated {
6644 [super viewWillDisappear:animated];
6646 [self resizeForKeyboardBounds:CGRectZero];
6647 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6648 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6651 - (void) viewDidAppear:(BOOL)animated {
6652 [super viewDidAppear:animated];
6653 [self deselectWithAnimation:animated];
6656 - (void) didSelectPackage:(Package *)package {
6657 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[[self referrerURL] absoluteString]] autorelease]);
6658 [view setDelegate:self.delegate];
6659 [[self navigationController] pushViewController:view animated:YES];
6662 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6663 NSInteger count([sections_ count]);
6664 return count == 0 ? 1 : count;
6667 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6668 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6670 return [[sections_ objectAtIndex:section] name];
6673 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6674 if ([sections_ count] == 0)
6676 return [[sections_ objectAtIndex:section] count];
6679 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6680 @synchronized (database_) {
6681 if ([database_ era] != era_)
6684 Section *section([sections_ objectAtIndex:[path section]]);
6685 NSInteger row([path row]);
6686 Package *package([packages_ objectAtIndex:([section row] + row)]);
6687 return [[package retain] autorelease];
6690 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6691 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6693 cell = [[[PackageCell alloc] init] autorelease];
6695 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6696 [cell setPackage:package asSummary:[self isSummarized]];
6700 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6701 Package *package([self packageAtIndexPath:path]);
6702 package = [database_ packageWithName:[package id]];
6703 [self didSelectPackage:package];
6706 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6710 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6711 return offset_[index];
6714 - (void) updateHeight {
6715 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6718 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6719 if ((self = [super init]) != nil) {
6720 database_ = database;
6721 title_ = [title copy];
6722 [[self navigationItem] setTitle:title_];
6727 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
6728 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
6729 [self setView:view];
6731 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6732 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6733 [view addSubview:list_];
6735 // XXX: is 20 the most optimal number here?
6736 [list_ setSectionIndexMinimumDisplayRowCount:20];
6738 [(UITableView *) list_ setDataSource:self];
6739 [list_ setDelegate:self];
6741 [self updateHeight];
6744 - (void) releaseSubviews {
6753 [super releaseSubviews];
6756 - (bool) shouldYield {
6760 - (bool) shouldBlock {
6764 - (NSMutableArray *) _reloadPackages {
6765 @synchronized (database_) {
6766 era_ = [database_ era];
6767 NSArray *packages([database_ packages]);
6769 return [NSMutableArray arrayWithArray:packages];
6772 - (void) _reloadData {
6773 if (reloading_ != 0) {
6778 NSMutableArray *packages;
6781 if ([self shouldYield]) {
6785 if (![self shouldBlock])
6788 hud = [self.delegate addProgressHUD];
6789 [hud setText:UCLocalize("LOADING")];
6793 packages = [self yieldToSelector:@selector(_reloadPackages)];
6796 [self.delegate removeProgressHUD:hud];
6797 } while (reloading_ == 2);
6799 packages = [self _reloadPackages];
6802 @synchronized (database_) {
6803 if (era_ != [database_ era])
6810 packages_ = packages;
6812 if ([self showsSections])
6813 sections_ = [self sectionsForPackages:packages];
6815 Section *section([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6816 [section setCount:[packages_ count]];
6817 sections_ = [NSArray arrayWithObject:section];
6820 [self updateHeight];
6822 _profile(PackageTable$reloadData$List)
6823 [(UITableView *) list_ setDataSource:self];
6831 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
6832 Section *prefix([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6833 size_t end([packages count]);
6835 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
6836 Section *section(prefix);
6838 thumbs_ = CollationThumbs_;
6839 offset_ = CollationOffset_;
6842 size_t offsets([CollationStarts_ count]);
6844 NSString *start([CollationStarts_ objectAtIndex:offset]);
6845 size_t length([start length]);
6847 for (size_t index(0); index != end; ++index) {
6849 Package *package([packages objectAtIndex:index]);
6850 NSString *name(PackageName(package, @selector(cyname)));
6852 //while ([start compare:name options:NSNumericSearch range:NSMakeRange(0, length) locale:CollationLocale_] != NSOrderedDescending) {
6853 while (StringNameCompare(start, name, length) != kCFCompareGreaterThan) {
6854 NSString *title([CollationTitles_ objectAtIndex:offset]);
6855 section = [[[Section alloc] initWithName:title row:index localize:NO] autorelease];
6856 [sections addObject:section];
6858 start = ++offset == offsets ? nil : [CollationStarts_ objectAtIndex:offset];
6861 length = [start length];
6865 [section addToCount];
6868 for (; offset != offsets; ++offset) {
6869 NSString *title([CollationTitles_ objectAtIndex:offset]);
6870 Section *section([[[Section alloc] initWithName:title row:end localize:NO] autorelease]);
6871 [sections addObject:section];
6874 if ([prefix count] != 0) {
6875 Section *suffix([sections lastObject]);
6876 [prefix setName:[suffix name]];
6877 [suffix setName:nil];
6878 [sections insertObject:prefix atIndex:(offsets - 1)];
6884 - (void) reloadData {
6887 if ([self shouldYield])
6888 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6893 - (void) resetCursor {
6894 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6897 - (void) clearData {
6898 [self updateHeight];
6900 [list_ setDataSource:nil];
6908 /* Filtered Package List Controller {{{ */
6909 typedef Function<bool, Package *> PackageFilter;
6910 typedef Function<void, NSMutableArray *> PackageSorter;
6911 @interface FilteredPackageListController : PackageListController {
6912 PackageFilter filter_;
6913 PackageSorter sorter_;
6916 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter;
6918 - (void) setFilter:(PackageFilter)filter;
6919 - (void) setSorter:(PackageSorter)sorter;
6923 @implementation FilteredPackageListController
6925 - (void) setFilter:(PackageFilter)filter {
6926 @synchronized (self) {
6930 - (void) setSorter:(PackageSorter)sorter {
6931 @synchronized (self) {
6935 - (NSMutableArray *) _reloadPackages {
6936 @synchronized (database_) {
6937 era_ = [database_ era];
6939 NSArray *packages([database_ packages]);
6940 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6942 PackageFilter filter;
6943 PackageSorter sorter;
6945 @synchronized (self) {
6950 _profile(PackageTable$reloadData$Filter)
6951 for (Package *package in packages)
6952 if (filter(package))
6953 [filtered addObject:package];
6961 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter {
6962 if ((self = [super initWithDatabase:database title:title]) != nil) {
6963 [self setFilter:filter];
6970 /* Home Controller {{{ */
6971 @interface HomeController : CydiaWebViewController {
6972 CFRunLoopRef runloop_;
6973 SCNetworkReachabilityRef reachability_;
6978 @implementation HomeController
6980 static void HomeControllerReachabilityCallback(SCNetworkReachabilityRef reachability, SCNetworkReachabilityFlags flags, void *info) {
6981 [(HomeController *) info dispatchEvent:@"CydiaReachabilityCallback"];
6985 if ((self = [super init]) != nil) {
6986 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6989 reachability_ = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "cydia.saurik.com");
6990 if (reachability_ != NULL) {
6991 SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
6992 SCNetworkReachabilitySetCallback(reachability_, HomeControllerReachabilityCallback, &context);
6994 CFRunLoopRef runloop(CFRunLoopGetCurrent());
6995 if (SCNetworkReachabilityScheduleWithRunLoop(reachability_, runloop, kCFRunLoopDefaultMode))
7002 if (reachability_ != NULL && runloop_ != NULL)
7003 SCNetworkReachabilityUnscheduleFromRunLoop(reachability_, runloop_, kCFRunLoopDefaultMode);
7007 - (NSURL *) navigationURL {
7008 return [NSURL URLWithString:@"cydia://home"];
7011 - (void) aboutButtonClicked {
7012 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
7014 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
7015 [alert addButtonWithTitle:UCLocalize("CLOSE")];
7016 [alert setCancelButtonIndex:0];
7019 @"Copyright \u00a9 2008-2015\n"
7022 "Jay Freeman (saurik)\n"
7023 "saurik@saurik.com\n"
7024 "http://www.saurik.com/"
7030 - (UIBarButtonItem *) leftButton {
7031 return [[[UIBarButtonItem alloc]
7032 initWithTitle:UCLocalize("ABOUT")
7033 style:UIBarButtonItemStylePlain
7035 action:@selector(aboutButtonClicked)
7042 /* Cydia Tab Bar Controller {{{ */
7043 @interface CydiaTabBarController : CyteTabBarController <
7044 UITabBarControllerDelegate,
7047 _transient Database *database_;
7049 _H<UIActivityIndicatorView> indicator_;
7052 // XXX: ok, "updatedelegate_"?...
7053 _transient NSObject<CydiaDelegate> *updatedelegate_;
7056 - (void) beginUpdate;
7061 @implementation CydiaTabBarController
7063 - (id) initWithDatabase:(Database *)database {
7064 if ((self = [super init]) != nil) {
7065 database_ = database;
7066 [self setDelegate:self];
7068 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteTiny] autorelease];
7069 [indicator_ setOrigin:CGPointMake(kCFCoreFoundationVersionNumber >= 800 ? 2 : 4, 2)];
7071 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7075 - (void) beginUpdate {
7079 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
7080 UITabBarItem *item([controller tabBarItem]);
7082 [item setBadgeValue:@""];
7083 UIView *badge(MSHookIvar<UIView *>([item view], "_badge"));
7085 [indicator_ startAnimating];
7086 [badge addSubview:indicator_];
7088 [updatedelegate_ retainNetworkActivityIndicator];
7092 detachNewThreadSelector:@selector(performUpdate)
7098 - (void) performUpdate {
7099 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
7101 SourceStatus status(self, database_);
7102 [database_ updateWithStatus:status];
7105 performSelectorOnMainThread:@selector(completeUpdate)
7113 - (void) stopUpdateWithSelector:(SEL)selector {
7115 [updatedelegate_ releaseNetworkActivityIndicator];
7117 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
7118 [[controller tabBarItem] setBadgeValue:nil];
7120 [indicator_ removeFromSuperview];
7121 [indicator_ stopAnimating];
7123 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
7126 - (void) completeUpdate {
7129 [self stopUpdateWithSelector:@selector(reloadData)];
7132 - (void) cancelUpdate {
7133 [self stopUpdateWithSelector:@selector(updateDataAndLoad)];
7136 - (void) cancelPressed {
7137 [self cancelUpdate];
7144 - (bool) isSourceCancelled {
7148 - (void) startSourceFetch:(NSString *)uri {
7151 - (void) stopSourceFetch:(NSString *)uri {
7154 - (void) setUpdateDelegate:(id)delegate {
7155 updatedelegate_ = delegate;
7161 /* Cydia:// Protocol {{{ */
7162 @interface CydiaURLProtocol : NSURLProtocol {
7167 @implementation CydiaURLProtocol
7169 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7170 NSURL *url([request URL]);
7174 NSString *scheme([[url scheme] lowercaseString]);
7175 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7177 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7183 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7187 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7188 id<NSURLProtocolClient> client([self client]);
7190 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7192 NSData *data(UIImagePNGRepresentation(icon));
7194 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7195 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7196 [client URLProtocol:self didLoadData:data];
7197 [client URLProtocolDidFinishLoading:self];
7201 - (void) startLoading {
7202 id<NSURLProtocolClient> client([self client]);
7203 NSURLRequest *request([self request]);
7205 NSURL *url([request URL]);
7206 NSString *href([url absoluteString]);
7207 NSString *scheme([[url scheme] lowercaseString]);
7211 if ([scheme isEqualToString:@"cydia"])
7212 path = [href substringFromIndex:8];
7213 else if ([scheme isEqualToString:@"about"])
7214 path = [href substringFromIndex:12];
7215 else _assert(false);
7217 NSRange slash([path rangeOfString:@"/"]);
7220 if (slash.location == NSNotFound) {
7224 command = [path substringToIndex:slash.location];
7225 path = [path substringFromIndex:(slash.location + 1)];
7228 Database *database([Database sharedInstance]);
7231 else if ([command isEqualToString:@"application-icon"]) {
7234 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7238 if (icon == nil && $SBSCopyIconImagePNGDataForDisplayIdentifier != NULL) {
7239 NSData *data([$SBSCopyIconImagePNGDataForDisplayIdentifier(path) autorelease]);
7240 icon = [UIImage imageWithData:data];
7244 if (NSString *file = SBSCopyIconImagePathForDisplayIdentifier(path))
7245 icon = [UIImage imageAtPath:file];
7248 icon = [UIImage imageNamed:@"unknown.png"];
7250 [self _returnPNGWithImage:icon forRequest:request];
7251 } else if ([command isEqualToString:@"package-icon"]) {
7254 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7255 Package *package([database packageWithName:path]);
7259 UIImage *icon([package icon]);
7260 [self _returnPNGWithImage:icon forRequest:request];
7261 } else if ([command isEqualToString:@"uikit-image"]) {
7264 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7265 UIImage *icon(_UIImageWithName(path));
7266 [self _returnPNGWithImage:icon forRequest:request];
7267 } else if ([command isEqualToString:@"section-icon"]) {
7270 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7271 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7273 icon = [UIImage imageNamed:@"unknown.png"];
7274 [self _returnPNGWithImage:icon forRequest:request];
7276 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7280 - (void) stopLoading {
7286 /* Section Controller {{{ */
7287 @interface SectionController : FilteredPackageListController {
7289 _H<NSString> section_;
7292 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section;
7296 @implementation SectionController
7298 - (NSURL *) referrerURL {
7299 NSString *name(section_);
7300 name = name ?: @"*";
7301 NSString *key(key_);
7303 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sections/%@/%@", UI_, [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7306 - (NSURL *) navigationURL {
7307 NSString *name(section_);
7308 name = name ?: @"*";
7309 NSString *key(key_);
7311 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@/%@", [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7314 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section {
7317 title = UCLocalize("ALL_PACKAGES");
7318 else if (![section isEqual:@""])
7319 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(section) value:nil table:@"Sections"];
7321 title = UCLocalize("NO_SECTION");
7323 if ((self = [super initWithDatabase:database title:title]) != nil) {
7324 key_ = [source key];
7329 - (void) reloadData {
7330 Source *source([database_ sourceWithKey:key_]);
7331 _H<NSString> name(section_);
7333 [self setFilter:[=](Package *package) {
7334 NSString *section([package section]);
7338 section == nil && [name length] == 0 ||
7339 [name isEqualToString:section]
7342 [package source] == source
7343 ) && [package visible];
7351 /* Sections Controller {{{ */
7352 @interface SectionsController : CyteViewController <
7353 UITableViewDataSource,
7356 _transient Database *database_;
7358 _H<NSMutableArray> sections_;
7359 _H<NSMutableArray> filtered_;
7360 _H<UITableView, 2> list_;
7363 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7364 - (void) editButtonClicked;
7368 @implementation SectionsController
7370 - (NSURL *) navigationURL {
7371 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
7374 - (Source *) source {
7377 return [database_ sourceWithKey:key_];
7380 - (void) updateNavigationItem {
7381 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7382 if ([sections_ count] == 0) {
7383 [[self navigationItem] setRightBarButtonItem:nil];
7385 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7386 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7388 action:@selector(editButtonClicked)
7389 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7393 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7394 [super setEditing:editing animated:animated];
7399 [self.delegate updateData];
7401 [self updateNavigationItem];
7404 - (void) viewDidAppear:(BOOL)animated {
7405 [super viewDidAppear:animated];
7406 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7409 - (void) viewWillDisappear:(BOOL)animated {
7410 [super viewWillDisappear:animated];
7411 [self setEditing:NO];
7414 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7415 Section *section = nil;
7416 int index = [indexPath row];
7417 if (![self isEditing]) {
7420 section = [filtered_ objectAtIndex:index];
7422 section = [sections_ objectAtIndex:index];
7427 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7428 if ([self isEditing])
7429 return [sections_ count];
7431 return [filtered_ count] + 1;
7434 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7438 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7439 static NSString *reuseIdentifier = @"SectionCell";
7441 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7443 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7445 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7450 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7451 if ([self isEditing])
7454 Section *section = [self sectionAtIndexPath:indexPath];
7456 SectionController *controller = [[[SectionController alloc]
7457 initWithDatabase:database_
7458 source:[self source]
7459 section:[section name]
7461 [controller setDelegate:self.delegate];
7463 [[self navigationController] pushViewController:controller animated:YES];
7467 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
7468 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7469 [list_ setRowHeight:46];
7470 [(UITableView *) list_ setDataSource:self];
7471 [list_ setDelegate:self];
7472 [self setView:list_];
7475 - (void) viewDidLoad {
7476 [super viewDidLoad];
7478 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7481 - (void) releaseSubviews {
7487 [super releaseSubviews];
7490 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7491 if ((self = [super init]) != nil) {
7492 database_ = database;
7493 key_ = [source key];
7497 - (void) reloadData {
7500 NSArray *packages = [database_ packages];
7502 sections_ = [NSMutableArray arrayWithCapacity:16];
7503 filtered_ = [NSMutableArray arrayWithCapacity:16];
7505 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7507 Source *source([self source]);
7510 for (Package *package in packages) {
7511 if (source != nil && [package source] != source)
7514 NSString *name([package section]);
7515 NSString *key(name == nil ? @"" : name);
7519 _profile(SectionsView$reloadData$Section)
7520 section = [sections objectForKey:key];
7521 if (section == nil) {
7522 _profile(SectionsView$reloadData$Section$Allocate)
7523 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7524 [sections setObject:section forKey:key];
7529 [section addToCount];
7531 _profile(SectionsView$reloadData$Filter)
7532 if (![package visible])
7540 [sections_ addObjectsFromArray:[sections allValues]];
7542 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7544 for (Section *section in (id) sections_) {
7545 size_t count([section row]);
7549 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7550 [section setCount:count];
7551 [filtered_ addObject:section];
7554 [self updateNavigationItem];
7559 - (void) editButtonClicked {
7560 [self setEditing:![self isEditing] animated:YES];
7566 /* Changes Controller {{{ */
7567 @interface ChangesController : FilteredPackageListController {
7571 - (id) initWithDatabase:(Database *)database;
7575 @implementation ChangesController
7577 - (NSURL *) referrerURL {
7578 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/changes/", UI_]];
7581 - (NSURL *) navigationURL {
7582 return [NSURL URLWithString:@"cydia://changes"];
7585 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7586 @synchronized (database_) {
7587 if ([database_ era] != era_)
7590 NSUInteger sectionIndex([path section]);
7591 if (sectionIndex >= [sections_ count])
7593 Section *section([sections_ objectAtIndex:sectionIndex]);
7594 NSInteger row([path row]);
7595 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7598 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7599 NSString *context([alert context]);
7601 if ([context isEqualToString:@"norefresh"])
7602 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7605 - (void) setLeftBarButtonItem {
7606 if ([self.delegate updating])
7607 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7608 initWithTitle:UCLocalize("CANCEL")
7609 style:UIBarButtonItemStyleDone
7611 action:@selector(cancelButtonClicked)
7612 ] autorelease] animated:YES];
7614 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7615 initWithTitle:UCLocalize("REFRESH")
7616 style:UIBarButtonItemStylePlain
7618 action:@selector(refreshButtonClicked)
7619 ] autorelease] animated:YES];
7622 - (void) refreshButtonClicked {
7623 if ([self.delegate requestUpdate])
7624 [self setLeftBarButtonItem];
7627 - (void) cancelButtonClicked {
7628 [self.delegate cancelUpdate];
7631 - (void) upgradeButtonClicked {
7632 [self.delegate distUpgrade];
7633 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7636 - (bool) shouldYield {
7640 - (bool) shouldBlock {
7644 - (void) useFilter {
7645 @synchronized (self) {
7646 [self setFilter:[](Package *package) {
7647 return [package upgradableAndEssential:YES] || [package visible];
7650 [self setSorter:[](NSMutableArray *packages) {
7651 [packages radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7655 - (id) initWithDatabase:(Database *)database {
7656 if ((self = [super initWithDatabase:database title:UCLocalize("CHANGES")]) != nil) {
7661 - (void) viewDidLoad {
7662 [super viewDidLoad];
7663 [self setLeftBarButtonItem];
7666 - (void) viewWillAppear:(BOOL)animated {
7667 [super viewWillAppear:animated];
7668 [self setLeftBarButtonItem];
7671 - (void) reloadData {
7672 [self setLeftBarButtonItem];
7676 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
7677 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
7679 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7680 Section *ignored = nil;
7681 Section *section = nil;
7685 bool unseens = false;
7687 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7689 for (size_t offset = 0, count = [packages count]; offset != count; ++offset) {
7690 Package *package = [packages objectAtIndex:offset];
7692 BOOL uae = [package upgradableAndEssential:YES];
7696 time_t seen([package seen]);
7698 if (section == nil || last != seen) {
7702 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7705 _profile(ChangesController$reloadData$Allocate)
7706 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7707 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7708 [sections addObject:section];
7712 [section addToCount];
7713 } else if ([package ignored]) {
7714 if (ignored == nil) {
7715 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7717 [ignored addToCount];
7720 [upgradable addToCount];
7725 CFRelease(formatter);
7728 Section *last = [sections lastObject];
7729 size_t count = [last count];
7730 [packages removeObjectsInRange:NSMakeRange([packages count] - count, count)];
7731 [sections removeLastObject];
7734 if ([ignored count] != 0)
7735 [sections insertObject:ignored atIndex:0];
7737 [sections insertObject:upgradable atIndex:0];
7741 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7742 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7743 style:UIBarButtonItemStylePlain
7745 action:@selector(upgradeButtonClicked)
7746 ] autorelease]) animated:YES];
7753 /* Search Controller {{{ */
7754 @interface SearchController : FilteredPackageListController <
7757 _H<UISearchBar, 1> search_;
7762 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7763 - (void) reloadData;
7767 @implementation SearchController
7769 - (NSURL *) referrerURL {
7770 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/search?q=%@", UI_, [([search_ text] ?: @"") stringByAddingPercentEscapesIncludingReserved]]];
7773 - (NSURL *) navigationURL {
7774 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7775 return [NSURL URLWithString:@"cydia://search"];
7777 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [[search_ text] stringByAddingPercentEscapesIncludingReserved]]];
7780 - (NSArray *) termsForQuery:(NSString *)query {
7781 NSMutableArray *terms([NSMutableArray arrayWithCapacity:2]);
7782 for (NSString *component in [query componentsSeparatedByString:@" "])
7783 if ([component length] != 0)
7784 [terms addObject:component];
7789 - (void) useSearch {
7790 _H<NSArray> query([self termsForQuery:[search_ text]]);
7793 @synchronized (self) {
7794 [self setFilter:[=](Package *package) {
7795 if (![package unfiltered])
7797 if (![package matches:query])
7802 [self setSorter:[](NSMutableArray *packages) {
7803 [packages radixSortUsingSelector:@selector(rank)];
7811 - (void) usePrefix:(NSString *)prefix {
7812 _H<NSString> query(prefix);
7815 @synchronized (self) {
7816 [self setFilter:[=](Package *package) {
7817 if ([query length] == 0)
7819 if (![package unfiltered])
7821 if ([[package name] compare:query options:MatchCompareOptions_ range:NSMakeRange(0, [query length])] != NSOrderedSame)
7826 [self setSorter:nullptr];
7832 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7834 [self usePrefix:[search_ text]];
7837 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7838 [search_ resignFirstResponder];
7842 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7843 [search_ setText:@""];
7844 [self searchBarButtonClicked:searchBar];
7847 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7848 [self searchBarButtonClicked:searchBar];
7851 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7852 [self usePrefix:text];
7855 - (bool) shouldYield {
7859 - (bool) shouldBlock {
7863 - (bool) isSummarized {
7867 - (bool) showsSections {
7871 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7872 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH")])) {
7873 search_ = [[[UISearchBar alloc] init] autorelease];
7874 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7875 [search_ setDelegate:self];
7877 UITextField *textField;
7878 if ([search_ respondsToSelector:@selector(searchField)])
7879 textField = [search_ searchField];
7881 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7883 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7884 [textField setEnablesReturnKeyAutomatically:NO];
7885 [[self navigationItem] setTitleView:textField];
7888 [search_ setText:query];
7893 - (void) viewDidAppear:(BOOL)animated {
7894 [super viewDidAppear:animated];
7896 if (!searchloaded_) {
7897 searchloaded_ = YES;
7898 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7899 [search_ layoutSubviews];
7902 if ([self isSummarized])
7903 [search_ becomeFirstResponder];
7906 - (void) reloadData {
7911 - (void) didSelectPackage:(Package *)package {
7912 [search_ resignFirstResponder];
7913 [super didSelectPackage:package];
7918 /* Package Settings Controller {{{ */
7919 @interface PackageSettingsController : CyteViewController <
7920 UITableViewDataSource,
7923 _transient Database *database_;
7925 _H<Package> package_;
7926 _H<UITableView, 2> table_;
7927 _H<UISwitch> subscribedSwitch_;
7928 _H<UISwitch> ignoredSwitch_;
7929 _H<UITableViewCell> subscribedCell_;
7930 _H<UITableViewCell> ignoredCell_;
7933 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7937 @implementation PackageSettingsController
7939 - (NSURL *) navigationURL {
7940 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
7943 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7944 if (package_ == nil)
7947 if ([package_ installed] == nil)
7953 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7954 if (package_ == nil)
7957 // both sections contain just one item right now.
7961 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7965 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7967 return UCLocalize("SHOW_ALL_CHANGES_EX");
7969 return UCLocalize("IGNORE_UPGRADES_EX");
7972 - (void) onSubscribed:(id)control {
7973 bool value([control isOn]);
7974 if (package_ == nil)
7976 if ([package_ setSubscribed:value])
7977 [self.delegate updateData];
7980 - (void) _updateIgnored {
7981 const char *package([name_ UTF8String]);
7982 bool on([ignoredSwitch_ isOn]);
7984 FILE *dpkg(popen("/usr/libexec/cydia/cydo --set-selections", "w"));
7985 fwrite(package, strlen(package), 1, dpkg);
7988 fwrite(" hold\n", 6, 1, dpkg);
7990 fwrite(" install\n", 9, 1, dpkg);
7995 - (void) onIgnored:(id)control {
7996 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7997 [invocation setTarget:self];
7998 [invocation setSelector:@selector(_updateIgnored)];
8000 [self.delegate reloadDataWithInvocation:invocation];
8003 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8004 if (package_ == nil)
8007 switch ([indexPath section]) {
8008 case 0: return subscribedCell_;
8009 case 1: return ignoredCell_;
8018 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8019 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8020 [self setView:view];
8022 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
8023 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8024 [(UITableView *) table_ setDataSource:self];
8025 [table_ setDelegate:self];
8026 [view addSubview:table_];
8028 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
8029 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
8030 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
8032 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
8033 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
8034 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
8036 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
8037 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
8038 [subscribedCell_ setAccessoryView:subscribedSwitch_];
8039 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
8041 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
8042 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
8043 [ignoredCell_ setAccessoryView:ignoredSwitch_];
8044 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
8047 - (void) viewDidLoad {
8048 [super viewDidLoad];
8050 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
8053 - (void) releaseSubviews {
8055 subscribedCell_ = nil;
8057 ignoredSwitch_ = nil;
8058 subscribedSwitch_ = nil;
8060 [super releaseSubviews];
8063 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
8064 if ((self = [super init]) != nil) {
8065 database_ = database;
8070 - (void) reloadData {
8073 package_ = [database_ packageWithName:name_];
8075 if (package_ != nil) {
8076 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
8077 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
8078 } // XXX: what now, G?
8080 [table_ reloadData];
8086 /* Installed Controller {{{ */
8087 @interface InstalledController : FilteredPackageListController {
8091 - (id) initWithDatabase:(Database *)database;
8092 - (void) queueStatusDidChange;
8096 @implementation InstalledController
8098 - (NSURL *) referrerURL {
8099 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/installed/", UI_]];
8102 - (NSURL *) navigationURL {
8103 return [NSURL URLWithString:@"cydia://installed"];
8106 - (void) useRecent {
8109 @synchronized (self) {
8110 [self setFilter:[](Package *package) {
8111 return ![package uninstalled] && package->role_ < 7;
8114 [self setSorter:[](NSMutableArray *packages) {
8115 [packages radixSortUsingSelector:@selector(recent)];
8119 - (void) useFilter:(UISegmentedControl *)segmented {
8120 NSInteger selected([segmented selectedSegmentIndex]);
8122 return [self useRecent];
8123 bool simple(selected == 0);
8126 @synchronized (self) {
8127 [self setFilter:[=](Package *package) {
8128 return ![package uninstalled] && package->role_ <= (simple ? 1 : 3);
8131 [self setSorter:nullptr];
8134 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
8136 return [super sectionsForPackages:packages];
8138 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterLongStyle, kCFDateFormatterNoStyle));
8140 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
8141 Section *section(nil);
8144 for (size_t offset(0), count([packages count]); offset != count; ++offset) {
8145 Package *package([packages objectAtIndex:offset]);
8147 time_t upgraded([package upgraded]);
8148 if (upgraded < 1168364520)
8151 upgraded -= upgraded % (60 * 60 * 24);
8153 if (section == nil || upgraded != last) {
8158 continue; // XXX: name = UCLocalize("...");
8160 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:upgraded]);
8164 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
8165 [sections addObject:section];
8168 [section addToCount];
8171 CFRelease(formatter);
8175 - (id) initWithDatabase:(Database *)database {
8176 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED")]) != nil) {
8177 UISegmentedControl *segmented([[[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:UCLocalize("USER"), UCLocalize("EXPERT"), UCLocalize("RECENT"), nil]] autorelease]);
8178 [segmented setSelectedSegmentIndex:0];
8179 [segmented setSegmentedControlStyle:UISegmentedControlStyleBar];
8180 [[self navigationItem] setTitleView:segmented];
8182 [segmented addTarget:self action:@selector(modeChanged:) forEvents:UIControlEventValueChanged];
8183 [self useFilter:segmented];
8185 [self queueStatusDidChange];
8190 - (void) queueButtonClicked {
8191 [self.delegate queue];
8195 - (void) queueStatusDidChange {
8198 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8199 initWithTitle:UCLocalize("QUEUE")
8200 style:UIBarButtonItemStyleDone
8202 action:@selector(queueButtonClicked)
8205 [[self navigationItem] setRightBarButtonItem:nil];
8210 - (void) modeChanged:(UISegmentedControl *)segmented {
8211 [self useFilter:segmented];
8218 /* Source Cell {{{ */
8219 @interface SourceCell : CyteTableViewCell <
8220 CyteTableViewCellDelegate,
8223 _H<Source, 1> source_;
8226 _H<NSString> origin_;
8227 _H<NSString> label_;
8228 _H<UIActivityIndicatorView> indicator_;
8231 - (void) setSource:(Source *)source;
8232 - (void) setFetch:(NSNumber *)fetch;
8236 @implementation SourceCell
8238 - (void) _setImage:(NSArray *)data {
8239 if ([url_ isEqual:[data objectAtIndex:0]]) {
8240 icon_ = [data objectAtIndex:1];
8241 [self.content setNeedsDisplay];
8245 - (void) _setSource:(NSURL *) url {
8246 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8248 if (NSData *data = [NSURLConnection
8249 sendSynchronousRequest:[NSURLRequest
8251 cachePolicy:NSURLRequestUseProtocolCachePolicy
8255 returningResponse:NULL
8258 if (UIImage *image = [UIImage imageWithData:data])
8259 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
8264 - (void) setSource:(Source *)source {
8266 [source_ setDelegate:self];
8268 [self setFetch:[NSNumber numberWithBool:[source_ fetch]]];
8270 icon_ = [UIImage imageNamed:@"unknown.png"];
8272 origin_ = [source name];
8273 label_ = [source rooturi];
8275 [self.content setNeedsDisplay];
8277 url_ = [source iconURL];
8278 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
8281 - (void) setAllSource {
8283 [indicator_ stopAnimating];
8285 icon_ = [UIImage imageNamed:@"folder.png"];
8286 origin_ = UCLocalize("ALL_SOURCES");
8287 label_ = UCLocalize("ALL_SOURCES_EX");
8288 [self.content setNeedsDisplay];
8291 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8292 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8293 UIView *content([self contentView]);
8294 CGRect bounds([content bounds]);
8296 self.content = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8297 [self.content setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8298 [self.content setBackgroundColor:[UIColor whiteColor]];
8299 [content addSubview:self.content];
8301 [self.content setDelegate:self];
8302 [self.content setOpaque:YES];
8304 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGraySmall] autorelease];
8305 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin];// | UIViewAutoresizingFlexibleBottomMargin];
8306 [content addSubview:indicator_];
8308 [[self.content layer] setContentsGravity:kCAGravityTopLeft];
8312 - (void) layoutSubviews {
8313 [super layoutSubviews];
8315 UIView *content([self contentView]);
8316 CGRect bounds([content bounds]);
8318 CGRect frame([indicator_ frame]);
8319 frame.origin.x = bounds.size.width - frame.size.width;
8320 frame.origin.y = Retina((bounds.size.height - frame.size.height) / 2);
8322 if (kCFCoreFoundationVersionNumber < 800)
8323 frame.origin.x -= 8;
8324 [indicator_ setFrame:frame];
8327 - (NSString *) accessibilityLabel {
8331 - (void) drawContentRect:(CGRect)rect {
8332 bool highlighted(self.highlighted);
8333 float width(rect.size.width);
8337 rect.size = [(UIImage *) icon_ size];
8339 while (rect.size.width > 32 || rect.size.height > 32) {
8340 rect.size.width /= 2;
8341 rect.size.height /= 2;
8344 rect.origin.x = 26 - rect.size.width / 2;
8345 rect.origin.y = 26 - rect.size.height / 2;
8347 [icon_ drawInRect:Retina(rect)];
8350 if (highlighted && kCFCoreFoundationVersionNumber < 800)
8355 [origin_ drawAtPoint:CGPointMake(52, 8) forWidth:(width - 49) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
8359 [label_ drawAtPoint:CGPointMake(52, 29) forWidth:(width - 49) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
8362 - (void) setFetch:(NSNumber *)fetch {
8363 if ([fetch boolValue])
8364 [indicator_ startAnimating];
8366 [indicator_ stopAnimating];
8371 /* Sources Controller {{{ */
8372 @interface SourcesController : CyteViewController <
8373 UITableViewDataSource,
8376 _transient Database *database_;
8379 _H<UITableView, 2> list_;
8380 _H<NSMutableArray> sources_;
8384 _H<UIProgressHUD> hud_;
8387 NSURLConnection *trivial_bz2_;
8388 NSURLConnection *trivial_gz_;
8393 - (id) initWithDatabase:(Database *)database;
8394 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated;
8398 @implementation SourcesController
8400 - (void) _releaseConnection:(NSURLConnection *)connection {
8401 if (connection != nil) {
8402 [connection cancel];
8403 //[connection setDelegate:nil];
8404 [connection release];
8409 [self _releaseConnection:trivial_gz_];
8410 [self _releaseConnection:trivial_bz2_];
8415 - (NSURL *) navigationURL {
8416 return [NSURL URLWithString:@"cydia://sources"];
8419 - (void) viewDidAppear:(BOOL)animated {
8420 [super viewDidAppear:animated];
8421 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8424 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8428 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8430 return UCLocalize("INDIVIDUAL_SOURCES");
8434 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8437 case 1: return [sources_ count];
8442 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8443 @synchronized (database_) {
8444 if ([database_ era] != era_)
8446 if ([indexPath section] != 1)
8448 NSUInteger index([indexPath row]);
8449 if (index >= [sources_ count])
8451 return [sources_ objectAtIndex:index];
8454 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8455 static NSString *cellIdentifier = @"SourceCell";
8457 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8458 if (cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8459 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8461 Source *source([self sourceAtIndexPath:indexPath]);
8463 [cell setAllSource];
8465 [cell setSource:source];
8470 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8471 SectionsController *controller([[[SectionsController alloc]
8472 initWithDatabase:database_
8473 source:[self sourceAtIndexPath:indexPath]
8476 [controller setDelegate:self.delegate];
8477 [[self navigationController] pushViewController:controller animated:YES];
8480 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8481 if ([indexPath section] != 1)
8483 Source *source = [self sourceAtIndexPath:indexPath];
8484 return [source record] != nil;
8487 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8488 _assert([indexPath section] == 1);
8489 if (editingStyle == UITableViewCellEditingStyleDelete) {
8490 Source *source = [self sourceAtIndexPath:indexPath];
8491 if (source == nil) return;
8493 [Sources_ removeObjectForKey:[source key]];
8495 [self.delegate syncData];
8499 - (void) tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath {
8500 [self updateButtonsForEditingStatusAnimated:YES];
8504 [self.delegate addTrivialSource:href_];
8507 [self.delegate syncData];
8510 - (NSString *) getWarning {
8511 NSString *href(href_);
8512 NSRange colon([href rangeOfString:@"://"]);
8513 if (colon.location != NSNotFound)
8514 href = [href substringFromIndex:(colon.location + 3)];
8515 href = [href stringByAddingPercentEscapes];
8516 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8518 NSURL *url([NSURL URLWithString:href]);
8520 NSStringEncoding encoding;
8521 NSError *error(nil);
8523 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8524 return [warning length] == 0 ? nil : warning;
8528 - (void) _endConnection:(NSURLConnection *)connection {
8529 // XXX: the memory management in this method is horribly awkward
8531 NSURLConnection **field = NULL;
8532 if (connection == trivial_bz2_)
8533 field = &trivial_bz2_;
8534 else if (connection == trivial_gz_)
8535 field = &trivial_gz_;
8536 _assert(field != NULL);
8537 [connection release];
8541 trivial_bz2_ == nil &&
8544 NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil);
8546 [self.delegate releaseNetworkActivityIndicator];
8548 [self.delegate removeProgressHUD:hud_];
8552 if (warning != nil) {
8553 UIAlertView *alert = [[[UIAlertView alloc]
8554 initWithTitle:UCLocalize("SOURCE_WARNING")
8557 cancelButtonTitle:UCLocalize("CANCEL")
8559 UCLocalize("ADD_ANYWAY"),
8563 [alert setContext:@"warning"];
8564 [alert setNumberOfRows:1];
8567 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
8573 } else if (error_ != nil) {
8574 UIAlertView *alert = [[[UIAlertView alloc]
8575 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8576 message:[error_ localizedDescription]
8578 cancelButtonTitle:UCLocalize("OK")
8579 otherButtonTitles:nil
8582 [alert setContext:@"urlerror"];
8587 UIAlertView *alert = [[[UIAlertView alloc]
8588 initWithTitle:UCLocalize("NOT_REPOSITORY")
8589 message:UCLocalize("NOT_REPOSITORY_EX")
8591 cancelButtonTitle:UCLocalize("OK")
8592 otherButtonTitles:nil
8595 [alert setContext:@"trivial"];
8605 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8606 switch ([response statusCode]) {
8612 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8613 lprintf("connection:\"%s\" didFailWithError:\"%s\"\n", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8615 [self _endConnection:connection];
8618 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8619 [self _endConnection:connection];
8622 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8623 NSURL *url([NSURL URLWithString:href]);
8625 NSMutableURLRequest *request = [NSMutableURLRequest
8627 cachePolicy:NSURLRequestUseProtocolCachePolicy
8631 [request setHTTPMethod:method];
8633 if (Machine_ != NULL)
8634 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8636 if (UniqueID_ != nil)
8637 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8639 if ([url isCydiaSecure]) {
8640 if (UniqueID_ != nil)
8641 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
8644 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8647 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8648 NSString *context([alert context]);
8650 if ([context isEqualToString:@"source"]) {
8653 NSString *href = [[alert textField] text];
8654 href = VerifySource(href);
8659 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8660 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8664 // XXX: this is stupid
8665 hud_ = [self.delegate addProgressHUD];
8666 [hud_ setText:UCLocalize("VERIFYING_URL")];
8667 [self.delegate retainNetworkActivityIndicator];
8676 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8677 } else if ([context isEqualToString:@"trivial"])
8678 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8679 else if ([context isEqualToString:@"urlerror"])
8680 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8681 else if ([context isEqualToString:@"warning"]) {
8684 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
8693 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8697 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated {
8698 BOOL editing([list_ isEditing]);
8701 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8702 initWithTitle:UCLocalize("ADD")
8703 style:UIBarButtonItemStylePlain
8705 action:@selector(addButtonClicked)
8706 ] autorelease] animated:animated];
8707 else if ([self.delegate updating])
8708 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8709 initWithTitle:UCLocalize("CANCEL")
8710 style:UIBarButtonItemStyleDone
8712 action:@selector(cancelButtonClicked)
8713 ] autorelease] animated:animated];
8715 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8716 initWithTitle:UCLocalize("REFRESH")
8717 style:UIBarButtonItemStylePlain
8719 action:@selector(refreshButtonClicked)
8720 ] autorelease] animated:animated];
8722 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8723 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8724 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8726 action:@selector(editButtonClicked)
8727 ] autorelease] animated:animated];
8731 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease];
8732 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8733 [list_ setRowHeight:53];
8734 [(UITableView *) list_ setDataSource:self];
8735 [list_ setDelegate:self];
8736 [self setView:list_];
8739 - (void) viewDidLoad {
8740 [super viewDidLoad];
8742 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8743 [self updateButtonsForEditingStatusAnimated:NO];
8746 - (void) viewWillAppear:(BOOL)animated {
8747 [super viewWillAppear:animated];
8749 [list_ setEditing:NO];
8750 [self updateButtonsForEditingStatusAnimated:NO];
8753 - (void) releaseSubviews {
8758 [super releaseSubviews];
8761 - (id) initWithDatabase:(Database *)database {
8762 if ((self = [super init]) != nil) {
8763 database_ = database;
8767 - (void) reloadData {
8769 [self updateButtonsForEditingStatusAnimated:YES];
8771 @synchronized (database_) {
8772 era_ = [database_ era];
8774 sources_ = [NSMutableArray arrayWithCapacity:16];
8775 [sources_ addObjectsFromArray:[database_ sources]];
8777 [sources_ sortUsingSelector:@selector(compareByName:)];
8780 int count([sources_ count]);
8782 for (int i = 0; i != count; i++) {
8783 if ([[sources_ objectAtIndex:i] record] == nil)
8791 - (void) showAddSourcePrompt {
8792 UIAlertView *alert = [[[UIAlertView alloc]
8793 initWithTitle:UCLocalize("ENTER_APT_URL")
8796 cancelButtonTitle:UCLocalize("CANCEL")
8798 UCLocalize("ADD_SOURCE"),
8802 [alert setContext:@"source"];
8804 [alert setNumberOfRows:1];
8805 [alert addTextFieldWithValue:@"http://" label:@""];
8807 NSObject<UITextInputTraits> *traits = [[alert textField] textInputTraits];
8808 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8809 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8810 [traits setKeyboardType:UIKeyboardTypeURL];
8811 // XXX: UIReturnKeyDone
8812 [traits setReturnKeyType:UIReturnKeyNext];
8817 - (void) addButtonClicked {
8818 [self showAddSourcePrompt];
8821 - (void) refreshButtonClicked {
8822 if ([self.delegate requestUpdate])
8823 [self updateButtonsForEditingStatusAnimated:YES];
8826 - (void) cancelButtonClicked {
8827 [self.delegate cancelUpdate];
8830 - (void) editButtonClicked {
8831 [list_ setEditing:![list_ isEditing] animated:YES];
8832 [self updateButtonsForEditingStatusAnimated:YES];
8838 /* Stash Controller {{{ */
8839 @interface StashController : CyteViewController {
8840 _H<UIActivityIndicatorView> spinner_;
8841 _H<UILabel> status_;
8842 _H<UILabel> caption_;
8847 @implementation StashController
8850 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8851 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8852 [self setView:view];
8854 [view setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8856 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8857 CGRect spinrect = [spinner_ frame];
8858 spinrect.origin.x = Retina([[self view] frame].size.width / 2 - spinrect.size.width / 2);
8859 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8860 [spinner_ setFrame:spinrect];
8861 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8862 [view addSubview:spinner_];
8863 [spinner_ startAnimating];
8866 captrect.size.width = [[self view] frame].size.width;
8867 captrect.size.height = 40.0f;
8868 captrect.origin.x = 0;
8869 captrect.origin.y = Retina([[self view] frame].size.height / 2 - captrect.size.height * 2);
8870 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8871 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8872 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8873 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8874 [caption_ setTextColor:[UIColor whiteColor]];
8875 [caption_ setBackgroundColor:[UIColor clearColor]];
8876 [caption_ setShadowColor:[UIColor blackColor]];
8877 [caption_ setTextAlignment:NSTextAlignmentCenter];
8878 [view addSubview:caption_];
8881 statusrect.size.width = [[self view] frame].size.width;
8882 statusrect.size.height = 30.0f;
8883 statusrect.origin.x = 0;
8884 statusrect.origin.y = Retina([[self view] frame].size.height / 2 - statusrect.size.height);
8885 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8886 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8887 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8888 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8889 [status_ setTextColor:[UIColor whiteColor]];
8890 [status_ setBackgroundColor:[UIColor clearColor]];
8891 [status_ setShadowColor:[UIColor blackColor]];
8892 [status_ setTextAlignment:NSTextAlignmentCenter];
8893 [view addSubview:status_];
8896 - (void) releaseSubviews {
8901 [super releaseSubviews];
8907 @interface Cydia : CyteApplication <
8908 ConfirmationControllerDelegate,
8912 _H<UIWindow> window_;
8913 _H<CydiaTabBarController> tabbar_;
8914 _H<CyteTabBarController> emulated_;
8915 _H<AppCacheController> appcache_;
8917 _H<NSMutableArray> essential_;
8918 _H<NSMutableArray> broken_;
8920 Database *database_;
8922 _H<NSURL> starturl_;
8927 _H<StashController> stash_;
8936 @implementation Cydia
8938 - (void) lockSuspend {
8939 if (locked_++ == 0) {
8940 if ($SBSSetInterceptsMenuButtonForever != NULL)
8941 (*$SBSSetInterceptsMenuButtonForever)(true);
8943 [self setIdleTimerDisabled:YES];
8947 - (void) unlockSuspend {
8948 if (--locked_ == 0) {
8949 [self setIdleTimerDisabled:NO];
8951 if ($SBSSetInterceptsMenuButtonForever != NULL)
8952 (*$SBSSetInterceptsMenuButtonForever)(false);
8956 - (void) beginUpdate {
8957 [tabbar_ beginUpdate];
8960 - (void) cancelUpdate {
8961 [tabbar_ cancelUpdate];
8964 - (bool) requestUpdate {
8965 if (IsReachable("cydia.saurik.com")) {
8969 UIAlertView *alert = [[[UIAlertView alloc]
8970 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("REFRESH")]
8971 message:@"Host Unreachable" // XXX: Localize
8973 cancelButtonTitle:UCLocalize("OK")
8974 otherButtonTitles:nil
8977 [alert setContext:@"norefresh"];
8985 return [tabbar_ updating];
8989 if ([broken_ count] != 0) {
8990 int count = [broken_ count];
8992 UIAlertView *alert = [[[UIAlertView alloc]
8993 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8994 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8996 cancelButtonTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("FORCIBLY_CLEAR"), UCLocalize("UNSAFE")]
8998 UCLocalize("TEMPORARY_IGNORE"),
9002 [alert setContext:@"fixhalf"];
9003 [alert setNumberOfRows:2];
9005 } else if (!Ignored_ && [essential_ count] != 0) {
9006 int count = [essential_ count];
9008 UIAlertView *alert = [[[UIAlertView alloc]
9009 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
9010 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
9012 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
9014 UCLocalize("UPGRADE_ESSENTIAL"),
9015 UCLocalize("COMPLETE_UPGRADE"),
9019 [alert setContext:@"upgrade"];
9024 - (void) returnToCydia {
9028 - (void) reloadSpringBoard {
9029 if (kCFCoreFoundationVersionNumber >= 700) // XXX: iOS 6.x
9030 system("/usr/libexec/cydia/cydo /bin/launchctl stop com.apple.backboardd");
9032 system("/usr/libexec/cydia/cydo /bin/launchctl stop com.apple.SpringBoard");
9034 system("/usr/bin/killall backboardd SpringBoard");
9037 - (void) _saveConfig {
9038 SaveConfig(database_);
9041 // Navigation controller for the queuing badge.
9042 - (UINavigationController *) queueNavigationController {
9043 NSArray *controllers = [tabbar_ viewControllers];
9044 return [controllers objectAtIndex:3];
9047 - (void) unloadData {
9048 [tabbar_ unloadData];
9051 - (void) _updateData {
9055 UINavigationController *navigation = [self queueNavigationController];
9057 id queuedelegate = nil;
9058 if ([[navigation viewControllers] count] > 0)
9059 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9061 [queuedelegate queueStatusDidChange];
9062 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9065 - (void) _refreshIfPossible {
9066 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9068 NSDate *update([[NSDictionary dictionaryWithContentsOfFile:@ CacheState_] objectForKey:@"LastUpdate"]);
9070 bool recently = false;
9071 if (update != nil) {
9072 NSTimeInterval interval([update timeIntervalSinceNow]);
9073 if (interval > -(15*60))
9077 // Don't automatic refresh if:
9078 // - We already refreshed recently.
9079 // - We already auto-refreshed this launch.
9080 // - Auto-refresh is disabled.
9081 // - Cydia's server is not reachable
9082 if (recently || loaded_ || ManualRefresh || !IsReachable("cydia.saurik.com")) {
9083 // If we are cancelling, we need to make sure it knows it's already loaded.
9086 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9088 // We are going to load, so remember that.
9091 [tabbar_ performSelectorOnMainThread:@selector(beginUpdate) withObject:nil waitUntilDone:NO];
9097 - (void) refreshIfPossible {
9098 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
9101 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9102 _profile(reloadDataWithInvocation)
9103 @synchronized (self) {
9104 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9106 [hud setText:UCLocalize("RELOADING_DATA")];
9108 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9112 [essential_ removeAllObjects];
9113 [broken_ removeAllObjects];
9115 _profile(reloadDataWithInvocation$Essential)
9116 NSArray *packages([database_ packages]);
9117 for (Package *package in packages) {
9119 [broken_ addObject:package];
9120 if ([package upgradableAndEssential:YES] && ![package ignored]) {
9121 if ([package essential] && [package installed] != nil)
9122 [essential_ addObject:package];
9128 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9131 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9132 [changesItem setBadgeValue:badge];
9133 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9134 [self setApplicationIconBadgeNumber:changes];
9137 [changesItem setBadgeValue:nil];
9138 [changesItem setAnimatedBadge:NO];
9139 [self setApplicationIconBadgeNumber:0];
9146 [self removeProgressHUD:hud];
9153 - (void) updateData {
9157 - (void) updateDataAndLoad {
9159 if ([database_ progressDelegate] == nil)
9165 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9168 - (void) disemulate {
9169 if (emulated_ == nil)
9172 if ([window_ respondsToSelector:@selector(setRootViewController:)])
9173 [window_ setRootViewController:tabbar_];
9175 [window_ addSubview:[tabbar_ view]];
9176 [[emulated_ view] removeFromSuperview];
9180 [window_ setUserInteractionEnabled:YES];
9183 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9184 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9186 UIViewController *parent;
9187 if (emulated_ == nil)
9197 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9198 [parent presentModalViewController:navigation animated:YES];
9201 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9202 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9204 if (navigation != nil)
9205 [navigation pushViewController:progress animated:YES];
9207 [self presentModalViewController:progress force:YES];
9209 [progress invoke:invocation withTitle:title];
9213 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9214 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9217 - (void) repairWithInvocation:(NSInvocation *)invocation {
9219 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9223 - (void) repairWithSelector:(SEL)selector {
9224 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9227 - (void) reloadData {
9228 [self reloadDataWithInvocation:nil];
9229 if ([database_ progressDelegate] == nil)
9235 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9238 - (void) addSource:(NSDictionary *) source {
9239 CydiaAddSource(source);
9242 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9243 CydiaAddSource(href, distribution, sections);
9246 // XXX: this method should not return anything
9247 - (BOOL) addTrivialSource:(NSString *)href {
9248 CydiaAddSource(href, @"./");
9253 pkgProblemResolver *resolver = [database_ resolver];
9255 resolver->InstallProtect();
9256 if (!resolver->Resolve(true))
9261 // XXX: this is a really crappy way of doing this.
9262 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9263 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9264 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9265 if ([tabbar_ updating])
9266 [tabbar_ cancelUpdate];
9268 if (![database_ prepare])
9271 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9272 [page setDelegate:self];
9273 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9276 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9277 [tabbar_ presentModalViewController:confirm_ animated:YES];
9283 @synchronized (self) {
9288 - (void) clearPackage:(Package *)package {
9289 @synchronized (self) {
9296 - (void) installPackages:(NSArray *)packages {
9297 @synchronized (self) {
9298 for (Package *package in packages)
9305 - (void) installPackage:(Package *)package {
9306 @synchronized (self) {
9313 - (void) removePackage:(Package *)package {
9314 @synchronized (self) {
9321 - (void) distUpgrade {
9322 @synchronized (self) {
9323 if (![database_ upgrade])
9331 system("/usr/bin/uicache");
9336 UIProgressHUD *hud([self addProgressHUD]);
9337 [hud setText:UCLocalize("LOADING")];
9338 [self yieldToSelector:@selector(_uicache)];
9339 [self removeProgressHUD:hud];
9343 [database_ perform];
9344 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9345 [self performSelectorOnMainThread:@selector(uicache) withObject:nil waitUntilDone:YES];
9348 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9351 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9352 [self unlockSuspend];
9355 - (void) retainNetworkActivityIndicator {
9356 if (activity_++ == 0)
9357 [self setNetworkActivityIndicatorVisible:YES];
9360 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9364 - (void) releaseNetworkActivityIndicator {
9365 if (--activity_ == 0)
9366 [self setNetworkActivityIndicatorVisible:NO];
9369 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9374 - (void) cancelAndClear:(bool)clear {
9375 @synchronized (self) {
9387 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9388 NSString *context([alert context]);
9390 if ([context isEqualToString:@"conffile"]) {
9391 FILE *input = [database_ input];
9392 if (button == [alert cancelButtonIndex])
9393 fprintf(input, "N\n");
9394 else if (button == [alert firstOtherButtonIndex])
9395 fprintf(input, "Y\n");
9398 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9399 } else if ([context isEqualToString:@"fixhalf"]) {
9400 if (button == [alert cancelButtonIndex]) {
9401 @synchronized (self) {
9402 for (Package *broken in (id) broken_) {
9404 NSString *id(ShellEscape([broken id]));
9405 system([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /bin/rm -f"
9406 " /var/lib/dpkg/info/%@.prerm"
9407 " /var/lib/dpkg/info/%@.postrm"
9408 " /var/lib/dpkg/info/%@.preinst"
9409 " /var/lib/dpkg/info/%@.postinst"
9410 " /var/lib/dpkg/info/%@.extrainst_"
9411 "", id, id, id, id, id] UTF8String]);
9417 } else if (button == [alert firstOtherButtonIndex]) {
9418 [broken_ removeAllObjects];
9422 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9423 } else if ([context isEqualToString:@"upgrade"]) {
9424 if (button == [alert firstOtherButtonIndex]) {
9425 @synchronized (self) {
9426 for (Package *essential in (id) essential_)
9427 [essential install];
9432 } else if (button == [alert firstOtherButtonIndex] + 1) {
9434 } else if (button == [alert cancelButtonIndex]) {
9438 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9442 - (void) system:(NSString *)command {
9443 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9446 system([command UTF8String]);
9452 - (void) applicationWillSuspend {
9454 [super applicationWillSuspend];
9457 - (BOOL) isSafeToSuspend {
9460 NSLog(@"isSafeToSuspend: locked_ != 0");
9465 if ([tabbar_ modalViewController] != nil)
9468 // Use external process status API internally.
9469 // This is probably a really bad idea.
9470 // XXX: what is the point of this? does this solve anything at all?
9471 uint64_t status = 0;
9473 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9474 notify_get_state(notify_token, &status);
9475 notify_cancel(notify_token);
9480 NSLog(@"isSafeToSuspend: status != 0");
9486 NSLog(@"isSafeToSuspend: -> true");
9491 - (void) suspendReturningToLastApp:(BOOL)returning {
9492 if ([self isSafeToSuspend])
9493 [super suspendReturningToLastApp:returning];
9497 if ([self isSafeToSuspend])
9501 - (void) applicationSuspend {
9502 if ([self isSafeToSuspend])
9503 [super applicationSuspend];
9506 - (void) applicationSuspend:(GSEventRef)event {
9507 if ([self isSafeToSuspend])
9508 [super applicationSuspend:event];
9511 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9512 if ([self isSafeToSuspend])
9513 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9516 - (void) _setSuspended:(BOOL)value {
9517 if ([self isSafeToSuspend])
9518 [super _setSuspended:value];
9521 - (UIProgressHUD *) addProgressHUD {
9522 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9523 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9525 [window_ setUserInteractionEnabled:NO];
9527 UIViewController *target(tabbar_);
9528 if (UIViewController *modal = [target modalViewController])
9531 [hud showInView:[target view]];
9537 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9538 [self unlockSuspend];
9540 [hud removeFromSuperview];
9541 [window_ setUserInteractionEnabled:YES];
9544 - (CyteViewController *) pageForPackage:(NSString *)name withReferrer:(NSString *)referrer {
9545 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name withReferrer:referrer] autorelease];
9548 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external withReferrer:(NSString *)referrer {
9549 NSString *scheme([[url scheme] lowercaseString]);
9550 if ([[url absoluteString] length] <= [scheme length] + 3)
9552 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9553 NSArray *components([path componentsSeparatedByString:@"/"]);
9555 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"]) {
9556 CyteViewController *controller([self pageForPackage:[components objectAtIndex:1] withReferrer:referrer]);
9557 if (controller != nil)
9558 [controller setDelegate:self];
9562 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9565 NSString *base([components objectAtIndex:0]);
9567 CyteViewController *controller = nil;
9569 if ([base isEqualToString:@"url"]) {
9570 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9571 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9572 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9573 } else if (!external && [components count] == 1) {
9574 if ([base isEqualToString:@"sources"]) {
9575 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9578 if ([base isEqualToString:@"home"]) {
9579 controller = [[[HomeController alloc] init] autorelease];
9582 if ([base isEqualToString:@"sections"]) {
9583 controller = [[[SectionsController alloc] initWithDatabase:database_ source:nil] autorelease];
9586 if ([base isEqualToString:@"search"]) {
9587 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9590 if ([base isEqualToString:@"changes"]) {
9591 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9594 if ([base isEqualToString:@"installed"]) {
9595 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9597 } else if ([components count] == 2) {
9598 NSString *argument = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9600 if ([base isEqualToString:@"package"]) {
9601 controller = [self pageForPackage:argument withReferrer:referrer];
9604 if (!external && [base isEqualToString:@"search"]) {
9605 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9608 if (!external && [base isEqualToString:@"sections"]) {
9609 if ([argument isEqualToString:@"all"] || [argument isEqualToString:@"*"])
9611 controller = [[[SectionController alloc] initWithDatabase:database_ source:nil section:argument] autorelease];
9614 if ([base isEqualToString:@"sources"]) {
9615 if ([argument isEqualToString:@"add"]) {
9616 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9617 [(SourcesController *)controller showAddSourcePrompt];
9619 Source *source([database_ sourceWithKey:argument]);
9620 controller = [[[SectionsController alloc] initWithDatabase:database_ source:source] autorelease];
9624 if (!external && [base isEqualToString:@"launch"]) {
9625 [self launchApplicationWithIdentifier:argument suspended:NO];
9628 } else if (!external && [components count] == 3) {
9629 NSString *arg1 = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9630 NSString *arg2 = [[components objectAtIndex:2] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9632 if ([base isEqualToString:@"package"]) {
9633 if ([arg2 isEqualToString:@"settings"]) {
9634 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9635 } else if ([arg2 isEqualToString:@"files"]) {
9636 if (Package *package = [database_ packageWithName:arg1]) {
9637 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9638 [(FileTable *)controller setPackage:package];
9643 if ([base isEqualToString:@"sections"]) {
9644 Source *source([arg1 isEqualToString:@"*"] ? nil : [database_ sourceWithKey:arg1]);
9645 NSString *section([arg2 isEqualToString:@"*"] ? nil : arg2);
9646 controller = [[[SectionController alloc] initWithDatabase:database_ source:source section:section] autorelease];
9650 [controller setDelegate:self];
9654 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9655 CyteViewController *page([self pageForURL:url forExternal:external withReferrer:nil]);
9658 [tabbar_ setUnselectedViewController:page];
9663 - (void) applicationOpenURL:(NSURL *)url {
9664 [super applicationOpenURL:url];
9669 [self openCydiaURL:url forExternal:YES];
9672 - (void) applicationWillResignActive:(UIApplication *)application {
9673 // Stop refreshing if you get a phone call or lock the device.
9674 if ([tabbar_ updating])
9675 [tabbar_ cancelUpdate];
9677 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9678 [super applicationWillResignActive:application];
9681 - (void) saveState {
9682 [[NSDictionary dictionaryWithObjectsAndKeys:
9683 @"InterfaceState", [tabbar_ navigationURLCollection],
9684 @"LastClosed", [NSDate date],
9685 @"InterfaceIndex", [NSNumber numberWithInt:[tabbar_ selectedIndex]],
9686 nil] writeToFile:@ SavedState_ atomically:YES];
9691 - (void) applicationWillTerminate:(UIApplication *)application {
9695 - (void) applicationDidEnterBackground:(UIApplication *)application {
9696 if (kCFCoreFoundationVersionNumber < 1000 && [self isSafeToSuspend])
9697 return [self terminateWithSuccess];
9698 Backgrounded_ = [NSDate date];
9702 - (void) applicationWillEnterForeground:(UIApplication *)application {
9703 if (Backgrounded_ == nil)
9706 NSTimeInterval interval([Backgrounded_ timeIntervalSinceNow]);
9708 if (interval <= -(30*60)) {
9709 [tabbar_ setSelectedIndex:0];
9710 [[[tabbar_ viewControllers] objectAtIndex:0] popToRootViewControllerAnimated:NO];
9713 if (interval <= -(15*60)) {
9714 if (IsReachable("cydia.saurik.com")) {
9715 [tabbar_ beginUpdate];
9716 [appcache_ reloadURLWithCache:YES];
9720 if ([database_ delocked])
9724 - (void) setConfigurationData:(NSString *)data {
9725 static RegEx conffile_r("'(.*)' '(.*)' ([01]) ([01])");
9727 if (!conffile_r(data)) {
9728 lprintf("E:invalid conffile\n");
9732 NSString *ofile = conffile_r[1];
9733 //NSString *nfile = conffile_r[2];
9735 UIAlertView *alert = [[[UIAlertView alloc]
9736 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9737 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9739 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9741 UCLocalize("ACCEPT_NEW_COPY"),
9742 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9746 [alert setContext:@"conffile"];
9747 [alert setNumberOfRows:2];
9751 - (void) addStashController {
9753 stash_ = [[[StashController alloc] init] autorelease];
9754 [window_ addSubview:[stash_ view]];
9757 - (void) removeStashController {
9758 [[stash_ view] removeFromSuperview];
9760 [self unlockSuspend];
9764 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9765 UpdateExternalStatus(1);
9766 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/cydo /usr/libexec/cydia/free.sh"];
9767 UpdateExternalStatus(0);
9769 [self removeStashController];
9770 [self reloadSpringBoard];
9773 - (void) setupViewControllers {
9774 tabbar_ = [[[CydiaTabBarController alloc] initWithDatabase:database_] autorelease];
9776 NSMutableArray *items;
9777 if (kCFCoreFoundationVersionNumber < 800) {
9778 items = [NSMutableArray arrayWithObjects:
9779 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage imageNamed:@"home.png"] tag:0] autorelease],
9780 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage imageNamed:@"install.png"] tag:0] autorelease],
9781 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage imageNamed:@"changes.png"] tag:0] autorelease],
9782 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage imageNamed:@"manage.png"] tag:0] autorelease],
9783 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage imageNamed:@"search.png"] tag:0] autorelease],
9786 items = [NSMutableArray arrayWithObjects:
9787 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage imageNamed:@"home7.png"] selectedImage:[UIImage imageNamed:@"home7s.png"]] autorelease],
9788 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage imageNamed:@"install7.png"] selectedImage:[UIImage imageNamed:@"install7s.png"]] autorelease],
9789 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage imageNamed:@"changes7.png"] selectedImage:[UIImage imageNamed:@"changes7s.png"]] autorelease],
9790 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage imageNamed:@"manage7.png"] selectedImage:[UIImage imageNamed:@"manage7s.png"]] autorelease],
9791 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage imageNamed:@"search7.png"] selectedImage:[UIImage imageNamed:@"search7s.png"]] autorelease],
9795 NSMutableArray *controllers([NSMutableArray array]);
9796 for (UITabBarItem *item in items) {
9797 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9798 [controller setTabBarItem:item];
9799 [controllers addObject:controller];
9801 [tabbar_ setViewControllers:controllers];
9803 [tabbar_ setUpdateDelegate:self];
9806 - (void) applicationDidFinishLaunching:(id)unused {
9807 [super applicationDidFinishLaunching:unused];
9810 @synchronized (HostConfig_) {
9811 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9814 [NSURLCache setSharedURLCache:[[[CyteURLCache alloc]
9815 initWithMemoryCapacity:524288
9816 diskCapacity:10485760
9817 diskPath:Cache("SDURLCache")
9820 [CydiaWebViewController _initialize];
9822 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9824 // this would disallow http{,s} URLs from accessing this data
9825 //[WebView registerURLSchemeAsLocal:@"cydia"];
9827 Font12_ = [UIFont systemFontOfSize:12];
9828 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9829 Font14_ = [UIFont systemFontOfSize:14];
9830 Font18_ = [UIFont systemFontOfSize:18];
9831 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9832 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9834 essential_ = [NSMutableArray arrayWithCapacity:4];
9835 broken_ = [NSMutableArray arrayWithCapacity:4];
9837 // XXX: I really need this thing... like, seriously... I'm sorry
9838 appcache_ = [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] autorelease];
9839 [appcache_ reloadData];
9841 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9842 [window_ orderFront:self];
9843 [window_ makeKey:self];
9844 [window_ setHidden:NO];
9846 if (access("/.cydia_no_stash", F_OK) == 0);
9850 [self addStashController];
9851 // XXX: this would be much cleaner as a yieldToSelector:
9852 // that way the removeStashController could happen right here inline
9853 // we also could no longer require the useless stash_ field anymore
9854 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9859 int error(stat("/", &root));
9860 _assert(error != -1);
9862 #define Stash_(path) do { \
9863 struct stat folder; \
9864 int error(lstat((path), &folder)); \
9865 if (error != -1 && ( \
9866 folder.st_dev == root.st_dev && \
9867 S_ISDIR(folder.st_mode) \
9868 ) || error == -1 && ( \
9869 errno == ENOENT || \
9874 Stash_("/Applications");
9875 Stash_("/Library/Ringtones");
9876 Stash_("/Library/Wallpaper");
9877 //Stash_("/usr/bin");
9878 Stash_("/usr/include");
9879 Stash_("/usr/share");
9880 //Stash_("/var/lib");
9884 database_ = [Database sharedInstance];
9885 [database_ setDelegate:self];
9887 [window_ setUserInteractionEnabled:NO];
9888 [self setupViewControllers];
9890 CydiaLoadingViewController *loading([[[CydiaLoadingViewController alloc] init] autorelease]);
9891 UINavigationController *navigation([[[UINavigationController alloc] init] autorelease]);
9892 [navigation setViewControllers:[NSArray arrayWithObject:loading]];
9894 emulated_ = [[[CyteTabBarController alloc] init] autorelease];
9895 [emulated_ setViewControllers:[NSArray arrayWithObject:navigation]];
9896 [emulated_ setSelectedIndex:0];
9898 if ([emulated_ respondsToSelector:@selector(concealTabBarSelection)])
9899 [emulated_ concealTabBarSelection];
9901 if ([window_ respondsToSelector:@selector(setRootViewController:)])
9902 [window_ setRootViewController:emulated_];
9904 [window_ addSubview:[emulated_ view]];
9906 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9910 - (NSArray *) defaultStartPages {
9911 NSMutableArray *standard = [NSMutableArray array];
9912 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9913 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9914 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9915 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9916 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9922 if ([emulated_ modalViewController] != nil)
9923 [emulated_ dismissModalViewControllerAnimated:YES];
9924 [window_ setUserInteractionEnabled:NO];
9926 [self reloadDataWithInvocation:nil];
9927 [self refreshIfPossible];
9930 NSDictionary *state([NSDictionary dictionaryWithContentsOfFile:@ SavedState_]);
9932 int savedIndex = [[state objectForKey:@"InterfaceIndex"] intValue];
9933 NSArray *saved = [[[state objectForKey:@"InterfaceState"] mutableCopy] autorelease];
9934 int standardIndex = 0;
9935 NSArray *standard = [self defaultStartPages];
9942 NSDate *closed = [state objectForKey:@"LastClosed"];
9943 if (valid && closed != nil) {
9944 NSTimeInterval interval([closed timeIntervalSinceNow]);
9945 if (interval <= -(30*60))
9949 if (valid && [saved count] != [standard count])
9953 for (unsigned int i = 0; i < [standard count]; i++) {
9954 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9955 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9956 // but it's good enough for now.
9957 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9964 NSArray *items = nil;
9966 [tabbar_ setSelectedIndex:savedIndex];
9969 [tabbar_ setSelectedIndex:standardIndex];
9973 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9974 NSArray *stack = [items objectAtIndex:tab];
9975 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9976 NSMutableArray *current = [NSMutableArray array];
9978 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9979 NSString *addr = [stack objectAtIndex:nav];
9980 NSURL *url = [NSURL URLWithString:addr];
9981 CyteViewController *page = [self pageForURL:url forExternal:NO withReferrer:nil];
9983 [current addObject:page];
9986 [navigation setViewControllers:current];
9989 // (Try to) show the startup URL.
9990 if (starturl_ != nil) {
9991 [self openCydiaURL:starturl_ forExternal:YES];
9996 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9998 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
9999 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
10002 if (item != nil && IsWildcat_) {
10003 [sheet showFromBarButtonItem:item animated:YES];
10005 [sheet showInView:window_];
10009 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
10010 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
10011 [progress setTitle:task];
10012 [progress addProgressEvent:event];
10015 - (void) addProgressEventForTask:(NSArray *)data {
10016 CydiaProgressEvent *event([data objectAtIndex:0]);
10017 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
10018 [self addProgressEvent:event forTask:task];
10021 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
10022 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
10028 id Alloc_(id self, SEL selector) {
10029 id object = alloc_(self, selector);
10030 lprintf("[%s]A-%p\n", self->isa->name, object);
10035 id Dealloc_(id self, SEL selector) {
10036 id object = dealloc_(self, selector);
10037 lprintf("[%s]D-%p\n", self->isa->name, object);
10043 static CGSize $WAKWindow$screenSize(WAKWindow *self, SEL _cmd) {
10044 CGSize size([[UIScreen mainScreen] bounds].size);
10045 /*if ([$WAKWindow respondsToSelector:@selector(hasLandscapeOrientation)])
10046 if ([$WAKWindow hasLandscapeOrientation])
10047 std::swap(size.width, size.height);*/
10051 Class $NSUserDefaults;
10053 MSHook(id, NSUserDefaults$objectForKey$, NSUserDefaults *self, SEL _cmd, NSString *key) {
10054 if ([key respondsToSelector:@selector(isEqualToString:)] && [key isEqualToString:@"WebKitLocalStorageDatabasePathPreferenceKey"])
10055 return Cache("LocalStorage");
10056 return _NSUserDefaults$objectForKey$(self, _cmd, key);
10059 static NSMutableDictionary *AutoreleaseDeepMutableCopyOfDictionary(CFTypeRef type) {
10062 if (CFGetTypeID(type) != CFDictionaryGetTypeID())
10064 CFTypeRef copy(CFPropertyListCreateDeepCopy(kCFAllocatorDefault, type, kCFPropertyListMutableContainers));
10066 return [(NSMutableDictionary *) copy autorelease];
10069 int main_store(int, char *argv[]);
10071 int main(int argc, char *argv[]) {
10073 const char *argv0(argv[0]);
10074 if (const char *slash = strrchr(argv0, '/'))
10077 else if (!strcmp(argv0, "store"))
10078 return main_store(argc, argv);
10081 int fd(open("/tmp/cydia.log", O_WRONLY | O_APPEND | O_CREAT, 0644));
10085 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10089 UpdateExternalStatus(0);
10091 UIScreen *screen([UIScreen mainScreen]);
10092 if ([screen respondsToSelector:@selector(scale)])
10093 ScreenScale_ = [screen scale];
10097 UIDevice *device([UIDevice currentDevice]);
10098 if ([device respondsToSelector:@selector(userInterfaceIdiom)]) {
10099 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10100 if (idiom == UIUserInterfaceIdiomPad)
10104 Idiom_ = IsWildcat_ ? @"ipad" : @"iphone";
10106 RegEx pattern("([0-9]+\\.[0-9]+).*");
10108 if (pattern([device systemVersion]))
10109 Firmware_ = pattern[1];
10110 if (pattern(Cydia_))
10111 Major_ = pattern[1];
10113 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
10115 HostConfig_ = [[[NSObject alloc] init] autorelease];
10116 @synchronized (HostConfig_) {
10117 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10118 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
10121 NSString *ui(@"ui/ios");
10123 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
10124 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"/%@", Major_]];
10125 UI_ = CydiaURL(ui);
10127 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10129 /* Library Hacks {{{ */
10130 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10132 $WAKWindow = objc_getClass("WAKWindow");
10133 if ($WAKWindow != NULL)
10134 if (Method method = class_getInstanceMethod($WAKWindow, @selector(screenSize)))
10135 method_setImplementation(method, (IMP) &$WAKWindow$screenSize);
10137 $NSUserDefaults = objc_getClass("NSUserDefaults");
10138 Method NSUserDefaults$objectForKey$(class_getInstanceMethod($NSUserDefaults, @selector(objectForKey:)));
10139 if (NSUserDefaults$objectForKey$ != NULL) {
10140 _NSUserDefaults$objectForKey$ = reinterpret_cast<id (*)(NSUserDefaults *, SEL, NSString *)>(method_getImplementation(NSUserDefaults$objectForKey$));
10141 method_setImplementation(NSUserDefaults$objectForKey$, reinterpret_cast<IMP>(&$NSUserDefaults$objectForKey$));
10144 /* Set Locale {{{ */
10145 Locale_ = CFLocaleCopyCurrent();
10146 Languages_ = [NSLocale preferredLanguages];
10148 std::string languages;
10149 const char *translation(NULL);
10151 // XXX: this isn't really a language, but this is compatible with older Cydia builds
10152 if (Locale_ != NULL)
10153 if (const char *language = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String]) {
10154 RegEx pattern("([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?");
10155 if (pattern(language)) {
10156 translation = strdup([pattern->*@"%1$@%2$@" UTF8String]);
10157 languages += translation;
10162 if (Languages_ != nil)
10163 for (NSString *locale : Languages_) {
10164 auto components([NSLocale componentsFromLocaleIdentifier:locale]);
10165 NSString *language([components objectForKey:(id)kCFLocaleLanguageCode]);
10166 if (NSString *script = [components objectForKey:(id)kCFLocaleScriptCode])
10167 language = [NSString stringWithFormat:@"%@-%@", language, script];
10168 languages += [language UTF8String];
10173 NSLog(@"Setting Language: [%s] %s", translation, languages.c_str());
10175 /* Index Collation {{{ */
10176 if (Class $UILocalizedIndexedCollation = objc_getClass("UILocalizedIndexedCollation")) { @try {
10177 NSBundle *bundle([NSBundle bundleForClass:$UILocalizedIndexedCollation]);
10178 NSString *path([bundle pathForResource:@"UITableViewLocalizedSectionIndex" ofType:@"plist"]);
10179 //path = @"/System/Library/Frameworks/UIKit.framework/.lproj/UITableViewLocalizedSectionIndex.plist";
10180 NSDictionary *dictionary([NSDictionary dictionaryWithContentsOfFile:path]);
10181 _H<UILocalizedIndexedCollation> collation([[[$UILocalizedIndexedCollation alloc] initWithDictionary:dictionary] autorelease]);
10183 CollationLocale_ = MSHookIvar<NSLocale *>(collation, "_locale");
10185 if (kCFCoreFoundationVersionNumber >= 800 && [[CollationLocale_ localeIdentifier] isEqualToString:@"zh@collation=stroke"]) {
10186 CollationThumbs_ = [NSArray arrayWithObjects:@"1",@"•",@"4",@"•",@"7",@"•",@"10",@"•",@"13",@"•",@"16",@"•",@"19",@"A",@"•",@"E",@"•",@"I",@"•",@"M",@"•",@"R",@"•",@"V",@"•",@"Z",@"#",nil];
10187 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})
10188 CollationOffset_.push_back(offset);
10189 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];
10190 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];
10193 CollationThumbs_ = [collation sectionIndexTitles];
10194 for (size_t index(0), end([CollationThumbs_ count]); index != end; ++index)
10195 CollationOffset_.push_back([collation sectionForSectionIndexTitleAtIndex:index]);
10197 CollationTitles_ = [collation sectionTitles];
10198 CollationStarts_ = MSHookIvar<NSArray *>(collation, "_sectionStartStrings");
10200 NSString *&transform(MSHookIvar<NSString *>(collation, "_transform"));
10201 if (&transform != NULL && transform != nil) {
10202 /*if ([collation respondsToSelector:@selector(transformedCollationStringForString:)])
10203 CollationModify_ = [=](NSString *value) { return [collation transformedCollationStringForString:value]; };*/
10204 const UChar *uid(reinterpret_cast<const UChar *>([transform cStringUsingEncoding:NSUnicodeStringEncoding]));
10205 UErrorCode code(U_ZERO_ERROR);
10206 CollationTransl_ = utrans_openU(uid, -1, UTRANS_FORWARD, NULL, 0, NULL, &code);
10207 if (!U_SUCCESS(code))
10208 NSLog(@"%s", u_errorName(code));
10212 } @catch (NSException *e) {
10216 CollationLocale_ = [[[NSLocale alloc] initWithLocaleIdentifier:@"en@collation=dictionary"] autorelease];
10218 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];
10219 for (NSInteger offset(0); offset != 28; ++offset)
10220 CollationOffset_.push_back(offset);
10222 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];
10223 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];
10227 App_ = [[NSBundle mainBundle] bundlePath];
10230 Cache_ = [[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia", @"/var/mobile"] retain];
10231 mkdir([Cache_ UTF8String], 0755);
10233 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10234 alloc_ = alloc->method_imp;
10235 alloc->method_imp = (IMP) &Alloc_;*/
10237 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10238 dealloc_ = dealloc->method_imp;
10239 dealloc->method_imp = (IMP) &Dealloc_;*/
10241 void *gestalt(dlopen("/usr/lib/libMobileGestalt.dylib", RTLD_GLOBAL | RTLD_LAZY));
10242 $MGCopyAnswer = reinterpret_cast<CFStringRef (*)(CFStringRef)>(dlsym(gestalt, "MGCopyAnswer"));
10244 /* System Information {{{ */
10248 size = sizeof(maxproc);
10249 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10250 perror("sysctlbyname(\"kern.maxproc\", ?)");
10251 else if (maxproc < 64) {
10253 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10254 perror("sysctlbyname(\"kern.maxproc\", #)");
10257 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10258 char *osversion = new char[size];
10259 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10260 perror("sysctlbyname(\"kern.osversion\", ?)");
10262 System_ = [NSString stringWithUTF8String:osversion];
10264 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10265 char *machine = new char[size];
10266 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10267 perror("sysctlbyname(\"hw.machine\", ?)");
10269 Machine_ = machine;
10271 int64_t usermem(0);
10272 size = sizeof(usermem);
10273 if (sysctlbyname("hw.usermem", &usermem, &size, NULL, 0) == -1)
10276 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10277 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10278 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10280 UniqueID_ = UniqueIdentifier(device);
10282 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10283 Product_ = [info objectForKey:@"SafariProductVersion"];
10284 Safari_ = [info objectForKey:@"CFBundleVersion"];
10287 NSString *agent([NSString stringWithFormat:@"Cydia/%@ CyF/%.2f", Cydia_, kCFCoreFoundationVersionNumber]);
10289 if (RegEx match = RegEx("([0-9]+(\\.[0-9]+)+).*", Safari_))
10290 agent = [NSString stringWithFormat:@"Safari/%@ %@", match[1], agent];
10291 if (RegEx match = RegEx("([0-9]+[A-Z][0-9]+[a-z]?).*", System_))
10292 agent = [NSString stringWithFormat:@"Mobile/%@ %@", match[1], agent];
10293 if (RegEx match = RegEx("([0-9]+(\\.[0-9]+)+).*", Product_))
10294 agent = [NSString stringWithFormat:@"Version/%@ %@", match[1], agent];
10296 UserAgent_ = agent;
10298 /* Load Database {{{ */
10299 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10302 mkdir("/var/mobile/Library/Cydia", 0755);
10303 MetaFile_.Open("/var/mobile/Library/Cydia/metadata.cb0");
10306 Values_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaValues"), CFSTR("com.saurik.Cydia")));
10307 Sections_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaSections"), CFSTR("com.saurik.Cydia")));
10308 Sources_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaSources"), CFSTR("com.saurik.Cydia")));
10309 Version_ = [(NSNumber *) CFPreferencesCopyAppValue(CFSTR("CydiaVersion"), CFSTR("com.saurik.Cydia")) autorelease];
10312 NSDictionary *metadata([[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease]);
10314 if (Values_ == nil)
10315 Values_ = [metadata objectForKey:@"Values"];
10316 if (Values_ == nil)
10317 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10319 if (Sections_ == nil)
10320 Sections_ = [metadata objectForKey:@"Sections"];
10321 if (Sections_ == nil)
10322 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10324 if (Sources_ == nil)
10325 Sources_ = [metadata objectForKey:@"Sources"];
10326 if (Sources_ == nil)
10327 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10329 // XXX: this wrong, but in a way that doesn't matter :/
10330 if (Version_ == nil)
10331 Version_ = [metadata objectForKey:@"Version"];
10332 if (Version_ == nil)
10333 Version_ = [NSNumber numberWithUnsignedInt:0];
10335 if (NSDictionary *packages = [metadata objectForKey:@"Packages"]) {
10337 CFDictionaryApplyFunction((CFDictionaryRef) packages, &PackageImport, &fail);
10340 NSLog(@"unable to import package preferences... from 2010? oh well :/");
10343 if ([Version_ unsignedIntValue] == 0) {
10344 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10345 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10346 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10347 CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./");
10349 Version_ = [NSNumber numberWithUnsignedInt:1];
10351 if (NSMutableDictionary *cache = [NSMutableDictionary dictionaryWithContentsOfFile:@ CacheState_]) {
10352 [cache removeObjectForKey:@"LastUpdate"];
10353 [cache writeToFile:@ CacheState_ atomically:YES];
10357 _H<NSMutableArray> broken([NSMutableArray array]);
10358 for (NSString *key in (id) Sources_)
10359 if ([key rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"# "]].location != NSNotFound || ![([[Sources_ objectForKey:key] objectForKey:@"URI"] ?: @"/") hasSuffix:@"/"])
10360 [broken addObject:key];
10361 if ([broken count] != 0)
10362 for (NSString *key in (id) broken)
10363 [Sources_ removeObjectForKey:key];
10367 system("/usr/libexec/cydia/cydo /bin/rm -f /var/lib/cydia/metadata.plist");
10370 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10372 if (kCFCoreFoundationVersionNumber > 1000)
10373 system("/usr/libexec/cydia/cydo /usr/libexec/cydia/setnsfpn /var/lib");
10375 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10377 if (access("/User", F_OK) != 0 || version != 6) {
10379 system("/usr/libexec/cydia/cydo /usr/libexec/cydia/firmware.sh");
10383 if (access("/tmp/cydia.chk", F_OK) == 0) {
10384 if (unlink([Cache("pkgcache.bin") UTF8String]) == -1)
10385 _assert(errno == ENOENT);
10386 if (unlink([Cache("srcpkgcache.bin") UTF8String]) == -1)
10387 _assert(errno == ENOENT);
10390 system("/usr/libexec/cydia/cydo /bin/ln -sf /var/mobile/Library/Caches/com.saurik.Cydia/sources.list /etc/apt/sources.list.d/cydia.list");
10392 /* APT Initialization {{{ */
10393 _assert(pkgInitConfig(*_config));
10394 _assert(pkgInitSystem(*_config, _system));
10396 _config->Set("Acquire::AllowInsecureRepositories", true);
10397 _config->Set("Acquire::Check-Valid-Until", false);
10398 _config->Set("Dir::Bin::Methods::store", "/Applications/Cydia.app/store");
10400 _config->Set("pkgCacheGen::ForceEssential", "");
10402 if (translation != NULL)
10403 _config->Set("APT::Acquire::Translation", translation);
10404 _config->Set("Acquire::Languages", languages);
10406 // XXX: this timeout might be important :(
10407 //_config->Set("Acquire::http::Timeout", 15);
10409 _config->Set("Acquire::http::MaxParallel", usermem >= 384 * 1024 * 1024 ? 16 : 3);
10411 mkdir([Cache("archives") UTF8String], 0755);
10412 mkdir([Cache("archives/partial") UTF8String], 0755);
10413 _config->Set("Dir::Cache", [Cache_ UTF8String]);
10415 symlink("/var/lib/apt/extended_states", [Cache("extended_states") UTF8String]);
10416 _config->Set("Dir::State", [Cache_ UTF8String]);
10418 mkdir([Cache("lists") UTF8String], 0755);
10419 mkdir([Cache("lists/partial") UTF8String], 0755);
10420 mkdir([Cache("periodic") UTF8String], 0755);
10421 _config->Set("Dir::State::Lists", [Cache("lists") UTF8String]);
10423 std::string logs("/var/mobile/Library/Logs/Cydia");
10424 mkdir(logs.c_str(), 0755);
10425 _config->Set("Dir::Log", logs);
10427 _config->Set("Dir::Bin::dpkg", "/usr/libexec/cydia/cydo");
10429 /* Color Choices {{{ */
10430 space_ = CGColorSpaceCreateDeviceRGB();
10432 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10433 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10434 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10435 Folder_.Set(space_, 0x8e/255.f, 0x8e/255.f, 0x93/255.f, 1.0);
10436 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10437 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10438 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10439 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10440 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10441 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10443 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10444 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10446 /* UIKit Configuration {{{ */
10447 // XXX: I have a feeling this was important
10448 //UIKeyboardDisableAutomaticAppearance();
10451 $SBSSetInterceptsMenuButtonForever = reinterpret_cast<void (*)(bool)>(dlsym(RTLD_DEFAULT, "SBSSetInterceptsMenuButtonForever"));
10452 $SBSCopyIconImagePNGDataForDisplayIdentifier = reinterpret_cast<NSData *(*)(NSString *)>(dlsym(RTLD_DEFAULT, "SBSCopyIconImagePNGDataForDisplayIdentifier"));
10454 const char *symbol(kCFCoreFoundationVersionNumber >= 800 ? "MGGetBoolAnswer" : "GSSystemHasCapability");
10455 BOOL (*GSSystemHasCapability)(CFStringRef) = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, symbol));
10456 bool fast = GSSystemHasCapability != NULL && GSSystemHasCapability(CFSTR("armv7"));
10458 PulseInterval_ = fast ? 50000 : 500000;
10460 Colon_ = UCLocalize("COLON_DELIMITED");
10461 Elision_ = UCLocalize("ELISION");
10462 Error_ = UCLocalize("ERROR");
10463 Warning_ = UCLocalize("WARNING");
10466 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10468 CGColorSpaceRelease(space_);
10469 CFRelease(Locale_);