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/CyteKit.h"
116 #include "CyteKit/RegEx.hpp"
118 #include "Cydia/MIMEAddress.h"
119 #include "Cydia/LoadingViewController.h"
120 #include "Cydia/ProgressEvent.h"
127 #define _timestamp ({ \
129 gettimeofday(&tv, NULL); \
130 tv.tv_sec * 1000000 + tv.tv_usec; \
133 typedef std::vector<class ProfileTime *> TimeList;
143 ProfileTime(const char *name) :
147 times_.push_back(this);
150 void AddTime(uint64_t time) {
157 std::cerr << std::setw(7) << count_ << ", " << std::setw(8) << total_ << " : " << name_ << std::endl;
169 ProfileTimer(ProfileTime &time) :
176 time_.AddTime(_timestamp - start_);
181 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
183 std::cerr << "========" << std::endl;
186 #define _profile(name) { \
187 static ProfileTime name(#name); \
188 ProfileTimer _ ## name(name);
193 extern NSString *Cydia_;
195 #define lprintf(args...) fprintf(stderr, args)
198 #define TraceLogging (1 && !ForRelease)
199 #define HistogramInsertionSort (0 && !ForRelease)
200 #define ProfileTimes (0 && !ForRelease)
201 #define ForSaurik (0 && !ForRelease)
202 #define LogBrowser (0 && !ForRelease)
203 #define TrackResize (0 && !ForRelease)
204 #define ManualRefresh (1 && !ForRelease)
205 #define ShowInternals (0 && !ForRelease)
206 #define AlwaysReload (0 && !ForRelease)
210 #define _trace(args...)
215 #define _profile(name) {
218 #define PrintTimes() do {} while (false)
221 // Hash Functions/Structures {{{
222 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
230 @implementation NSDictionary (Cydia)
231 - (id) invokeUndefinedMethodFromWebScript:(NSString *)name withArguments:(NSArray *)arguments {
233 else if ([name isEqualToString:@"get"])
234 return [self objectForKey:[arguments objectAtIndex:0]];
235 else if ([name isEqualToString:@"keys"])
236 return [self allKeys];
240 static NSString *Colon_;
242 static NSString *Error_;
243 static NSString *Warning_;
245 static NSString *Cache_;
246 #define Cache(file) \
247 [NSString stringWithFormat:@"%@/%s", Cache_, file]
249 static void (*$SBSSetInterceptsMenuButtonForever)(bool);
250 static NSData *(*$SBSCopyIconImagePNGDataForDisplayIdentifier)(NSString *);
252 static CFStringRef (*$MGCopyAnswer)(CFStringRef);
254 static NSString *UniqueIdentifier(UIDevice *device = nil) {
255 if (kCFCoreFoundationVersionNumber < 800) // iOS 7.x
256 return [device ?: [UIDevice currentDevice] uniqueIdentifier];
258 return [(id)$MGCopyAnswer(CFSTR("UniqueDeviceID")) autorelease];
261 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
263 static _finline NSString *CydiaURL(NSString *path) {
265 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
266 page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
267 page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
268 page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
269 page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
271 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
274 static NSString *ShellEscape(NSString *value) {
275 return [NSString stringWithFormat:@"'%@'", [value stringByReplacingOccurrencesOfString:@"'" withString:@"'\\''"]];
278 static _finline void UpdateExternalStatus(uint64_t newStatus) {
280 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
281 notify_set_state(notify_token, newStatus);
282 notify_cancel(notify_token);
284 notify_post("com.saurik.Cydia.status");
287 static CGFloat CYStatusBarHeight() {
288 CGSize size([[UIApplication sharedApplication] statusBarFrame].size);
289 return UIInterfaceOrientationIsPortrait([[UIApplication sharedApplication] statusBarOrientation]) ? size.height : size.width;
292 /* NSForcedOrderingSearch doesn't work on the iPhone */
293 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
294 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
295 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
297 /* Insertion Sort {{{ */
299 template <typename Type_>
300 size_t CFBSearch_(const Type_ &element, const void *list, size_t count, CFComparisonResult (*comparator)(Type_, Type_, void *), void *context) {
301 const char *ptr = (const char *)list;
303 size_t half = count / 2;
304 const char *probe = ptr + sizeof(Type_) * half;
305 CFComparisonResult cr = comparator(element, * (const Type_ *) probe, context);
306 if (0 == cr) return (probe - (const char *)list) / sizeof(Type_);
307 ptr = (cr < 0) ? ptr : probe + sizeof(Type_);
308 count = (cr < 0) ? half : (half + (count & 1) - 1);
310 return (ptr - (const char *)list) / sizeof(Type_);
313 template <typename Type_>
314 void CYArrayInsertionSortValues(Type_ *values, size_t length, CFComparisonResult (*comparator)(Type_, Type_, void *), void *context) {
318 #if HistogramInsertionSort > 0
319 uint32_t total(0), *offsets(new uint32_t[length]);
322 for (size_t index(1); index != length; ++index) {
323 Type_ value(values[index]);
325 size_t correct(CFBSearch_(value, values, index, comparator, context));
327 size_t correct(index);
328 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
329 #if HistogramInsertionSort > 1
330 NSLog(@"%@ < %@", value, values[correct - 1]);
334 if (index - correct >= 8) {
335 correct = CFBSearch_(value, values, correct, comparator, context);
340 if (correct != index) {
341 size_t offset(index - correct);
342 #if HistogramInsertionSort
346 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
348 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
349 values[correct] = value;
353 #if HistogramInsertionSort > 0
354 for (size_t index(0); index != range.length; ++index)
355 if (offsets[index] != 0)
356 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
357 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
364 /* Cydia NSString Additions {{{ */
365 @interface NSString (Cydia)
366 - (NSComparisonResult) compareByPath:(NSString *)other;
367 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
370 @implementation NSString (Cydia)
372 - (NSComparisonResult) compareByPath:(NSString *)other {
373 NSString *prefix = [self commonPrefixWithString:other options:0];
374 size_t length = [prefix length];
376 NSRange lrange = NSMakeRange(length, [self length] - length);
377 NSRange rrange = NSMakeRange(length, [other length] - length);
379 lrange = [self rangeOfString:@"/" options:0 range:lrange];
380 rrange = [other rangeOfString:@"/" options:0 range:rrange];
382 NSComparisonResult value;
384 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
385 value = NSOrderedSame;
386 else if (lrange.location == NSNotFound)
387 value = NSOrderedAscending;
388 else if (rrange.location == NSNotFound)
389 value = NSOrderedDescending;
391 value = NSOrderedSame;
393 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
394 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
395 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
396 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
398 NSComparisonResult result = [lpath compare:rpath];
399 return result == NSOrderedSame ? value : result;
402 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
403 return [(id)CFURLCreateStringByAddingPercentEscapes(
408 kCFStringEncodingUTF8
415 /* C++ NSString Wrapper Cache {{{ */
416 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
417 return size == 0 ? NULL :
418 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
419 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
422 static _finline CFStringRef CYStringCreate(const std::string &data) {
423 return CYStringCreate(data.data(), data.size());
426 static _finline CFStringRef CYStringCreate(const char *data) {
427 return CYStringCreate(data, strlen(data));
436 _finline void clear_() {
437 if (cache_ != NULL) {
444 _finline bool empty() const {
448 _finline size_t size() const {
452 _finline char *data() const {
456 _finline void clear() {
461 _finline CYString() :
468 _finline ~CYString() {
472 void operator =(const CYString &rhs) {
476 if (rhs.cache_ == nil)
479 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
482 void copy(CYPool *pool) {
483 char *temp(pool->malloc<char>(size_ + 1));
484 memcpy(temp, data_, size_);
489 void set(CYPool *pool, const char *data, size_t size) {
495 data_ = const_cast<char *>(data);
503 _finline void set(CYPool *pool, const char *data) {
504 set(pool, data, data == NULL ? 0 : strlen(data));
507 _finline void set(CYPool *pool, const std::string &rhs) {
508 set(pool, rhs.data(), rhs.size());
511 bool operator ==(const CYString &rhs) const {
512 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
515 _finline operator CFStringRef() {
517 cache_ = CYStringCreate(data_, size_);
521 _finline operator id() {
522 return (NSString *) static_cast<CFStringRef>(*this);
525 _finline operator const char *() {
526 return reinterpret_cast<const char *>(data_);
530 /* C++ NSString Algorithm Adapters {{{ */
532 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
535 struct NSStringMapHash :
536 std::unary_function<NSString *, size_t>
538 _finline size_t operator ()(NSString *value) const {
539 return CFStringHashNSString((CFStringRef) value);
543 struct NSStringMapLess :
544 std::binary_function<NSString *, NSString *, bool>
546 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
547 return [lhs compare:rhs] == NSOrderedAscending;
551 struct NSStringMapEqual :
552 std::binary_function<NSString *, NSString *, bool>
554 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
555 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
556 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
557 //[lhs isEqualToString:rhs];
562 /* CoreGraphics Primitives {{{ */
567 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
568 CGFloat color[] = {red, green, blue, alpha};
569 return CGColorCreate(space, color);
578 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
579 color_(Create_(space, red, green, blue, alpha))
581 Set(space, red, green, blue, alpha);
586 CGColorRelease(color_);
593 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
595 color_ = Create_(space, red, green, blue, alpha);
598 operator CGColorRef() {
604 /* Random Global Variables {{{ */
605 static int PulseInterval_ = 500000;
607 static const NSString *UI_;
610 static bool RestartSubstrate_;
611 static NSArray *Finishes_;
613 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
614 #define NotifyConfig_ "/etc/notify.conf"
616 static bool Queuing_;
618 static CYColor Blue_;
619 static CYColor Blueish_;
620 static CYColor Black_;
621 static CYColor Folder_;
623 static CYColor White_;
624 static CYColor Gray_;
625 static CYColor Green_;
626 static CYColor Purple_;
627 static CYColor Purplish_;
629 static UIColor *InstallingColor_;
630 static UIColor *RemovingColor_;
632 static NSString *App_;
634 static BOOL Advanced_;
635 static BOOL Ignored_;
637 static _H<UIFont> Font12_;
638 static _H<UIFont> Font12Bold_;
639 static _H<UIFont> Font14_;
640 static _H<UIFont> Font18_;
641 static _H<UIFont> Font18Bold_;
642 static _H<UIFont> Font22Bold_;
644 static NSString *SerialNumber_ = nil;
645 static NSString *ChipID_ = nil;
646 static NSString *BBSNum_ = nil;
647 static _H<NSString> UniqueID_;
649 static _H<NSLocale> CollationLocale_;
650 static _H<NSArray> CollationThumbs_;
651 static std::vector<NSInteger> CollationOffset_;
652 static _H<NSArray> CollationTitles_;
653 static _H<NSArray> CollationStarts_;
654 static UTransliterator *CollationTransl_;
655 //static Function<NSString *, NSString *> CollationModify_;
657 typedef std::basic_string<UChar> ustring;
658 static ustring CollationString_;
660 #define CUC const ustring &str(*reinterpret_cast<const ustring *>(rep))
661 #define UC ustring &str(*reinterpret_cast<ustring *>(rep))
662 static struct UReplaceableCallbacks CollationUCalls_ = {
663 .length = [](const UReplaceable *rep) -> int32_t { CUC;
667 .charAt = [](const UReplaceable *rep, int32_t offset) -> UChar { CUC;
668 //fprintf(stderr, "charAt(%d) : %d\n", offset, str.size());
669 if (offset >= str.size())
674 .char32At = [](const UReplaceable *rep, int32_t offset) -> UChar32 { CUC;
675 //fprintf(stderr, "char32At(%d) : %d\n", offset, str.size());
676 if (offset >= str.size())
679 U16_GET(str.data(), 0, offset, str.size(), c);
683 .replace = [](UReplaceable *rep, int32_t start, int32_t limit, const UChar *text, int32_t length) -> void { UC;
684 //fprintf(stderr, "replace(%d, %d, %d) : %d\n", start, limit, length, str.size());
685 str.replace(start, limit - start, text, length);
688 .extract = [](UReplaceable *rep, int32_t start, int32_t limit, UChar *dst) -> void { UC;
689 //fprintf(stderr, "extract(%d, %d) : %d\n", start, limit, str.size());
690 str.copy(dst, limit - start, start);
693 .copy = [](UReplaceable *rep, int32_t start, int32_t limit, int32_t dest) -> void { UC;
694 //fprintf(stderr, "copy(%d, %d, %d) : %d\n", start, limit, dest, str.size());
695 str.replace(dest, 0, str, start, limit - start);
699 static CFLocaleRef Locale_;
700 static NSArray *Languages_;
701 static CGColorSpaceRef space_;
703 #define CacheState_ "/var/mobile/Library/Caches/com.saurik.Cydia/CacheState.plist"
704 #define SavedState_ "/var/mobile/Library/Caches/com.saurik.Cydia/SavedState.plist"
706 static NSDictionary *SectionMap_;
707 static _H<NSDate> Backgrounded_;
708 static _transient NSMutableDictionary *Values_;
709 static _transient NSMutableDictionary *Sections_;
710 _H<NSMutableDictionary> Sources_;
711 static _transient NSNumber *Version_;
714 static NSString *Idiom_;
715 static _H<NSString> Firmware_;
716 static NSString *Major_;
718 static _H<NSMutableDictionary> SessionData_;
719 static _H<NSMutableSet> BridgedHosts_;
720 static _H<NSMutableSet> InsecureHosts_;
722 static NSString *kCydiaProgressEventTypeError = @"Error";
723 static NSString *kCydiaProgressEventTypeInformation = @"Information";
724 static NSString *kCydiaProgressEventTypeStatus = @"Status";
725 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
728 /* Display Helpers {{{ */
729 inline float Interpolate(float begin, float end, float fraction) {
730 return (end - begin) * fraction + begin;
733 static inline double Retina(double value) {
734 value *= ScreenScale_;
735 value = round(value);
736 value /= ScreenScale_;
740 static inline CGRect Retina(CGRect value) {
741 value.origin.x *= ScreenScale_;
742 value.origin.y *= ScreenScale_;
743 value.size.width *= ScreenScale_;
744 value.size.height *= ScreenScale_;
745 value = CGRectIntegral(value);
746 value.origin.x /= ScreenScale_;
747 value.origin.y /= ScreenScale_;
748 value.size.width /= ScreenScale_;
749 value.size.height /= ScreenScale_;
753 static _finline const char *StripVersion_(const char *version) {
754 const char *colon(strchr(version, ':'));
755 return colon == NULL ? version : colon + 1;
758 NSString *LocalizeSection(NSString *section) {
759 static RegEx title_r("(.*?) \\((.*)\\)");
760 if (title_r(section)) {
761 NSString *parent(title_r[1]);
762 NSString *child(title_r[2]);
764 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
765 LocalizeSection(parent),
766 LocalizeSection(child)
770 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
773 NSString *Simplify(NSString *title) {
774 const char *data = [title UTF8String];
775 size_t size = [title lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
777 static RegEx square_r("\\[(.*)\\]");
778 if (square_r(data, size))
779 return Simplify(square_r[1]);
781 static RegEx paren_r("\\((.*)\\)");
782 if (paren_r(data, size))
783 return Simplify(paren_r[1]);
785 static RegEx title_r("(.*?) \\((.*)\\)");
786 if (title_r(data, size))
787 return Simplify(title_r[1]);
793 bool isSectionVisible(NSString *section) {
794 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
795 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
796 return hidden == nil || ![hidden boolValue];
799 static NSObject *CYIOGetValue(const char *path, NSString *property) {
800 io_registry_entry_t entry(IORegistryEntryFromPath(kIOMasterPortDefault, path));
801 if (entry == MACH_PORT_NULL)
804 CFTypeRef value(IORegistryEntryCreateCFProperty(entry, (CFStringRef) property, kCFAllocatorDefault, 0));
805 IOObjectRelease(entry);
809 return [(id) value autorelease];
812 static NSString *CYHex(NSData *data, bool reverse = false) {
816 size_t length([data length]);
817 uint8_t bytes[length];
818 [data getBytes:bytes];
820 char string[length * 2 + 1];
821 for (size_t i(0); i != length; ++i)
822 sprintf(string + i * 2, "%.2x", bytes[reverse ? length - i - 1 : i]);
824 return [NSString stringWithUTF8String:string];
827 static NSString *VerifySource(NSString *href) {
828 static RegEx href_r("(http(s?)://|file:///)[^# ]*");
830 [[[[UIAlertView alloc]
831 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("INVALID_URL")]
832 message:UCLocalize("INVALID_URL_EX")
834 cancelButtonTitle:UCLocalize("OK")
835 otherButtonTitles:nil
836 ] autorelease] show];
841 if (![href hasSuffix:@"/"])
842 href = [href stringByAppendingString:@"/"];
848 /* Delegate Prototypes {{{ */
851 @class CydiaProgressEvent;
853 @protocol DatabaseDelegate
854 - (void) repairWithSelector:(SEL)selector;
855 - (void) setConfigurationData:(NSString *)data;
856 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
859 @class CYPackageController;
861 @protocol SourceDelegate
862 - (void) setFetch:(NSNumber *)fetch;
865 @protocol FetchDelegate
866 - (bool) isSourceCancelled;
867 - (void) startSourceFetch:(NSString *)uri;
868 - (void) stopSourceFetch:(NSString *)uri;
871 @protocol CydiaDelegate
872 - (void) returnToCydia;
874 - (void) retainNetworkActivityIndicator;
875 - (void) releaseNetworkActivityIndicator;
876 - (void) clearPackage:(Package *)package;
877 - (void) installPackage:(Package *)package;
878 - (void) installPackages:(NSArray *)packages;
879 - (void) removePackage:(Package *)package;
880 - (void) beginUpdate;
882 - (bool) requestUpdate;
883 - (void) distUpgrade;
886 - (void) _saveConfig;
888 - (void) addSource:(NSDictionary *)source;
889 - (BOOL) addTrivialSource:(NSString *)href;
890 - (UIProgressHUD *) addProgressHUD;
891 - (void) removeProgressHUD:(UIProgressHUD *)hud;
892 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
893 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
897 /* CancelStatus {{{ */
899 public pkgAcquireStatus
910 virtual bool MediaChange(std::string media, std::string drive) {
914 virtual void IMSHit(pkgAcquire::ItemDesc &desc) {
918 virtual bool Pulse_(pkgAcquire *Owner) = 0;
920 virtual bool Pulse(pkgAcquire *Owner) {
921 if (pkgAcquireStatus::Pulse(Owner) && Pulse_(Owner))
929 _finline bool WasCancelled() const {
934 /* DelegateStatus {{{ */
939 _transient NSObject<ProgressDelegate> *delegate_;
947 void setDelegate(NSObject<ProgressDelegate> *delegate) {
948 delegate_ = delegate;
951 virtual void Fetch(pkgAcquire::ItemDesc &desc) {
952 NSString *name([NSString stringWithUTF8String:desc.ShortDesc.c_str()]);
953 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItemDesc:desc]);
954 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
957 virtual void Done(pkgAcquire::ItemDesc &desc) {
958 NSString *name([NSString stringWithUTF8String:desc.ShortDesc.c_str()]);
959 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:Colon_, UCLocalize("DONE"), name] ofType:kCydiaProgressEventTypeStatus forItemDesc:desc]);
960 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
963 virtual void Fail(pkgAcquire::ItemDesc &desc) {
965 desc.Owner->Status == pkgAcquire::Item::StatIdle ||
966 desc.Owner->Status == pkgAcquire::Item::StatDone
970 std::string &error(desc.Owner->ErrorText);
974 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItemDesc:desc]);
975 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
978 virtual bool Pulse_(pkgAcquire *Owner) {
980 double(CurrentBytes + CurrentItems) /
981 double(TotalBytes + TotalItems)
984 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
985 [NSNumber numberWithDouble:percent], @"Percent",
987 [NSNumber numberWithDouble:CurrentBytes], @"Current",
988 [NSNumber numberWithDouble:TotalBytes], @"Total",
989 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
990 nil] waitUntilDone:YES];
992 return ![delegate_ isProgressCancelled];
995 virtual void Start() {
996 pkgAcquireStatus::Start();
997 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
1000 virtual void Stop() {
1001 pkgAcquireStatus::Stop();
1002 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
1003 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
1007 /* Database Interface {{{ */
1008 typedef std::map< unsigned long, _H<Source> > SourceMap;
1010 @interface Database : NSObject {
1017 pkgCacheFile cache_;
1018 pkgDepCache::Policy *policy_;
1019 pkgRecords *records_;
1020 pkgProblemResolver *resolver_;
1021 pkgAcquire *fetcher_;
1023 SPtr<pkgPackageManager> manager_;
1024 pkgSourceList *list_;
1026 SourceMap sourceMap_;
1027 _H<NSMutableArray> sourceList_;
1029 _H<NSArray> packages_;
1031 _transient NSObject<DatabaseDelegate> *delegate_;
1032 _transient NSObject<ProgressDelegate> *progress_;
1034 CydiaStatus status_;
1040 std::map<const char *, _H<NSString> > sections_;
1043 + (Database *) sharedInstance;
1045 - (bool) hasPackages;
1047 - (void) _readCydia:(NSNumber *)fd;
1048 - (void) _readStatus:(NSNumber *)fd;
1049 - (void) _readOutput:(NSNumber *)fd;
1053 - (Package *) packageWithName:(NSString *)name;
1055 - (pkgCacheFile &) cache;
1056 - (pkgDepCache::Policy *) policy;
1057 - (pkgRecords *) records;
1058 - (pkgProblemResolver *) resolver;
1059 - (pkgAcquire &) fetcher;
1060 - (pkgSourceList &) list;
1061 - (NSArray *) packages;
1062 - (NSArray *) sources;
1063 - (Source *) sourceWithKey:(NSString *)key;
1064 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1072 - (void) updateWithStatus:(CancelStatus &)status;
1074 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1076 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1077 - (NSObject<ProgressDelegate> *) progressDelegate;
1079 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1080 - (void) setFetch:(bool)fetch forURI:(const char *)uri;
1081 - (void) resetFetch;
1083 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1087 /* SourceStatus {{{ */
1088 class SourceStatus :
1092 _transient NSObject<FetchDelegate> *delegate_;
1093 _transient Database *database_;
1094 std::set<std::string> fetches_;
1097 SourceStatus(NSObject<FetchDelegate> *delegate, Database *database) :
1098 delegate_(delegate),
1103 void Set(bool fetch, const std::string &uri) {
1105 if (!fetches_.insert(uri).second)
1108 if (fetches_.erase(uri) == 0)
1112 //printf("Set(%s, %s)\n", fetch ? "true" : "false", uri.c_str());
1114 auto slash(uri.rfind('/'));
1115 if (slash != std::string::npos)
1116 [database_ setFetch:fetch forURI:uri.substr(0, slash).c_str()];
1119 _finline void Set(bool fetch, pkgAcquire::Item *item) {
1120 /*unsigned long ID(fetch ? 1 : 0);
1124 Set(fetch, item->DescURI());
1127 void Log(const char *tag, pkgAcquire::Item *item) {
1128 //printf("%s(%s) S:%u Q:%u\n", tag, item->DescURI().c_str(), item->Status, item->QueueCounter);
1131 virtual void Fetch(pkgAcquire::ItemDesc &desc) {
1132 Log("Fetch", desc.Owner);
1133 Set(true, desc.Owner);
1136 virtual void Done(pkgAcquire::ItemDesc &desc) {
1137 Log("Done", desc.Owner);
1138 Set(false, desc.Owner);
1141 virtual void Fail(pkgAcquire::ItemDesc &desc) {
1142 Log("Fail", desc.Owner);
1143 Set(false, desc.Owner);
1146 virtual bool Pulse_(pkgAcquire *Owner) {
1147 std::set<std::string> fetches;
1148 for (pkgAcquire::ItemCIterator item(Owner->ItemsBegin()); item != Owner->ItemsEnd(); ++item) {
1150 if ((*item)->QueueCounter == 0)
1152 else switch ((*item)->Status) {
1153 case pkgAcquire::Item::StatFetching:
1154 fetches.insert((*item)->DescURI());
1163 Log(fetch ? "Pulse<true>" : "Pulse<false>", *item);
1167 std::vector<std::string> stops;
1168 std::set_difference(fetches_.begin(), fetches_.end(), fetches.begin(), fetches.end(), std::back_insert_iterator<std::vector<std::string>>(stops));
1169 for (std::vector<std::string>::const_iterator stop(stops.begin()); stop != stops.end(); ++stop) {
1170 //printf("Stop(%s)\n", stop->c_str());
1174 return ![delegate_ isSourceCancelled];
1177 virtual void Stop() {
1178 pkgAcquireStatus::Stop();
1179 [database_ resetFetch];
1183 /* ProgressEvent Implementation {{{ */
1184 @implementation CydiaProgressEvent
1186 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1187 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1190 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1191 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1192 [event setPackage:package];
1196 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItemDesc:(pkgAcquire::ItemDesc &)desc {
1197 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1199 NSString *description([NSString stringWithUTF8String:desc.Description.c_str()]);
1200 NSArray *fields([description componentsSeparatedByString:@" "]);
1201 [event setItem:fields];
1203 if ([fields count] > 3) {
1204 [event setPackage:[fields objectAtIndex:2]];
1205 [event setVersion:[fields objectAtIndex:3]];
1208 [event setURL:[NSString stringWithUTF8String:desc.URI.c_str()]];
1213 + (NSArray *) _attributeKeys {
1214 return [NSArray arrayWithObjects:
1224 - (NSArray *) attributeKeys {
1225 return [[self class] _attributeKeys];
1228 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1229 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1232 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1233 if ((self = [super init]) != nil) {
1239 - (NSString *) message {
1243 - (NSString *) type {
1247 - (NSArray *) item {
1248 return (id) item_ ?: [NSNull null];
1251 - (void) setItem:(NSArray *)item {
1255 - (NSString *) package {
1256 return (id) package_ ?: [NSNull null];
1259 - (void) setPackage:(NSString *)package {
1263 - (NSString *) url {
1264 return (id) url_ ?: [NSNull null];
1267 - (void) setURL:(NSString *)url {
1271 - (void) setVersion:(NSString *)version {
1275 - (NSString *) version {
1276 return (id) version_ ?: [NSNull null];
1279 - (NSString *) compound:(NSString *)value {
1281 NSString *mode(nil); {
1282 NSString *type([self type]);
1283 if ([type isEqualToString:kCydiaProgressEventTypeError])
1284 mode = UCLocalize("ERROR");
1285 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1286 mode = UCLocalize("WARNING");
1290 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1296 - (NSString *) compoundMessage {
1297 return [self compound:[self message]];
1300 - (NSString *) compoundTitle {
1303 if (package_ == nil)
1305 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1306 title = [package name];
1310 return [self compound:title];
1316 // Cytore Definitions {{{
1317 struct PackageValue :
1320 Cytore::Offset<PackageValue> next_;
1322 uint32_t index_ : 23;
1323 uint32_t subscribed_ : 1;
1340 Cytore::Offset<PackageValue> packages_[1 << 16];
1343 static Cytore::File<MetaValue> MetaFile_;
1345 // Cytore Helper Functions {{{
1346 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1347 SplitHash nhash = { hashlittle(name, length) };
1349 PackageValue *metadata;
1351 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1352 for (;; offset = &metadata->next_) { if (offset->IsNull()) {
1353 *offset = MetaFile_.New<PackageValue>(length + 1);
1354 metadata = &MetaFile_.Get(*offset);
1356 if (metadata == NULL) {
1360 metadata = new PackageValue();
1361 memset(metadata, 0, sizeof(*metadata));
1364 memcpy(metadata->name_, name, length);
1365 metadata->name_[length] = '\0';
1366 metadata->nhash_ = nhash.u16[1];
1368 metadata = &MetaFile_.Get(*offset);
1369 if (metadata->nhash_ != nhash.u16[1])
1371 if (strncmp(metadata->name_, name, length) != 0)
1373 if (metadata->name_[length] != '\0')
1380 static void PackageImport(const void *key, const void *value, void *context) {
1381 bool &fail(*reinterpret_cast<bool *>(context));
1384 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1385 NSLog(@"failed to import package %@", key);
1389 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1390 NSDictionary *package((NSDictionary *) value);
1392 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1393 if ([subscribed boolValue] && !metadata->subscribed_)
1394 metadata->subscribed_ = true;
1396 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1397 time_t time([date timeIntervalSince1970]);
1398 if (metadata->first_ > time || metadata->first_ == 0)
1399 metadata->first_ = time;
1402 NSDate *date([package objectForKey:@"LastSeen"]);
1403 NSString *version([package objectForKey:@"LastVersion"]);
1405 if (date != nil && version != nil) {
1406 time_t time([date timeIntervalSince1970]);
1407 if (metadata->last_ < time || metadata->last_ == 0)
1408 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1409 size_t length(strlen(buffer));
1410 uint16_t vhash(hashlittle(buffer, length));
1412 size_t capped(std::min<size_t>(8, length));
1413 char *latest(buffer + length - capped);
1415 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1416 metadata->vhash_ = vhash;
1418 metadata->last_ = time;
1424 static NSDate *GetStatusDate() {
1425 return [[[NSFileManager defaultManager] attributesOfItemAtPath:@"/var/lib/dpkg/status" error:NULL] fileModificationDate];
1428 static void SaveConfig(NSObject *lock) {
1429 @synchronized (lock) {
1435 CFPreferencesSetMultiple((CFDictionaryRef) [NSDictionary dictionaryWithObjectsAndKeys:
1436 Values_, @"CydiaValues",
1437 Sections_, @"CydiaSections",
1438 (id) Sources_, @"CydiaSources",
1439 Version_, @"CydiaVersion",
1440 nil], NULL, CFSTR("com.saurik.Cydia"), kCFPreferencesCurrentUser, kCFPreferencesCurrentHost);
1442 if (!CFPreferencesAppSynchronize(CFSTR("com.saurik.Cydia")))
1443 NSLog(@"CFPreferencesAppSynchronize(com.saurik.Cydia) == false");
1445 CydiaWriteSources();
1448 /* Source Class {{{ */
1449 @interface Source : NSObject {
1451 Database *database_;
1454 CYString depiction_;
1455 CYString description_;
1461 CYString distribution_;
1467 _H<NSString> authority_;
1469 CYString defaultIcon_;
1471 _H<NSMutableDictionary> record_;
1474 std::set<std::string> fetches_;
1475 std::set<std::string> files_;
1476 _transient NSObject<SourceDelegate> *delegate_;
1479 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(CYPool *)pool;
1481 - (NSComparisonResult) compareByName:(Source *)source;
1483 - (NSString *) depictionForPackage:(NSString *)package;
1484 - (NSString *) supportForPackage:(NSString *)package;
1486 - (metaIndex *) metaIndex;
1487 - (NSDictionary *) record;
1490 - (NSString *) rooturi;
1491 - (NSString *) distribution;
1492 - (NSString *) type;
1495 - (NSString *) host;
1497 - (NSString *) name;
1498 - (NSString *) shortDescription;
1499 - (NSString *) label;
1500 - (NSString *) origin;
1501 - (NSString *) version;
1503 - (NSString *) defaultIcon;
1504 - (NSURL *) iconURL;
1506 - (void) setFetch:(bool)fetch forURI:(const char *)uri;
1507 - (void) resetFetch;
1511 @implementation Source
1513 + (NSString *) webScriptNameForSelector:(SEL)selector {
1515 else if (selector == @selector(addSection:))
1516 return @"addSection";
1517 else if (selector == @selector(getField:))
1519 else if (selector == @selector(removeSection:))
1520 return @"removeSection";
1521 else if (selector == @selector(remove))
1527 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1528 return [self webScriptNameForSelector:selector] == nil;
1531 + (NSArray *) _attributeKeys {
1532 return [NSArray arrayWithObjects:
1543 @"shortDescription",
1550 - (NSArray *) attributeKeys {
1551 return [[self class] _attributeKeys];
1554 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1555 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1558 - (metaIndex *) metaIndex {
1562 - (void) setMetaIndex:(metaIndex *)index inPool:(CYPool *)pool {
1563 trusted_ = index->IsTrusted();
1565 uri_.set(pool, index->GetURI());
1566 distribution_.set(pool, index->GetDist());
1567 type_.set(pool, index->GetType());
1569 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1570 if (dindex != NULL) {
1571 std::string file(dindex->MetaIndexURI(""));
1572 base_.set(pool, file);
1575 _profile(Source$setMetaIndex$GetIndexes)
1576 dindex->GetIndexes(&acquire, true);
1578 _profile(Source$setMetaIndex$DescURI)
1579 for (pkgAcquire::ItemIterator item(acquire.ItemsBegin()); item != acquire.ItemsEnd(); item++) {
1580 std::string file((*item)->DescURI());
1581 auto slash(file.rfind('/'));
1582 if (slash == std::string::npos)
1584 files_.insert(file.substr(0, slash));
1589 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1592 pkgTagFile tags(&fd);
1594 pkgTagSection section;
1601 {"default-icon", &defaultIcon_},
1602 {"depiction", &depiction_},
1603 {"description", &description_},
1605 {"origin", &origin_},
1606 {"support", &support_},
1607 {"version", &version_},
1610 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1611 const char *start, *end;
1613 if (section.Find(names[i].name_, start, end)) {
1614 CYString &value(*names[i].value_);
1615 value.set(pool, start, end - start);
1621 record_ = [Sources_ objectForKey:[self key]];
1623 NSURL *url([NSURL URLWithString:uri_]);
1627 host_ = [host_ lowercaseString];
1632 authority_ = [url path];
1635 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(CYPool *)pool {
1636 if ((self = [super init]) != nil) {
1637 era_ = [database era];
1638 database_ = database;
1641 _profile(Source$initWithMetaIndex$setMetaIndex)
1642 [self setMetaIndex:index inPool:pool];
1647 - (NSString *) getField:(NSString *)name {
1648 @synchronized (database_) {
1649 if ([database_ era] != era_ || index_ == NULL)
1652 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index_));
1657 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly)) {
1662 pkgTagFile tags(&fd);
1664 pkgTagSection section;
1667 const char *start, *end;
1668 if (!section.Find([name UTF8String], start, end))
1669 return (NSString *) [NSNull null];
1671 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
1674 - (NSComparisonResult) compareByName:(Source *)source {
1675 NSString *lhs = [self name];
1676 NSString *rhs = [source name];
1678 if ([lhs length] != 0 && [rhs length] != 0) {
1679 unichar lhc = [lhs characterAtIndex:0];
1680 unichar rhc = [rhs characterAtIndex:0];
1682 if (isalpha(lhc) && !isalpha(rhc))
1683 return NSOrderedAscending;
1684 else if (!isalpha(lhc) && isalpha(rhc))
1685 return NSOrderedDescending;
1688 return [lhs compare:rhs options:LaxCompareOptions_];
1691 - (NSString *) depictionForPackage:(NSString *)package {
1692 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1695 - (NSString *) supportForPackage:(NSString *)package {
1696 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1699 - (NSArray *) sections {
1700 return record_ == nil ? (id) [NSNull null] : [record_ objectForKey:@"Sections"] ?: [NSArray array];
1703 - (void) _addSection:(NSString *)section {
1706 else if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) {
1707 if (![sections containsObject:section])
1708 [sections addObject:section];
1710 [record_ setObject:[NSMutableArray arrayWithObject:section] forKey:@"Sections"];
1713 - (bool) addSection:(NSString *)section {
1717 [self performSelectorOnMainThread:@selector(_addSection:) withObject:section waitUntilDone:NO];
1721 - (void) _removeSection:(NSString *)section {
1725 if (NSMutableArray *sections = [record_ objectForKey:@"Sections"])
1726 if ([sections containsObject:section])
1727 [sections removeObject:section];
1730 - (bool) removeSection:(NSString *)section {
1734 [self performSelectorOnMainThread:@selector(_removeSection:) withObject:section waitUntilDone:NO];
1739 [Sources_ removeObjectForKey:[self key]];
1743 bool value(record_ != nil);
1744 [self performSelectorOnMainThread:@selector(_remove) withObject:nil waitUntilDone:NO];
1748 - (NSDictionary *) record {
1756 - (NSString *) rooturi {
1760 - (NSString *) distribution {
1761 return distribution_;
1764 - (NSString *) type {
1768 - (NSString *) baseuri {
1769 return base_.empty() ? nil : (id) base_;
1772 - (NSString *) iconuri {
1773 if (NSString *base = [self baseuri])
1774 return [base stringByAppendingString:@"CydiaIcon.png"];
1779 - (NSURL *) iconURL {
1780 if (NSString *uri = [self iconuri])
1781 return [NSURL URLWithString:uri];
1785 - (NSString *) key {
1786 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1789 - (NSString *) host {
1793 - (NSString *) name {
1794 return origin_.empty() ? (id) authority_ : origin_;
1797 - (NSString *) shortDescription {
1798 return description_;
1801 - (NSString *) label {
1802 return label_.empty() ? (id) authority_ : label_;
1805 - (NSString *) origin {
1809 - (NSString *) version {
1813 - (NSString *) defaultIcon {
1814 return defaultIcon_;
1817 - (void) setDelegate:(NSObject<SourceDelegate> *)delegate {
1818 delegate_ = delegate;
1822 return !fetches_.empty();
1825 - (void) setFetch:(bool)fetch forURI:(const char *)uri {
1827 if (fetches_.erase(uri) == 0)
1829 } else if (files_.find(uri) == files_.end())
1831 else if (!fetches_.insert(uri).second)
1834 [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:[self fetch]] waitUntilDone:NO];
1837 - (void) resetFetch {
1839 [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:NO];
1844 /* CydiaOperation Class {{{ */
1845 @interface CydiaOperation : NSObject {
1846 _H<NSString> operator_;
1847 _H<NSString> value_;
1850 - (NSString *) operator;
1851 - (NSString *) value;
1855 @implementation CydiaOperation
1857 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1858 if ((self = [super init]) != nil) {
1859 operator_ = [NSString stringWithUTF8String:_operator];
1860 value_ = [NSString stringWithUTF8String:value];
1864 + (NSArray *) _attributeKeys {
1865 return [NSArray arrayWithObjects:
1871 - (NSArray *) attributeKeys {
1872 return [[self class] _attributeKeys];
1875 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1876 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1879 - (NSString *) operator {
1883 - (NSString *) value {
1889 /* CydiaClause Class {{{ */
1890 @interface CydiaClause : NSObject {
1891 _H<NSString> package_;
1892 _H<CydiaOperation> version_;
1895 - (NSString *) package;
1896 - (CydiaOperation *) version;
1900 @implementation CydiaClause
1902 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1903 if ((self = [super init]) != nil) {
1904 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1906 if (const char *version = dep.TargetVer())
1907 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1909 version_ = (id) [NSNull null];
1913 + (NSArray *) _attributeKeys {
1914 return [NSArray arrayWithObjects:
1920 - (NSArray *) attributeKeys {
1921 return [[self class] _attributeKeys];
1924 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1925 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1928 - (NSString *) package {
1932 - (CydiaOperation *) version {
1938 /* CydiaRelation Class {{{ */
1939 @interface CydiaRelation : NSObject {
1940 _H<NSString> relationship_;
1941 _H<NSMutableArray> clauses_;
1944 - (NSString *) relationship;
1945 - (NSArray *) clauses;
1949 @implementation CydiaRelation
1951 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1952 if ((self = [super init]) != nil) {
1953 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
1954 clauses_ = [NSMutableArray arrayWithCapacity:8];
1956 pkgCache::DepIterator start;
1957 pkgCache::DepIterator end;
1958 dep.GlobOr(start, end); // ++dep
1961 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1963 // yes, seriously. (wtf?)
1971 + (NSArray *) _attributeKeys {
1972 return [NSArray arrayWithObjects:
1978 - (NSArray *) attributeKeys {
1979 return [[self class] _attributeKeys];
1982 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1983 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1986 - (NSString *) relationship {
1987 return relationship_;
1990 - (NSArray *) clauses {
1994 - (void) addClause:(CydiaClause *)clause {
1995 [clauses_ addObject:clause];
2000 /* Package Class {{{ */
2001 struct ParsedPackage {
2005 CYString architecture_;
2008 CYString depiction_;
2015 @interface Package : NSObject {
2017 @public uint32_t role_ : 3;
2018 uint32_t essential_ : 1;
2019 uint32_t obsolete_ : 1;
2020 uint32_t ignored_ : 1;
2021 uint32_t pooled_ : 1;
2027 _transient Database *database_;
2029 pkgCache::VerIterator version_;
2030 pkgCache::PkgIterator iterator_;
2031 pkgCache::VerFileIterator file_;
2035 CYString transform_;
2038 CYString installed_;
2041 const char *section_;
2042 _transient NSString *section$_;
2046 PackageValue *metadata_;
2047 ParsedPackage *parsed_;
2049 _H<NSMutableArray> tags_;
2052 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database;
2053 + (Package *) newPackageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database;
2055 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database;
2057 - (pkgCache::PkgIterator) iterator;
2060 - (NSString *) section;
2061 - (NSString *) simpleSection;
2063 - (NSString *) longSection;
2064 - (NSString *) shortSection;
2068 - (MIMEAddress *) maintainer;
2070 - (NSString *) longDescription;
2071 - (NSString *) shortDescription;
2074 - (PackageValue *) metadata;
2077 - (bool) subscribed;
2078 - (bool) setSubscribed:(bool)subscribed;
2082 - (NSString *) latest;
2083 - (NSString *) installed;
2084 - (BOOL) uninstalled;
2086 - (BOOL) upgradableAndEssential:(BOOL)essential;
2089 - (BOOL) unfiltered;
2093 - (BOOL) halfConfigured;
2094 - (BOOL) halfInstalled;
2096 - (NSString *) mode;
2099 - (NSString *) name;
2101 - (NSString *) homepage;
2102 - (NSString *) depiction;
2103 - (MIMEAddress *) author;
2105 - (NSString *) support;
2107 - (NSArray *) files;
2108 - (NSArray *) warnings;
2109 - (NSArray *) applications;
2111 - (Source *) source;
2114 - (BOOL) matches:(NSArray *)query;
2116 - (BOOL) hasTag:(NSString *)tag;
2117 - (NSString *) primaryPurpose;
2118 - (NSArray *) purposes;
2119 - (bool) isCommercial;
2121 - (void) setIndex:(size_t)index;
2123 - (CYString &) cyname;
2125 - (uint32_t) compareBySection:(NSArray *)sections;
2132 uint32_t PackageChangesRadix(Package *self, void *) {
2137 uint32_t timestamp : 30;
2138 uint32_t ignored : 1;
2139 uint32_t upgradable : 1;
2143 bool upgradable([self upgradableAndEssential:YES]);
2144 value.bits.upgradable = upgradable ? 1 : 0;
2147 value.bits.timestamp = 0;
2148 value.bits.ignored = [self ignored] ? 0 : 1;
2149 value.bits.upgradable = 1;
2151 value.bits.timestamp = [self seen] >> 2;
2152 value.bits.ignored = 0;
2153 value.bits.upgradable = 0;
2156 return _not(uint32_t) - value.key;
2159 CYString &(*PackageName)(Package *self, SEL sel);
2161 uint32_t PackagePrefixRadix(Package *self, void *context) {
2162 size_t offset(reinterpret_cast<size_t>(context));
2163 CYString &name(PackageName(self, @selector(cyname)));
2165 size_t size(name.size());
2168 char *text(name.data());
2171 if (!isdigit(text[0]))
2175 while (size != digits && isdigit(text[digits]))
2183 if (offset == 0 && zeros != 0) {
2184 memset(data, '0', zeros);
2185 memcpy(data + zeros, text, 4 - zeros);
2187 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2188 if (size <= offset - zeros)
2191 text += offset - zeros;
2192 size -= offset - zeros;
2195 memcpy(data, text, 4);
2197 memcpy(data, text, size);
2198 memset(data + size, 0, 4 - size);
2201 for (size_t i(0); i != 4; ++i)
2202 if (isalpha(data[i]))
2210 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2212 /* XXX: ntohl may be more honest */
2213 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2216 CFComparisonResult StringNameCompare(CFStringRef lhn, CFStringRef rhn, size_t length) {
2217 _profile(PackageNameCompare)
2219 return rhn == NULL ? kCFCompareEqualTo : kCFCompareLessThan;
2220 else if (rhn == NULL)
2221 return kCFCompareGreaterThan;
2223 CFIndex length(CFStringGetLength(lhn));
2225 _profile(PackageNameCompare$NumbersLast)
2226 if (length != 0 && CFStringGetLength(rhn) != 0) {
2227 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2228 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2229 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2230 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2231 return lha ? kCFCompareLessThan : kCFCompareGreaterThan;
2235 _profile(PackageNameCompare$Compare)
2236 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, (CFLocaleRef) (id) CollationLocale_);
2241 _finline CFComparisonResult StringNameCompare(NSString *lhn, NSString*rhn, size_t length) {
2242 return StringNameCompare((CFStringRef) lhn, (CFStringRef) rhn, length);
2245 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2246 CYString &lhn(PackageName(lhs, @selector(cyname)));
2247 NSString *rhn(PackageName(rhs, @selector(cyname)));
2248 return StringNameCompare(lhn, rhn, lhn.size());
2251 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *arg) {
2252 return PackageNameCompare(*lhs, *rhs, arg);
2255 struct PackageNameOrdering :
2256 std::binary_function<Package *, Package *, bool>
2258 _finline bool operator ()(Package *lhs, Package *rhs) const {
2259 return PackageNameCompare(lhs, rhs, NULL) == kCFCompareLessThan;
2263 @implementation Package
2265 - (NSString *) description {
2266 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2272 if (parsed_ != NULL)
2277 + (NSString *) webScriptNameForSelector:(SEL)selector {
2279 else if (selector == @selector(clear))
2281 else if (selector == @selector(getField:))
2283 else if (selector == @selector(getRecord))
2284 return @"getRecord";
2285 else if (selector == @selector(hasTag:))
2287 else if (selector == @selector(install))
2289 else if (selector == @selector(remove))
2295 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2296 return [self webScriptNameForSelector:selector] == nil;
2299 + (NSArray *) _attributeKeys {
2300 return [NSArray arrayWithObjects:
2321 @"shortDescription",
2334 - (NSArray *) attributeKeys {
2335 return [[self class] _attributeKeys];
2338 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2339 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2342 - (NSArray *) relations {
2343 @synchronized (database_) {
2344 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2345 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2346 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2350 - (NSString *) architecture {
2352 @synchronized (database_) {
2353 return parsed_->architecture_.empty() ? [NSNull null] : (id) parsed_->architecture_;
2356 - (NSString *) getField:(NSString *)name {
2357 @synchronized (database_) {
2358 if ([database_ era] != era_ || file_.end())
2361 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2363 const char *start, *end;
2364 if (!parser.Find([name UTF8String], start, end))
2365 return (NSString *) [NSNull null];
2367 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2370 - (NSString *) getRecord {
2371 @synchronized (database_) {
2372 if ([database_ era] != era_ || file_.end())
2375 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2377 const char *start, *end;
2378 parser.GetRec(start, end);
2380 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2384 if (parsed_ != NULL)
2386 @synchronized (database_) {
2387 if ([database_ era] != era_ || file_.end())
2390 ParsedPackage *parsed(new ParsedPackage);
2393 _profile(Package$parse)
2394 pkgRecords::Parser *parser;
2396 _profile(Package$parse$Lookup)
2397 parser = &[database_ records]->Lookup(file_);
2403 _profile(Package$parse$Find)
2408 {"architecture", &parsed->architecture_},
2409 {"icon", &parsed->icon_},
2410 {"depiction", &parsed->depiction_},
2411 {"homepage", &parsed->homepage_},
2412 {"website", &website},
2414 {"support", &parsed->support_},
2415 {"author", &parsed->author_},
2416 {"md5sum", &parsed->md5sum_},
2419 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2420 const char *start, *end;
2422 if (parser->Find(names[i].name_, start, end)) {
2423 CYString &value(*names[i].value_);
2424 _profile(Package$parse$Value)
2425 value.set(pool_, start, end - start);
2431 _profile(Package$parse$Tagline)
2432 parsed->tagline_.set(pool_, parser->ShortDesc());
2435 _profile(Package$parse$Retain)
2436 if (parsed->homepage_.empty())
2437 parsed->homepage_ = website;
2438 if (parsed->homepage_ == parsed->depiction_)
2439 parsed->homepage_.clear();
2440 if (parsed->support_.empty())
2441 parsed->support_ = bugs;
2446 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database {
2447 if ((self = [super init]) != nil) {
2448 _profile(Package$initWithVersion)
2450 pool_ = new CYPool();
2456 database_ = database;
2457 era_ = [database era];
2461 pkgCache::PkgIterator iterator(version_.ParentPkg());
2462 iterator_ = iterator;
2464 _profile(Package$initWithVersion$Version)
2465 file_ = version_.FileList();
2468 _profile(Package$initWithVersion$Cache)
2469 name_.set(NULL, version_.Display());
2471 latest_.set(NULL, StripVersion_(version_.VerStr()));
2473 pkgCache::VerIterator current(iterator.CurrentVer());
2475 installed_.set(NULL, StripVersion_(current.VerStr()));
2478 _profile(Package$initWithVersion$Transliterate) do {
2479 if (CollationTransl_ == NULL)
2484 _profile(Package$initWithVersion$Transliterate$utf8)
2485 const uint8_t *data(reinterpret_cast<const uint8_t *>(name_.data()));
2486 for (size_t i(0), e(name_.size()); i != e; ++i)
2487 if (data[i] >= 0x80)
2492 UErrorCode code(U_ZERO_ERROR);
2495 _profile(Package$initWithVersion$Transliterate$u_strFromUTF8WithSub)
2496 CollationString_.resize(name_.size());
2497 u_strFromUTF8WithSub(&CollationString_[0], CollationString_.size(), &length, name_.data(), name_.size(), 0xfffd, NULL, &code);
2498 if (!U_SUCCESS(code))
2500 CollationString_.resize(length);
2503 _profile(Package$initWithVersion$Transliterate$utrans_trans)
2504 length = CollationString_.size();
2505 utrans_trans(CollationTransl_, reinterpret_cast<UReplaceable *>(&CollationString_), &CollationUCalls_, 0, &length, &code);
2506 if (!U_SUCCESS(code))
2508 _assert(CollationString_.size() == length);
2511 _profile(Package$initWithVersion$Transliterate$u_strToUTF8WithSub$preflight)
2512 u_strToUTF8WithSub(NULL, 0, &length, CollationString_.data(), CollationString_.size(), 0xfffd, NULL, &code);
2513 if (code == U_BUFFER_OVERFLOW_ERROR)
2514 code = U_ZERO_ERROR;
2515 else if (!U_SUCCESS(code))
2520 _profile(Package$initWithVersion$Transliterate$apr_palloc)
2521 transform = pool_->malloc<char>(length);
2523 _profile(Package$initWithVersion$Transliterate$u_strToUTF8WithSub$transform)
2524 u_strToUTF8WithSub(transform, length, NULL, CollationString_.data(), CollationString_.size(), 0xfffd, NULL, &code);
2525 if (!U_SUCCESS(code))
2529 transform_.set(NULL, transform, length);
2530 } while (false); _end
2532 _profile(Package$initWithVersion$Tags)
2534 pkgCache::TagIterator tag(version_.TagList());
2536 pkgCache::TagIterator tag(iterator.TagList());
2539 tags_ = [NSMutableArray arrayWithCapacity:8];
2541 goto tag; for (; !tag.end(); ++tag) tag: {
2542 const char *name(tag.Name());
2543 NSString *string((NSString *) CYStringCreate(name));
2547 [tags_ addObject:[string autorelease]];
2549 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2550 if (strcmp(name + 6, "enduser") == 0)
2552 else if (strcmp(name + 6, "hacker") == 0)
2554 else if (strcmp(name + 6, "developer") == 0)
2556 else if (strcmp(name + 6, "cydia") == 0)
2562 if (strncmp(name, "cydia::", 7) == 0) {
2563 if (strcmp(name + 7, "essential") == 0)
2565 else if (strcmp(name + 7, "obsolete") == 0)
2572 _profile(Package$initWithVersion$Metadata)
2573 const char *mixed(iterator.Name());
2574 size_t size(strlen(mixed));
2575 static const size_t prefix(sizeof("/var/lib/dpkg/info/") - 1);
2576 char lower[prefix + size + 5 + 1];
2578 for (size_t i(0); i != size; ++i)
2579 lower[prefix + i] = mixed[i] | 0x20;
2581 if (!installed_.empty()) {
2582 memcpy(lower, "/var/lib/dpkg/info/", prefix);
2583 memcpy(lower + prefix + size, ".list", 6);
2585 if (stat(lower, &info) != -1)
2586 upgraded_ = info.st_birthtime;
2589 PackageValue *metadata(PackageFind(lower + prefix, size));
2590 metadata_ = metadata;
2592 id_.set(NULL, metadata->name_, size);
2594 const char *latest(version_.VerStr());
2595 size_t length(strlen(latest));
2597 uint16_t vhash(hashlittle(latest, length));
2599 size_t capped(std::min<size_t>(8, length));
2600 latest = latest + length - capped;
2602 if (metadata->first_ == 0)
2603 metadata->first_ = now_;
2605 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2606 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2607 metadata->vhash_ = vhash;
2608 metadata->last_ = now_;
2609 } else if (metadata->last_ == 0)
2610 metadata->last_ = metadata->first_;
2613 _profile(Package$initWithVersion$Section)
2614 section_ = version_.Section();
2617 _profile(Package$initWithVersion$Flags)
2618 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2619 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2624 + (Package *) newPackageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database {
2625 pkgCache::VerIterator version;
2627 _profile(Package$packageWithIterator$GetCandidateVer)
2628 version = [database policy]->GetCandidateVer(iterator);
2636 _profile(Package$packageWithIterator$Allocate)
2637 package = [Package allocWithZone:zone];
2640 _profile(Package$packageWithIterator$Initialize)
2642 initWithVersion:version
2652 // XXX: just in case a Cydia extension is using this (I bet this is unlikely, though, due to CYPool?)
2653 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database {
2654 return [[self newPackageWithIterator:iterator withZone:zone inPool:pool database:database] autorelease];
2657 - (pkgCache::PkgIterator) iterator {
2661 - (NSArray *) downgrades {
2662 NSMutableArray *versions([NSMutableArray arrayWithCapacity:4]);
2664 for (auto version(iterator_.VersionList()); !version.end(); ++version) {
2665 if (version == version_)
2667 Package *package([[[Package allocWithZone:NULL] initWithVersion:version withZone:NULL inPool:NULL database:database_] autorelease]);
2668 if ([package source] == nil)
2670 [versions addObject:package];
2676 - (NSString *) section {
2677 if (section$_ == nil) {
2678 if (section_ == NULL)
2681 _profile(Package$section$mappedSectionForPointer)
2682 section$_ = [database_ mappedSectionForPointer:section_];
2687 - (NSString *) simpleSection {
2688 if (NSString *section = [self section])
2689 return Simplify(section);
2694 - (NSString *) longSection {
2695 if (NSString *section = [self section])
2696 return LocalizeSection(section);
2701 - (NSString *) shortSection {
2702 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2705 - (NSString *) uri {
2708 pkgIndexFile *index;
2709 pkgCache::PkgFileIterator file(file_.File());
2710 if (![database_ list].FindIndex(file, index))
2712 return [NSString stringWithUTF8String:iterator_->Path];
2713 //return [NSString stringWithUTF8String:file.Site()];
2714 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2718 - (MIMEAddress *) maintainer {
2719 @synchronized (database_) {
2720 if ([database_ era] != era_ || file_.end())
2723 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2724 const std::string &maintainer(parser->Maintainer());
2725 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2728 - (NSString *) md5sum {
2729 return parsed_ == NULL ? nil : (id) parsed_->md5sum_;
2733 @synchronized (database_) {
2734 if ([database_ era] != era_ || version_.end())
2737 return version_->InstalledSize;
2740 - (NSString *) longDescription {
2741 @synchronized (database_) {
2742 if ([database_ era] != era_ || file_.end())
2745 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2746 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2748 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2749 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2750 if ([lines count] < 2)
2753 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2754 for (size_t i(1), e([lines count]); i != e; ++i) {
2755 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2756 [trimmed addObject:trim];
2759 return [trimmed componentsJoinedByString:@"\n"];
2762 - (NSString *) shortDescription {
2763 if (parsed_ != NULL)
2764 return static_cast<NSString *>(parsed_->tagline_);
2766 @synchronized (database_) {
2767 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2768 std::string value(parser.ShortDesc());
2771 if (value.size() > 200)
2773 return [(id) CYStringCreate(value) autorelease];
2777 _profile(Package$index)
2778 CFStringRef name((CFStringRef) [self name]);
2779 if (CFStringGetLength(name) == 0)
2781 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2782 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2784 return toupper(character);
2788 - (PackageValue *) metadata {
2793 PackageValue *metadata([self metadata]);
2794 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2797 - (bool) subscribed {
2798 return [self metadata]->subscribed_;
2801 - (bool) setSubscribed:(bool)subscribed {
2802 PackageValue *metadata([self metadata]);
2803 if (metadata->subscribed_ == subscribed)
2805 metadata->subscribed_ = subscribed;
2813 - (NSString *) latest {
2817 - (NSString *) installed {
2821 - (BOOL) uninstalled {
2822 return installed_.empty();
2825 - (BOOL) upgradableAndEssential:(BOOL)essential {
2826 _profile(Package$upgradableAndEssential)
2827 pkgCache::VerIterator current(iterator_.CurrentVer());
2829 return essential && essential_;
2831 return version_ != current;
2835 - (BOOL) essential {
2840 return [database_ cache][iterator_].InstBroken();
2843 - (BOOL) unfiltered {
2844 _profile(Package$unfiltered$obsolete)
2845 if (_unlikely(obsolete_))
2849 _profile(Package$unfiltered$role)
2850 if (_unlikely(role_ > 3))
2858 if (![self unfiltered])
2863 _profile(Package$visible$section)
2864 section = [self section];
2867 _profile(Package$visible$isSectionVisible)
2868 if (!isSectionVisible(section))
2876 unsigned char current(iterator_->CurrentState);
2877 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2880 - (BOOL) halfConfigured {
2881 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2884 - (BOOL) halfInstalled {
2885 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2889 @synchronized (database_) {
2890 if ([database_ era] != era_ || iterator_.end())
2893 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2894 return state.Mode != pkgDepCache::ModeKeep;
2897 - (NSString *) mode {
2898 @synchronized (database_) {
2899 if ([database_ era] != era_ || iterator_.end())
2902 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2904 switch (state.Mode) {
2905 case pkgDepCache::ModeDelete:
2906 if ((state.iFlags & pkgDepCache::Purge) != 0)
2910 case pkgDepCache::ModeKeep:
2911 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2912 return @"REINSTALL";
2913 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2917 case pkgDepCache::ModeInstall:
2918 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2919 return @"REINSTALL";
2920 else*/ switch (state.Status) {
2922 return @"DOWNGRADE";
2928 return @"NEW_INSTALL";
2939 - (NSString *) name {
2940 return name_.empty() ? id_ : name_;
2943 - (UIImage *) icon {
2944 NSString *section = [self simpleSection];
2947 if (parsed_ != NULL)
2948 if (NSString *href = parsed_->icon_)
2949 if ([href hasPrefix:@"file:///"])
2950 icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2951 if (icon == nil) if (section != nil)
2952 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]];
2953 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2954 if ([dicon hasPrefix:@"file:///"])
2955 icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2957 icon = [UIImage imageNamed:@"unknown.png"];
2961 - (NSString *) homepage {
2962 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2965 - (NSString *) depiction {
2966 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2969 - (MIMEAddress *) author {
2970 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
2973 - (NSString *) support {
2974 return parsed_ != NULL && !parsed_->support_.empty() ? parsed_->support_ : [[self source] supportForPackage:id_];
2977 - (NSArray *) files {
2978 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2979 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2982 fin.open([path UTF8String]);
2987 while (std::getline(fin, line))
2988 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2993 - (NSString *) state {
2994 @synchronized (database_) {
2995 if ([database_ era] != era_ || file_.end())
2998 switch (iterator_->CurrentState) {
2999 case pkgCache::State::NotInstalled:
3000 return @"NotInstalled";
3001 case pkgCache::State::UnPacked:
3003 case pkgCache::State::HalfConfigured:
3004 return @"HalfConfigured";
3005 case pkgCache::State::HalfInstalled:
3006 return @"HalfInstalled";
3007 case pkgCache::State::ConfigFiles:
3008 return @"ConfigFiles";
3009 case pkgCache::State::Installed:
3010 return @"Installed";
3011 case pkgCache::State::TriggersAwaited:
3012 return @"TriggersAwaited";
3013 case pkgCache::State::TriggersPending:
3014 return @"TriggersPending";
3017 return (NSString *) [NSNull null];
3020 - (NSString *) selection {
3021 @synchronized (database_) {
3022 if ([database_ era] != era_ || file_.end())
3025 switch (iterator_->SelectedState) {
3026 case pkgCache::State::Unknown:
3028 case pkgCache::State::Install:
3030 case pkgCache::State::Hold:
3032 case pkgCache::State::DeInstall:
3033 return @"DeInstall";
3034 case pkgCache::State::Purge:
3038 return (NSString *) [NSNull null];
3041 - (NSArray *) warnings {
3042 @synchronized (database_) {
3043 if ([database_ era] != era_ || file_.end())
3046 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
3047 const char *name(iterator_.Name());
3049 size_t length(strlen(name));
3050 if (length < 2) invalid:
3051 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
3052 else for (size_t i(0); i != length; ++i)
3054 /* XXX: technically this is not allowed */
3055 (name[i] < 'A' || name[i] > 'Z') &&
3056 (name[i] < 'a' || name[i] > 'z') &&
3057 (name[i] < '0' || name[i] > '9') &&
3058 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
3061 if (strcmp(name, "cydia") != 0) {
3064 bool _private = false;
3066 bool dbstash = false;
3067 bool dsstore = false;
3069 bool repository = [[self section] isEqualToString:@"Repositories"];
3071 if (NSArray *files = [self files])
3072 for (NSString *file in files)
3073 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
3075 else if (!user && [file isEqualToString:@"/User"])
3077 else if (!_private && [file isEqualToString:@"/private"])
3079 else if (!stash && [file isEqualToString:@"/var/stash"])
3081 else if (!dbstash && [file isEqualToString:@"/var/db/stash"])
3083 else if (!dsstore && [file hasSuffix:@"/.DS_Store"])
3086 /* XXX: this is not sensitive enough. only some folders are valid. */
3087 if (cydia && !repository)
3088 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
3090 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
3092 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
3094 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
3096 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/db/stash"]];
3098 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @".DS_Store"]];
3101 return [warnings count] == 0 ? nil : warnings;
3104 - (NSArray *) applications {
3105 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
3107 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
3109 static RegEx application_r("/Applications/(.*)\\.app/Info.plist");
3110 if (NSArray *files = [self files])
3111 for (NSString *file in files)
3112 if (application_r(file)) {
3113 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
3116 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
3117 if (id == nil || [id isEqualToString:me])
3120 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
3122 display = application_r[1];
3124 NSString *bundle([file stringByDeletingLastPathComponent]);
3125 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
3126 // XXX: maybe this should check if this is really a string, not just for length
3127 if (icon == nil || ![icon respondsToSelector:@selector(length)] || [icon length] == 0)
3129 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
3131 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
3132 [applications addObject:application];
3134 [application addObject:id];
3135 [application addObject:display];
3136 [application addObject:url];
3139 return [applications count] == 0 ? nil : applications;
3142 - (Source *) source {
3143 if (source_ == nil) {
3144 @synchronized (database_) {
3145 if ([database_ era] != era_ || file_.end())
3146 source_ = (Source *) [NSNull null];
3148 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
3152 return source_ == (Source *) [NSNull null] ? nil : source_;
3155 - (time_t) upgraded {
3159 - (uint32_t) recent {
3160 return std::numeric_limits<uint32_t>::max() - upgraded_;
3167 - (BOOL) matches:(NSArray *)query {
3168 if (query == nil || [query count] == 0)
3177 string = [self name];
3178 length = [string length];
3181 for (NSString *term in query) {
3182 range = [string rangeOfString:term options:MatchCompareOptions_];
3183 if (range.location != NSNotFound)
3184 rank_ -= 6 * 1000000 / length;
3189 length = [string length];
3192 for (NSString *term in query) {
3193 range = [string rangeOfString:term options:MatchCompareOptions_];
3194 if (range.location != NSNotFound)
3195 rank_ -= 6 * 1000000 / length;
3199 string = [self shortDescription];
3200 length = [string length];
3201 NSUInteger stop(std::min<NSUInteger>(length, 200));
3204 for (NSString *term in query) {
3205 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
3206 if (range.location != NSNotFound)
3207 rank_ -= 2 * 100000;
3213 - (NSArray *) tags {
3217 - (BOOL) hasTag:(NSString *)tag {
3218 return tags_ == nil ? NO : [tags_ containsObject:tag];
3221 - (NSString *) primaryPurpose {
3222 for (NSString *tag in (NSArray *) tags_)
3223 if ([tag hasPrefix:@"purpose::"])
3224 return [tag substringFromIndex:9];
3228 - (NSArray *) purposes {
3229 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
3230 for (NSString *tag in (NSArray *) tags_)
3231 if ([tag hasPrefix:@"purpose::"])
3232 [purposes addObject:[tag substringFromIndex:9]];
3233 return [purposes count] == 0 ? nil : purposes;
3236 - (bool) isCommercial {
3237 return [self hasTag:@"cydia::commercial"];
3240 - (void) setIndex:(size_t)index {
3241 if (metadata_->index_ != index + 1)
3242 metadata_->index_ = index + 1;
3245 - (CYString &) cyname {
3246 return !transform_.empty() ? transform_ : !name_.empty() ? name_ : id_;
3249 - (uint32_t) compareBySection:(NSArray *)sections {
3250 NSString *section([self section]);
3251 for (size_t i(0), e([sections count]); i != e; ++i) {
3252 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3256 return _not(uint32_t);
3260 @synchronized (database_) {
3261 if ([database_ era] != era_ || file_.end())
3264 pkgProblemResolver *resolver = [database_ resolver];
3265 resolver->Clear(iterator_);
3267 pkgCacheFile &cache([database_ cache]);
3268 cache->SetReInstall(iterator_, false);
3269 cache->MarkKeep(iterator_, false);
3273 @synchronized (database_) {
3274 if ([database_ era] != era_ || file_.end())
3277 pkgProblemResolver *resolver = [database_ resolver];
3278 resolver->Clear(iterator_);
3279 resolver->Protect(iterator_);
3281 pkgCacheFile &cache([database_ cache]);
3282 cache->SetCandidateVersion(version_);
3283 cache->SetReInstall(iterator_, false);
3284 cache->MarkInstall(iterator_, false);
3286 pkgDepCache::StateCache &state((*cache)[iterator_]);
3287 if (!state.Install())
3288 cache->SetReInstall(iterator_, true);
3292 @synchronized (database_) {
3293 if ([database_ era] != era_ || file_.end())
3296 pkgProblemResolver *resolver = [database_ resolver];
3297 resolver->Clear(iterator_);
3298 resolver->Remove(iterator_);
3299 resolver->Protect(iterator_);
3301 pkgCacheFile &cache([database_ cache]);
3302 cache->SetReInstall(iterator_, false);
3303 cache->MarkDelete(iterator_, true);
3308 /* Section Class {{{ */
3309 @interface Section : NSObject {
3313 _H<NSString> localized_;
3316 - (NSComparisonResult) compareByLocalized:(Section *)section;
3317 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3318 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3319 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3321 - (NSString *) name;
3322 - (void) setName:(NSString *)name;
3328 - (void) addToCount;
3330 - (void) setCount:(size_t)count;
3331 - (NSString *) localized;
3335 @implementation Section
3337 - (NSComparisonResult) compareByLocalized:(Section *)section {
3338 NSString *lhs(localized_);
3339 NSString *rhs([section localized]);
3341 /*if ([lhs length] != 0 && [rhs length] != 0) {
3342 unichar lhc = [lhs characterAtIndex:0];
3343 unichar rhc = [rhs characterAtIndex:0];
3345 if (isalpha(lhc) && !isalpha(rhc))
3346 return NSOrderedAscending;
3347 else if (!isalpha(lhc) && isalpha(rhc))
3348 return NSOrderedDescending;
3351 return [lhs compare:rhs options:LaxCompareOptions_];
3354 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3355 if ((self = [self initWithName:name localize:NO]) != nil) {
3356 if (localized != nil)
3357 localized_ = localized;
3361 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3362 return [self initWithName:name row:0 localize:localize];
3365 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3366 if ((self = [super init]) != nil) {
3370 localized_ = LocalizeSection(name_);
3374 - (NSString *) name {
3378 - (void) setName:(NSString *)name {
3394 - (void) addToCount {
3398 - (void) setCount:(size_t)count {
3402 - (NSString *) localized {
3409 class CydiaLogCleaner :
3410 public pkgArchiveCleaner
3413 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3418 /* Database Implementation {{{ */
3419 @implementation Database
3421 + (Database *) sharedInstance {
3422 static _H<Database> instance;
3423 if (instance == nil)
3424 instance = [[[Database alloc] init] autorelease];
3432 - (void) releasePackages {
3436 - (bool) hasPackages {
3437 return [packages_ count] != 0;
3441 // XXX: actually implement this thing
3443 [self releasePackages];
3444 NSRecycleZone(zone_);
3448 - (void) _readCydia:(NSNumber *)fd {
3449 boost::fdistream is([fd intValue]);
3452 static RegEx finish_r("finish:([^:]*)");
3454 while (std::getline(is, line)) {
3455 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3457 const char *data(line.c_str());
3458 size_t size = line.size();
3459 lprintf("C:%s\n", data);
3461 if (finish_r(data, size)) {
3462 NSString *finish = finish_r[1];
3463 int index = [Finishes_ indexOfObject:finish];
3464 if (index != INT_MAX && index > Finish_)
3474 - (void) _readStatus:(NSNumber *)fd {
3475 boost::fdistream is([fd intValue]);
3478 static RegEx conffile_r("status: [^ ]* : conffile-prompt : (.*?) *");
3479 static RegEx pmstatus_r("([^:]*):([^:]*):([^:]*):(.*)");
3481 while (std::getline(is, line)) {
3482 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3484 const char *data(line.c_str());
3485 size_t size(line.size());
3486 lprintf("S:%s\n", data);
3488 if (conffile_r(data, size)) {
3489 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3490 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3491 } else if (strncmp(data, "status: ", 8) == 0) {
3492 // status: <package>: {unpacked,half-configured,installed}
3493 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3494 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3495 } else if (strncmp(data, "processing: ", 12) == 0) {
3496 // processing: configure: config-test
3497 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3498 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3499 } else if (pmstatus_r(data, size)) {
3500 std::string type([pmstatus_r[1] UTF8String]);
3502 NSString *package = pmstatus_r[2];
3503 if ([package isEqualToString:@"dpkg-exec"])
3506 float percent([pmstatus_r[3] floatValue]);
3507 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3509 NSString *string = pmstatus_r[4];
3511 if (type == "pmerror") {
3512 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3513 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3514 } else if (type == "pmstatus") {
3515 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3516 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3517 } else if (type == "pmconffile")
3518 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3520 lprintf("E:unknown pmstatus\n");
3522 lprintf("E:unknown status\n");
3530 - (void) _readOutput:(NSNumber *)fd {
3531 boost::fdistream is([fd intValue]);
3534 while (std::getline(is, line)) {
3535 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3537 lprintf("O:%s\n", line.c_str());
3539 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3540 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3552 - (Package *) packageWithName:(NSString *)name {
3555 @synchronized (self) {
3556 if (static_cast<pkgDepCache *>(cache_) == NULL)
3558 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]
3563 return iterator.end() ? nil : [[Package newPackageWithIterator:iterator withZone:NULL inPool:NULL database:self] autorelease];
3567 if ((self = [super init]) != nil) {
3574 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3576 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3580 _assert(pipe(fds) != -1);
3583 _config->Set("APT::Keep-Fds::", cydiafd_);
3584 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3587 detachNewThreadSelector:@selector(_readCydia:)
3589 withObject:[NSNumber numberWithInt:fds[0]]
3592 _assert(pipe(fds) != -1);
3596 detachNewThreadSelector:@selector(_readStatus:)
3598 withObject:[NSNumber numberWithInt:fds[0]]
3601 _assert(pipe(fds) != -1);
3602 _assert(dup2(fds[0], 0) != -1);
3603 _assert(close(fds[0]) != -1);
3605 input_ = fdopen(fds[1], "a");
3607 _assert(pipe(fds) != -1);
3608 _assert(dup2(fds[1], 1) != -1);
3609 _assert(close(fds[1]) != -1);
3612 detachNewThreadSelector:@selector(_readOutput:)
3614 withObject:[NSNumber numberWithInt:fds[0]]
3619 - (pkgCacheFile &) cache {
3623 - (pkgDepCache::Policy *) policy {
3627 - (pkgRecords *) records {
3631 - (pkgProblemResolver *) resolver {
3635 - (pkgAcquire &) fetcher {
3639 - (pkgSourceList &) list {
3643 - (NSArray *) packages {
3647 - (NSArray *) sources {
3651 - (Source *) sourceWithKey:(NSString *)key {
3652 for (Source *source in [self sources]) {
3653 if ([[source key] isEqualToString:key])
3658 - (bool) popErrorWithTitle:(NSString *)title {
3661 while (!_error->empty()) {
3663 bool warning(!_error->PopMessage(error));
3668 size_t size(error.size());
3669 if (size == 0 || error[size - 1] != '\n')
3671 error.resize(size - 1);
3674 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3676 static RegEx no_pubkey("GPG error:.* NO_PUBKEY .*");
3677 if (warning && no_pubkey(error.c_str()))
3680 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3686 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3687 return [self popErrorWithTitle:title] || !success;
3690 - (bool) popErrorWithTitle:(NSString *)title forReadList:(pkgSourceList &)list {
3691 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3699 if (access("/etc/apt/sources.list", F_OK) == 0)
3700 error |= [self popErrorWithTitle:title forOperation:list.ReadAppend("/etc/apt/sources.list")];
3702 std::string base("/etc/apt/sources.list.d");
3703 if (DIR *sources = opendir(base.c_str())) {
3704 while (dirent *source = readdir(sources))
3705 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)
3706 error |= [self popErrorWithTitle:title forOperation:list.ReadAppend((base + "/" + source->d_name).c_str())];
3710 error |= [self popErrorWithTitle:title forOperation:list.ReadAppend(SOURCES_LIST)];
3715 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3716 @synchronized (self) {
3719 [self releasePackages];
3722 [sourceList_ removeAllObjects];
3743 new (&pool_) CYPool();
3745 NSRecycleZone(zone_);
3746 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3748 int chk(creat("/tmp/cydia.chk", 0644));
3752 if (invocation != nil)
3753 [invocation invoke];
3755 NSString *title(UCLocalize("DATABASE"));
3757 list_ = new pkgSourceList();
3758 _profile(reloadDataWithInvocation$ReadMainList)
3759 if ([self popErrorWithTitle:title forReadList:*list_])
3763 _profile(reloadDataWithInvocation$Source$initWithMetaIndex)
3764 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3765 Source *object([[[Source alloc] initWithMetaIndex:*source forDatabase:self inPool:&pool_] autorelease]);
3766 [sourceList_ addObject:object];
3771 OpProgress progress;
3774 delock_ = GetStatusDate();
3775 _profile(reloadDataWithInvocation$pkgCacheFile)
3776 opened = cache_.Open(progress, false);
3779 // XXX: this block should probably be merged with popError: in some way
3780 while (!_error->empty()) {
3782 bool warning(!_error->PopMessage(error));
3784 lprintf("cache_.Open():[%s]\n", error.c_str());
3786 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3790 else if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3791 repair = @selector(configure);
3792 //else if (error == "The package lists or status file could not be parsed or opened.")
3793 // repair = @selector(update);
3794 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3795 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3796 // else if (error == "Malformed Status line")
3797 // else if (error == "The list of sources could not be read.")
3799 if (repair != NULL) {
3801 [delegate_ repairWithSelector:repair];
3807 } else if ([self popErrorWithTitle:title forOperation:true])
3811 unlink("/tmp/cydia.chk");
3813 now_ = [[NSDate date] timeIntervalSince1970];
3815 policy_ = new pkgDepCache::Policy();
3816 records_ = new pkgRecords(cache_);
3817 resolver_ = new pkgProblemResolver(cache_);
3818 fetcher_ = new pkgAcquire(&status_);
3821 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3822 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3826 _profile(reloadDataWithInvocation$pkgApplyStatus)
3827 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3831 if (cache_->BrokenCount() != 0) {
3832 _profile(pkgApplyStatus$pkgFixBroken)
3833 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3837 if (cache_->BrokenCount() != 0) {
3838 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3842 _profile(pkgApplyStatus$pkgMinimizeUpgrade)
3843 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3848 for (Source *object in (id) sourceList_) {
3849 metaIndex *source([object metaIndex]);
3850 std::vector<pkgIndexFile *> *indices = source->GetIndexFiles();
3851 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3852 // XXX: this could be more intelligent
3853 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3854 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3856 sourceMap_[cached->ID] = object;
3861 size_t capacity(MetaFile_->active_);
3863 capacity = 128*1024;
3867 std::vector<Package *> packages;
3868 packages.reserve(capacity);
3872 _profile(reloadDataWithInvocation$packageWithIterator)
3873 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3874 if (Package *package = [Package newPackageWithIterator:iterator withZone:zone_ inPool:&pool_ database:self]) {
3875 if (unsigned index = package.metadata->index_) {
3877 if (packages.size() == index) {
3878 packages.push_back(package);
3879 } else if (packages.size() <= index) {
3880 packages.resize(index + 1, nil);
3881 packages[index] = package;
3884 std::swap(package, packages[index]);
3885 if (package != nil) {
3886 if (package.metadata->index_ == index + 1)
3895 lost: if (last == packages.size())
3896 packages.push_back(package);
3898 packages[last] = package;
3902 for (; last != packages.size(); ++last)
3903 if (packages[last] == nil)
3908 for (size_t next(last + 1); last != packages.size(); ++last, ++next) {
3910 if (next == packages.size())
3912 if (packages[next] != nil)
3917 std::swap(packages[last], packages[next]);
3920 packages.resize(last);
3923 NSLog(@"lost = %zu", lost);
3925 _profile(reloadDataWithInvocation$radix$8)
3926 CYRadixSortUsingFunction(packages.data(), packages.size(), reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix), reinterpret_cast<void *>(8));
3929 _profile(reloadDataWithInvocation$radix$4)
3930 CYRadixSortUsingFunction(packages.data(), packages.size(), reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix), reinterpret_cast<void *>(4));
3933 _profile(reloadDataWithInvocation$radix$0)
3934 CYRadixSortUsingFunction(packages.data(), packages.size(), reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix), reinterpret_cast<void *>(0));
3938 _profile(reloadDataWithInvocation$insertion)
3939 CYArrayInsertionSortValues(packages.data(), packages.size(), &PackageNameCompare, NULL);
3942 packages_ = [[[NSArray alloc] initWithObjects:packages.data() count:packages.size()] autorelease];
3944 /*_profile(reloadDataWithInvocation$CFQSortArray)
3945 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);
3948 /*_profile(reloadDataWithInvocation$stdsort)
3949 std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3952 /*_profile(reloadDataWithInvocation$CFArraySortValues)
3953 CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3956 /*_profile(reloadDataWithInvocation$sortUsingFunction)
3957 [packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3960 MetaFile_->active_ = packages.size();
3961 for (size_t index(0), count(packages.size()); index != count; ++index) {
3962 auto package(packages[index]);
3963 [package setIndex:index];
3970 @synchronized (self) {
3972 resolver_ = new pkgProblemResolver(cache_);
3974 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3975 if (!cache_[iterator].Keep())
3976 cache_->MarkKeep(iterator, false);
3977 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3978 cache_->SetReInstall(iterator, false);
3981 - (void) configure {
3982 NSString *dpkg = [NSString stringWithFormat:@"/usr/libexec/cydo --configure -a --status-fd %u", statusfd_];
3984 system([dpkg UTF8String]);
3989 @synchronized (self) {
3990 // XXX: I don't remember this condition
3995 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3997 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3999 if ([self popErrorWithTitle:title])
4003 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
4005 CydiaLogCleaner cleaner;
4006 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
4013 fetcher_->Shutdown();
4015 pkgRecords records(cache_);
4017 lock_ = new FileFd();
4018 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
4020 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
4022 if ([self popErrorWithTitle:title])
4026 if ([self popErrorWithTitle:title forReadList:list])
4029 manager_ = (_system->CreatePM(cache_));
4030 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
4037 bool substrate(RestartSubstrate_);
4038 RestartSubstrate_ = false;
4040 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
4042 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
4044 if ([self popErrorWithTitle:title forReadList:list])
4046 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
4047 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
4050 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4052 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
4054 [self popErrorWithTitle:title];
4058 bool failed = false;
4059 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
4060 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
4062 if ((*item)->Status == pkgAcquire::Item::StatIdle)
4065 std::string uri = (*item)->DescURI();
4066 std::string error = (*item)->ErrorText;
4068 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
4071 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError]);
4072 [delegate_ addProgressEventOnMainThread:event forTask:title];
4075 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4083 RestartSubstrate_ = true;
4085 if (![delock_ isEqual:GetStatusDate()]) {
4086 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("DPKG_LOCKED") ofType:kCydiaProgressEventTypeError] forTask:title];
4092 pkgPackageManager::OrderResult result(manager_->DoInstall(statusfd_));
4094 NSString *oextended(@"/var/lib/apt/extended_states");
4095 NSString *nextended(Cache("extended_states"));
4098 if (stat([nextended UTF8String], &info) != -1 && (info.st_mode & S_IFMT) == S_IFREG)
4099 system([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /bin/cp --remove-destination %@ %@", ShellEscape(nextended), ShellEscape(oextended)] UTF8String]);
4101 unlink([nextended UTF8String]);
4102 symlink([oextended UTF8String], [nextended UTF8String]);
4104 if ([self popErrorWithTitle:title])
4107 if (result == pkgPackageManager::Failed) {
4112 if (result != pkgPackageManager::Completed) {
4117 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
4119 if ([self popErrorWithTitle:title forReadList:list])
4121 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
4122 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
4125 if (![before isEqualToArray:after])
4130 return ![delock_ isEqual:GetStatusDate()];
4134 NSString *title(UCLocalize("UPGRADE"));
4135 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
4141 [self updateWithStatus:status_];
4144 - (void) updateWithStatus:(CancelStatus &)status {
4145 NSString *title(UCLocalize("REFRESHING_DATA"));
4148 if ([self popErrorWithTitle:title forReadList:list])
4152 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
4153 if ([self popErrorWithTitle:title])
4156 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4158 bool success(ListUpdate(status, list, PulseInterval_));
4159 if (status.WasCancelled())
4162 [self popErrorWithTitle:title forOperation:success];
4164 [[NSDictionary dictionaryWithObjectsAndKeys:
4165 [NSDate date], @"LastUpdate",
4166 nil] writeToFile:@ CacheState_ atomically:YES];
4169 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4172 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
4173 delegate_ = delegate;
4176 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
4177 progress_ = delegate;
4178 status_.setDelegate(delegate);
4181 - (NSObject<ProgressDelegate> *) progressDelegate {
4185 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
4186 SourceMap::const_iterator i(sourceMap_.find(file->ID));
4187 return i == sourceMap_.end() ? nil : i->second;
4190 - (void) setFetch:(bool)fetch forURI:(const char *)uri {
4191 for (Source *source in (id) sourceList_)
4192 [source setFetch:fetch forURI:uri];
4195 - (void) resetFetch {
4196 for (Source *source in (id) sourceList_)
4197 [source resetFetch];
4200 - (NSString *) mappedSectionForPointer:(const char *)section {
4201 _H<NSString> *mapped;
4203 _profile(Database$mappedSectionForPointer$Cache)
4204 mapped = §ions_[section];
4207 if (*mapped == NULL) {
4208 size_t length(strlen(section));
4209 char spaced[length + 1];
4211 _profile(Database$mappedSectionForPointer$Replace)
4212 for (size_t index(0); index != length; ++index)
4213 spaced[index] = section[index] == '_' ? ' ' : section[index];
4214 spaced[length] = '\0';
4219 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
4220 string = [NSString stringWithUTF8String:spaced];
4223 _profile(Database$mappedSectionForPointer$Map)
4224 string = [SectionMap_ objectForKey:string] ?: string;
4234 @interface CydiaObject : NSObject {
4235 _H<CyteWebViewController> indirect_;
4236 _transient id delegate_;
4239 - (id) initWithDelegate:(CyteWebViewController *)indirect;
4245 @interface CydiaWebViewController : CyteWebViewController {
4246 _H<CydiaObject> cydia_;
4249 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request;
4250 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia;
4251 - (void) setDelegate:(id)delegate;
4255 /* Web Scripting {{{ */
4256 @implementation CydiaObject
4258 - (id) initWithDelegate:(CyteWebViewController *)indirect {
4259 if ((self = [super init]) != nil) {
4260 indirect_ = indirect;
4264 - (void) setDelegate:(id)delegate {
4265 delegate_ = delegate;
4268 + (NSArray *) _attributeKeys {
4269 return [NSArray arrayWithObjects:
4274 @"coreFoundationVersionNumber",
4290 - (NSArray *) attributeKeys {
4291 return [[self class] _attributeKeys];
4294 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4295 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4298 - (NSString *) version {
4302 - (unsigned) bittage {
4304 #elif defined(__arm64__)
4306 #elif defined(__arm__)
4313 - (NSString *) build {
4314 return [NSString stringWithUTF8String:System_];
4317 - (NSString *) coreFoundationVersionNumber {
4318 return [NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber];
4321 - (NSString *) device {
4322 return UniqueIdentifier();
4325 - (NSString *) firmware {
4326 return [[UIDevice currentDevice] systemVersion];
4329 - (NSString *) hostname {
4330 return [[UIDevice currentDevice] name];
4333 - (NSString *) idiom {
4334 return (id) Idiom_ ?: [NSNull null];
4337 - (NSArray *) cells {
4338 auto *$_CTServerConnectionCreate(reinterpret_cast<id (*)(void *, void *, void *)>(dlsym(RTLD_DEFAULT, "_CTServerConnectionCreate")));
4339 if ($_CTServerConnectionCreate == NULL)
4342 struct CTResult { int flag; int error; };
4343 auto *$_CTServerConnectionCellMonitorCopyCellInfo(reinterpret_cast<CTResult (*)(CFTypeRef, void *, CFArrayRef *)>(dlsym(RTLD_DEFAULT, "_CTServerConnectionCellMonitorCopyCellInfo")));
4344 if ($_CTServerConnectionCellMonitorCopyCellInfo == NULL)
4347 _H<const void> connection($_CTServerConnectionCreate(NULL, NULL, NULL), true);
4348 if (connection == nil)
4352 CFArrayRef cells(NULL);
4353 auto result($_CTServerConnectionCellMonitorCopyCellInfo(connection, &count, &cells));
4354 if (result.flag != 0)
4357 return [(NSArray *) cells autorelease];
4360 - (NSString *) mcc {
4361 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode")))
4362 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault) autorelease];
4366 - (NSString *) mnc {
4367 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberNetworkCode")))
4368 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault) autorelease];
4372 - (NSString *) operator {
4373 if (CFStringRef (*$CTRegistrationCopyOperatorName)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTRegistrationCopyOperatorName")))
4374 return [(NSString *) (*$CTRegistrationCopyOperatorName)(kCFAllocatorDefault) autorelease];
4378 - (NSString *) bbsnum {
4379 return (id) BBSNum_ ?: [NSNull null];
4382 - (NSString *) ecid {
4383 return (id) ChipID_ ?: [NSNull null];
4386 - (NSString *) serial {
4387 return SerialNumber_;
4390 - (NSString *) role {
4391 return (id) [NSNull null];
4394 - (NSString *) model {
4395 return [NSString stringWithUTF8String:Machine_];
4398 + (NSString *) webScriptNameForSelector:(SEL)selector {
4400 else if (selector == @selector(addBridgedHost:))
4401 return @"addBridgedHost";
4402 else if (selector == @selector(addInsecureHost:))
4403 return @"addInsecureHost";
4404 else if (selector == @selector(addInternalRedirect::))
4405 return @"addInternalRedirect";
4406 else if (selector == @selector(addSource:::))
4407 return @"addSource";
4408 else if (selector == @selector(addTrivialSource:))
4409 return @"addTrivialSource";
4410 else if (selector == @selector(close))
4412 else if (selector == @selector(du:))
4414 else if (selector == @selector(stringWithFormat:arguments:))
4416 else if (selector == @selector(getAllSources))
4417 return @"getAllSources";
4418 else if (selector == @selector(getApplicationInfo:value:))
4419 return @"getApplicationInfoValue";
4420 else if (selector == @selector(getDisplayIdentifiers))
4421 return @"getDisplayIdentifiers";
4422 else if (selector == @selector(getLocalizedNameForDisplayIdentifier:))
4423 return @"getLocalizedNameForDisplayIdentifier";
4424 else if (selector == @selector(getKernelNumber:))
4425 return @"getKernelNumber";
4426 else if (selector == @selector(getKernelString:))
4427 return @"getKernelString";
4428 else if (selector == @selector(getInstalledPackages))
4429 return @"getInstalledPackages";
4430 else if (selector == @selector(getIORegistryEntry::))
4431 return @"getIORegistryEntry";
4432 else if (selector == @selector(getLocaleIdentifier))
4433 return @"getLocaleIdentifier";
4434 else if (selector == @selector(getPreferredLanguages))
4435 return @"getPreferredLanguages";
4436 else if (selector == @selector(getPackageById:))
4437 return @"getPackageById";
4438 else if (selector == @selector(getMetadataKeys))
4439 return @"getMetadataKeys";
4440 else if (selector == @selector(getMetadataValue:))
4441 return @"getMetadataValue";
4442 else if (selector == @selector(getSessionValue:))
4443 return @"getSessionValue";
4444 else if (selector == @selector(installPackages:))
4445 return @"installPackages";
4446 else if (selector == @selector(isReachable:))
4447 return @"isReachable";
4448 else if (selector == @selector(localizedStringForKey:value:table:))
4450 else if (selector == @selector(popViewController:))
4451 return @"popViewController";
4452 else if (selector == @selector(refreshSources))
4453 return @"refreshSources";
4454 else if (selector == @selector(registerFrame:))
4455 return @"registerFrame";
4456 else if (selector == @selector(removeButton))
4457 return @"removeButton";
4458 else if (selector == @selector(saveConfig))
4459 return @"saveConfig";
4460 else if (selector == @selector(setMetadataValue::))
4461 return @"setMetadataValue";
4462 else if (selector == @selector(setSessionValue::))
4463 return @"setSessionValue";
4464 else if (selector == @selector(substitutePackageNames:))
4465 return @"substitutePackageNames";
4466 else if (selector == @selector(scrollToBottom:))
4467 return @"scrollToBottom";
4468 else if (selector == @selector(setAllowsNavigationAction:))
4469 return @"setAllowsNavigationAction";
4470 else if (selector == @selector(setBadgeValue:))
4471 return @"setBadgeValue";
4472 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4473 return @"setButtonImage";
4474 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4475 return @"setButtonTitle";
4476 else if (selector == @selector(setHidesBackButton:))
4477 return @"setHidesBackButton";
4478 else if (selector == @selector(setHidesNavigationBar:))
4479 return @"setHidesNavigationBar";
4480 else if (selector == @selector(setNavigationBarStyle:))
4481 return @"setNavigationBarStyle";
4482 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4483 return @"setNavigationBarTintColor";
4484 else if (selector == @selector(setPasteboardString:))
4485 return @"setPasteboardString";
4486 else if (selector == @selector(setPasteboardURL:))
4487 return @"setPasteboardURL";
4488 else if (selector == @selector(setScrollAlwaysBounceVertical:))
4489 return @"setScrollAlwaysBounceVertical";
4490 else if (selector == @selector(setScrollIndicatorStyle:))
4491 return @"setScrollIndicatorStyle";
4492 else if (selector == @selector(setToken:))
4494 else if (selector == @selector(setViewportWidth:))
4495 return @"setViewportWidth";
4496 else if (selector == @selector(statfs:))
4498 else if (selector == @selector(supports:))
4500 else if (selector == @selector(unload))
4506 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4507 return [self webScriptNameForSelector:selector] == nil;
4510 - (BOOL) supports:(NSString *)feature {
4511 return [feature isEqualToString:@"window.open"];
4515 [[indirect_ rootViewController] performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4518 - (void) setScrollAlwaysBounceVertical:(NSNumber *)value {
4519 [indirect_ performSelectorOnMainThread:@selector(setScrollAlwaysBounceVerticalNumber:) withObject:value waitUntilDone:NO];
4522 - (void) setScrollIndicatorStyle:(NSString *)style {
4523 [indirect_ performSelectorOnMainThread:@selector(setScrollIndicatorStyleWithName:) withObject:style waitUntilDone:NO];
4526 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4527 [CyteWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4530 - (NSDictionary *) getApplicationInfo:(NSString *)display value:(NSString *)key {
4532 if (SBBundlePathForDisplayIdentifier(SBSSpringBoardServerPort(), [display UTF8String], path) != 0)
4533 return (id) [NSNull null];
4534 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:[[NSString stringWithUTF8String:path] stringByAppendingString:@"/Info.plist"]]);
4536 return (id) [NSNull null];
4537 return [info objectForKey:key];
4540 - (NSArray *) getDisplayIdentifiers {
4541 return SBSCopyApplicationDisplayIdentifiers(false, false);
4544 - (NSString *) getLocalizedNameForDisplayIdentifier:(NSString *)identifier {
4545 return [SBSCopyLocalizedApplicationNameForDisplayIdentifier(identifier) autorelease] ?: (id) [NSNull null];
4548 - (NSNumber *) getKernelNumber:(NSString *)name {
4549 const char *string([name UTF8String]);
4552 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4553 return (id) [NSNull null];
4555 if (size != sizeof(int))
4556 return (id) [NSNull null];
4559 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4560 return (id) [NSNull null];
4562 return [NSNumber numberWithInt:value];
4565 - (NSString *) getKernelString:(NSString *)name {
4566 const char *string([name UTF8String]);
4569 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4570 return (id) [NSNull null];
4572 char value[size + 1];
4573 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4574 return (id) [NSNull null];
4576 // XXX: just in case you request something ludicrous
4579 return [NSString stringWithCString:value];
4582 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4583 NSObject *value(CYIOGetValue([path UTF8String], entry));
4586 if ([value isKindOfClass:[NSData class]])
4587 value = CYHex((NSData *) value);
4592 - (NSArray *) getMetadataKeys {
4593 @synchronized (Values_) {
4594 return [Values_ allKeys];
4597 - (void) registerFrame:(DOMHTMLIFrameElement *)iframe {
4598 WebFrame *frame([iframe contentFrame]);
4599 [indirect_ registerFrame:frame];
4602 - (id) getMetadataValue:(NSString *)key {
4603 @synchronized (Values_) {
4604 return [Values_ objectForKey:key];
4607 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4608 @synchronized (Values_) {
4609 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4610 [Values_ removeObjectForKey:key];
4612 [Values_ setObject:value forKey:key];
4615 - (id) getSessionValue:(NSString *)key {
4616 @synchronized (SessionData_) {
4617 return [SessionData_ objectForKey:key];
4620 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4621 @synchronized (SessionData_) {
4622 if (value == (id) [WebUndefined undefined])
4623 [SessionData_ removeObjectForKey:key];
4625 [SessionData_ setObject:value forKey:key];
4628 - (void) addBridgedHost:(NSString *)host {
4629 @synchronized (BridgedHosts_) {
4630 [BridgedHosts_ addObject:host];
4633 - (void) addInsecureHost:(NSString *)host {
4634 @synchronized (InsecureHosts_) {
4635 [InsecureHosts_ addObject:host];
4638 - (void) popViewController:(NSNumber *)value {
4639 if (value == (id) [WebUndefined undefined])
4640 value = [NSNumber numberWithBool:YES];
4641 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4644 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4645 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4647 for (NSString *section in sections)
4648 [array addObject:section];
4650 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4653 distribution, @"Distribution",
4655 nil] waitUntilDone:NO];
4658 - (BOOL) addTrivialSource:(NSString *)href {
4659 href = VerifySource(href);
4662 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4666 - (void) refreshSources {
4667 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4670 - (void) saveConfig {
4671 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4674 - (NSArray *) getAllSources {
4675 return [[Database sharedInstance] sources];
4678 - (NSArray *) getInstalledPackages {
4679 Database *database([Database sharedInstance]);
4680 @synchronized (database) {
4681 NSArray *packages([database packages]);
4682 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4683 for (Package *package in packages)
4684 if (![package uninstalled])
4685 [installed addObject:package];
4689 - (Package *) getPackageById:(NSString *)id {
4690 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4694 return (Package *) [NSNull null];
4697 - (NSString *) getLocaleIdentifier {
4698 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4701 - (NSArray *) getPreferredLanguages {
4705 - (NSArray *) statfs:(NSString *)path {
4708 if (path == nil || statfs([path UTF8String], &stat) == -1)
4711 return [NSArray arrayWithObjects:
4712 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4713 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4714 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4718 - (NSNumber *) du:(NSString *)path {
4719 NSNumber *value(nil);
4721 FILE *du(popen([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /usr/libexec/cydia/du -ks %@", ShellEscape(path)] UTF8String], "r"));
4724 while (fgets(line, sizeof(line), du) != NULL) {
4725 size_t length(strlen(line));
4726 while (length != 0 && line[length - 1] == '\n')
4727 line[--length] = '\0';
4728 if (char *tab = strchr(line, '\t')) {
4730 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4740 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4743 - (NSNumber *) isReachable:(NSString *)name {
4744 return [NSNumber numberWithBool:CyteIsReachable([name UTF8String])];
4747 - (void) installPackages:(NSArray *)packages {
4748 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4751 - (NSString *) substitutePackageNames:(NSString *)message {
4752 auto database([Database sharedInstance]);
4754 // XXX: this check is less racy than you'd expect, but this entire concept is a little awkward
4755 if (![database hasPackages])
4758 NSMutableArray *words([[[message componentsSeparatedByString:@" "] mutableCopy] autorelease]);
4759 for (size_t i(0), e([words count]); i != e; ++i) {
4760 NSString *word([words objectAtIndex:i]);
4761 if (Package *package = [database packageWithName:word])
4762 [words replaceObjectAtIndex:i withObject:[package name]];
4765 return [words componentsJoinedByString:@" "];
4768 - (void) removeButton {
4769 [indirect_ removeButton];
4772 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4773 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4776 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4777 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4780 - (void) setBadgeValue:(id)value {
4781 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4784 - (void) setAllowsNavigationAction:(NSString *)value {
4785 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4788 - (void) setHidesBackButton:(NSString *)value {
4789 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4792 - (void) setHidesNavigationBar:(NSString *)value {
4793 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4796 - (void) setNavigationBarStyle:(NSString *)value {
4797 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4800 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4801 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4802 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4803 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4806 - (void) setPasteboardString:(NSString *)value {
4807 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4810 - (void) setPasteboardURL:(NSString *)value {
4811 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4814 - (void) setToken:(NSString *)token {
4815 // XXX: the website expects this :/
4818 - (void) scrollToBottom:(NSNumber *)animated {
4819 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4822 - (void) setViewportWidth:(float)width {
4823 [indirect_ setViewportWidthOnMainThread:width];
4826 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4827 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4828 unsigned count([arguments count]);
4830 for (unsigned i(0); i != count; ++i)
4831 values[i] = [arguments objectAtIndex:i];
4832 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4835 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4836 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4838 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4840 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4846 @interface NSURL (CydiaSecure)
4849 @implementation NSURL (CydiaSecure)
4851 - (bool) isCydiaSecure {
4852 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4855 @synchronized (InsecureHosts_) {
4856 if ([InsecureHosts_ containsObject:[self host]])
4865 /* Cydia Browser Controller {{{ */
4866 @implementation CydiaWebViewController
4868 - (NSURL *) navigationURL {
4869 if (NSURLRequest *request = self.request)
4870 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request URL] absoluteString]]];
4875 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4876 [super webView:view didClearWindowObject:window forFrame:frame];
4877 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
4880 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia {
4881 WebDataSource *source([frame dataSource]);
4882 NSURLResponse *response([source response]);
4883 NSURL *url([response URL]);
4884 NSString *scheme([[url scheme] lowercaseString]);
4886 bool bridged(false);
4888 @synchronized (BridgedHosts_) {
4889 if ([scheme isEqualToString:@"file"])
4891 else if ([scheme isEqualToString:@"https"])
4892 if ([BridgedHosts_ containsObject:[url host]])
4897 [window setValue:cydia forKey:@"cydia"];
4900 - (void) _setupMail:(MFMailComposeViewController *)controller {
4901 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4903 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4904 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4907 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4908 return [CydiaWebViewController requestWithHeaders:[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
4911 - (NSURLRequest *) webThreadWebView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4912 return [CydiaWebViewController requestWithHeaders:[super webThreadWebView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
4915 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request {
4916 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
4918 NSURL *url([copy URL]);
4919 NSString *href([url absoluteString]);
4920 NSString *host([url host]);
4922 if ([href hasPrefix:@"https://cydia.saurik.com/TSS/"]) {
4923 if (NSString *agent = [copy valueForHTTPHeaderField:@"X-User-Agent"]) {
4924 [copy setValue:agent forHTTPHeaderField:@"User-Agent"];
4925 [copy setValue:nil forHTTPHeaderField:@"X-User-Agent"];
4928 [copy setValue:nil forHTTPHeaderField:@"Referer"];
4929 [copy setValue:nil forHTTPHeaderField:@"Origin"];
4931 [copy setURL:[NSURL URLWithString:[@"http://gs.apple.com/TSS/" stringByAppendingString:[href substringFromIndex:29]]]];
4935 if ([copy valueForHTTPHeaderField:@"X-Cydia-Cf"] == nil)
4936 [copy setValue:[NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber] forHTTPHeaderField:@"X-Cydia-Cf"];
4937 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4938 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4940 bool bridged; @synchronized (BridgedHosts_) {
4941 bridged = [BridgedHosts_ containsObject:host];
4944 if ([url isCydiaSecure] && bridged && UniqueID_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Id"] == nil)
4945 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
4950 - (void) setDelegate:(id)delegate {
4951 [super setDelegate:delegate];
4952 [cydia_ setDelegate:delegate];
4956 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4957 cydia_ = [[[CydiaObject alloc] initWithDelegate:self.indirect] autorelease];
4963 @interface AppCacheController : CydiaWebViewController {
4968 @implementation AppCacheController
4970 - (void) didReceiveMemoryWarning {
4971 // XXX: this doesn't work
4974 - (bool) retainsNetworkActivityIndicator {
4981 /* Confirmation Controller {{{ */
4982 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4983 if (!iterator.end())
4984 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4985 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4987 pkgCache::PkgIterator package(dep.TargetPkg());
4990 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4997 @protocol ConfirmationControllerDelegate
4998 - (void) cancelAndClear:(bool)clear;
4999 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
5003 @interface ConfirmationController : CydiaWebViewController {
5004 _transient Database *database_;
5006 _H<UIAlertView> essential_;
5008 _H<NSDictionary> changes_;
5009 _H<NSMutableArray> issues_;
5010 _H<NSDictionary> sizes_;
5015 - (id) initWithDatabase:(Database *)database;
5019 @implementation ConfirmationController
5023 RestartSubstrate_ = true;
5024 [self.delegate confirmWithNavigationController:[self navigationController]];
5027 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
5028 NSString *context([alert context]);
5030 if ([context isEqualToString:@"remove"]) {
5031 if (button == [alert cancelButtonIndex])
5033 else if (button == [alert firstOtherButtonIndex]) {
5034 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
5037 [alert dismissWithClickedButtonIndex:-1 animated:YES];
5038 } else if ([context isEqualToString:@"unable"]) {
5039 [self dismissModalViewControllerAnimated:YES];
5040 [alert dismissWithClickedButtonIndex:-1 animated:YES];
5042 [super alertView:alert clickedButtonAtIndex:button];
5046 - (void) _doContinue {
5047 [self.delegate cancelAndClear:NO];
5048 [self dismissModalViewControllerAnimated:YES];
5051 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
5052 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
5056 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5057 [super webView:view didClearWindowObject:window forFrame:frame];
5059 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
5060 (id) changes_, @"changes",
5061 (id) issues_, @"issues",
5062 (id) sizes_, @"sizes",
5064 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
5067 - (id) initWithDatabase:(Database *)database {
5068 if ((self = [super init]) != nil) {
5069 database_ = database;
5071 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
5072 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
5073 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
5074 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
5075 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
5079 pkgCacheFile &cache([database_ cache]);
5080 NSArray *packages([database_ packages]);
5081 pkgDepCache::Policy *policy([database_ policy]);
5083 issues_ = [NSMutableArray arrayWithCapacity:4];
5085 for (Package *package in packages) {
5086 pkgCache::PkgIterator iterator([package iterator]);
5087 NSString *name([package id]);
5089 if ([package broken]) {
5090 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
5092 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5094 reasons, @"reasons",
5097 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
5101 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
5102 pkgCache::DepIterator start;
5103 pkgCache::DepIterator end;
5104 dep.GlobOr(start, end); // ++dep
5106 if (!cache->IsImportantDep(end))
5108 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
5111 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
5113 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5114 [NSString stringWithUTF8String:start.DepType()], @"relationship",
5115 clauses, @"clauses",
5119 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
5121 pkgCache::PkgIterator target(start.TargetPkg());
5122 if (target->ProvidesList != 0)
5123 reason = @"missing";
5125 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
5127 reason = @"installed";
5128 installed = [NSString stringWithUTF8String:ver.VerStr()];
5129 } else if (!cache[target].CandidateVerIter(cache).end())
5130 reason = @"uninstalled";
5131 else if (target->ProvidesList == 0)
5132 reason = @"uninstallable";
5134 reason = @"virtual";
5137 NSDictionary *version(start.TargetVer() == 0 ? (NSDictionary *) [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
5138 [NSString stringWithUTF8String:start.CompType()], @"operator",
5139 [NSString stringWithUTF8String:start.TargetVer()], @"value",
5142 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5143 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
5144 version, @"version",
5146 installed, @"installed",
5149 // yes, seriously. (wtf?)
5157 pkgDepCache::StateCache &state(cache[iterator]);
5159 static RegEx special_r("(firmware|gsc\\..*|cy\\+.*)");
5161 if (state.NewInstall())
5162 [installs addObject:name];
5163 // XXX: else if (state.Install())
5164 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
5165 [reinstalls addObject:name];
5166 // XXX: move before previous if
5167 else if (state.Upgrade())
5168 [upgrades addObject:name];
5169 else if (state.Downgrade())
5170 [downgrades addObject:name];
5171 else if (!state.Delete())
5172 // XXX: _assert(state.Keep());
5174 else if (special_r(name))
5175 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5176 [NSNull null], @"package",
5177 [NSArray arrayWithObjects:
5178 [NSDictionary dictionaryWithObjectsAndKeys:
5179 @"Conflicts", @"relationship",
5180 [NSArray arrayWithObjects:
5181 [NSDictionary dictionaryWithObjectsAndKeys:
5183 [NSNull null], @"version",
5184 @"installed", @"reason",
5191 if ([package essential])
5193 [removes addObject:name];
5196 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
5197 substrate_ |= DepSubstrate(iterator.CurrentVer());
5202 else if (Advanced_) {
5203 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
5205 essential_ = [[[UIAlertView alloc]
5206 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
5207 message:UCLocalize("REMOVING_ESSENTIALS_EX")
5209 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
5211 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
5215 [essential_ setContext:@"remove"];
5216 [essential_ setNumberOfRows:2];
5218 essential_ = [[[UIAlertView alloc]
5219 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
5220 message:UCLocalize("UNABLE_TO_COMPLY_EX")
5222 cancelButtonTitle:UCLocalize("OKAY")
5223 otherButtonTitles:nil
5226 [essential_ setContext:@"unable"];
5229 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5230 installs, @"installs",
5231 reinstalls, @"reinstalls",
5232 upgrades, @"upgrades",
5233 downgrades, @"downgrades",
5234 removes, @"removes",
5237 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5238 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
5239 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
5242 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
5246 - (UIBarButtonItem *) leftButton {
5247 return [[[UIBarButtonItem alloc]
5248 initWithTitle:UCLocalize("CANCEL")
5249 style:UIBarButtonItemStylePlain
5251 action:@selector(cancelButtonClicked)
5256 - (void) applyRightButton {
5257 if ([issues_ count] == 0 && ![self isLoading])
5258 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
5259 initWithTitle:UCLocalize("CONFIRM")
5260 style:UIBarButtonItemStyleDone
5262 action:@selector(confirmButtonClicked)
5265 [[self navigationItem] setRightBarButtonItem:nil];
5269 - (void) cancelButtonClicked {
5270 [self.delegate cancelAndClear:YES];
5271 [self dismissModalViewControllerAnimated:YES];
5275 - (void) confirmButtonClicked {
5276 if (essential_ != nil)
5286 /* Progress Data {{{ */
5287 @interface CydiaProgressData : NSObject {
5288 _transient id delegate_;
5297 _H<NSMutableArray> events_;
5298 _H<NSString> title_;
5300 _H<NSString> status_;
5301 _H<NSString> finish_;
5306 @implementation CydiaProgressData
5308 + (NSArray *) _attributeKeys {
5309 return [NSArray arrayWithObjects:
5321 - (NSArray *) attributeKeys {
5322 return [[self class] _attributeKeys];
5325 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5326 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5330 if ((self = [super init]) != nil) {
5331 events_ = [NSMutableArray arrayWithCapacity:32];
5339 - (void) setDelegate:(id)delegate {
5340 delegate_ = delegate;
5343 - (void) setPercent:(float)value {
5347 - (NSNumber *) percent {
5348 return [NSNumber numberWithFloat:percent_];
5351 - (void) setCurrent:(float)value {
5355 - (NSNumber *) current {
5356 return [NSNumber numberWithFloat:current_];
5359 - (void) setTotal:(float)value {
5363 - (NSNumber *) total {
5364 return [NSNumber numberWithFloat:total_];
5367 - (void) setSpeed:(float)value {
5371 - (NSNumber *) speed {
5372 return [NSNumber numberWithFloat:speed_];
5375 - (NSArray *) events {
5379 - (void) removeAllEvents {
5380 [events_ removeAllObjects];
5383 - (void) addEvent:(CydiaProgressEvent *)event {
5384 [events_ addObject:event];
5387 - (void) setTitle:(NSString *)text {
5391 - (NSString *) title {
5395 - (void) setFinish:(NSString *)text {
5399 - (NSString *) finish {
5400 return (id) finish_ ?: [NSNull null];
5403 - (void) setRunning:(bool)running {
5407 - (NSNumber *) running {
5408 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5413 /* Progress Controller {{{ */
5414 @interface ProgressController : CydiaWebViewController <
5417 _transient Database *database_;
5418 _H<CydiaProgressData, 1> progress_;
5422 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5424 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5426 - (void) setTitle:(NSString *)title;
5427 - (void) setCancellable:(bool)cancellable;
5431 @implementation ProgressController
5434 [database_ setProgressDelegate:nil];
5438 - (UIBarButtonItem *) leftButton {
5439 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5440 initWithTitle:UCLocalize("CANCEL")
5441 style:UIBarButtonItemStylePlain
5443 action:@selector(cancel)
5444 ] autorelease] : nil;
5447 - (void) updateCancel {
5448 [super applyLeftButton];
5451 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5452 if ((self = [super init]) != nil) {
5453 database_ = database;
5454 self.delegate = delegate;
5456 [database_ setProgressDelegate:self];
5458 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5459 [progress_ setDelegate:self];
5461 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5463 [self setPageColor:[UIColor blackColor]];
5465 [[self navigationItem] setHidesBackButton:YES];
5467 [self updateCancel];
5471 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5472 [super webView:view didClearWindowObject:window forFrame:frame];
5473 [window setValue:progress_ forKey:@"cydiaProgress"];
5476 - (void) updateProgress {
5477 [self dispatchEvent:@"CydiaProgressUpdate"];
5480 - (void) viewWillAppear:(BOOL)animated {
5481 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5482 [super viewWillAppear:animated];
5486 UpdateExternalStatus(0);
5489 [self.delegate saveState];
5493 [self.delegate returnToCydia];
5497 [self.delegate terminateWithSuccess];
5498 /*if ([self.delegate respondsToSelector:@selector(suspendWithAnimation:)])
5499 [self.delegate suspendWithAnimation:YES];
5501 [self.delegate suspend];*/
5513 UIProgressHUD *hud([self.delegate addProgressHUD]);
5514 [hud setText:UCLocalize("LOADING")];
5515 [self.delegate performSelector:@selector(reloadSpringBoard) withObject:nil afterDelay:0.5];
5521 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5522 SBReboot(SBSSpringBoardServerPort());
5524 reboot2(RB_AUTOBOOT);
5531 - (void) setTitle:(NSString *)title {
5532 [progress_ setTitle:title];
5533 [self updateProgress];
5536 - (UIBarButtonItem *) rightButton {
5537 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5538 initWithTitle:UCLocalize("CLOSE")
5539 style:UIBarButtonItemStylePlain
5541 action:@selector(close)
5545 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5546 UpdateExternalStatus(1);
5548 [progress_ setRunning:true];
5549 [self setTitle:title];
5550 // implicit updateProgress
5552 SHA1SumValue notifyconf; {
5554 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5557 MMap mmap(file, MMap::ReadOnly);
5559 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5560 notifyconf = sha1.Result();
5564 SHA1SumValue springlist; {
5566 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5569 MMap mmap(file, MMap::ReadOnly);
5571 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5572 springlist = sha1.Result();
5576 if (invocation != nil) {
5577 [invocation yieldToSelector:@selector(invoke)];
5578 [self setTitle:@"COMPLETE"];
5583 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5586 MMap mmap(file, MMap::ReadOnly);
5588 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5589 if (!(notifyconf == sha1.Result()))
5596 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5599 MMap mmap(file, MMap::ReadOnly);
5601 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5602 if (!(springlist == sha1.Result()))
5608 if (RestartSubstrate_)
5612 RestartSubstrate_ = false;
5615 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5616 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5617 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5618 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5619 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5622 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5624 [progress_ setRunning:false];
5625 [self updateProgress];
5627 [self applyRightButton];
5630 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5631 [progress_ addEvent:event];
5632 [self updateProgress];
5635 - (bool) isProgressCancelled {
5636 return cancel_ == 2;
5641 [self updateCancel];
5644 - (void) setCancellable:(bool)cancellable {
5645 unsigned cancel(cancel_);
5649 else if (cancel_ == 0)
5652 if (cancel != cancel_)
5653 [self updateCancel];
5656 - (void) setProgressCancellable:(NSNumber *)cancellable {
5657 [self setCancellable:[cancellable boolValue]];
5660 - (void) setProgressPercent:(NSNumber *)percent {
5661 [progress_ setPercent:[percent floatValue]];
5662 [self updateProgress];
5665 - (void) setProgressStatus:(NSDictionary *)status {
5666 if (status == nil) {
5667 [progress_ setCurrent:0];
5668 [progress_ setTotal:0];
5669 [progress_ setSpeed:0];
5671 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5673 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5674 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5675 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5678 [self updateProgress];
5684 /* Package Cell {{{ */
5685 @interface PackageCell : CyteTableViewCell <
5686 CyteTableViewCellDelegate
5690 _H<NSString> description_;
5692 _H<NSString> source_;
5694 _H<UIImage> placard_;
5698 - (PackageCell *) init;
5699 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5701 - (void) drawContentRect:(CGRect)rect;
5705 @implementation PackageCell
5707 - (PackageCell *) init {
5708 CGRect frame(CGRectMake(0, 0, 320, 74));
5709 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5710 UIView *content([self contentView]);
5711 CGRect bounds([content bounds]);
5713 self.content = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5714 [self.content setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5715 [content addSubview:self.content];
5717 [self.content setDelegate:self];
5718 [self.content setOpaque:YES];
5722 - (NSString *) accessibilityLabel {
5726 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5727 summarized_ = summary;
5737 [self.content setBackgroundColor:[UIColor whiteColor]];
5741 Source *source = [package source];
5743 icon_ = [package icon];
5745 if (NSString *name = [package name])
5746 name_ = [NSString stringWithString:name];
5748 if (NSString *description = [package shortDescription])
5749 description_ = [NSString stringWithString:description];
5751 commercial_ = [package isCommercial];
5753 NSString *label = nil;
5754 bool trusted = false;
5756 if (source != nil) {
5757 label = [source label];
5758 trusted = [source trusted];
5759 } else if ([[package id] isEqualToString:@"firmware"])
5760 label = UCLocalize("APPLE");
5762 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5764 NSString *from(label);
5766 NSString *section = [package simpleSection];
5767 if (section != nil && ![section isEqualToString:label]) {
5768 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5769 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5772 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5774 if (NSString *purpose = [package primaryPurpose])
5775 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5780 if (NSString *mode = [package mode]) {
5781 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5782 color = RemovingColor_;
5783 placard = @"removing";
5785 color = InstallingColor_;
5786 placard = @"installing";
5789 color = [UIColor whiteColor];
5791 if ([package installed] != nil)
5792 placard = @"installed";
5797 [self.content setBackgroundColor:color];
5800 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5803 [self setNeedsDisplay];
5804 [self.content setNeedsDisplay];
5807 - (void) drawSummaryContentRect:(CGRect)rect {
5808 bool highlighted(self.highlighted);
5809 float width([self bounds].size.width);
5813 rect.size = [(UIImage *) icon_ size];
5815 while (rect.size.width > 16 || rect.size.height > 16) {
5816 rect.size.width /= 2;
5817 rect.size.height /= 2;
5820 rect.origin.x = 19 - rect.size.width / 2;
5821 rect.origin.y = 19 - rect.size.height / 2;
5823 [icon_ drawInRect:Retina(rect)];
5826 if (badge_ != nil) {
5828 rect.size = [(UIImage *) badge_ size];
5830 rect.size.width /= 4;
5831 rect.size.height /= 4;
5833 rect.origin.x = 25 - rect.size.width / 2;
5834 rect.origin.y = 25 - rect.size.height / 2;
5836 [badge_ drawInRect:Retina(rect)];
5839 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5843 UISetColor(commercial_ ? Purple_ : Black_);
5844 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
5846 if (placard_ != nil)
5847 [placard_ drawAtPoint:CGPointMake(width - 52, 11)];
5850 - (void) drawNormalContentRect:(CGRect)rect {
5851 bool highlighted(self.highlighted);
5852 float width([self bounds].size.width);
5856 rect.size = [(UIImage *) icon_ size];
5858 while (rect.size.width > 32 || rect.size.height > 32) {
5859 rect.size.width /= 2;
5860 rect.size.height /= 2;
5863 rect.origin.x = 25 - rect.size.width / 2;
5864 rect.origin.y = 25 - rect.size.height / 2;
5866 [icon_ drawInRect:Retina(rect)];
5869 if (badge_ != nil) {
5871 rect.size = [(UIImage *) badge_ size];
5873 rect.size.width /= 2;
5874 rect.size.height /= 2;
5876 rect.origin.x = 36 - rect.size.width / 2;
5877 rect.origin.y = 36 - rect.size.height / 2;
5879 [badge_ drawInRect:Retina(rect)];
5882 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5886 UISetColor(commercial_ ? Purple_ : Black_);
5887 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
5888 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
5891 UISetColor(commercial_ ? Purplish_ : Gray_);
5892 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:NSLineBreakByTruncatingTail];
5894 if (placard_ != nil)
5895 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5898 - (void) drawContentRect:(CGRect)rect {
5900 [self drawSummaryContentRect:rect];
5902 [self drawNormalContentRect:rect];
5907 /* Section Cell {{{ */
5908 @interface SectionCell : CyteTableViewCell <
5909 CyteTableViewCellDelegate
5911 _H<NSString> basic_;
5912 _H<NSString> section_;
5914 _H<NSString> count_;
5916 _H<UISwitch> switch_;
5920 - (void) setSection:(Section *)section editing:(BOOL)editing;
5924 @implementation SectionCell
5926 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5927 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5928 icon_ = [UIImage imageNamed:@"folder.png"];
5929 // XXX: this initial frame is wrong, but is fixed later
5930 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5931 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5933 UIView *content([self contentView]);
5934 CGRect bounds([content bounds]);
5936 self.content = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5937 [self.content setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5938 [content addSubview:self.content];
5939 [self.content setBackgroundColor:[UIColor whiteColor]];
5941 [self.content setDelegate:self];
5945 - (void) onSwitch:(id)sender {
5946 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5947 if (metadata == nil) {
5948 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5949 [Sections_ setObject:metadata forKey:basic_];
5952 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5955 - (void) setSection:(Section *)section editing:(BOOL)editing {
5956 if (editing != editing_) {
5958 [switch_ removeFromSuperview];
5960 [self addSubview:switch_];
5969 if (section == nil) {
5970 name_ = UCLocalize("ALL_PACKAGES");
5973 basic_ = [section name];
5974 section_ = [section localized];
5976 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5977 count_ = [NSString stringWithFormat:@"%zd", [section count]];
5980 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5983 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5984 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5986 [self.content setNeedsDisplay];
5989 - (void) setFrame:(CGRect)frame {
5990 [super setFrame:frame];
5992 CGRect rect([switch_ frame]);
5993 [switch_ setFrame:CGRectMake(frame.size.width - rect.size.width - 9, 9, rect.size.width, rect.size.height)];
5996 - (NSString *) accessibilityLabel {
6000 - (void) drawContentRect:(CGRect)rect {
6001 bool highlighted(self.highlighted && !editing_);
6003 [icon_ drawInRect:CGRectMake(7, 7, 32, 32)];
6005 if (highlighted && kCFCoreFoundationVersionNumber < 800)
6008 float width(rect.size.width);
6010 width -= 9 + [switch_ frame].size.width;
6014 [name_ drawAtPoint:CGPointMake(48, 12) forWidth:(width - 58) withFont:Font18_ lineBreakMode:NSLineBreakByTruncatingTail];
6016 CGSize size = [count_ sizeWithFont:Font14_];
6018 UISetColor(Folder_);
6020 [count_ drawAtPoint:CGPointMake(Retina(10 + (30 - size.width) / 2), 18) withFont:Font12Bold_];
6026 /* File Table {{{ */
6027 @interface FileTable : CyteViewController <
6028 UITableViewDataSource,
6031 _transient Database *database_;
6032 _H<Package> package_;
6034 _H<NSMutableArray> files_;
6035 _H<UITableView, 2> list_;
6038 - (id) initWithDatabase:(Database *)database;
6039 - (void) setPackage:(Package *)package;
6043 @implementation FileTable
6045 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6046 return files_ == nil ? 0 : [files_ count];
6049 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6053 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6054 static NSString *reuseIdentifier = @"Cell";
6056 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6058 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6059 [cell setFont:[UIFont systemFontOfSize:16]];
6061 [cell setText:[files_ objectAtIndex:indexPath.row]];
6062 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
6067 - (NSURL *) navigationURL {
6068 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
6072 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
6073 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6074 [list_ setRowHeight:24.0f];
6075 [(UITableView *) list_ setDataSource:self];
6076 [list_ setDelegate:self];
6077 [self setView:list_];
6080 - (void) viewDidLoad {
6081 [super viewDidLoad];
6083 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
6086 - (void) releaseSubviews {
6092 [super releaseSubviews];
6095 - (id) initWithDatabase:(Database *)database {
6096 if ((self = [super init]) != nil) {
6097 database_ = database;
6101 - (void) setPackage:(Package *)package {
6105 files_ = [NSMutableArray arrayWithCapacity:32];
6107 if (package != nil) {
6109 name_ = [package id];
6111 if (NSArray *files = [package files])
6112 [files_ addObjectsFromArray:files];
6114 if ([files_ count] != 0) {
6115 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
6116 [files_ removeObjectAtIndex:0];
6117 [files_ sortUsingSelector:@selector(compareByPath:)];
6119 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
6120 [stack addObject:@"/"];
6122 for (int i(0), e([files_ count]); i != e; ++i) {
6123 NSString *file = [files_ objectAtIndex:i];
6124 while (![file hasPrefix:[stack lastObject]])
6125 [stack removeLastObject];
6126 NSString *directory = [stack lastObject];
6127 [stack addObject:[file stringByAppendingString:@"/"]];
6128 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
6129 int(([stack count] - 2) * 3), "",
6130 [file substringFromIndex:[directory length]]
6139 - (void) reloadData {
6142 [self setPackage:[database_ packageWithName:name_]];
6147 /* Package Controller {{{ */
6148 @interface CYPackageController : CydiaWebViewController <
6149 UIActionSheetDelegate
6151 _transient Database *database_;
6152 _H<Package> package_;
6155 std::vector<std::pair<_H<NSString>, _H<NSString>>> buttons_;
6156 _H<UIActionSheet> sheet_;
6157 _H<UIBarButtonItem> button_;
6158 _H<NSArray> versions_;
6161 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer;
6165 @implementation CYPackageController
6167 - (NSURL *) navigationURL {
6168 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
6171 - (void) _clickButtonWithPackage:(Package *)package {
6172 [self.delegate installPackage:package];
6175 - (void) _clickButtonWithName:(NSString *)name {
6176 if ([name isEqualToString:@"CLEAR"])
6177 return [self.delegate clearPackage:package_];
6178 else if ([name isEqualToString:@"REMOVE"])
6179 return [self.delegate removePackage:package_];
6180 else if ([name isEqualToString:@"DOWNGRADE"]) {
6181 sheet_ = [[[UIActionSheet alloc]
6184 cancelButtonTitle:nil
6185 destructiveButtonTitle:nil
6186 otherButtonTitles:nil
6189 for (Package *version in (id) versions_)
6190 [sheet_ addButtonWithTitle:[version latest]];
6191 [sheet_ setContext:@"version"];
6193 [self.delegate showActionSheet:sheet_ fromItem:[[self navigationItem] rightBarButtonItem]];
6197 else if ([name isEqualToString:@"INSTALL"]);
6198 else if ([name isEqualToString:@"REINSTALL"]);
6199 else if ([name isEqualToString:@"UPGRADE"]);
6200 else _assert(false);
6202 [self.delegate installPackage:package_];
6205 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
6206 NSString *context([sheet context]);
6207 if (sheet_ == sheet)
6210 if ([context isEqualToString:@"modify"]) {
6211 if (button != [sheet cancelButtonIndex]) {
6213 [self performSelector:@selector(_clickButtonWithName:) withObject:buttons_[button].first afterDelay:0];
6215 [self _clickButtonWithName:buttons_[button].first];
6218 [sheet dismissWithClickedButtonIndex:button animated:YES];
6219 } else if ([context isEqualToString:@"version"]) {
6220 if (button != [sheet cancelButtonIndex]) {
6221 Package *version([versions_ objectAtIndex:button]);
6223 [self performSelector:@selector(_clickButtonWithPackage:) withObject:version afterDelay:0];
6225 [self _clickButtonWithPackage:version];
6228 [sheet dismissWithClickedButtonIndex:button animated:YES];
6232 - (bool) _allowJavaScriptPanel {
6237 - (void) _customButtonClicked {
6238 if (commercial_ && self.isLoading && [package_ uninstalled])
6239 return [self reloadURLWithCache:NO];
6241 size_t count(buttons_.size());
6246 [self _clickButtonWithName:buttons_[0].first];
6248 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
6249 for (const auto &button : buttons_)
6250 [buttons addObject:button.second];
6252 sheet_ = [[[UIActionSheet alloc]
6255 cancelButtonTitle:nil
6256 destructiveButtonTitle:nil
6257 otherButtonTitles:nil
6260 for (NSString *button in buttons)
6261 [sheet_ addButtonWithTitle:button];
6262 [sheet_ setContext:@"modify"];
6264 [self.delegate showActionSheet:sheet_ fromItem:[[self navigationItem] rightBarButtonItem]];
6268 - (void) applyLoadingTitle {
6269 // Don't show "Loading" as the title. Ever.
6272 - (UIBarButtonItem *) rightButton {
6277 - (void) setPageColor:(UIColor *)color {
6278 return [super setPageColor:nil];
6281 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer {
6282 if ((self = [super init]) != nil) {
6283 database_ = database;
6284 name_ = name == nil ? @"" : [NSString stringWithString:name];
6285 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]] withReferrer:referrer];
6289 - (void) reloadData {
6292 [sheet_ dismissWithClickedButtonIndex:[sheet_ cancelButtonIndex] animated:YES];
6295 package_ = [database_ packageWithName:name_];
6296 versions_ = [package_ downgrades];
6300 if (package_ != nil) {
6301 [(Package *) package_ parse];
6303 commercial_ = [package_ isCommercial];
6305 if ([package_ mode] != nil)
6306 buttons_.push_back(std::make_pair(@"CLEAR", UCLocalize("CLEAR")));
6307 if ([package_ source] == nil);
6308 else if ([package_ upgradableAndEssential:NO])
6309 buttons_.push_back(std::make_pair(@"UPGRADE", UCLocalize("UPGRADE")));
6310 else if ([package_ uninstalled])
6311 buttons_.push_back(std::make_pair(@"INSTALL", UCLocalize("INSTALL")));
6313 buttons_.push_back(std::make_pair(@"REINSTALL", UCLocalize("REINSTALL")));
6314 if (![package_ uninstalled])
6315 buttons_.push_back(std::make_pair(@"REMOVE", UCLocalize("REMOVE")));
6316 if ([versions_ count] != 0)
6317 buttons_.push_back(std::make_pair(@"DOWNGRADE", UCLocalize("DOWNGRADE")));
6321 switch (buttons_.size()) {
6322 case 0: title = nil; break;
6323 case 1: title = buttons_[0].second; break;
6324 default: title = UCLocalize("MODIFY"); break;
6327 button_ = [[[UIBarButtonItem alloc]
6329 style:UIBarButtonItemStylePlain
6331 action:@selector(customButtonClicked)
6335 - (bool) isLoading {
6336 return commercial_ ? [super isLoading] : false;
6342 /* Package List Controller {{{ */
6343 @interface PackageListController : CyteViewController <
6344 UITableViewDataSource,
6347 _transient Database *database_;
6349 _H<NSArray> packages_;
6350 _H<NSArray> sections_;
6351 _H<UITableView, 2> list_;
6353 _H<NSArray> thumbs_;
6354 std::vector<NSInteger> offset_;
6356 _H<NSString> title_;
6357 unsigned reloading_;
6360 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6361 - (void) resetCursor;
6364 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages;
6368 @implementation PackageListController
6370 - (NSURL *) referrerURL {
6371 return [self navigationURL];
6374 - (bool) isSummarized {
6378 - (bool) showsSections {
6382 - (void) deselectWithAnimation:(BOOL)animated {
6383 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6386 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6387 CGRect base = [[self view] bounds];
6388 base.size.height -= bounds.size.height;
6389 base.origin = [list_ frame].origin;
6391 [UIView beginAnimations:nil context:NULL];
6392 [UIView setAnimationBeginsFromCurrentState:YES];
6393 [UIView setAnimationCurve:curve];
6394 [UIView setAnimationDuration:duration];
6395 [list_ setFrame:base];
6396 [UIView commitAnimations];
6399 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6400 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6403 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6404 [self resizeForKeyboardBounds:bounds duration:0];
6407 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6408 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6409 *curve = UIViewAnimationCurveEaseInOut;
6411 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6413 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6416 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6419 - (void) keyboardWillShow:(NSNotification *)notification {
6422 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6423 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6425 NSTimeInterval duration;
6426 UIViewAnimationCurve curve;
6427 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6429 CGRect kbframe = CGRectMake(Retina(center.x - bounds.size.width / 2), Retina(center.y - bounds.size.height / 2), bounds.size.width, bounds.size.height);
6430 UIViewController *base([self rootViewController]);
6431 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6432 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6434 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6435 intersection.size.height += CYStatusBarHeight();
6437 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6440 - (void) keyboardWillHide:(NSNotification *)notification {
6441 NSTimeInterval duration;
6442 UIViewAnimationCurve curve;
6443 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6445 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6448 - (void) viewWillAppear:(BOOL)animated {
6449 [super viewWillAppear:animated];
6451 [self resizeForKeyboardBounds:CGRectZero];
6452 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6453 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6456 - (void) viewWillDisappear:(BOOL)animated {
6457 [super viewWillDisappear:animated];
6459 [self resizeForKeyboardBounds:CGRectZero];
6460 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6461 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6464 - (void) viewDidAppear:(BOOL)animated {
6465 [super viewDidAppear:animated];
6466 [self deselectWithAnimation:animated];
6469 - (void) didSelectPackage:(Package *)package {
6470 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[[self referrerURL] absoluteString]] autorelease]);
6471 [view setDelegate:self.delegate];
6472 [[self navigationController] pushViewController:view animated:YES];
6475 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6476 NSInteger count([sections_ count]);
6477 return count == 0 ? 1 : count;
6480 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6481 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6483 return [[sections_ objectAtIndex:section] name];
6486 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6487 if ([sections_ count] == 0)
6489 return [[sections_ objectAtIndex:section] count];
6492 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6493 @synchronized (database_) {
6494 if ([database_ era] != era_)
6497 Section *section([sections_ objectAtIndex:[path section]]);
6498 NSInteger row([path row]);
6499 Package *package([packages_ objectAtIndex:([section row] + row)]);
6500 return [[package retain] autorelease];
6503 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6504 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6506 cell = [[[PackageCell alloc] init] autorelease];
6508 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6509 [cell setPackage:package asSummary:[self isSummarized]];
6513 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6514 Package *package([self packageAtIndexPath:path]);
6515 package = [database_ packageWithName:[package id]];
6516 [self didSelectPackage:package];
6519 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6523 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6524 return offset_[index];
6527 - (void) updateHeight {
6528 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6531 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6532 if ((self = [super init]) != nil) {
6533 database_ = database;
6534 title_ = [title copy];
6535 [[self navigationItem] setTitle:title_];
6540 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
6541 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
6542 [self setView:view];
6544 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6545 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6546 [view addSubview:list_];
6548 // XXX: is 20 the most optimal number here?
6549 [list_ setSectionIndexMinimumDisplayRowCount:20];
6551 [(UITableView *) list_ setDataSource:self];
6552 [list_ setDelegate:self];
6554 [self updateHeight];
6557 - (void) releaseSubviews {
6566 [super releaseSubviews];
6569 - (bool) shouldYield {
6573 - (bool) shouldBlock {
6577 - (NSMutableArray *) _reloadPackages {
6578 @synchronized (database_) {
6579 era_ = [database_ era];
6580 NSArray *packages([database_ packages]);
6582 return [NSMutableArray arrayWithArray:packages];
6585 - (void) _reloadData {
6586 if (reloading_ != 0) {
6591 NSMutableArray *packages;
6594 if ([self shouldYield]) {
6598 if (![self shouldBlock])
6601 hud = [self.delegate addProgressHUD];
6602 [hud setText:UCLocalize("LOADING")];
6606 packages = [self yieldToSelector:@selector(_reloadPackages)];
6609 [self.delegate removeProgressHUD:hud];
6610 } while (reloading_ == 2);
6612 packages = [self _reloadPackages];
6615 @synchronized (database_) {
6616 if (era_ != [database_ era])
6623 packages_ = packages;
6625 if ([self showsSections])
6626 sections_ = [self sectionsForPackages:packages];
6628 Section *section([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6629 [section setCount:[packages_ count]];
6630 sections_ = [NSArray arrayWithObject:section];
6633 [self updateHeight];
6635 _profile(PackageTable$reloadData$List)
6636 [(UITableView *) list_ setDataSource:self];
6644 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
6645 Section *prefix([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6646 size_t end([packages count]);
6648 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
6649 Section *section(prefix);
6651 thumbs_ = CollationThumbs_;
6652 offset_ = CollationOffset_;
6655 size_t offsets([CollationStarts_ count]);
6657 NSString *start([CollationStarts_ objectAtIndex:offset]);
6658 size_t length([start length]);
6660 for (size_t index(0); index != end; ++index) {
6662 Package *package([packages objectAtIndex:index]);
6663 NSString *name(PackageName(package, @selector(cyname)));
6665 //while ([start compare:name options:NSNumericSearch range:NSMakeRange(0, length) locale:CollationLocale_] != NSOrderedDescending) {
6666 while (StringNameCompare(start, name, length) != kCFCompareGreaterThan) {
6667 NSString *title([CollationTitles_ objectAtIndex:offset]);
6668 section = [[[Section alloc] initWithName:title row:index localize:NO] autorelease];
6669 [sections addObject:section];
6671 start = ++offset == offsets ? nil : [CollationStarts_ objectAtIndex:offset];
6674 length = [start length];
6678 [section addToCount];
6681 for (; offset != offsets; ++offset) {
6682 NSString *title([CollationTitles_ objectAtIndex:offset]);
6683 Section *section([[[Section alloc] initWithName:title row:end localize:NO] autorelease]);
6684 [sections addObject:section];
6687 if ([prefix count] != 0) {
6688 Section *suffix([sections lastObject]);
6689 [prefix setName:[suffix name]];
6690 [suffix setName:nil];
6691 [sections insertObject:prefix atIndex:(offsets - 1)];
6697 - (void) reloadData {
6700 if ([self shouldYield])
6701 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6706 - (void) resetCursor {
6707 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6710 - (void) clearData {
6711 [self updateHeight];
6713 [list_ setDataSource:nil];
6721 /* Filtered Package List Controller {{{ */
6722 typedef Function<bool, Package *> PackageFilter;
6723 typedef Function<void, NSMutableArray *> PackageSorter;
6724 @interface FilteredPackageListController : PackageListController {
6725 PackageFilter filter_;
6726 PackageSorter sorter_;
6729 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter;
6731 - (void) setFilter:(PackageFilter)filter;
6732 - (void) setSorter:(PackageSorter)sorter;
6736 @implementation FilteredPackageListController
6738 - (void) setFilter:(PackageFilter)filter {
6739 @synchronized (self) {
6743 - (void) setSorter:(PackageSorter)sorter {
6744 @synchronized (self) {
6748 - (NSMutableArray *) _reloadPackages {
6749 @synchronized (database_) {
6750 era_ = [database_ era];
6752 NSArray *packages([database_ packages]);
6753 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6755 PackageFilter filter;
6756 PackageSorter sorter;
6758 @synchronized (self) {
6763 _profile(PackageTable$reloadData$Filter)
6764 for (Package *package in packages)
6765 if (filter(package))
6766 [filtered addObject:package];
6774 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter {
6775 if ((self = [super initWithDatabase:database title:title]) != nil) {
6776 [self setFilter:filter];
6783 /* Home Controller {{{ */
6784 @interface HomeController : CydiaWebViewController {
6785 CFRunLoopRef runloop_;
6786 SCNetworkReachabilityRef reachability_;
6791 @implementation HomeController
6793 static void HomeControllerReachabilityCallback(SCNetworkReachabilityRef reachability, SCNetworkReachabilityFlags flags, void *info) {
6794 [(HomeController *) info dispatchEvent:@"CydiaReachabilityCallback"];
6798 if ((self = [super init]) != nil) {
6799 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6802 reachability_ = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "cydia.saurik.com");
6803 if (reachability_ != NULL) {
6804 SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
6805 SCNetworkReachabilitySetCallback(reachability_, HomeControllerReachabilityCallback, &context);
6807 CFRunLoopRef runloop(CFRunLoopGetCurrent());
6808 if (SCNetworkReachabilityScheduleWithRunLoop(reachability_, runloop, kCFRunLoopDefaultMode))
6815 if (reachability_ != NULL && runloop_ != NULL)
6816 SCNetworkReachabilityUnscheduleFromRunLoop(reachability_, runloop_, kCFRunLoopDefaultMode);
6820 - (NSURL *) navigationURL {
6821 return [NSURL URLWithString:@"cydia://home"];
6824 - (void) aboutButtonClicked {
6825 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6827 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6828 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6829 [alert setCancelButtonIndex:0];
6832 @"Copyright \u00a9 2008-2015\n"
6835 "Jay Freeman (saurik)\n"
6836 "saurik@saurik.com\n"
6837 "http://www.saurik.com/"
6843 - (UIBarButtonItem *) leftButton {
6844 return [[[UIBarButtonItem alloc]
6845 initWithTitle:UCLocalize("ABOUT")
6846 style:UIBarButtonItemStylePlain
6848 action:@selector(aboutButtonClicked)
6855 /* Cydia Tab Bar Controller {{{ */
6856 @interface CydiaTabBarController : CyteTabBarController <
6857 UITabBarControllerDelegate,
6860 _transient Database *database_;
6862 _H<UIActivityIndicatorView> indicator_;
6865 // XXX: ok, "updatedelegate_"?...
6866 _transient NSObject<CydiaDelegate> *updatedelegate_;
6869 - (void) beginUpdate;
6874 @implementation CydiaTabBarController
6876 - (id) initWithDatabase:(Database *)database {
6877 if ((self = [super init]) != nil) {
6878 database_ = database;
6879 [self setDelegate:self];
6881 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteTiny] autorelease];
6882 [indicator_ setOrigin:CGPointMake(kCFCoreFoundationVersionNumber >= 800 ? 2 : 4, 2)];
6884 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6888 - (void) beginUpdate {
6892 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
6893 UITabBarItem *item([controller tabBarItem]);
6895 [item setBadgeValue:@""];
6896 UIView *badge(MSHookIvar<UIView *>([item view], "_badge"));
6898 [indicator_ startAnimating];
6899 [badge addSubview:indicator_];
6901 [updatedelegate_ retainNetworkActivityIndicator];
6905 detachNewThreadSelector:@selector(performUpdate)
6911 - (void) performUpdate {
6912 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
6914 SourceStatus status(self, database_);
6915 [database_ updateWithStatus:status];
6918 performSelectorOnMainThread:@selector(completeUpdate)
6926 - (void) stopUpdateWithSelector:(SEL)selector {
6928 [updatedelegate_ releaseNetworkActivityIndicator];
6930 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
6931 [[controller tabBarItem] setBadgeValue:nil];
6933 [indicator_ removeFromSuperview];
6934 [indicator_ stopAnimating];
6936 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6939 - (void) completeUpdate {
6942 [self stopUpdateWithSelector:@selector(reloadData)];
6945 - (void) cancelUpdate {
6946 [self stopUpdateWithSelector:@selector(updateDataAndLoad)];
6949 - (void) cancelPressed {
6950 [self cancelUpdate];
6957 - (bool) isSourceCancelled {
6961 - (void) startSourceFetch:(NSString *)uri {
6964 - (void) stopSourceFetch:(NSString *)uri {
6967 - (void) setUpdateDelegate:(id)delegate {
6968 updatedelegate_ = delegate;
6974 /* Cydia:// Protocol {{{ */
6975 @interface CydiaURLProtocol : NSURLProtocol {
6980 @implementation CydiaURLProtocol
6982 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6983 NSURL *url([request URL]);
6987 NSString *scheme([[url scheme] lowercaseString]);
6988 if (scheme != nil && [scheme isEqualToString:@"cydia"])
6990 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
6996 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7000 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7001 id<NSURLProtocolClient> client([self client]);
7003 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7005 NSData *data(UIImagePNGRepresentation(icon));
7007 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7008 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7009 [client URLProtocol:self didLoadData:data];
7010 [client URLProtocolDidFinishLoading:self];
7014 - (void) startLoading {
7015 id<NSURLProtocolClient> client([self client]);
7016 NSURLRequest *request([self request]);
7018 NSURL *url([request URL]);
7019 NSString *href([url absoluteString]);
7020 NSString *scheme([[url scheme] lowercaseString]);
7024 if ([scheme isEqualToString:@"cydia"])
7025 path = [href substringFromIndex:8];
7026 else if ([scheme isEqualToString:@"about"])
7027 path = [href substringFromIndex:12];
7028 else _assert(false);
7030 NSRange slash([path rangeOfString:@"/"]);
7033 if (slash.location == NSNotFound) {
7037 command = [path substringToIndex:slash.location];
7038 path = [path substringFromIndex:(slash.location + 1)];
7041 Database *database([Database sharedInstance]);
7044 else if ([command isEqualToString:@"application-icon"]) {
7047 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7051 if (icon == nil && $SBSCopyIconImagePNGDataForDisplayIdentifier != NULL) {
7052 NSData *data([$SBSCopyIconImagePNGDataForDisplayIdentifier(path) autorelease]);
7053 icon = [UIImage imageWithData:data];
7057 if (NSString *file = SBSCopyIconImagePathForDisplayIdentifier(path))
7058 icon = [UIImage imageAtPath:file];
7061 icon = [UIImage imageNamed:@"unknown.png"];
7063 [self _returnPNGWithImage:icon forRequest:request];
7064 } else if ([command isEqualToString:@"package-icon"]) {
7067 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7068 Package *package([database packageWithName:path]);
7072 UIImage *icon([package icon]);
7073 [self _returnPNGWithImage:icon forRequest:request];
7074 } else if ([command isEqualToString:@"uikit-image"]) {
7077 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7078 UIImage *icon(_UIImageWithName(path));
7079 [self _returnPNGWithImage:icon forRequest:request];
7080 } else if ([command isEqualToString:@"section-icon"]) {
7083 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7084 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7086 icon = [UIImage imageNamed:@"unknown.png"];
7087 [self _returnPNGWithImage:icon forRequest:request];
7089 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7093 - (void) stopLoading {
7099 /* Section Controller {{{ */
7100 @interface SectionController : FilteredPackageListController {
7102 _H<NSString> section_;
7105 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section;
7109 @implementation SectionController
7111 - (NSURL *) referrerURL {
7112 NSString *name(section_);
7113 name = name ?: @"*";
7114 NSString *key(key_);
7116 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sections/%@/%@", UI_, [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7119 - (NSURL *) navigationURL {
7120 NSString *name(section_);
7121 name = name ?: @"*";
7122 NSString *key(key_);
7124 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@/%@", [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7127 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section {
7130 title = UCLocalize("ALL_PACKAGES");
7131 else if (![section isEqual:@""])
7132 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(section) value:nil table:@"Sections"];
7134 title = UCLocalize("NO_SECTION");
7136 if ((self = [super initWithDatabase:database title:title]) != nil) {
7137 key_ = [source key];
7142 - (void) reloadData {
7143 Source *source([database_ sourceWithKey:key_]);
7144 _H<NSString> name(section_);
7146 [self setFilter:[=](Package *package) {
7147 NSString *section([package section]);
7151 section == nil && [name length] == 0 ||
7152 [name isEqualToString:section]
7155 [package source] == source
7156 ) && [package visible];
7164 /* Sections Controller {{{ */
7165 @interface SectionsController : CyteViewController <
7166 UITableViewDataSource,
7169 _transient Database *database_;
7171 _H<NSMutableArray> sections_;
7172 _H<NSMutableArray> filtered_;
7173 _H<UITableView, 2> list_;
7176 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7177 - (void) editButtonClicked;
7181 @implementation SectionsController
7183 - (NSURL *) navigationURL {
7184 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
7187 - (Source *) source {
7190 return [database_ sourceWithKey:key_];
7193 - (void) updateNavigationItem {
7194 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7195 if ([sections_ count] == 0) {
7196 [[self navigationItem] setRightBarButtonItem:nil];
7198 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7199 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7201 action:@selector(editButtonClicked)
7202 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7206 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7207 [super setEditing:editing animated:animated];
7212 [self.delegate updateData];
7214 [self updateNavigationItem];
7217 - (void) viewDidAppear:(BOOL)animated {
7218 [super viewDidAppear:animated];
7219 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7222 - (void) viewWillDisappear:(BOOL)animated {
7223 [super viewWillDisappear:animated];
7224 [self setEditing:NO];
7227 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7228 Section *section = nil;
7229 int index = [indexPath row];
7230 if (![self isEditing]) {
7233 section = [filtered_ objectAtIndex:index];
7235 section = [sections_ objectAtIndex:index];
7240 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7241 if ([self isEditing])
7242 return [sections_ count];
7244 return [filtered_ count] + 1;
7247 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7251 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7252 static NSString *reuseIdentifier = @"SectionCell";
7254 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7256 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7258 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7263 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7264 if ([self isEditing])
7267 Section *section = [self sectionAtIndexPath:indexPath];
7269 SectionController *controller = [[[SectionController alloc]
7270 initWithDatabase:database_
7271 source:[self source]
7272 section:[section name]
7274 [controller setDelegate:self.delegate];
7276 [[self navigationController] pushViewController:controller animated:YES];
7280 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
7281 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7282 [list_ setRowHeight:46];
7283 [(UITableView *) list_ setDataSource:self];
7284 [list_ setDelegate:self];
7285 [self setView:list_];
7288 - (void) viewDidLoad {
7289 [super viewDidLoad];
7291 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7294 - (void) releaseSubviews {
7300 [super releaseSubviews];
7303 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7304 if ((self = [super init]) != nil) {
7305 database_ = database;
7306 key_ = [source key];
7310 - (void) reloadData {
7313 NSArray *packages = [database_ packages];
7315 sections_ = [NSMutableArray arrayWithCapacity:16];
7316 filtered_ = [NSMutableArray arrayWithCapacity:16];
7318 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7320 Source *source([self source]);
7323 for (Package *package in packages) {
7324 if (source != nil && [package source] != source)
7327 NSString *name([package section]);
7328 NSString *key(name == nil ? @"" : name);
7332 _profile(SectionsView$reloadData$Section)
7333 section = [sections objectForKey:key];
7334 if (section == nil) {
7335 _profile(SectionsView$reloadData$Section$Allocate)
7336 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7337 [sections setObject:section forKey:key];
7342 [section addToCount];
7344 _profile(SectionsView$reloadData$Filter)
7345 if (![package visible])
7353 [sections_ addObjectsFromArray:[sections allValues]];
7355 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7357 for (Section *section in (id) sections_) {
7358 size_t count([section row]);
7362 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7363 [section setCount:count];
7364 [filtered_ addObject:section];
7367 [self updateNavigationItem];
7372 - (void) editButtonClicked {
7373 [self setEditing:![self isEditing] animated:YES];
7379 /* Changes Controller {{{ */
7380 @interface ChangesController : FilteredPackageListController {
7384 - (id) initWithDatabase:(Database *)database;
7388 @implementation ChangesController
7390 - (NSURL *) referrerURL {
7391 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/changes/", UI_]];
7394 - (NSURL *) navigationURL {
7395 return [NSURL URLWithString:@"cydia://changes"];
7398 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7399 @synchronized (database_) {
7400 if ([database_ era] != era_)
7403 NSUInteger sectionIndex([path section]);
7404 if (sectionIndex >= [sections_ count])
7406 Section *section([sections_ objectAtIndex:sectionIndex]);
7407 NSInteger row([path row]);
7408 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7411 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7412 NSString *context([alert context]);
7414 if ([context isEqualToString:@"norefresh"])
7415 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7418 - (void) setLeftBarButtonItem {
7419 if ([self.delegate updating])
7420 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7421 initWithTitle:UCLocalize("CANCEL")
7422 style:UIBarButtonItemStyleDone
7424 action:@selector(cancelButtonClicked)
7425 ] autorelease] animated:YES];
7427 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7428 initWithTitle:UCLocalize("REFRESH")
7429 style:UIBarButtonItemStylePlain
7431 action:@selector(refreshButtonClicked)
7432 ] autorelease] animated:YES];
7435 - (void) refreshButtonClicked {
7436 if ([self.delegate requestUpdate])
7437 [self setLeftBarButtonItem];
7440 - (void) cancelButtonClicked {
7441 [self.delegate cancelUpdate];
7444 - (void) upgradeButtonClicked {
7445 [self.delegate distUpgrade];
7446 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7449 - (bool) shouldYield {
7453 - (bool) shouldBlock {
7457 - (void) useFilter {
7458 @synchronized (self) {
7459 [self setFilter:[](Package *package) {
7460 return [package upgradableAndEssential:YES] || [package visible];
7463 [self setSorter:[](NSMutableArray *packages) {
7464 [packages radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7468 - (id) initWithDatabase:(Database *)database {
7469 if ((self = [super initWithDatabase:database title:UCLocalize("CHANGES")]) != nil) {
7474 - (void) viewDidLoad {
7475 [super viewDidLoad];
7476 [self setLeftBarButtonItem];
7479 - (void) viewWillAppear:(BOOL)animated {
7480 [super viewWillAppear:animated];
7481 [self setLeftBarButtonItem];
7484 - (void) reloadData {
7485 [self setLeftBarButtonItem];
7489 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
7490 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
7492 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7493 Section *ignored = nil;
7494 Section *section = nil;
7498 bool unseens = false;
7500 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7502 for (size_t offset = 0, count = [packages count]; offset != count; ++offset) {
7503 Package *package = [packages objectAtIndex:offset];
7505 BOOL uae = [package upgradableAndEssential:YES];
7509 time_t seen([package seen]);
7511 if (section == nil || last != seen) {
7515 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7518 _profile(ChangesController$reloadData$Allocate)
7519 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7520 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7521 [sections addObject:section];
7525 [section addToCount];
7526 } else if ([package ignored]) {
7527 if (ignored == nil) {
7528 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7530 [ignored addToCount];
7533 [upgradable addToCount];
7538 CFRelease(formatter);
7541 Section *last = [sections lastObject];
7542 size_t count = [last count];
7543 [packages removeObjectsInRange:NSMakeRange([packages count] - count, count)];
7544 [sections removeLastObject];
7547 if ([ignored count] != 0)
7548 [sections insertObject:ignored atIndex:0];
7550 [sections insertObject:upgradable atIndex:0];
7554 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7555 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7556 style:UIBarButtonItemStylePlain
7558 action:@selector(upgradeButtonClicked)
7559 ] autorelease]) animated:YES];
7566 /* Search Controller {{{ */
7567 @interface SearchController : FilteredPackageListController <
7570 _H<UISearchBar, 1> search_;
7575 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7576 - (void) reloadData;
7580 @implementation SearchController
7582 - (NSURL *) referrerURL {
7583 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/search?q=%@", UI_, [([search_ text] ?: @"") stringByAddingPercentEscapesIncludingReserved]]];
7586 - (NSURL *) navigationURL {
7587 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7588 return [NSURL URLWithString:@"cydia://search"];
7590 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [[search_ text] stringByAddingPercentEscapesIncludingReserved]]];
7593 - (NSArray *) termsForQuery:(NSString *)query {
7594 NSMutableArray *terms([NSMutableArray arrayWithCapacity:2]);
7595 for (NSString *component in [query componentsSeparatedByString:@" "])
7596 if ([component length] != 0)
7597 [terms addObject:component];
7602 - (void) useSearch {
7603 _H<NSArray> query([self termsForQuery:[search_ text]]);
7606 @synchronized (self) {
7607 [self setFilter:[=](Package *package) {
7608 if (![package unfiltered])
7610 if (![package matches:query])
7615 [self setSorter:[](NSMutableArray *packages) {
7616 [packages radixSortUsingSelector:@selector(rank)];
7624 - (void) usePrefix:(NSString *)prefix {
7625 _H<NSString> query(prefix);
7628 @synchronized (self) {
7629 [self setFilter:[=](Package *package) {
7630 if ([query length] == 0)
7632 if (![package unfiltered])
7634 if ([[package name] compare:query options:MatchCompareOptions_ range:NSMakeRange(0, [query length])] != NSOrderedSame)
7639 [self setSorter:nullptr];
7645 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7647 [self usePrefix:[search_ text]];
7650 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7651 [search_ resignFirstResponder];
7655 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7656 [search_ setText:@""];
7657 [self searchBarButtonClicked:searchBar];
7660 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7661 [self searchBarButtonClicked:searchBar];
7664 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7665 [self usePrefix:text];
7668 - (bool) shouldYield {
7672 - (bool) shouldBlock {
7676 - (bool) isSummarized {
7680 - (bool) showsSections {
7684 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7685 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH")])) {
7686 search_ = [[[UISearchBar alloc] init] autorelease];
7687 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7688 [search_ setDelegate:self];
7690 UITextField *textField;
7691 if ([search_ respondsToSelector:@selector(searchField)])
7692 textField = [search_ searchField];
7694 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7696 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7697 [textField setEnablesReturnKeyAutomatically:NO];
7698 [[self navigationItem] setTitleView:textField];
7701 [search_ setText:query];
7706 - (void) viewDidAppear:(BOOL)animated {
7707 [super viewDidAppear:animated];
7709 if (!searchloaded_) {
7710 searchloaded_ = YES;
7711 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7712 [search_ layoutSubviews];
7715 if ([self isSummarized])
7716 [search_ becomeFirstResponder];
7719 - (void) reloadData {
7724 - (void) didSelectPackage:(Package *)package {
7725 [search_ resignFirstResponder];
7726 [super didSelectPackage:package];
7731 /* Package Settings Controller {{{ */
7732 @interface PackageSettingsController : CyteViewController <
7733 UITableViewDataSource,
7736 _transient Database *database_;
7738 _H<Package> package_;
7739 _H<UITableView, 2> table_;
7740 _H<UISwitch> subscribedSwitch_;
7741 _H<UISwitch> ignoredSwitch_;
7742 _H<UITableViewCell> subscribedCell_;
7743 _H<UITableViewCell> ignoredCell_;
7746 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7750 @implementation PackageSettingsController
7752 - (NSURL *) navigationURL {
7753 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
7756 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7757 if (package_ == nil)
7760 if ([package_ installed] == nil)
7766 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7767 if (package_ == nil)
7770 // both sections contain just one item right now.
7774 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7778 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7780 return UCLocalize("SHOW_ALL_CHANGES_EX");
7782 return UCLocalize("IGNORE_UPGRADES_EX");
7785 - (void) onSubscribed:(id)control {
7786 bool value([control isOn]);
7787 if (package_ == nil)
7789 if ([package_ setSubscribed:value])
7790 [self.delegate updateData];
7793 - (void) _updateIgnored {
7794 const char *package([name_ UTF8String]);
7795 bool on([ignoredSwitch_ isOn]);
7797 FILE *dpkg(popen("/usr/libexec/cydia/cydo --set-selections", "w"));
7798 fwrite(package, strlen(package), 1, dpkg);
7801 fwrite(" hold\n", 6, 1, dpkg);
7803 fwrite(" install\n", 9, 1, dpkg);
7808 - (void) onIgnored:(id)control {
7809 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7810 [invocation setTarget:self];
7811 [invocation setSelector:@selector(_updateIgnored)];
7813 [self.delegate reloadDataWithInvocation:invocation];
7816 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7817 if (package_ == nil)
7820 switch ([indexPath section]) {
7821 case 0: return subscribedCell_;
7822 case 1: return ignoredCell_;
7831 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
7832 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
7833 [self setView:view];
7835 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7836 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7837 [(UITableView *) table_ setDataSource:self];
7838 [table_ setDelegate:self];
7839 [view addSubview:table_];
7841 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7842 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7843 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7845 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7846 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7847 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7849 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7850 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7851 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7852 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7854 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7855 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7856 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7857 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7860 - (void) viewDidLoad {
7861 [super viewDidLoad];
7863 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7866 - (void) releaseSubviews {
7868 subscribedCell_ = nil;
7870 ignoredSwitch_ = nil;
7871 subscribedSwitch_ = nil;
7873 [super releaseSubviews];
7876 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7877 if ((self = [super init]) != nil) {
7878 database_ = database;
7883 - (void) reloadData {
7886 package_ = [database_ packageWithName:name_];
7888 if (package_ != nil) {
7889 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7890 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7891 } // XXX: what now, G?
7893 [table_ reloadData];
7899 /* Installed Controller {{{ */
7900 @interface InstalledController : FilteredPackageListController {
7904 - (id) initWithDatabase:(Database *)database;
7905 - (void) queueStatusDidChange;
7909 @implementation InstalledController
7911 - (NSURL *) referrerURL {
7912 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/installed/", UI_]];
7915 - (NSURL *) navigationURL {
7916 return [NSURL URLWithString:@"cydia://installed"];
7919 - (void) useRecent {
7922 @synchronized (self) {
7923 [self setFilter:[](Package *package) {
7924 return ![package uninstalled] && package->role_ < 7;
7927 [self setSorter:[](NSMutableArray *packages) {
7928 [packages radixSortUsingSelector:@selector(recent)];
7932 - (void) useFilter:(UISegmentedControl *)segmented {
7933 NSInteger selected([segmented selectedSegmentIndex]);
7935 return [self useRecent];
7936 bool simple(selected == 0);
7939 @synchronized (self) {
7940 [self setFilter:[=](Package *package) {
7941 return ![package uninstalled] && package->role_ <= (simple ? 1 : 3);
7944 [self setSorter:nullptr];
7947 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
7949 return [super sectionsForPackages:packages];
7951 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterLongStyle, kCFDateFormatterNoStyle));
7953 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
7954 Section *section(nil);
7957 for (size_t offset(0), count([packages count]); offset != count; ++offset) {
7958 Package *package([packages objectAtIndex:offset]);
7960 time_t upgraded([package upgraded]);
7961 if (upgraded < 1168364520)
7964 upgraded -= upgraded % (60 * 60 * 24);
7966 if (section == nil || upgraded != last) {
7971 continue; // XXX: name = UCLocalize("...");
7973 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:upgraded]);
7977 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7978 [sections addObject:section];
7981 [section addToCount];
7984 CFRelease(formatter);
7988 - (id) initWithDatabase:(Database *)database {
7989 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED")]) != nil) {
7990 UISegmentedControl *segmented([[[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:UCLocalize("USER"), UCLocalize("EXPERT"), UCLocalize("RECENT"), nil]] autorelease]);
7991 [segmented setSelectedSegmentIndex:0];
7992 [segmented setSegmentedControlStyle:UISegmentedControlStyleBar];
7993 [[self navigationItem] setTitleView:segmented];
7995 [segmented addTarget:self action:@selector(modeChanged:) forEvents:UIControlEventValueChanged];
7996 [self useFilter:segmented];
7998 [self queueStatusDidChange];
8003 - (void) queueButtonClicked {
8004 [self.delegate queue];
8008 - (void) queueStatusDidChange {
8011 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8012 initWithTitle:UCLocalize("QUEUE")
8013 style:UIBarButtonItemStyleDone
8015 action:@selector(queueButtonClicked)
8018 [[self navigationItem] setRightBarButtonItem:nil];
8023 - (void) modeChanged:(UISegmentedControl *)segmented {
8024 [self useFilter:segmented];
8031 /* Source Cell {{{ */
8032 @interface SourceCell : CyteTableViewCell <
8033 CyteTableViewCellDelegate,
8036 _H<Source, 1> source_;
8039 _H<NSString> origin_;
8040 _H<NSString> label_;
8041 _H<UIActivityIndicatorView> indicator_;
8044 - (void) setSource:(Source *)source;
8045 - (void) setFetch:(NSNumber *)fetch;
8049 @implementation SourceCell
8051 - (void) _setImage:(NSArray *)data {
8052 if ([url_ isEqual:[data objectAtIndex:0]]) {
8053 icon_ = [data objectAtIndex:1];
8054 [self.content setNeedsDisplay];
8058 - (void) _setSource:(NSURL *) url {
8059 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8061 if (NSData *data = [NSURLConnection
8062 sendSynchronousRequest:[NSURLRequest
8064 cachePolicy:NSURLRequestUseProtocolCachePolicy
8068 returningResponse:NULL
8071 if (UIImage *image = [UIImage imageWithData:data])
8072 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
8077 - (void) setSource:(Source *)source {
8079 [source_ setDelegate:self];
8081 [self setFetch:[NSNumber numberWithBool:[source_ fetch]]];
8083 icon_ = [UIImage imageNamed:@"unknown.png"];
8085 origin_ = [source name];
8086 label_ = [source rooturi];
8088 [self.content setNeedsDisplay];
8090 url_ = [source iconURL];
8091 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
8094 - (void) setAllSource {
8096 [indicator_ stopAnimating];
8098 icon_ = [UIImage imageNamed:@"folder.png"];
8099 origin_ = UCLocalize("ALL_SOURCES");
8100 label_ = UCLocalize("ALL_SOURCES_EX");
8101 [self.content setNeedsDisplay];
8104 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8105 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8106 UIView *content([self contentView]);
8107 CGRect bounds([content bounds]);
8109 self.content = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8110 [self.content setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8111 [self.content setBackgroundColor:[UIColor whiteColor]];
8112 [content addSubview:self.content];
8114 [self.content setDelegate:self];
8115 [self.content setOpaque:YES];
8117 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGraySmall] autorelease];
8118 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin];// | UIViewAutoresizingFlexibleBottomMargin];
8119 [content addSubview:indicator_];
8121 [[self.content layer] setContentsGravity:kCAGravityTopLeft];
8125 - (void) layoutSubviews {
8126 [super layoutSubviews];
8128 UIView *content([self contentView]);
8129 CGRect bounds([content bounds]);
8131 CGRect frame([indicator_ frame]);
8132 frame.origin.x = bounds.size.width - frame.size.width;
8133 frame.origin.y = Retina((bounds.size.height - frame.size.height) / 2);
8135 if (kCFCoreFoundationVersionNumber < 800)
8136 frame.origin.x -= 8;
8137 [indicator_ setFrame:frame];
8140 - (NSString *) accessibilityLabel {
8144 - (void) drawContentRect:(CGRect)rect {
8145 bool highlighted(self.highlighted);
8146 float width(rect.size.width);
8150 rect.size = [(UIImage *) icon_ size];
8152 while (rect.size.width > 32 || rect.size.height > 32) {
8153 rect.size.width /= 2;
8154 rect.size.height /= 2;
8157 rect.origin.x = 26 - rect.size.width / 2;
8158 rect.origin.y = 26 - rect.size.height / 2;
8160 [icon_ drawInRect:Retina(rect)];
8163 if (highlighted && kCFCoreFoundationVersionNumber < 800)
8168 [origin_ drawAtPoint:CGPointMake(52, 8) forWidth:(width - 49) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
8172 [label_ drawAtPoint:CGPointMake(52, 29) forWidth:(width - 49) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
8175 - (void) setFetch:(NSNumber *)fetch {
8176 if ([fetch boolValue])
8177 [indicator_ startAnimating];
8179 [indicator_ stopAnimating];
8184 /* Sources Controller {{{ */
8185 @interface SourcesController : CyteViewController <
8186 UITableViewDataSource,
8189 _transient Database *database_;
8192 _H<UITableView, 2> list_;
8193 _H<NSMutableArray> sources_;
8197 _H<UIProgressHUD> hud_;
8200 NSURLConnection *trivial_bz2_;
8201 NSURLConnection *trivial_gz_;
8206 - (id) initWithDatabase:(Database *)database;
8207 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated;
8211 @implementation SourcesController
8213 - (void) _releaseConnection:(NSURLConnection *)connection {
8214 if (connection != nil) {
8215 [connection cancel];
8216 //[connection setDelegate:nil];
8217 [connection release];
8222 [self _releaseConnection:trivial_gz_];
8223 [self _releaseConnection:trivial_bz2_];
8228 - (NSURL *) navigationURL {
8229 return [NSURL URLWithString:@"cydia://sources"];
8232 - (void) viewDidAppear:(BOOL)animated {
8233 [super viewDidAppear:animated];
8234 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8237 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8241 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8243 return UCLocalize("INDIVIDUAL_SOURCES");
8247 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8250 case 1: return [sources_ count];
8255 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8256 @synchronized (database_) {
8257 if ([database_ era] != era_)
8259 if ([indexPath section] != 1)
8261 NSUInteger index([indexPath row]);
8262 if (index >= [sources_ count])
8264 return [sources_ objectAtIndex:index];
8267 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8268 static NSString *cellIdentifier = @"SourceCell";
8270 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8271 if (cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8272 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8274 Source *source([self sourceAtIndexPath:indexPath]);
8276 [cell setAllSource];
8278 [cell setSource:source];
8283 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8284 SectionsController *controller([[[SectionsController alloc]
8285 initWithDatabase:database_
8286 source:[self sourceAtIndexPath:indexPath]
8289 [controller setDelegate:self.delegate];
8290 [[self navigationController] pushViewController:controller animated:YES];
8293 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8294 if ([indexPath section] != 1)
8296 Source *source = [self sourceAtIndexPath:indexPath];
8297 return [source record] != nil;
8300 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8301 _assert([indexPath section] == 1);
8302 if (editingStyle == UITableViewCellEditingStyleDelete) {
8303 Source *source = [self sourceAtIndexPath:indexPath];
8304 if (source == nil) return;
8306 [Sources_ removeObjectForKey:[source key]];
8308 [self.delegate syncData];
8312 - (void) tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath {
8313 [self updateButtonsForEditingStatusAnimated:YES];
8317 [self.delegate addTrivialSource:href_];
8320 [self.delegate syncData];
8323 - (NSString *) getWarning {
8324 NSString *href(href_);
8325 NSRange colon([href rangeOfString:@"://"]);
8326 if (colon.location != NSNotFound)
8327 href = [href substringFromIndex:(colon.location + 3)];
8328 href = [href stringByAddingPercentEscapes];
8329 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8331 NSURL *url([NSURL URLWithString:href]);
8333 NSStringEncoding encoding;
8334 NSError *error(nil);
8336 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8337 return [warning length] == 0 ? nil : warning;
8341 - (void) _endConnection:(NSURLConnection *)connection {
8342 // XXX: the memory management in this method is horribly awkward
8344 NSURLConnection **field = NULL;
8345 if (connection == trivial_bz2_)
8346 field = &trivial_bz2_;
8347 else if (connection == trivial_gz_)
8348 field = &trivial_gz_;
8349 _assert(field != NULL);
8350 [connection release];
8354 trivial_bz2_ == nil &&
8357 NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil);
8359 [self.delegate releaseNetworkActivityIndicator];
8361 [self.delegate removeProgressHUD:hud_];
8365 if (warning != nil) {
8366 UIAlertView *alert = [[[UIAlertView alloc]
8367 initWithTitle:UCLocalize("SOURCE_WARNING")
8370 cancelButtonTitle:UCLocalize("CANCEL")
8372 UCLocalize("ADD_ANYWAY"),
8376 [alert setContext:@"warning"];
8377 [alert setNumberOfRows:1];
8380 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
8386 } else if (error_ != nil) {
8387 UIAlertView *alert = [[[UIAlertView alloc]
8388 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8389 message:[error_ localizedDescription]
8391 cancelButtonTitle:UCLocalize("OK")
8392 otherButtonTitles:nil
8395 [alert setContext:@"urlerror"];
8400 UIAlertView *alert = [[[UIAlertView alloc]
8401 initWithTitle:UCLocalize("NOT_REPOSITORY")
8402 message:UCLocalize("NOT_REPOSITORY_EX")
8404 cancelButtonTitle:UCLocalize("OK")
8405 otherButtonTitles:nil
8408 [alert setContext:@"trivial"];
8418 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8419 switch ([response statusCode]) {
8425 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8426 lprintf("connection:\"%s\" didFailWithError:\"%s\"\n", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8428 [self _endConnection:connection];
8431 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8432 [self _endConnection:connection];
8435 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8436 NSURL *url([NSURL URLWithString:href]);
8438 NSMutableURLRequest *request = [NSMutableURLRequest
8440 cachePolicy:NSURLRequestUseProtocolCachePolicy
8444 [request setHTTPMethod:method];
8446 if (Machine_ != NULL)
8447 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8449 if (UniqueID_ != nil)
8450 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8452 if ([url isCydiaSecure]) {
8453 if (UniqueID_ != nil)
8454 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
8457 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8460 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8461 NSString *context([alert context]);
8463 if ([context isEqualToString:@"source"]) {
8466 NSString *href = [[alert textField] text];
8467 href = VerifySource(href);
8472 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8473 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8477 // XXX: this is stupid
8478 hud_ = [self.delegate addProgressHUD];
8479 [hud_ setText:UCLocalize("VERIFYING_URL")];
8480 [self.delegate retainNetworkActivityIndicator];
8489 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8490 } else if ([context isEqualToString:@"trivial"])
8491 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8492 else if ([context isEqualToString:@"urlerror"])
8493 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8494 else if ([context isEqualToString:@"warning"]) {
8497 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
8506 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8510 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated {
8511 BOOL editing([list_ isEditing]);
8514 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8515 initWithTitle:UCLocalize("ADD")
8516 style:UIBarButtonItemStylePlain
8518 action:@selector(addButtonClicked)
8519 ] autorelease] animated:animated];
8520 else if ([self.delegate updating])
8521 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8522 initWithTitle:UCLocalize("CANCEL")
8523 style:UIBarButtonItemStyleDone
8525 action:@selector(cancelButtonClicked)
8526 ] autorelease] animated:animated];
8528 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8529 initWithTitle:UCLocalize("REFRESH")
8530 style:UIBarButtonItemStylePlain
8532 action:@selector(refreshButtonClicked)
8533 ] autorelease] animated:animated];
8535 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8536 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8537 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8539 action:@selector(editButtonClicked)
8540 ] autorelease] animated:animated];
8544 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease];
8545 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8546 [list_ setRowHeight:53];
8547 [(UITableView *) list_ setDataSource:self];
8548 [list_ setDelegate:self];
8549 [self setView:list_];
8552 - (void) viewDidLoad {
8553 [super viewDidLoad];
8555 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8556 [self updateButtonsForEditingStatusAnimated:NO];
8559 - (void) viewWillAppear:(BOOL)animated {
8560 [super viewWillAppear:animated];
8562 [list_ setEditing:NO];
8563 [self updateButtonsForEditingStatusAnimated:NO];
8566 - (void) releaseSubviews {
8571 [super releaseSubviews];
8574 - (id) initWithDatabase:(Database *)database {
8575 if ((self = [super init]) != nil) {
8576 database_ = database;
8580 - (void) reloadData {
8582 [self updateButtonsForEditingStatusAnimated:YES];
8584 @synchronized (database_) {
8585 era_ = [database_ era];
8587 sources_ = [NSMutableArray arrayWithCapacity:16];
8588 [sources_ addObjectsFromArray:[database_ sources]];
8590 [sources_ sortUsingSelector:@selector(compareByName:)];
8593 int count([sources_ count]);
8595 for (int i = 0; i != count; i++) {
8596 if ([[sources_ objectAtIndex:i] record] == nil)
8604 - (void) showAddSourcePrompt {
8605 UIAlertView *alert = [[[UIAlertView alloc]
8606 initWithTitle:UCLocalize("ENTER_APT_URL")
8609 cancelButtonTitle:UCLocalize("CANCEL")
8611 UCLocalize("ADD_SOURCE"),
8615 [alert setContext:@"source"];
8617 [alert setNumberOfRows:1];
8618 [alert addTextFieldWithValue:@"http://" label:@""];
8620 NSObject<UITextInputTraits> *traits = [[alert textField] textInputTraits];
8621 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8622 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8623 [traits setKeyboardType:UIKeyboardTypeURL];
8624 // XXX: UIReturnKeyDone
8625 [traits setReturnKeyType:UIReturnKeyNext];
8630 - (void) addButtonClicked {
8631 [self showAddSourcePrompt];
8634 - (void) refreshButtonClicked {
8635 if ([self.delegate requestUpdate])
8636 [self updateButtonsForEditingStatusAnimated:YES];
8639 - (void) cancelButtonClicked {
8640 [self.delegate cancelUpdate];
8643 - (void) editButtonClicked {
8644 [list_ setEditing:![list_ isEditing] animated:YES];
8645 [self updateButtonsForEditingStatusAnimated:YES];
8651 /* Stash Controller {{{ */
8652 @interface StashController : CyteViewController {
8653 _H<UIActivityIndicatorView> spinner_;
8654 _H<UILabel> status_;
8655 _H<UILabel> caption_;
8660 @implementation StashController
8663 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8664 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8665 [self setView:view];
8667 [view setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8669 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8670 CGRect spinrect = [spinner_ frame];
8671 spinrect.origin.x = Retina([[self view] frame].size.width / 2 - spinrect.size.width / 2);
8672 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8673 [spinner_ setFrame:spinrect];
8674 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8675 [view addSubview:spinner_];
8676 [spinner_ startAnimating];
8679 captrect.size.width = [[self view] frame].size.width;
8680 captrect.size.height = 40.0f;
8681 captrect.origin.x = 0;
8682 captrect.origin.y = Retina([[self view] frame].size.height / 2 - captrect.size.height * 2);
8683 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8684 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8685 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8686 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8687 [caption_ setTextColor:[UIColor whiteColor]];
8688 [caption_ setBackgroundColor:[UIColor clearColor]];
8689 [caption_ setShadowColor:[UIColor blackColor]];
8690 [caption_ setTextAlignment:NSTextAlignmentCenter];
8691 [view addSubview:caption_];
8694 statusrect.size.width = [[self view] frame].size.width;
8695 statusrect.size.height = 30.0f;
8696 statusrect.origin.x = 0;
8697 statusrect.origin.y = Retina([[self view] frame].size.height / 2 - statusrect.size.height);
8698 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8699 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8700 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8701 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8702 [status_ setTextColor:[UIColor whiteColor]];
8703 [status_ setBackgroundColor:[UIColor clearColor]];
8704 [status_ setShadowColor:[UIColor blackColor]];
8705 [status_ setTextAlignment:NSTextAlignmentCenter];
8706 [view addSubview:status_];
8709 - (void) releaseSubviews {
8714 [super releaseSubviews];
8720 @interface Cydia : CyteApplication <
8721 ConfirmationControllerDelegate,
8725 _H<CyteWindow> window_;
8726 _H<CydiaTabBarController> tabbar_;
8727 _H<CyteTabBarController> emulated_;
8728 _H<AppCacheController> appcache_;
8730 _H<NSMutableArray> essential_;
8731 _H<NSMutableArray> broken_;
8733 Database *database_;
8735 _H<NSURL> starturl_;
8740 _H<StashController> stash_;
8749 @implementation Cydia
8751 - (void) lockSuspend {
8752 if (locked_++ == 0) {
8753 if ($SBSSetInterceptsMenuButtonForever != NULL)
8754 (*$SBSSetInterceptsMenuButtonForever)(true);
8756 [self setIdleTimerDisabled:YES];
8760 - (void) unlockSuspend {
8761 if (--locked_ == 0) {
8762 [self setIdleTimerDisabled:NO];
8764 if ($SBSSetInterceptsMenuButtonForever != NULL)
8765 (*$SBSSetInterceptsMenuButtonForever)(false);
8769 - (void) beginUpdate {
8770 [tabbar_ beginUpdate];
8773 - (void) cancelUpdate {
8774 [tabbar_ cancelUpdate];
8777 - (bool) requestUpdate {
8778 if (CyteIsReachable("cydia.saurik.com")) {
8782 UIAlertView *alert = [[[UIAlertView alloc]
8783 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("REFRESH")]
8784 message:@"Host Unreachable" // XXX: Localize
8786 cancelButtonTitle:UCLocalize("OK")
8787 otherButtonTitles:nil
8790 [alert setContext:@"norefresh"];
8798 return [tabbar_ updating];
8802 if ([broken_ count] != 0) {
8803 int count = [broken_ count];
8805 UIAlertView *alert = [[[UIAlertView alloc]
8806 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8807 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8809 cancelButtonTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("FORCIBLY_CLEAR"), UCLocalize("UNSAFE")]
8811 UCLocalize("TEMPORARY_IGNORE"),
8815 [alert setContext:@"fixhalf"];
8816 [alert setNumberOfRows:2];
8818 } else if (!Ignored_ && [essential_ count] != 0) {
8819 int count = [essential_ count];
8821 UIAlertView *alert = [[[UIAlertView alloc]
8822 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8823 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8825 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8827 UCLocalize("UPGRADE_ESSENTIAL"),
8828 UCLocalize("COMPLETE_UPGRADE"),
8832 [alert setContext:@"upgrade"];
8837 - (void) returnToCydia {
8841 - (void) reloadSpringBoard {
8842 if (kCFCoreFoundationVersionNumber >= 700) // XXX: iOS 6.x
8843 system("/usr/libexec/cydia/cydo /bin/launchctl stop com.apple.backboardd");
8845 system("/usr/libexec/cydia/cydo /bin/launchctl stop com.apple.SpringBoard");
8847 system("/usr/bin/killall backboardd SpringBoard");
8850 - (void) _saveConfig {
8851 SaveConfig(database_);
8854 // Navigation controller for the queuing badge.
8855 - (UINavigationController *) queueNavigationController {
8856 NSArray *controllers = [tabbar_ viewControllers];
8857 return [controllers objectAtIndex:3];
8860 - (void) _updateData {
8862 [window_ unloadData];
8864 UINavigationController *navigation = [self queueNavigationController];
8866 id queuedelegate = nil;
8867 if ([[navigation viewControllers] count] > 0)
8868 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8870 [queuedelegate queueStatusDidChange];
8871 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8874 - (void) _refreshIfPossible {
8875 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8877 NSDate *update([[NSDictionary dictionaryWithContentsOfFile:@ CacheState_] objectForKey:@"LastUpdate"]);
8879 bool recently = false;
8880 if (update != nil) {
8881 NSTimeInterval interval([update timeIntervalSinceNow]);
8882 if (interval > -(15*60))
8886 // Don't automatic refresh if:
8887 // - We already refreshed recently.
8888 // - We already auto-refreshed this launch.
8889 // - Auto-refresh is disabled.
8890 // - Cydia's server is not reachable
8891 if (recently || loaded_ || ManualRefresh || !CyteIsReachable("cydia.saurik.com")) {
8892 // If we are cancelling, we need to make sure it knows it's already loaded.
8895 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8897 // We are going to load, so remember that.
8900 [tabbar_ performSelectorOnMainThread:@selector(beginUpdate) withObject:nil waitUntilDone:NO];
8906 - (void) refreshIfPossible {
8907 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
8910 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
8911 _profile(reloadDataWithInvocation)
8912 @synchronized (self) {
8913 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8915 [hud setText:UCLocalize("RELOADING_DATA")];
8917 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
8921 [essential_ removeAllObjects];
8922 [broken_ removeAllObjects];
8924 _profile(reloadDataWithInvocation$Essential)
8925 NSArray *packages([database_ packages]);
8926 for (Package *package in packages) {
8928 [broken_ addObject:package];
8929 if ([package upgradableAndEssential:YES] && ![package ignored]) {
8930 if ([package essential] && [package installed] != nil)
8931 [essential_ addObject:package];
8937 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
8940 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8941 [changesItem setBadgeValue:badge];
8942 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8943 [self setApplicationIconBadgeNumber:changes];
8946 [changesItem setBadgeValue:nil];
8947 [changesItem setAnimatedBadge:NO];
8948 [self setApplicationIconBadgeNumber:0];
8955 [self removeProgressHUD:hud];
8962 - (void) updateData {
8966 - (void) updateDataAndLoad {
8968 if ([database_ progressDelegate] == nil)
8974 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
8977 - (void) disemulate {
8978 if (emulated_ == nil)
8981 [window_ setRootViewController:tabbar_];
8984 [window_ setUserInteractionEnabled:YES];
8987 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
8988 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
8990 UIViewController *parent;
8991 if (emulated_ == nil)
9001 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9002 [parent presentModalViewController:navigation animated:YES];
9005 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9006 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9008 if (navigation != nil)
9009 [navigation pushViewController:progress animated:YES];
9011 [self presentModalViewController:progress force:YES];
9013 [progress invoke:invocation withTitle:title];
9017 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9018 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9021 - (void) repairWithInvocation:(NSInvocation *)invocation {
9023 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9027 - (void) repairWithSelector:(SEL)selector {
9028 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9031 - (void) reloadData {
9032 [self reloadDataWithInvocation:nil];
9033 if ([database_ progressDelegate] == nil)
9039 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9042 - (void) addSource:(NSDictionary *) source {
9043 CydiaAddSource(source);
9046 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9047 CydiaAddSource(href, distribution, sections);
9050 // XXX: this method should not return anything
9051 - (BOOL) addTrivialSource:(NSString *)href {
9052 CydiaAddSource(href, @"./");
9057 pkgProblemResolver *resolver = [database_ resolver];
9059 resolver->InstallProtect();
9060 if (!resolver->Resolve(true))
9065 // XXX: this is a really crappy way of doing this.
9066 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9067 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9068 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9069 if ([tabbar_ updating])
9070 [tabbar_ cancelUpdate];
9072 if (![database_ prepare])
9075 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9076 [page setDelegate:self];
9077 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9080 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9081 [tabbar_ presentModalViewController:confirm_ animated:YES];
9087 @synchronized (self) {
9092 - (void) clearPackage:(Package *)package {
9093 @synchronized (self) {
9100 - (void) installPackages:(NSArray *)packages {
9101 @synchronized (self) {
9102 for (Package *package in packages)
9109 - (void) installPackage:(Package *)package {
9110 @synchronized (self) {
9117 - (void) removePackage:(Package *)package {
9118 @synchronized (self) {
9125 - (void) distUpgrade {
9126 @synchronized (self) {
9127 if (![database_ upgrade])
9135 system("/usr/bin/uicache");
9140 UIProgressHUD *hud([self addProgressHUD]);
9141 [hud setText:UCLocalize("LOADING")];
9142 [self yieldToSelector:@selector(_uicache)];
9143 [self removeProgressHUD:hud];
9147 [database_ perform];
9148 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9149 [self performSelectorOnMainThread:@selector(uicache) withObject:nil waitUntilDone:YES];
9152 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9155 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9156 [self unlockSuspend];
9159 - (void) retainNetworkActivityIndicator {
9160 if (activity_++ == 0)
9161 [self setNetworkActivityIndicatorVisible:YES];
9164 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9168 - (void) releaseNetworkActivityIndicator {
9169 if (--activity_ == 0)
9170 [self setNetworkActivityIndicatorVisible:NO];
9173 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9178 - (void) cancelAndClear:(bool)clear {
9179 @synchronized (self) {
9191 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9192 NSString *context([alert context]);
9194 if ([context isEqualToString:@"conffile"]) {
9195 FILE *input = [database_ input];
9196 if (button == [alert cancelButtonIndex])
9197 fprintf(input, "N\n");
9198 else if (button == [alert firstOtherButtonIndex])
9199 fprintf(input, "Y\n");
9202 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9203 } else if ([context isEqualToString:@"fixhalf"]) {
9204 if (button == [alert cancelButtonIndex]) {
9205 @synchronized (self) {
9206 for (Package *broken in (id) broken_) {
9208 NSString *id(ShellEscape([broken id]));
9209 system([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /bin/rm -f"
9210 " /var/lib/dpkg/info/%@.prerm"
9211 " /var/lib/dpkg/info/%@.postrm"
9212 " /var/lib/dpkg/info/%@.preinst"
9213 " /var/lib/dpkg/info/%@.postinst"
9214 " /var/lib/dpkg/info/%@.extrainst_"
9215 "", id, id, id, id, id] UTF8String]);
9221 } else if (button == [alert firstOtherButtonIndex]) {
9222 [broken_ removeAllObjects];
9226 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9227 } else if ([context isEqualToString:@"upgrade"]) {
9228 if (button == [alert firstOtherButtonIndex]) {
9229 @synchronized (self) {
9230 for (Package *essential in (id) essential_)
9231 [essential install];
9236 } else if (button == [alert firstOtherButtonIndex] + 1) {
9238 } else if (button == [alert cancelButtonIndex]) {
9242 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9246 - (void) system:(NSString *)command {
9247 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9250 system([command UTF8String]);
9256 - (void) applicationWillSuspend {
9258 [super applicationWillSuspend];
9261 - (BOOL) isSafeToSuspend {
9264 NSLog(@"isSafeToSuspend: locked_ != 0");
9269 if ([tabbar_ modalViewController] != nil)
9272 // Use external process status API internally.
9273 // This is probably a really bad idea.
9274 // XXX: what is the point of this? does this solve anything at all?
9275 uint64_t status = 0;
9277 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9278 notify_get_state(notify_token, &status);
9279 notify_cancel(notify_token);
9284 NSLog(@"isSafeToSuspend: status != 0");
9290 NSLog(@"isSafeToSuspend: -> true");
9295 - (void) suspendReturningToLastApp:(BOOL)returning {
9296 if ([self isSafeToSuspend])
9297 [super suspendReturningToLastApp:returning];
9301 if ([self isSafeToSuspend])
9305 - (void) applicationSuspend {
9306 if ([self isSafeToSuspend])
9307 [super applicationSuspend];
9310 - (void) applicationSuspend:(GSEventRef)event {
9311 if ([self isSafeToSuspend])
9312 [super applicationSuspend:event];
9315 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9316 if ([self isSafeToSuspend])
9317 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9320 - (void) _setSuspended:(BOOL)value {
9321 if ([self isSafeToSuspend])
9322 [super _setSuspended:value];
9325 - (UIProgressHUD *) addProgressHUD {
9326 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9327 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9329 [window_ setUserInteractionEnabled:NO];
9331 UIViewController *target(tabbar_);
9332 if (UIViewController *modal = [target modalViewController])
9335 [hud showInView:[target view]];
9341 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9342 [self unlockSuspend];
9344 [hud removeFromSuperview];
9345 [window_ setUserInteractionEnabled:YES];
9348 - (CyteViewController *) pageForPackage:(NSString *)name withReferrer:(NSString *)referrer {
9349 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name withReferrer:referrer] autorelease];
9352 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external withReferrer:(NSString *)referrer {
9353 NSString *scheme([[url scheme] lowercaseString]);
9354 if ([[url absoluteString] length] <= [scheme length] + 3)
9356 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9357 NSArray *components([path componentsSeparatedByString:@"/"]);
9359 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"]) {
9360 CyteViewController *controller([self pageForPackage:[components objectAtIndex:1] withReferrer:referrer]);
9361 if (controller != nil)
9362 [controller setDelegate:self];
9366 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9369 NSString *base([components objectAtIndex:0]);
9371 CyteViewController *controller = nil;
9373 if ([base isEqualToString:@"url"]) {
9374 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9375 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9376 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9377 } else if (!external && [components count] == 1) {
9378 if ([base isEqualToString:@"sources"]) {
9379 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9382 if ([base isEqualToString:@"home"]) {
9383 controller = [[[HomeController alloc] init] autorelease];
9386 if ([base isEqualToString:@"sections"]) {
9387 controller = [[[SectionsController alloc] initWithDatabase:database_ source:nil] autorelease];
9390 if ([base isEqualToString:@"search"]) {
9391 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9394 if ([base isEqualToString:@"changes"]) {
9395 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9398 if ([base isEqualToString:@"installed"]) {
9399 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9401 } else if ([components count] == 2) {
9402 NSString *argument = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9404 if ([base isEqualToString:@"package"]) {
9405 controller = [self pageForPackage:argument withReferrer:referrer];
9408 if (!external && [base isEqualToString:@"search"]) {
9409 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9412 if (!external && [base isEqualToString:@"sections"]) {
9413 if ([argument isEqualToString:@"all"] || [argument isEqualToString:@"*"])
9415 controller = [[[SectionController alloc] initWithDatabase:database_ source:nil section:argument] autorelease];
9418 if ([base isEqualToString:@"sources"]) {
9419 if ([argument isEqualToString:@"add"]) {
9420 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9421 [(SourcesController *)controller showAddSourcePrompt];
9423 Source *source([database_ sourceWithKey:argument]);
9424 controller = [[[SectionsController alloc] initWithDatabase:database_ source:source] autorelease];
9428 if (!external && [base isEqualToString:@"launch"]) {
9429 [self launchApplicationWithIdentifier:argument suspended:NO];
9432 } else if (!external && [components count] == 3) {
9433 NSString *arg1 = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9434 NSString *arg2 = [[components objectAtIndex:2] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9436 if ([base isEqualToString:@"package"]) {
9437 if ([arg2 isEqualToString:@"settings"]) {
9438 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9439 } else if ([arg2 isEqualToString:@"files"]) {
9440 if (Package *package = [database_ packageWithName:arg1]) {
9441 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9442 [(FileTable *)controller setPackage:package];
9447 if ([base isEqualToString:@"sections"]) {
9448 Source *source([arg1 isEqualToString:@"*"] ? nil : [database_ sourceWithKey:arg1]);
9449 NSString *section([arg2 isEqualToString:@"*"] ? nil : arg2);
9450 controller = [[[SectionController alloc] initWithDatabase:database_ source:source section:section] autorelease];
9454 [controller setDelegate:self];
9458 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9459 CyteViewController *page([self pageForURL:url forExternal:external withReferrer:nil]);
9462 [tabbar_ setUnselectedViewController:page];
9467 - (void) applicationOpenURL:(NSURL *)url {
9468 [super applicationOpenURL:url];
9473 [self openCydiaURL:url forExternal:YES];
9476 - (void) applicationWillResignActive:(UIApplication *)application {
9477 // Stop refreshing if you get a phone call or lock the device.
9478 if ([tabbar_ updating])
9479 [tabbar_ cancelUpdate];
9481 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9482 [super applicationWillResignActive:application];
9485 - (void) saveState {
9486 [[NSDictionary dictionaryWithObjectsAndKeys:
9487 @"InterfaceState", [tabbar_ navigationURLCollection],
9488 @"LastClosed", [NSDate date],
9489 @"InterfaceIndex", [NSNumber numberWithInt:[tabbar_ selectedIndex]],
9490 nil] writeToFile:@ SavedState_ atomically:YES];
9495 - (void) applicationWillTerminate:(UIApplication *)application {
9499 - (void) applicationDidEnterBackground:(UIApplication *)application {
9500 if (kCFCoreFoundationVersionNumber < 1000 && [self isSafeToSuspend])
9501 return [self terminateWithSuccess];
9502 Backgrounded_ = [NSDate date];
9506 - (void) applicationWillEnterForeground:(UIApplication *)application {
9507 if (Backgrounded_ == nil)
9510 NSTimeInterval interval([Backgrounded_ timeIntervalSinceNow]);
9512 if (interval <= -(30*60)) {
9513 [tabbar_ setSelectedIndex:0];
9514 [[[tabbar_ viewControllers] objectAtIndex:0] popToRootViewControllerAnimated:NO];
9517 if (interval <= -(15*60)) {
9518 if (CyteIsReachable("cydia.saurik.com")) {
9519 [tabbar_ beginUpdate];
9520 [appcache_ reloadURLWithCache:YES];
9524 if ([database_ delocked])
9528 - (void) setConfigurationData:(NSString *)data {
9529 static RegEx conffile_r("'(.*)' '(.*)' ([01]) ([01])");
9531 if (!conffile_r(data)) {
9532 lprintf("E:invalid conffile\n");
9536 NSString *ofile = conffile_r[1];
9537 //NSString *nfile = conffile_r[2];
9539 UIAlertView *alert = [[[UIAlertView alloc]
9540 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9541 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9543 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9545 UCLocalize("ACCEPT_NEW_COPY"),
9546 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9550 [alert setContext:@"conffile"];
9551 [alert setNumberOfRows:2];
9555 - (void) addStashController {
9557 stash_ = [[[StashController alloc] init] autorelease];
9558 [window_ addSubview:[stash_ view]];
9561 - (void) removeStashController {
9562 [[stash_ view] removeFromSuperview];
9564 [self unlockSuspend];
9568 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9569 UpdateExternalStatus(1);
9570 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/cydo /usr/libexec/cydia/free.sh"];
9571 UpdateExternalStatus(0);
9573 [self removeStashController];
9574 [self reloadSpringBoard];
9577 - (void) applicationDidFinishLaunching:(id)unused {
9578 [super applicationDidFinishLaunching:unused];
9581 @synchronized (BridgedHosts_) {
9582 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9585 [CyteWebViewController _initialize];
9587 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9589 // this would disallow http{,s} URLs from accessing this data
9590 //[WebView registerURLSchemeAsLocal:@"cydia"];
9592 Font12_ = [UIFont systemFontOfSize:12];
9593 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9594 Font14_ = [UIFont systemFontOfSize:14];
9595 Font18_ = [UIFont systemFontOfSize:18];
9596 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9597 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9599 essential_ = [NSMutableArray arrayWithCapacity:4];
9600 broken_ = [NSMutableArray arrayWithCapacity:4];
9602 // XXX: I really need this thing... like, seriously... I'm sorry
9603 appcache_ = [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] autorelease];
9604 [appcache_ reloadData];
9606 window_ = [[[CyteWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9607 [window_ orderFront:self];
9608 [window_ makeKey:self];
9609 [window_ setHidden:NO];
9611 if (access("/.cydia_no_stash", F_OK) == 0);
9615 [self addStashController];
9616 // XXX: this would be much cleaner as a yieldToSelector:
9617 // that way the removeStashController could happen right here inline
9618 // we also could no longer require the useless stash_ field anymore
9619 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9624 int error(stat("/", &root));
9625 _assert(error != -1);
9627 #define Stash_(path) do { \
9628 struct stat folder; \
9629 int error(lstat((path), &folder)); \
9630 if (error != -1 && ( \
9631 folder.st_dev == root.st_dev && \
9632 S_ISDIR(folder.st_mode) \
9633 ) || error == -1 && ( \
9634 errno == ENOENT || \
9639 Stash_("/Applications");
9640 Stash_("/Library/Ringtones");
9641 Stash_("/Library/Wallpaper");
9642 //Stash_("/usr/bin");
9643 Stash_("/usr/include");
9644 Stash_("/usr/share");
9645 //Stash_("/var/lib");
9649 database_ = [Database sharedInstance];
9650 [database_ setDelegate:self];
9652 [window_ setUserInteractionEnabled:NO];
9654 tabbar_ = [[[CydiaTabBarController alloc] initWithDatabase:database_] autorelease];
9656 [tabbar_ addViewControllers:nil,
9657 @"Cydia", @"home.png", @"home7.png", @"home7s.png",
9658 UCLocalize("SOURCES"), @"install.png", @"install7.png", @"install7s.png",
9659 UCLocalize("CHANGES"), @"changes.png", @"changes7.png", @"changes7s.png",
9660 UCLocalize("INSTALLED"), @"manage.png", @"manage7.png", @"manage7s.png",
9661 UCLocalize("SEARCH"), @"search.png", @"search7.png", @"search7s.png",
9664 [tabbar_ setUpdateDelegate:self];
9666 CydiaLoadingViewController *loading([[[CydiaLoadingViewController alloc] init] autorelease]);
9667 UINavigationController *navigation([[[UINavigationController alloc] init] autorelease]);
9668 [navigation setViewControllers:[NSArray arrayWithObject:loading]];
9670 emulated_ = [[[CyteTabBarController alloc] init] autorelease];
9671 [emulated_ setViewControllers:[NSArray arrayWithObject:navigation]];
9672 [emulated_ setSelectedIndex:0];
9674 if ([emulated_ respondsToSelector:@selector(concealTabBarSelection)])
9675 [emulated_ concealTabBarSelection];
9677 [window_ setRootViewController:emulated_];
9679 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9683 - (NSArray *) defaultStartPages {
9684 NSMutableArray *standard = [NSMutableArray array];
9685 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9686 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9687 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9688 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9689 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9695 if ([emulated_ modalViewController] != nil)
9696 [emulated_ dismissModalViewControllerAnimated:YES];
9697 [window_ setUserInteractionEnabled:NO];
9699 [self reloadDataWithInvocation:nil];
9700 [self refreshIfPossible];
9703 NSDictionary *state([NSDictionary dictionaryWithContentsOfFile:@ SavedState_]);
9705 int savedIndex = [[state objectForKey:@"InterfaceIndex"] intValue];
9706 NSArray *saved = [[[state objectForKey:@"InterfaceState"] mutableCopy] autorelease];
9707 int standardIndex = 0;
9708 NSArray *standard = [self defaultStartPages];
9715 NSDate *closed = [state objectForKey:@"LastClosed"];
9716 if (valid && closed != nil) {
9717 NSTimeInterval interval([closed timeIntervalSinceNow]);
9718 if (interval <= -(30*60))
9722 if (valid && [saved count] != [standard count])
9726 for (unsigned int i = 0; i < [standard count]; i++) {
9727 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9728 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9729 // but it's good enough for now.
9730 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9737 NSArray *items = nil;
9739 [tabbar_ setSelectedIndex:savedIndex];
9742 [tabbar_ setSelectedIndex:standardIndex];
9746 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9747 NSArray *stack = [items objectAtIndex:tab];
9748 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9749 NSMutableArray *current = [NSMutableArray array];
9751 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9752 NSString *addr = [stack objectAtIndex:nav];
9753 NSURL *url = [NSURL URLWithString:addr];
9754 CyteViewController *page = [self pageForURL:url forExternal:NO withReferrer:nil];
9756 [current addObject:page];
9759 [navigation setViewControllers:current];
9762 // (Try to) show the startup URL.
9763 if (starturl_ != nil) {
9764 [self openCydiaURL:starturl_ forExternal:YES];
9769 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9771 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
9772 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
9775 if (item != nil && IsWildcat_) {
9776 [sheet showFromBarButtonItem:item animated:YES];
9778 [sheet showInView:window_];
9782 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9783 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9784 [progress setTitle:task];
9785 [progress addProgressEvent:event];
9788 - (void) addProgressEventForTask:(NSArray *)data {
9789 CydiaProgressEvent *event([data objectAtIndex:0]);
9790 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9791 [self addProgressEvent:event forTask:task];
9794 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9795 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9801 id Alloc_(id self, SEL selector) {
9802 id object = alloc_(self, selector);
9803 lprintf("[%s]A-%p\n", self->isa->name, object);
9808 id Dealloc_(id self, SEL selector) {
9809 id object = dealloc_(self, selector);
9810 lprintf("[%s]D-%p\n", self->isa->name, object);
9814 static NSMutableDictionary *AutoreleaseDeepMutableCopyOfDictionary(CFTypeRef type) {
9817 if (CFGetTypeID(type) != CFDictionaryGetTypeID())
9819 CFTypeRef copy(CFPropertyListCreateDeepCopy(kCFAllocatorDefault, type, kCFPropertyListMutableContainers));
9821 return [(NSMutableDictionary *) copy autorelease];
9824 int main_store(int, char *argv[]);
9826 int main(int argc, char *argv[]) {
9828 const char *argv0(argv[0]);
9829 if (const char *slash = strrchr(argv0, '/'))
9832 else if (!strcmp(argv0, "store"))
9833 return main_store(argc, argv);
9836 int fd(open("/tmp/cydia.log", O_WRONLY | O_APPEND | O_CREAT, 0644));
9840 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9844 CyteInitialize(@"Cydia", Cydia_);
9845 UpdateExternalStatus(0);
9847 Idiom_ = IsWildcat_ ? @"ipad" : @"iphone";
9849 RegEx pattern("([0-9]+\\.[0-9]+).*");
9851 UIDevice *device([UIDevice currentDevice]);
9852 if (pattern([device systemVersion]))
9853 Firmware_ = pattern[1];
9855 if (pattern(Cydia_))
9856 Major_ = pattern[1];
9858 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
9859 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
9860 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
9862 NSString *ui(@"ui/ios");
9864 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
9865 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"/%@", Major_]];
9868 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9870 /* Set Locale {{{ */
9871 Locale_ = CFLocaleCopyCurrent();
9872 Languages_ = [NSLocale preferredLanguages];
9874 std::string languages;
9875 const char *translation(NULL);
9877 // XXX: this isn't really a language, but this is compatible with older Cydia builds
9878 if (Locale_ != NULL)
9879 if (const char *language = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String]) {
9880 RegEx pattern("([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?");
9881 if (pattern(language)) {
9882 translation = strdup([pattern->*@"%1$@%2$@" UTF8String]);
9883 languages += translation;
9888 if (Languages_ != nil)
9889 for (NSString *locale : Languages_) {
9890 auto components([NSLocale componentsFromLocaleIdentifier:locale]);
9891 NSString *language([components objectForKey:(id)kCFLocaleLanguageCode]);
9892 if (NSString *script = [components objectForKey:(id)kCFLocaleScriptCode])
9893 language = [NSString stringWithFormat:@"%@-%@", language, script];
9894 languages += [language UTF8String];
9899 NSLog(@"Setting Language: [%s] %s", translation, languages.c_str());
9901 /* Index Collation {{{ */
9902 if (Class $UILocalizedIndexedCollation = objc_getClass("UILocalizedIndexedCollation")) { @try {
9903 NSBundle *bundle([NSBundle bundleForClass:$UILocalizedIndexedCollation]);
9904 NSString *path([bundle pathForResource:@"UITableViewLocalizedSectionIndex" ofType:@"plist"]);
9905 //path = @"/System/Library/Frameworks/UIKit.framework/.lproj/UITableViewLocalizedSectionIndex.plist";
9906 NSDictionary *dictionary([NSDictionary dictionaryWithContentsOfFile:path]);
9907 _H<UILocalizedIndexedCollation> collation([[[$UILocalizedIndexedCollation alloc] initWithDictionary:dictionary] autorelease]);
9909 CollationLocale_ = MSHookIvar<NSLocale *>(collation, "_locale");
9911 if (kCFCoreFoundationVersionNumber >= 800 && [[CollationLocale_ localeIdentifier] isEqualToString:@"zh@collation=stroke"]) {
9912 CollationThumbs_ = [NSArray arrayWithObjects:@"1",@"•",@"4",@"•",@"7",@"•",@"10",@"•",@"13",@"•",@"16",@"•",@"19",@"A",@"•",@"E",@"•",@"I",@"•",@"M",@"•",@"R",@"•",@"V",@"•",@"Z",@"#",nil];
9913 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})
9914 CollationOffset_.push_back(offset);
9915 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];
9916 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];
9919 CollationThumbs_ = [collation sectionIndexTitles];
9920 for (size_t index(0), end([CollationThumbs_ count]); index != end; ++index)
9921 CollationOffset_.push_back([collation sectionForSectionIndexTitleAtIndex:index]);
9923 CollationTitles_ = [collation sectionTitles];
9924 CollationStarts_ = MSHookIvar<NSArray *>(collation, "_sectionStartStrings");
9926 NSString *&transform(MSHookIvar<NSString *>(collation, "_transform"));
9927 if (&transform != NULL && transform != nil) {
9928 /*if ([collation respondsToSelector:@selector(transformedCollationStringForString:)])
9929 CollationModify_ = [=](NSString *value) { return [collation transformedCollationStringForString:value]; };*/
9930 const UChar *uid(reinterpret_cast<const UChar *>([transform cStringUsingEncoding:NSUnicodeStringEncoding]));
9931 UErrorCode code(U_ZERO_ERROR);
9932 CollationTransl_ = utrans_openU(uid, -1, UTRANS_FORWARD, NULL, 0, NULL, &code);
9933 if (!U_SUCCESS(code))
9934 NSLog(@"%s", u_errorName(code));
9938 } @catch (NSException *e) {
9942 CollationLocale_ = [[[NSLocale alloc] initWithLocaleIdentifier:@"en@collation=dictionary"] autorelease];
9944 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];
9945 for (NSInteger offset(0); offset != 28; ++offset)
9946 CollationOffset_.push_back(offset);
9948 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];
9949 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];
9953 App_ = [[NSBundle mainBundle] bundlePath];
9956 Cache_ = [[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia", @"/var/mobile"] retain];
9957 mkdir([Cache_ UTF8String], 0755);
9959 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
9960 alloc_ = alloc->method_imp;
9961 alloc->method_imp = (IMP) &Alloc_;*/
9963 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
9964 dealloc_ = dealloc->method_imp;
9965 dealloc->method_imp = (IMP) &Dealloc_;*/
9967 void *gestalt(dlopen("/usr/lib/libMobileGestalt.dylib", RTLD_GLOBAL | RTLD_LAZY));
9968 $MGCopyAnswer = reinterpret_cast<CFStringRef (*)(CFStringRef)>(dlsym(gestalt, "MGCopyAnswer"));
9970 /* System Information {{{ */
9974 size = sizeof(maxproc);
9975 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9976 perror("sysctlbyname(\"kern.maxproc\", ?)");
9977 else if (maxproc < 64) {
9979 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9980 perror("sysctlbyname(\"kern.maxproc\", #)");
9983 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
9984 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
9985 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
9987 UniqueID_ = UniqueIdentifier(device);
9989 /* Load Database {{{ */
9990 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9993 mkdir("/var/mobile/Library/Cydia", 0755);
9994 MetaFile_.Open("/var/mobile/Library/Cydia/metadata.cb0");
9997 Values_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaValues"), CFSTR("com.saurik.Cydia")));
9998 Sections_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaSections"), CFSTR("com.saurik.Cydia")));
9999 Sources_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaSources"), CFSTR("com.saurik.Cydia")));
10000 Version_ = [(NSNumber *) CFPreferencesCopyAppValue(CFSTR("CydiaVersion"), CFSTR("com.saurik.Cydia")) autorelease];
10003 NSDictionary *metadata([[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease]);
10005 if (Values_ == nil)
10006 Values_ = [metadata objectForKey:@"Values"];
10007 if (Values_ == nil)
10008 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10010 if (Sections_ == nil)
10011 Sections_ = [metadata objectForKey:@"Sections"];
10012 if (Sections_ == nil)
10013 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10015 if (Sources_ == nil)
10016 Sources_ = [metadata objectForKey:@"Sources"];
10017 if (Sources_ == nil)
10018 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10020 // XXX: this wrong, but in a way that doesn't matter :/
10021 if (Version_ == nil)
10022 Version_ = [metadata objectForKey:@"Version"];
10023 if (Version_ == nil)
10024 Version_ = [NSNumber numberWithUnsignedInt:0];
10026 if (NSDictionary *packages = [metadata objectForKey:@"Packages"]) {
10028 CFDictionaryApplyFunction((CFDictionaryRef) packages, &PackageImport, &fail);
10031 NSLog(@"unable to import package preferences... from 2010? oh well :/");
10034 if ([Version_ unsignedIntValue] == 0) {
10035 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10036 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10037 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10038 CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./");
10040 Version_ = [NSNumber numberWithUnsignedInt:1];
10042 if (NSMutableDictionary *cache = [NSMutableDictionary dictionaryWithContentsOfFile:@ CacheState_]) {
10043 [cache removeObjectForKey:@"LastUpdate"];
10044 [cache writeToFile:@ CacheState_ atomically:YES];
10048 _H<NSMutableArray> broken([NSMutableArray array]);
10049 for (NSString *key in (id) Sources_)
10050 if ([key rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"# "]].location != NSNotFound || ![([[Sources_ objectForKey:key] objectForKey:@"URI"] ?: @"/") hasSuffix:@"/"])
10051 [broken addObject:key];
10052 if ([broken count] != 0)
10053 for (NSString *key in (id) broken)
10054 [Sources_ removeObjectForKey:key];
10058 system("/usr/libexec/cydia/cydo /bin/rm -f /var/lib/cydia/metadata.plist");
10061 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10063 if (kCFCoreFoundationVersionNumber > 1000)
10064 system("/usr/libexec/cydia/cydo /usr/libexec/cydia/setnsfpn /var/lib");
10066 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10068 if (access("/User", F_OK) != 0 || version != 6) {
10070 system("/usr/libexec/cydia/cydo /usr/libexec/cydia/firmware.sh");
10074 if (access("/tmp/cydia.chk", F_OK) == 0) {
10075 if (unlink([Cache("pkgcache.bin") UTF8String]) == -1)
10076 _assert(errno == ENOENT);
10077 if (unlink([Cache("srcpkgcache.bin") UTF8String]) == -1)
10078 _assert(errno == ENOENT);
10081 system("/usr/libexec/cydia/cydo /bin/ln -sf /var/mobile/Library/Caches/com.saurik.Cydia/sources.list /etc/apt/sources.list.d/cydia.list");
10083 /* APT Initialization {{{ */
10084 _assert(pkgInitConfig(*_config));
10085 _assert(pkgInitSystem(*_config, _system));
10087 _config->Set("Acquire::AllowInsecureRepositories", true);
10088 _config->Set("Acquire::Check-Valid-Until", false);
10089 _config->Set("Dir::Bin::Methods::store", "/Applications/Cydia.app/store");
10091 _config->Set("pkgCacheGen::ForceEssential", "");
10093 if (translation != NULL)
10094 _config->Set("APT::Acquire::Translation", translation);
10095 _config->Set("Acquire::Languages", languages);
10097 // XXX: this timeout might be important :(
10098 //_config->Set("Acquire::http::Timeout", 15);
10100 int64_t usermem(0);
10101 size = sizeof(usermem);
10102 if (sysctlbyname("hw.usermem", &usermem, &size, NULL, 0) == -1)
10104 _config->Set("Acquire::http::MaxParallel", usermem >= 384 * 1024 * 1024 ? 16 : 3);
10106 mkdir([Cache("archives") UTF8String], 0755);
10107 mkdir([Cache("archives/partial") UTF8String], 0755);
10108 _config->Set("Dir::Cache", [Cache_ UTF8String]);
10110 symlink("/var/lib/apt/extended_states", [Cache("extended_states") UTF8String]);
10111 _config->Set("Dir::State", [Cache_ UTF8String]);
10113 mkdir([Cache("lists") UTF8String], 0755);
10114 mkdir([Cache("lists/partial") UTF8String], 0755);
10115 mkdir([Cache("periodic") UTF8String], 0755);
10116 _config->Set("Dir::State::Lists", [Cache("lists") UTF8String]);
10118 std::string logs("/var/mobile/Library/Logs/Cydia");
10119 mkdir(logs.c_str(), 0755);
10120 _config->Set("Dir::Log", logs);
10122 _config->Set("Dir::Bin::dpkg", "/usr/libexec/cydia/cydo");
10124 /* Color Choices {{{ */
10125 space_ = CGColorSpaceCreateDeviceRGB();
10127 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10128 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10129 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10130 Folder_.Set(space_, 0x8e/255.f, 0x8e/255.f, 0x93/255.f, 1.0);
10131 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10132 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10133 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10134 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10135 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10136 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10138 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10139 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10141 /* UIKit Configuration {{{ */
10142 // XXX: I have a feeling this was important
10143 //UIKeyboardDisableAutomaticAppearance();
10146 $SBSSetInterceptsMenuButtonForever = reinterpret_cast<void (*)(bool)>(dlsym(RTLD_DEFAULT, "SBSSetInterceptsMenuButtonForever"));
10147 $SBSCopyIconImagePNGDataForDisplayIdentifier = reinterpret_cast<NSData *(*)(NSString *)>(dlsym(RTLD_DEFAULT, "SBSCopyIconImagePNGDataForDisplayIdentifier"));
10149 const char *symbol(kCFCoreFoundationVersionNumber >= 800 ? "MGGetBoolAnswer" : "GSSystemHasCapability");
10150 BOOL (*GSSystemHasCapability)(CFStringRef) = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, symbol));
10151 bool fast = GSSystemHasCapability != NULL && GSSystemHasCapability(CFSTR("armv7"));
10153 PulseInterval_ = fast ? 50000 : 500000;
10155 Colon_ = UCLocalize("COLON_DELIMITED");
10156 Elision_ = UCLocalize("ELISION");
10157 Error_ = UCLocalize("ERROR");
10158 Warning_ = UCLocalize("WARNING");
10161 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10163 CGColorSpaceRelease(space_);
10164 CFRelease(Locale_);