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 const char *Machine_ = NULL;
645 static _H<NSString> System_;
646 static NSString *SerialNumber_ = nil;
647 static NSString *ChipID_ = nil;
648 static NSString *BBSNum_ = nil;
649 static _H<NSString> UniqueID_;
650 static _H<NSString> Product_;
651 static _H<NSString> Safari_;
653 static _H<NSLocale> CollationLocale_;
654 static _H<NSArray> CollationThumbs_;
655 static std::vector<NSInteger> CollationOffset_;
656 static _H<NSArray> CollationTitles_;
657 static _H<NSArray> CollationStarts_;
658 static UTransliterator *CollationTransl_;
659 //static Function<NSString *, NSString *> CollationModify_;
661 typedef std::basic_string<UChar> ustring;
662 static ustring CollationString_;
664 #define CUC const ustring &str(*reinterpret_cast<const ustring *>(rep))
665 #define UC ustring &str(*reinterpret_cast<ustring *>(rep))
666 static struct UReplaceableCallbacks CollationUCalls_ = {
667 .length = [](const UReplaceable *rep) -> int32_t { CUC;
671 .charAt = [](const UReplaceable *rep, int32_t offset) -> UChar { CUC;
672 //fprintf(stderr, "charAt(%d) : %d\n", offset, str.size());
673 if (offset >= str.size())
678 .char32At = [](const UReplaceable *rep, int32_t offset) -> UChar32 { CUC;
679 //fprintf(stderr, "char32At(%d) : %d\n", offset, str.size());
680 if (offset >= str.size())
683 U16_GET(str.data(), 0, offset, str.size(), c);
687 .replace = [](UReplaceable *rep, int32_t start, int32_t limit, const UChar *text, int32_t length) -> void { UC;
688 //fprintf(stderr, "replace(%d, %d, %d) : %d\n", start, limit, length, str.size());
689 str.replace(start, limit - start, text, length);
692 .extract = [](UReplaceable *rep, int32_t start, int32_t limit, UChar *dst) -> void { UC;
693 //fprintf(stderr, "extract(%d, %d) : %d\n", start, limit, str.size());
694 str.copy(dst, limit - start, start);
697 .copy = [](UReplaceable *rep, int32_t start, int32_t limit, int32_t dest) -> void { UC;
698 //fprintf(stderr, "copy(%d, %d, %d) : %d\n", start, limit, dest, str.size());
699 str.replace(dest, 0, str, start, limit - start);
703 static CFLocaleRef Locale_;
704 static NSArray *Languages_;
705 static CGColorSpaceRef space_;
707 #define CacheState_ "/var/mobile/Library/Caches/com.saurik.Cydia/CacheState.plist"
708 #define SavedState_ "/var/mobile/Library/Caches/com.saurik.Cydia/SavedState.plist"
710 static NSDictionary *SectionMap_;
711 static _H<NSDate> Backgrounded_;
712 static _transient NSMutableDictionary *Values_;
713 static _transient NSMutableDictionary *Sections_;
714 _H<NSMutableDictionary> Sources_;
715 static _transient NSNumber *Version_;
718 static NSString *Idiom_;
719 static _H<NSString> Firmware_;
720 static NSString *Major_;
722 static _H<NSMutableDictionary> SessionData_;
723 static _H<NSObject> HostConfig_;
724 static _H<NSMutableSet> BridgedHosts_;
725 static _H<NSMutableSet> InsecureHosts_;
727 static NSString *kCydiaProgressEventTypeError = @"Error";
728 static NSString *kCydiaProgressEventTypeInformation = @"Information";
729 static NSString *kCydiaProgressEventTypeStatus = @"Status";
730 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
733 /* Display Helpers {{{ */
734 inline float Interpolate(float begin, float end, float fraction) {
735 return (end - begin) * fraction + begin;
738 static inline double Retina(double value) {
739 value *= ScreenScale_;
740 value = round(value);
741 value /= ScreenScale_;
745 static inline CGRect Retina(CGRect value) {
746 value.origin.x *= ScreenScale_;
747 value.origin.y *= ScreenScale_;
748 value.size.width *= ScreenScale_;
749 value.size.height *= ScreenScale_;
750 value = CGRectIntegral(value);
751 value.origin.x /= ScreenScale_;
752 value.origin.y /= ScreenScale_;
753 value.size.width /= ScreenScale_;
754 value.size.height /= ScreenScale_;
758 static _finline const char *StripVersion_(const char *version) {
759 const char *colon(strchr(version, ':'));
760 return colon == NULL ? version : colon + 1;
763 NSString *LocalizeSection(NSString *section) {
764 static RegEx title_r("(.*?) \\((.*)\\)");
765 if (title_r(section)) {
766 NSString *parent(title_r[1]);
767 NSString *child(title_r[2]);
769 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
770 LocalizeSection(parent),
771 LocalizeSection(child)
775 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
778 NSString *Simplify(NSString *title) {
779 const char *data = [title UTF8String];
780 size_t size = [title lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
782 static RegEx square_r("\\[(.*)\\]");
783 if (square_r(data, size))
784 return Simplify(square_r[1]);
786 static RegEx paren_r("\\((.*)\\)");
787 if (paren_r(data, size))
788 return Simplify(paren_r[1]);
790 static RegEx title_r("(.*?) \\((.*)\\)");
791 if (title_r(data, size))
792 return Simplify(title_r[1]);
798 bool isSectionVisible(NSString *section) {
799 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
800 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
801 return hidden == nil || ![hidden boolValue];
804 static NSObject *CYIOGetValue(const char *path, NSString *property) {
805 io_registry_entry_t entry(IORegistryEntryFromPath(kIOMasterPortDefault, path));
806 if (entry == MACH_PORT_NULL)
809 CFTypeRef value(IORegistryEntryCreateCFProperty(entry, (CFStringRef) property, kCFAllocatorDefault, 0));
810 IOObjectRelease(entry);
814 return [(id) value autorelease];
817 static NSString *CYHex(NSData *data, bool reverse = false) {
821 size_t length([data length]);
822 uint8_t bytes[length];
823 [data getBytes:bytes];
825 char string[length * 2 + 1];
826 for (size_t i(0); i != length; ++i)
827 sprintf(string + i * 2, "%.2x", bytes[reverse ? length - i - 1 : i]);
829 return [NSString stringWithUTF8String:string];
832 static NSString *VerifySource(NSString *href) {
833 static RegEx href_r("(http(s?)://|file:///)[^# ]*");
835 [[[[UIAlertView alloc]
836 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("INVALID_URL")]
837 message:UCLocalize("INVALID_URL_EX")
839 cancelButtonTitle:UCLocalize("OK")
840 otherButtonTitles:nil
841 ] autorelease] show];
846 if (![href hasSuffix:@"/"])
847 href = [href stringByAppendingString:@"/"];
853 /* Delegate Prototypes {{{ */
856 @class CydiaProgressEvent;
858 @protocol DatabaseDelegate
859 - (void) repairWithSelector:(SEL)selector;
860 - (void) setConfigurationData:(NSString *)data;
861 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
864 @class CYPackageController;
866 @protocol SourceDelegate
867 - (void) setFetch:(NSNumber *)fetch;
870 @protocol FetchDelegate
871 - (bool) isSourceCancelled;
872 - (void) startSourceFetch:(NSString *)uri;
873 - (void) stopSourceFetch:(NSString *)uri;
876 @protocol CydiaDelegate
877 - (void) returnToCydia;
879 - (void) retainNetworkActivityIndicator;
880 - (void) releaseNetworkActivityIndicator;
881 - (void) clearPackage:(Package *)package;
882 - (void) installPackage:(Package *)package;
883 - (void) installPackages:(NSArray *)packages;
884 - (void) removePackage:(Package *)package;
885 - (void) beginUpdate;
887 - (bool) requestUpdate;
888 - (void) distUpgrade;
891 - (void) _saveConfig;
893 - (void) addSource:(NSDictionary *)source;
894 - (BOOL) addTrivialSource:(NSString *)href;
895 - (UIProgressHUD *) addProgressHUD;
896 - (void) removeProgressHUD:(UIProgressHUD *)hud;
897 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
898 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
902 /* CancelStatus {{{ */
904 public pkgAcquireStatus
915 virtual bool MediaChange(std::string media, std::string drive) {
919 virtual void IMSHit(pkgAcquire::ItemDesc &desc) {
923 virtual bool Pulse_(pkgAcquire *Owner) = 0;
925 virtual bool Pulse(pkgAcquire *Owner) {
926 if (pkgAcquireStatus::Pulse(Owner) && Pulse_(Owner))
934 _finline bool WasCancelled() const {
939 /* DelegateStatus {{{ */
944 _transient NSObject<ProgressDelegate> *delegate_;
952 void setDelegate(NSObject<ProgressDelegate> *delegate) {
953 delegate_ = delegate;
956 virtual void Fetch(pkgAcquire::ItemDesc &desc) {
957 NSString *name([NSString stringWithUTF8String:desc.ShortDesc.c_str()]);
958 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItemDesc:desc]);
959 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
962 virtual void Done(pkgAcquire::ItemDesc &desc) {
963 NSString *name([NSString stringWithUTF8String:desc.ShortDesc.c_str()]);
964 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:Colon_, UCLocalize("DONE"), name] ofType:kCydiaProgressEventTypeStatus forItemDesc:desc]);
965 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
968 virtual void Fail(pkgAcquire::ItemDesc &desc) {
970 desc.Owner->Status == pkgAcquire::Item::StatIdle ||
971 desc.Owner->Status == pkgAcquire::Item::StatDone
975 std::string &error(desc.Owner->ErrorText);
979 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItemDesc:desc]);
980 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
983 virtual bool Pulse_(pkgAcquire *Owner) {
985 double(CurrentBytes + CurrentItems) /
986 double(TotalBytes + TotalItems)
989 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
990 [NSNumber numberWithDouble:percent], @"Percent",
992 [NSNumber numberWithDouble:CurrentBytes], @"Current",
993 [NSNumber numberWithDouble:TotalBytes], @"Total",
994 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
995 nil] waitUntilDone:YES];
997 return ![delegate_ isProgressCancelled];
1000 virtual void Start() {
1001 pkgAcquireStatus::Start();
1002 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
1005 virtual void Stop() {
1006 pkgAcquireStatus::Stop();
1007 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
1008 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
1012 /* Database Interface {{{ */
1013 typedef std::map< unsigned long, _H<Source> > SourceMap;
1015 @interface Database : NSObject {
1022 pkgCacheFile cache_;
1023 pkgDepCache::Policy *policy_;
1024 pkgRecords *records_;
1025 pkgProblemResolver *resolver_;
1026 pkgAcquire *fetcher_;
1028 SPtr<pkgPackageManager> manager_;
1029 pkgSourceList *list_;
1031 SourceMap sourceMap_;
1032 _H<NSMutableArray> sourceList_;
1034 _H<NSArray> packages_;
1036 _transient NSObject<DatabaseDelegate> *delegate_;
1037 _transient NSObject<ProgressDelegate> *progress_;
1039 CydiaStatus status_;
1045 std::map<const char *, _H<NSString> > sections_;
1048 + (Database *) sharedInstance;
1050 - (bool) hasPackages;
1052 - (void) _readCydia:(NSNumber *)fd;
1053 - (void) _readStatus:(NSNumber *)fd;
1054 - (void) _readOutput:(NSNumber *)fd;
1058 - (Package *) packageWithName:(NSString *)name;
1060 - (pkgCacheFile &) cache;
1061 - (pkgDepCache::Policy *) policy;
1062 - (pkgRecords *) records;
1063 - (pkgProblemResolver *) resolver;
1064 - (pkgAcquire &) fetcher;
1065 - (pkgSourceList &) list;
1066 - (NSArray *) packages;
1067 - (NSArray *) sources;
1068 - (Source *) sourceWithKey:(NSString *)key;
1069 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1077 - (void) updateWithStatus:(CancelStatus &)status;
1079 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1081 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1082 - (NSObject<ProgressDelegate> *) progressDelegate;
1084 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1085 - (void) setFetch:(bool)fetch forURI:(const char *)uri;
1086 - (void) resetFetch;
1088 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1092 /* SourceStatus {{{ */
1093 class SourceStatus :
1097 _transient NSObject<FetchDelegate> *delegate_;
1098 _transient Database *database_;
1099 std::set<std::string> fetches_;
1102 SourceStatus(NSObject<FetchDelegate> *delegate, Database *database) :
1103 delegate_(delegate),
1108 void Set(bool fetch, const std::string &uri) {
1110 if (!fetches_.insert(uri).second)
1113 if (fetches_.erase(uri) == 0)
1117 //printf("Set(%s, %s)\n", fetch ? "true" : "false", uri.c_str());
1119 auto slash(uri.rfind('/'));
1120 if (slash != std::string::npos)
1121 [database_ setFetch:fetch forURI:uri.substr(0, slash).c_str()];
1124 _finline void Set(bool fetch, pkgAcquire::Item *item) {
1125 /*unsigned long ID(fetch ? 1 : 0);
1129 Set(fetch, item->DescURI());
1132 void Log(const char *tag, pkgAcquire::Item *item) {
1133 //printf("%s(%s) S:%u Q:%u\n", tag, item->DescURI().c_str(), item->Status, item->QueueCounter);
1136 virtual void Fetch(pkgAcquire::ItemDesc &desc) {
1137 Log("Fetch", desc.Owner);
1138 Set(true, desc.Owner);
1141 virtual void Done(pkgAcquire::ItemDesc &desc) {
1142 Log("Done", desc.Owner);
1143 Set(false, desc.Owner);
1146 virtual void Fail(pkgAcquire::ItemDesc &desc) {
1147 Log("Fail", desc.Owner);
1148 Set(false, desc.Owner);
1151 virtual bool Pulse_(pkgAcquire *Owner) {
1152 std::set<std::string> fetches;
1153 for (pkgAcquire::ItemCIterator item(Owner->ItemsBegin()); item != Owner->ItemsEnd(); ++item) {
1155 if ((*item)->QueueCounter == 0)
1157 else switch ((*item)->Status) {
1158 case pkgAcquire::Item::StatFetching:
1159 fetches.insert((*item)->DescURI());
1168 Log(fetch ? "Pulse<true>" : "Pulse<false>", *item);
1172 std::vector<std::string> stops;
1173 std::set_difference(fetches_.begin(), fetches_.end(), fetches.begin(), fetches.end(), std::back_insert_iterator<std::vector<std::string>>(stops));
1174 for (std::vector<std::string>::const_iterator stop(stops.begin()); stop != stops.end(); ++stop) {
1175 //printf("Stop(%s)\n", stop->c_str());
1179 return ![delegate_ isSourceCancelled];
1182 virtual void Stop() {
1183 pkgAcquireStatus::Stop();
1184 [database_ resetFetch];
1188 /* ProgressEvent Implementation {{{ */
1189 @implementation CydiaProgressEvent
1191 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1192 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1195 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1196 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1197 [event setPackage:package];
1201 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItemDesc:(pkgAcquire::ItemDesc &)desc {
1202 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1204 NSString *description([NSString stringWithUTF8String:desc.Description.c_str()]);
1205 NSArray *fields([description componentsSeparatedByString:@" "]);
1206 [event setItem:fields];
1208 if ([fields count] > 3) {
1209 [event setPackage:[fields objectAtIndex:2]];
1210 [event setVersion:[fields objectAtIndex:3]];
1213 [event setURL:[NSString stringWithUTF8String:desc.URI.c_str()]];
1218 + (NSArray *) _attributeKeys {
1219 return [NSArray arrayWithObjects:
1229 - (NSArray *) attributeKeys {
1230 return [[self class] _attributeKeys];
1233 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1234 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1237 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1238 if ((self = [super init]) != nil) {
1244 - (NSString *) message {
1248 - (NSString *) type {
1252 - (NSArray *) item {
1253 return (id) item_ ?: [NSNull null];
1256 - (void) setItem:(NSArray *)item {
1260 - (NSString *) package {
1261 return (id) package_ ?: [NSNull null];
1264 - (void) setPackage:(NSString *)package {
1268 - (NSString *) url {
1269 return (id) url_ ?: [NSNull null];
1272 - (void) setURL:(NSString *)url {
1276 - (void) setVersion:(NSString *)version {
1280 - (NSString *) version {
1281 return (id) version_ ?: [NSNull null];
1284 - (NSString *) compound:(NSString *)value {
1286 NSString *mode(nil); {
1287 NSString *type([self type]);
1288 if ([type isEqualToString:kCydiaProgressEventTypeError])
1289 mode = UCLocalize("ERROR");
1290 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1291 mode = UCLocalize("WARNING");
1295 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1301 - (NSString *) compoundMessage {
1302 return [self compound:[self message]];
1305 - (NSString *) compoundTitle {
1308 if (package_ == nil)
1310 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1311 title = [package name];
1315 return [self compound:title];
1321 // Cytore Definitions {{{
1322 struct PackageValue :
1325 Cytore::Offset<PackageValue> next_;
1327 uint32_t index_ : 23;
1328 uint32_t subscribed_ : 1;
1345 Cytore::Offset<PackageValue> packages_[1 << 16];
1348 static Cytore::File<MetaValue> MetaFile_;
1350 // Cytore Helper Functions {{{
1351 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1352 SplitHash nhash = { hashlittle(name, length) };
1354 PackageValue *metadata;
1356 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1357 for (;; offset = &metadata->next_) { if (offset->IsNull()) {
1358 *offset = MetaFile_.New<PackageValue>(length + 1);
1359 metadata = &MetaFile_.Get(*offset);
1361 if (metadata == NULL) {
1365 metadata = new PackageValue();
1366 memset(metadata, 0, sizeof(*metadata));
1369 memcpy(metadata->name_, name, length);
1370 metadata->name_[length] = '\0';
1371 metadata->nhash_ = nhash.u16[1];
1373 metadata = &MetaFile_.Get(*offset);
1374 if (metadata->nhash_ != nhash.u16[1])
1376 if (strncmp(metadata->name_, name, length) != 0)
1378 if (metadata->name_[length] != '\0')
1385 static void PackageImport(const void *key, const void *value, void *context) {
1386 bool &fail(*reinterpret_cast<bool *>(context));
1389 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1390 NSLog(@"failed to import package %@", key);
1394 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1395 NSDictionary *package((NSDictionary *) value);
1397 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1398 if ([subscribed boolValue] && !metadata->subscribed_)
1399 metadata->subscribed_ = true;
1401 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1402 time_t time([date timeIntervalSince1970]);
1403 if (metadata->first_ > time || metadata->first_ == 0)
1404 metadata->first_ = time;
1407 NSDate *date([package objectForKey:@"LastSeen"]);
1408 NSString *version([package objectForKey:@"LastVersion"]);
1410 if (date != nil && version != nil) {
1411 time_t time([date timeIntervalSince1970]);
1412 if (metadata->last_ < time || metadata->last_ == 0)
1413 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1414 size_t length(strlen(buffer));
1415 uint16_t vhash(hashlittle(buffer, length));
1417 size_t capped(std::min<size_t>(8, length));
1418 char *latest(buffer + length - capped);
1420 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1421 metadata->vhash_ = vhash;
1423 metadata->last_ = time;
1429 static NSDate *GetStatusDate() {
1430 return [[[NSFileManager defaultManager] attributesOfItemAtPath:@"/var/lib/dpkg/status" error:NULL] fileModificationDate];
1433 static void SaveConfig(NSObject *lock) {
1434 @synchronized (lock) {
1440 CFPreferencesSetMultiple((CFDictionaryRef) [NSDictionary dictionaryWithObjectsAndKeys:
1441 Values_, @"CydiaValues",
1442 Sections_, @"CydiaSections",
1443 (id) Sources_, @"CydiaSources",
1444 Version_, @"CydiaVersion",
1445 nil], NULL, CFSTR("com.saurik.Cydia"), kCFPreferencesCurrentUser, kCFPreferencesCurrentHost);
1447 if (!CFPreferencesAppSynchronize(CFSTR("com.saurik.Cydia")))
1448 NSLog(@"CFPreferencesAppSynchronize(com.saurik.Cydia) == false");
1450 CydiaWriteSources();
1453 /* Source Class {{{ */
1454 @interface Source : NSObject {
1456 Database *database_;
1459 CYString depiction_;
1460 CYString description_;
1466 CYString distribution_;
1472 _H<NSString> authority_;
1474 CYString defaultIcon_;
1476 _H<NSMutableDictionary> record_;
1479 std::set<std::string> fetches_;
1480 std::set<std::string> files_;
1481 _transient NSObject<SourceDelegate> *delegate_;
1484 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(CYPool *)pool;
1486 - (NSComparisonResult) compareByName:(Source *)source;
1488 - (NSString *) depictionForPackage:(NSString *)package;
1489 - (NSString *) supportForPackage:(NSString *)package;
1491 - (metaIndex *) metaIndex;
1492 - (NSDictionary *) record;
1495 - (NSString *) rooturi;
1496 - (NSString *) distribution;
1497 - (NSString *) type;
1500 - (NSString *) host;
1502 - (NSString *) name;
1503 - (NSString *) shortDescription;
1504 - (NSString *) label;
1505 - (NSString *) origin;
1506 - (NSString *) version;
1508 - (NSString *) defaultIcon;
1509 - (NSURL *) iconURL;
1511 - (void) setFetch:(bool)fetch forURI:(const char *)uri;
1512 - (void) resetFetch;
1516 @implementation Source
1518 + (NSString *) webScriptNameForSelector:(SEL)selector {
1520 else if (selector == @selector(addSection:))
1521 return @"addSection";
1522 else if (selector == @selector(getField:))
1524 else if (selector == @selector(removeSection:))
1525 return @"removeSection";
1526 else if (selector == @selector(remove))
1532 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1533 return [self webScriptNameForSelector:selector] == nil;
1536 + (NSArray *) _attributeKeys {
1537 return [NSArray arrayWithObjects:
1548 @"shortDescription",
1555 - (NSArray *) attributeKeys {
1556 return [[self class] _attributeKeys];
1559 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1560 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1563 - (metaIndex *) metaIndex {
1567 - (void) setMetaIndex:(metaIndex *)index inPool:(CYPool *)pool {
1568 trusted_ = index->IsTrusted();
1570 uri_.set(pool, index->GetURI());
1571 distribution_.set(pool, index->GetDist());
1572 type_.set(pool, index->GetType());
1574 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1575 if (dindex != NULL) {
1576 std::string file(dindex->MetaIndexURI(""));
1577 base_.set(pool, file);
1580 _profile(Source$setMetaIndex$GetIndexes)
1581 dindex->GetIndexes(&acquire, true);
1583 _profile(Source$setMetaIndex$DescURI)
1584 for (pkgAcquire::ItemIterator item(acquire.ItemsBegin()); item != acquire.ItemsEnd(); item++) {
1585 std::string file((*item)->DescURI());
1586 auto slash(file.rfind('/'));
1587 if (slash == std::string::npos)
1589 files_.insert(file.substr(0, slash));
1594 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1597 pkgTagFile tags(&fd);
1599 pkgTagSection section;
1606 {"default-icon", &defaultIcon_},
1607 {"depiction", &depiction_},
1608 {"description", &description_},
1610 {"origin", &origin_},
1611 {"support", &support_},
1612 {"version", &version_},
1615 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1616 const char *start, *end;
1618 if (section.Find(names[i].name_, start, end)) {
1619 CYString &value(*names[i].value_);
1620 value.set(pool, start, end - start);
1626 record_ = [Sources_ objectForKey:[self key]];
1628 NSURL *url([NSURL URLWithString:uri_]);
1632 host_ = [host_ lowercaseString];
1637 authority_ = [url path];
1640 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(CYPool *)pool {
1641 if ((self = [super init]) != nil) {
1642 era_ = [database era];
1643 database_ = database;
1646 _profile(Source$initWithMetaIndex$setMetaIndex)
1647 [self setMetaIndex:index inPool:pool];
1652 - (NSString *) getField:(NSString *)name {
1653 @synchronized (database_) {
1654 if ([database_ era] != era_ || index_ == NULL)
1657 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index_));
1662 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly)) {
1667 pkgTagFile tags(&fd);
1669 pkgTagSection section;
1672 const char *start, *end;
1673 if (!section.Find([name UTF8String], start, end))
1674 return (NSString *) [NSNull null];
1676 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
1679 - (NSComparisonResult) compareByName:(Source *)source {
1680 NSString *lhs = [self name];
1681 NSString *rhs = [source name];
1683 if ([lhs length] != 0 && [rhs length] != 0) {
1684 unichar lhc = [lhs characterAtIndex:0];
1685 unichar rhc = [rhs characterAtIndex:0];
1687 if (isalpha(lhc) && !isalpha(rhc))
1688 return NSOrderedAscending;
1689 else if (!isalpha(lhc) && isalpha(rhc))
1690 return NSOrderedDescending;
1693 return [lhs compare:rhs options:LaxCompareOptions_];
1696 - (NSString *) depictionForPackage:(NSString *)package {
1697 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1700 - (NSString *) supportForPackage:(NSString *)package {
1701 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1704 - (NSArray *) sections {
1705 return record_ == nil ? (id) [NSNull null] : [record_ objectForKey:@"Sections"] ?: [NSArray array];
1708 - (void) _addSection:(NSString *)section {
1711 else if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) {
1712 if (![sections containsObject:section])
1713 [sections addObject:section];
1715 [record_ setObject:[NSMutableArray arrayWithObject:section] forKey:@"Sections"];
1718 - (bool) addSection:(NSString *)section {
1722 [self performSelectorOnMainThread:@selector(_addSection:) withObject:section waitUntilDone:NO];
1726 - (void) _removeSection:(NSString *)section {
1730 if (NSMutableArray *sections = [record_ objectForKey:@"Sections"])
1731 if ([sections containsObject:section])
1732 [sections removeObject:section];
1735 - (bool) removeSection:(NSString *)section {
1739 [self performSelectorOnMainThread:@selector(_removeSection:) withObject:section waitUntilDone:NO];
1744 [Sources_ removeObjectForKey:[self key]];
1748 bool value(record_ != nil);
1749 [self performSelectorOnMainThread:@selector(_remove) withObject:nil waitUntilDone:NO];
1753 - (NSDictionary *) record {
1761 - (NSString *) rooturi {
1765 - (NSString *) distribution {
1766 return distribution_;
1769 - (NSString *) type {
1773 - (NSString *) baseuri {
1774 return base_.empty() ? nil : (id) base_;
1777 - (NSString *) iconuri {
1778 if (NSString *base = [self baseuri])
1779 return [base stringByAppendingString:@"CydiaIcon.png"];
1784 - (NSURL *) iconURL {
1785 if (NSString *uri = [self iconuri])
1786 return [NSURL URLWithString:uri];
1790 - (NSString *) key {
1791 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1794 - (NSString *) host {
1798 - (NSString *) name {
1799 return origin_.empty() ? (id) authority_ : origin_;
1802 - (NSString *) shortDescription {
1803 return description_;
1806 - (NSString *) label {
1807 return label_.empty() ? (id) authority_ : label_;
1810 - (NSString *) origin {
1814 - (NSString *) version {
1818 - (NSString *) defaultIcon {
1819 return defaultIcon_;
1822 - (void) setDelegate:(NSObject<SourceDelegate> *)delegate {
1823 delegate_ = delegate;
1827 return !fetches_.empty();
1830 - (void) setFetch:(bool)fetch forURI:(const char *)uri {
1832 if (fetches_.erase(uri) == 0)
1834 } else if (files_.find(uri) == files_.end())
1836 else if (!fetches_.insert(uri).second)
1839 [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:[self fetch]] waitUntilDone:NO];
1842 - (void) resetFetch {
1844 [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:NO];
1849 /* CydiaOperation Class {{{ */
1850 @interface CydiaOperation : NSObject {
1851 _H<NSString> operator_;
1852 _H<NSString> value_;
1855 - (NSString *) operator;
1856 - (NSString *) value;
1860 @implementation CydiaOperation
1862 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1863 if ((self = [super init]) != nil) {
1864 operator_ = [NSString stringWithUTF8String:_operator];
1865 value_ = [NSString stringWithUTF8String:value];
1869 + (NSArray *) _attributeKeys {
1870 return [NSArray arrayWithObjects:
1876 - (NSArray *) attributeKeys {
1877 return [[self class] _attributeKeys];
1880 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1881 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1884 - (NSString *) operator {
1888 - (NSString *) value {
1894 /* CydiaClause Class {{{ */
1895 @interface CydiaClause : NSObject {
1896 _H<NSString> package_;
1897 _H<CydiaOperation> version_;
1900 - (NSString *) package;
1901 - (CydiaOperation *) version;
1905 @implementation CydiaClause
1907 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1908 if ((self = [super init]) != nil) {
1909 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1911 if (const char *version = dep.TargetVer())
1912 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1914 version_ = (id) [NSNull null];
1918 + (NSArray *) _attributeKeys {
1919 return [NSArray arrayWithObjects:
1925 - (NSArray *) attributeKeys {
1926 return [[self class] _attributeKeys];
1929 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1930 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1933 - (NSString *) package {
1937 - (CydiaOperation *) version {
1943 /* CydiaRelation Class {{{ */
1944 @interface CydiaRelation : NSObject {
1945 _H<NSString> relationship_;
1946 _H<NSMutableArray> clauses_;
1949 - (NSString *) relationship;
1950 - (NSArray *) clauses;
1954 @implementation CydiaRelation
1956 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1957 if ((self = [super init]) != nil) {
1958 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
1959 clauses_ = [NSMutableArray arrayWithCapacity:8];
1961 pkgCache::DepIterator start;
1962 pkgCache::DepIterator end;
1963 dep.GlobOr(start, end); // ++dep
1966 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1968 // yes, seriously. (wtf?)
1976 + (NSArray *) _attributeKeys {
1977 return [NSArray arrayWithObjects:
1983 - (NSArray *) attributeKeys {
1984 return [[self class] _attributeKeys];
1987 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1988 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1991 - (NSString *) relationship {
1992 return relationship_;
1995 - (NSArray *) clauses {
1999 - (void) addClause:(CydiaClause *)clause {
2000 [clauses_ addObject:clause];
2005 /* Package Class {{{ */
2006 struct ParsedPackage {
2010 CYString architecture_;
2013 CYString depiction_;
2020 @interface Package : NSObject {
2022 @public uint32_t role_ : 3;
2023 uint32_t essential_ : 1;
2024 uint32_t obsolete_ : 1;
2025 uint32_t ignored_ : 1;
2026 uint32_t pooled_ : 1;
2032 _transient Database *database_;
2034 pkgCache::VerIterator version_;
2035 pkgCache::PkgIterator iterator_;
2036 pkgCache::VerFileIterator file_;
2040 CYString transform_;
2043 CYString installed_;
2046 const char *section_;
2047 _transient NSString *section$_;
2051 PackageValue *metadata_;
2052 ParsedPackage *parsed_;
2054 _H<NSMutableArray> tags_;
2057 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database;
2058 + (Package *) newPackageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database;
2060 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database;
2062 - (pkgCache::PkgIterator) iterator;
2065 - (NSString *) section;
2066 - (NSString *) simpleSection;
2068 - (NSString *) longSection;
2069 - (NSString *) shortSection;
2073 - (MIMEAddress *) maintainer;
2075 - (NSString *) longDescription;
2076 - (NSString *) shortDescription;
2079 - (PackageValue *) metadata;
2082 - (bool) subscribed;
2083 - (bool) setSubscribed:(bool)subscribed;
2087 - (NSString *) latest;
2088 - (NSString *) installed;
2089 - (BOOL) uninstalled;
2091 - (BOOL) upgradableAndEssential:(BOOL)essential;
2094 - (BOOL) unfiltered;
2098 - (BOOL) halfConfigured;
2099 - (BOOL) halfInstalled;
2101 - (NSString *) mode;
2104 - (NSString *) name;
2106 - (NSString *) homepage;
2107 - (NSString *) depiction;
2108 - (MIMEAddress *) author;
2110 - (NSString *) support;
2112 - (NSArray *) files;
2113 - (NSArray *) warnings;
2114 - (NSArray *) applications;
2116 - (Source *) source;
2119 - (BOOL) matches:(NSArray *)query;
2121 - (BOOL) hasTag:(NSString *)tag;
2122 - (NSString *) primaryPurpose;
2123 - (NSArray *) purposes;
2124 - (bool) isCommercial;
2126 - (void) setIndex:(size_t)index;
2128 - (CYString &) cyname;
2130 - (uint32_t) compareBySection:(NSArray *)sections;
2137 uint32_t PackageChangesRadix(Package *self, void *) {
2142 uint32_t timestamp : 30;
2143 uint32_t ignored : 1;
2144 uint32_t upgradable : 1;
2148 bool upgradable([self upgradableAndEssential:YES]);
2149 value.bits.upgradable = upgradable ? 1 : 0;
2152 value.bits.timestamp = 0;
2153 value.bits.ignored = [self ignored] ? 0 : 1;
2154 value.bits.upgradable = 1;
2156 value.bits.timestamp = [self seen] >> 2;
2157 value.bits.ignored = 0;
2158 value.bits.upgradable = 0;
2161 return _not(uint32_t) - value.key;
2164 CYString &(*PackageName)(Package *self, SEL sel);
2166 uint32_t PackagePrefixRadix(Package *self, void *context) {
2167 size_t offset(reinterpret_cast<size_t>(context));
2168 CYString &name(PackageName(self, @selector(cyname)));
2170 size_t size(name.size());
2173 char *text(name.data());
2176 if (!isdigit(text[0]))
2180 while (size != digits && isdigit(text[digits]))
2188 if (offset == 0 && zeros != 0) {
2189 memset(data, '0', zeros);
2190 memcpy(data + zeros, text, 4 - zeros);
2192 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2193 if (size <= offset - zeros)
2196 text += offset - zeros;
2197 size -= offset - zeros;
2200 memcpy(data, text, 4);
2202 memcpy(data, text, size);
2203 memset(data + size, 0, 4 - size);
2206 for (size_t i(0); i != 4; ++i)
2207 if (isalpha(data[i]))
2215 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2217 /* XXX: ntohl may be more honest */
2218 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2221 CFComparisonResult StringNameCompare(CFStringRef lhn, CFStringRef rhn, size_t length) {
2222 _profile(PackageNameCompare)
2224 return rhn == NULL ? kCFCompareEqualTo : kCFCompareLessThan;
2225 else if (rhn == NULL)
2226 return kCFCompareGreaterThan;
2228 CFIndex length(CFStringGetLength(lhn));
2230 _profile(PackageNameCompare$NumbersLast)
2231 if (length != 0 && CFStringGetLength(rhn) != 0) {
2232 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2233 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2234 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2235 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2236 return lha ? kCFCompareLessThan : kCFCompareGreaterThan;
2240 _profile(PackageNameCompare$Compare)
2241 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, (CFLocaleRef) (id) CollationLocale_);
2246 _finline CFComparisonResult StringNameCompare(NSString *lhn, NSString*rhn, size_t length) {
2247 return StringNameCompare((CFStringRef) lhn, (CFStringRef) rhn, length);
2250 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2251 CYString &lhn(PackageName(lhs, @selector(cyname)));
2252 NSString *rhn(PackageName(rhs, @selector(cyname)));
2253 return StringNameCompare(lhn, rhn, lhn.size());
2256 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *arg) {
2257 return PackageNameCompare(*lhs, *rhs, arg);
2260 struct PackageNameOrdering :
2261 std::binary_function<Package *, Package *, bool>
2263 _finline bool operator ()(Package *lhs, Package *rhs) const {
2264 return PackageNameCompare(lhs, rhs, NULL) == kCFCompareLessThan;
2268 @implementation Package
2270 - (NSString *) description {
2271 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2277 if (parsed_ != NULL)
2282 + (NSString *) webScriptNameForSelector:(SEL)selector {
2284 else if (selector == @selector(clear))
2286 else if (selector == @selector(getField:))
2288 else if (selector == @selector(getRecord))
2289 return @"getRecord";
2290 else if (selector == @selector(hasTag:))
2292 else if (selector == @selector(install))
2294 else if (selector == @selector(remove))
2300 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2301 return [self webScriptNameForSelector:selector] == nil;
2304 + (NSArray *) _attributeKeys {
2305 return [NSArray arrayWithObjects:
2326 @"shortDescription",
2339 - (NSArray *) attributeKeys {
2340 return [[self class] _attributeKeys];
2343 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2344 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2347 - (NSArray *) relations {
2348 @synchronized (database_) {
2349 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2350 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2351 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2355 - (NSString *) architecture {
2357 @synchronized (database_) {
2358 return parsed_->architecture_.empty() ? [NSNull null] : (id) parsed_->architecture_;
2361 - (NSString *) getField:(NSString *)name {
2362 @synchronized (database_) {
2363 if ([database_ era] != era_ || file_.end())
2366 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2368 const char *start, *end;
2369 if (!parser.Find([name UTF8String], start, end))
2370 return (NSString *) [NSNull null];
2372 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2375 - (NSString *) getRecord {
2376 @synchronized (database_) {
2377 if ([database_ era] != era_ || file_.end())
2380 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2382 const char *start, *end;
2383 parser.GetRec(start, end);
2385 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2389 if (parsed_ != NULL)
2391 @synchronized (database_) {
2392 if ([database_ era] != era_ || file_.end())
2395 ParsedPackage *parsed(new ParsedPackage);
2398 _profile(Package$parse)
2399 pkgRecords::Parser *parser;
2401 _profile(Package$parse$Lookup)
2402 parser = &[database_ records]->Lookup(file_);
2408 _profile(Package$parse$Find)
2413 {"architecture", &parsed->architecture_},
2414 {"icon", &parsed->icon_},
2415 {"depiction", &parsed->depiction_},
2416 {"homepage", &parsed->homepage_},
2417 {"website", &website},
2419 {"support", &parsed->support_},
2420 {"author", &parsed->author_},
2421 {"md5sum", &parsed->md5sum_},
2424 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2425 const char *start, *end;
2427 if (parser->Find(names[i].name_, start, end)) {
2428 CYString &value(*names[i].value_);
2429 _profile(Package$parse$Value)
2430 value.set(pool_, start, end - start);
2436 _profile(Package$parse$Tagline)
2437 parsed->tagline_.set(pool_, parser->ShortDesc());
2440 _profile(Package$parse$Retain)
2441 if (parsed->homepage_.empty())
2442 parsed->homepage_ = website;
2443 if (parsed->homepage_ == parsed->depiction_)
2444 parsed->homepage_.clear();
2445 if (parsed->support_.empty())
2446 parsed->support_ = bugs;
2451 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database {
2452 if ((self = [super init]) != nil) {
2453 _profile(Package$initWithVersion)
2455 pool_ = new CYPool();
2461 database_ = database;
2462 era_ = [database era];
2466 pkgCache::PkgIterator iterator(version_.ParentPkg());
2467 iterator_ = iterator;
2469 _profile(Package$initWithVersion$Version)
2470 file_ = version_.FileList();
2473 _profile(Package$initWithVersion$Cache)
2474 name_.set(NULL, version_.Display());
2476 latest_.set(NULL, StripVersion_(version_.VerStr()));
2478 pkgCache::VerIterator current(iterator.CurrentVer());
2480 installed_.set(NULL, StripVersion_(current.VerStr()));
2483 _profile(Package$initWithVersion$Transliterate) do {
2484 if (CollationTransl_ == NULL)
2489 _profile(Package$initWithVersion$Transliterate$utf8)
2490 const uint8_t *data(reinterpret_cast<const uint8_t *>(name_.data()));
2491 for (size_t i(0), e(name_.size()); i != e; ++i)
2492 if (data[i] >= 0x80)
2497 UErrorCode code(U_ZERO_ERROR);
2500 _profile(Package$initWithVersion$Transliterate$u_strFromUTF8WithSub)
2501 CollationString_.resize(name_.size());
2502 u_strFromUTF8WithSub(&CollationString_[0], CollationString_.size(), &length, name_.data(), name_.size(), 0xfffd, NULL, &code);
2503 if (!U_SUCCESS(code))
2505 CollationString_.resize(length);
2508 _profile(Package$initWithVersion$Transliterate$utrans_trans)
2509 length = CollationString_.size();
2510 utrans_trans(CollationTransl_, reinterpret_cast<UReplaceable *>(&CollationString_), &CollationUCalls_, 0, &length, &code);
2511 if (!U_SUCCESS(code))
2513 _assert(CollationString_.size() == length);
2516 _profile(Package$initWithVersion$Transliterate$u_strToUTF8WithSub$preflight)
2517 u_strToUTF8WithSub(NULL, 0, &length, CollationString_.data(), CollationString_.size(), 0xfffd, NULL, &code);
2518 if (code == U_BUFFER_OVERFLOW_ERROR)
2519 code = U_ZERO_ERROR;
2520 else if (!U_SUCCESS(code))
2525 _profile(Package$initWithVersion$Transliterate$apr_palloc)
2526 transform = pool_->malloc<char>(length);
2528 _profile(Package$initWithVersion$Transliterate$u_strToUTF8WithSub$transform)
2529 u_strToUTF8WithSub(transform, length, NULL, CollationString_.data(), CollationString_.size(), 0xfffd, NULL, &code);
2530 if (!U_SUCCESS(code))
2534 transform_.set(NULL, transform, length);
2535 } while (false); _end
2537 _profile(Package$initWithVersion$Tags)
2539 pkgCache::TagIterator tag(version_.TagList());
2541 pkgCache::TagIterator tag(iterator.TagList());
2544 tags_ = [NSMutableArray arrayWithCapacity:8];
2546 goto tag; for (; !tag.end(); ++tag) tag: {
2547 const char *name(tag.Name());
2548 NSString *string((NSString *) CYStringCreate(name));
2552 [tags_ addObject:[string autorelease]];
2554 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2555 if (strcmp(name + 6, "enduser") == 0)
2557 else if (strcmp(name + 6, "hacker") == 0)
2559 else if (strcmp(name + 6, "developer") == 0)
2561 else if (strcmp(name + 6, "cydia") == 0)
2567 if (strncmp(name, "cydia::", 7) == 0) {
2568 if (strcmp(name + 7, "essential") == 0)
2570 else if (strcmp(name + 7, "obsolete") == 0)
2577 _profile(Package$initWithVersion$Metadata)
2578 const char *mixed(iterator.Name());
2579 size_t size(strlen(mixed));
2580 static const size_t prefix(sizeof("/var/lib/dpkg/info/") - 1);
2581 char lower[prefix + size + 5 + 1];
2583 for (size_t i(0); i != size; ++i)
2584 lower[prefix + i] = mixed[i] | 0x20;
2586 if (!installed_.empty()) {
2587 memcpy(lower, "/var/lib/dpkg/info/", prefix);
2588 memcpy(lower + prefix + size, ".list", 6);
2590 if (stat(lower, &info) != -1)
2591 upgraded_ = info.st_birthtime;
2594 PackageValue *metadata(PackageFind(lower + prefix, size));
2595 metadata_ = metadata;
2597 id_.set(NULL, metadata->name_, size);
2599 const char *latest(version_.VerStr());
2600 size_t length(strlen(latest));
2602 uint16_t vhash(hashlittle(latest, length));
2604 size_t capped(std::min<size_t>(8, length));
2605 latest = latest + length - capped;
2607 if (metadata->first_ == 0)
2608 metadata->first_ = now_;
2610 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2611 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2612 metadata->vhash_ = vhash;
2613 metadata->last_ = now_;
2614 } else if (metadata->last_ == 0)
2615 metadata->last_ = metadata->first_;
2618 _profile(Package$initWithVersion$Section)
2619 section_ = version_.Section();
2622 _profile(Package$initWithVersion$Flags)
2623 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2624 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2629 + (Package *) newPackageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database {
2630 pkgCache::VerIterator version;
2632 _profile(Package$packageWithIterator$GetCandidateVer)
2633 version = [database policy]->GetCandidateVer(iterator);
2641 _profile(Package$packageWithIterator$Allocate)
2642 package = [Package allocWithZone:zone];
2645 _profile(Package$packageWithIterator$Initialize)
2647 initWithVersion:version
2657 // XXX: just in case a Cydia extension is using this (I bet this is unlikely, though, due to CYPool?)
2658 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database {
2659 return [[self newPackageWithIterator:iterator withZone:zone inPool:pool database:database] autorelease];
2662 - (pkgCache::PkgIterator) iterator {
2666 - (NSArray *) downgrades {
2667 NSMutableArray *versions([NSMutableArray arrayWithCapacity:4]);
2669 for (auto version(iterator_.VersionList()); !version.end(); ++version) {
2670 if (version == version_)
2672 Package *package([[[Package allocWithZone:NULL] initWithVersion:version withZone:NULL inPool:NULL database:database_] autorelease]);
2673 if ([package source] == nil)
2675 [versions addObject:package];
2681 - (NSString *) section {
2682 if (section$_ == nil) {
2683 if (section_ == NULL)
2686 _profile(Package$section$mappedSectionForPointer)
2687 section$_ = [database_ mappedSectionForPointer:section_];
2692 - (NSString *) simpleSection {
2693 if (NSString *section = [self section])
2694 return Simplify(section);
2699 - (NSString *) longSection {
2700 if (NSString *section = [self section])
2701 return LocalizeSection(section);
2706 - (NSString *) shortSection {
2707 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2710 - (NSString *) uri {
2713 pkgIndexFile *index;
2714 pkgCache::PkgFileIterator file(file_.File());
2715 if (![database_ list].FindIndex(file, index))
2717 return [NSString stringWithUTF8String:iterator_->Path];
2718 //return [NSString stringWithUTF8String:file.Site()];
2719 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2723 - (MIMEAddress *) maintainer {
2724 @synchronized (database_) {
2725 if ([database_ era] != era_ || file_.end())
2728 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2729 const std::string &maintainer(parser->Maintainer());
2730 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2733 - (NSString *) md5sum {
2734 return parsed_ == NULL ? nil : (id) parsed_->md5sum_;
2738 @synchronized (database_) {
2739 if ([database_ era] != era_ || version_.end())
2742 return version_->InstalledSize;
2745 - (NSString *) longDescription {
2746 @synchronized (database_) {
2747 if ([database_ era] != era_ || file_.end())
2750 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2751 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2753 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2754 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2755 if ([lines count] < 2)
2758 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2759 for (size_t i(1), e([lines count]); i != e; ++i) {
2760 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2761 [trimmed addObject:trim];
2764 return [trimmed componentsJoinedByString:@"\n"];
2767 - (NSString *) shortDescription {
2768 if (parsed_ != NULL)
2769 return static_cast<NSString *>(parsed_->tagline_);
2771 @synchronized (database_) {
2772 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2773 std::string value(parser.ShortDesc());
2776 if (value.size() > 200)
2778 return [(id) CYStringCreate(value) autorelease];
2782 _profile(Package$index)
2783 CFStringRef name((CFStringRef) [self name]);
2784 if (CFStringGetLength(name) == 0)
2786 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2787 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2789 return toupper(character);
2793 - (PackageValue *) metadata {
2798 PackageValue *metadata([self metadata]);
2799 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2802 - (bool) subscribed {
2803 return [self metadata]->subscribed_;
2806 - (bool) setSubscribed:(bool)subscribed {
2807 PackageValue *metadata([self metadata]);
2808 if (metadata->subscribed_ == subscribed)
2810 metadata->subscribed_ = subscribed;
2818 - (NSString *) latest {
2822 - (NSString *) installed {
2826 - (BOOL) uninstalled {
2827 return installed_.empty();
2830 - (BOOL) upgradableAndEssential:(BOOL)essential {
2831 _profile(Package$upgradableAndEssential)
2832 pkgCache::VerIterator current(iterator_.CurrentVer());
2834 return essential && essential_;
2836 return version_ != current;
2840 - (BOOL) essential {
2845 return [database_ cache][iterator_].InstBroken();
2848 - (BOOL) unfiltered {
2849 _profile(Package$unfiltered$obsolete)
2850 if (_unlikely(obsolete_))
2854 _profile(Package$unfiltered$role)
2855 if (_unlikely(role_ > 3))
2863 if (![self unfiltered])
2868 _profile(Package$visible$section)
2869 section = [self section];
2872 _profile(Package$visible$isSectionVisible)
2873 if (!isSectionVisible(section))
2881 unsigned char current(iterator_->CurrentState);
2882 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2885 - (BOOL) halfConfigured {
2886 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2889 - (BOOL) halfInstalled {
2890 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2894 @synchronized (database_) {
2895 if ([database_ era] != era_ || iterator_.end())
2898 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2899 return state.Mode != pkgDepCache::ModeKeep;
2902 - (NSString *) mode {
2903 @synchronized (database_) {
2904 if ([database_ era] != era_ || iterator_.end())
2907 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2909 switch (state.Mode) {
2910 case pkgDepCache::ModeDelete:
2911 if ((state.iFlags & pkgDepCache::Purge) != 0)
2915 case pkgDepCache::ModeKeep:
2916 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2917 return @"REINSTALL";
2918 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2922 case pkgDepCache::ModeInstall:
2923 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2924 return @"REINSTALL";
2925 else*/ switch (state.Status) {
2927 return @"DOWNGRADE";
2933 return @"NEW_INSTALL";
2944 - (NSString *) name {
2945 return name_.empty() ? id_ : name_;
2948 - (UIImage *) icon {
2949 NSString *section = [self simpleSection];
2952 if (parsed_ != NULL)
2953 if (NSString *href = parsed_->icon_)
2954 if ([href hasPrefix:@"file:///"])
2955 icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2956 if (icon == nil) if (section != nil)
2957 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]];
2958 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2959 if ([dicon hasPrefix:@"file:///"])
2960 icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2962 icon = [UIImage imageNamed:@"unknown.png"];
2966 - (NSString *) homepage {
2967 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2970 - (NSString *) depiction {
2971 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2974 - (MIMEAddress *) author {
2975 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
2978 - (NSString *) support {
2979 return parsed_ != NULL && !parsed_->support_.empty() ? parsed_->support_ : [[self source] supportForPackage:id_];
2982 - (NSArray *) files {
2983 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2984 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2987 fin.open([path UTF8String]);
2992 while (std::getline(fin, line))
2993 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2998 - (NSString *) state {
2999 @synchronized (database_) {
3000 if ([database_ era] != era_ || file_.end())
3003 switch (iterator_->CurrentState) {
3004 case pkgCache::State::NotInstalled:
3005 return @"NotInstalled";
3006 case pkgCache::State::UnPacked:
3008 case pkgCache::State::HalfConfigured:
3009 return @"HalfConfigured";
3010 case pkgCache::State::HalfInstalled:
3011 return @"HalfInstalled";
3012 case pkgCache::State::ConfigFiles:
3013 return @"ConfigFiles";
3014 case pkgCache::State::Installed:
3015 return @"Installed";
3016 case pkgCache::State::TriggersAwaited:
3017 return @"TriggersAwaited";
3018 case pkgCache::State::TriggersPending:
3019 return @"TriggersPending";
3022 return (NSString *) [NSNull null];
3025 - (NSString *) selection {
3026 @synchronized (database_) {
3027 if ([database_ era] != era_ || file_.end())
3030 switch (iterator_->SelectedState) {
3031 case pkgCache::State::Unknown:
3033 case pkgCache::State::Install:
3035 case pkgCache::State::Hold:
3037 case pkgCache::State::DeInstall:
3038 return @"DeInstall";
3039 case pkgCache::State::Purge:
3043 return (NSString *) [NSNull null];
3046 - (NSArray *) warnings {
3047 @synchronized (database_) {
3048 if ([database_ era] != era_ || file_.end())
3051 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
3052 const char *name(iterator_.Name());
3054 size_t length(strlen(name));
3055 if (length < 2) invalid:
3056 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
3057 else for (size_t i(0); i != length; ++i)
3059 /* XXX: technically this is not allowed */
3060 (name[i] < 'A' || name[i] > 'Z') &&
3061 (name[i] < 'a' || name[i] > 'z') &&
3062 (name[i] < '0' || name[i] > '9') &&
3063 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
3066 if (strcmp(name, "cydia") != 0) {
3069 bool _private = false;
3071 bool dbstash = false;
3072 bool dsstore = false;
3074 bool repository = [[self section] isEqualToString:@"Repositories"];
3076 if (NSArray *files = [self files])
3077 for (NSString *file in files)
3078 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
3080 else if (!user && [file isEqualToString:@"/User"])
3082 else if (!_private && [file isEqualToString:@"/private"])
3084 else if (!stash && [file isEqualToString:@"/var/stash"])
3086 else if (!dbstash && [file isEqualToString:@"/var/db/stash"])
3088 else if (!dsstore && [file hasSuffix:@"/.DS_Store"])
3091 /* XXX: this is not sensitive enough. only some folders are valid. */
3092 if (cydia && !repository)
3093 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
3095 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
3097 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
3099 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
3101 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/db/stash"]];
3103 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @".DS_Store"]];
3106 return [warnings count] == 0 ? nil : warnings;
3109 - (NSArray *) applications {
3110 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
3112 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
3114 static RegEx application_r("/Applications/(.*)\\.app/Info.plist");
3115 if (NSArray *files = [self files])
3116 for (NSString *file in files)
3117 if (application_r(file)) {
3118 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
3121 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
3122 if (id == nil || [id isEqualToString:me])
3125 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
3127 display = application_r[1];
3129 NSString *bundle([file stringByDeletingLastPathComponent]);
3130 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
3131 // XXX: maybe this should check if this is really a string, not just for length
3132 if (icon == nil || ![icon respondsToSelector:@selector(length)] || [icon length] == 0)
3134 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
3136 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
3137 [applications addObject:application];
3139 [application addObject:id];
3140 [application addObject:display];
3141 [application addObject:url];
3144 return [applications count] == 0 ? nil : applications;
3147 - (Source *) source {
3148 if (source_ == nil) {
3149 @synchronized (database_) {
3150 if ([database_ era] != era_ || file_.end())
3151 source_ = (Source *) [NSNull null];
3153 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
3157 return source_ == (Source *) [NSNull null] ? nil : source_;
3160 - (time_t) upgraded {
3164 - (uint32_t) recent {
3165 return std::numeric_limits<uint32_t>::max() - upgraded_;
3172 - (BOOL) matches:(NSArray *)query {
3173 if (query == nil || [query count] == 0)
3182 string = [self name];
3183 length = [string length];
3186 for (NSString *term in query) {
3187 range = [string rangeOfString:term options:MatchCompareOptions_];
3188 if (range.location != NSNotFound)
3189 rank_ -= 6 * 1000000 / length;
3194 length = [string length];
3197 for (NSString *term in query) {
3198 range = [string rangeOfString:term options:MatchCompareOptions_];
3199 if (range.location != NSNotFound)
3200 rank_ -= 6 * 1000000 / length;
3204 string = [self shortDescription];
3205 length = [string length];
3206 NSUInteger stop(std::min<NSUInteger>(length, 200));
3209 for (NSString *term in query) {
3210 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
3211 if (range.location != NSNotFound)
3212 rank_ -= 2 * 100000;
3218 - (NSArray *) tags {
3222 - (BOOL) hasTag:(NSString *)tag {
3223 return tags_ == nil ? NO : [tags_ containsObject:tag];
3226 - (NSString *) primaryPurpose {
3227 for (NSString *tag in (NSArray *) tags_)
3228 if ([tag hasPrefix:@"purpose::"])
3229 return [tag substringFromIndex:9];
3233 - (NSArray *) purposes {
3234 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
3235 for (NSString *tag in (NSArray *) tags_)
3236 if ([tag hasPrefix:@"purpose::"])
3237 [purposes addObject:[tag substringFromIndex:9]];
3238 return [purposes count] == 0 ? nil : purposes;
3241 - (bool) isCommercial {
3242 return [self hasTag:@"cydia::commercial"];
3245 - (void) setIndex:(size_t)index {
3246 if (metadata_->index_ != index + 1)
3247 metadata_->index_ = index + 1;
3250 - (CYString &) cyname {
3251 return !transform_.empty() ? transform_ : !name_.empty() ? name_ : id_;
3254 - (uint32_t) compareBySection:(NSArray *)sections {
3255 NSString *section([self section]);
3256 for (size_t i(0), e([sections count]); i != e; ++i) {
3257 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3261 return _not(uint32_t);
3265 @synchronized (database_) {
3266 if ([database_ era] != era_ || file_.end())
3269 pkgProblemResolver *resolver = [database_ resolver];
3270 resolver->Clear(iterator_);
3272 pkgCacheFile &cache([database_ cache]);
3273 cache->SetReInstall(iterator_, false);
3274 cache->MarkKeep(iterator_, false);
3278 @synchronized (database_) {
3279 if ([database_ era] != era_ || file_.end())
3282 pkgProblemResolver *resolver = [database_ resolver];
3283 resolver->Clear(iterator_);
3284 resolver->Protect(iterator_);
3286 pkgCacheFile &cache([database_ cache]);
3287 cache->SetCandidateVersion(version_);
3288 cache->SetReInstall(iterator_, false);
3289 cache->MarkInstall(iterator_, false);
3291 pkgDepCache::StateCache &state((*cache)[iterator_]);
3292 if (!state.Install())
3293 cache->SetReInstall(iterator_, true);
3297 @synchronized (database_) {
3298 if ([database_ era] != era_ || file_.end())
3301 pkgProblemResolver *resolver = [database_ resolver];
3302 resolver->Clear(iterator_);
3303 resolver->Remove(iterator_);
3304 resolver->Protect(iterator_);
3306 pkgCacheFile &cache([database_ cache]);
3307 cache->SetReInstall(iterator_, false);
3308 cache->MarkDelete(iterator_, true);
3313 /* Section Class {{{ */
3314 @interface Section : NSObject {
3318 _H<NSString> localized_;
3321 - (NSComparisonResult) compareByLocalized:(Section *)section;
3322 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3323 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3324 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3326 - (NSString *) name;
3327 - (void) setName:(NSString *)name;
3333 - (void) addToCount;
3335 - (void) setCount:(size_t)count;
3336 - (NSString *) localized;
3340 @implementation Section
3342 - (NSComparisonResult) compareByLocalized:(Section *)section {
3343 NSString *lhs(localized_);
3344 NSString *rhs([section localized]);
3346 /*if ([lhs length] != 0 && [rhs length] != 0) {
3347 unichar lhc = [lhs characterAtIndex:0];
3348 unichar rhc = [rhs characterAtIndex:0];
3350 if (isalpha(lhc) && !isalpha(rhc))
3351 return NSOrderedAscending;
3352 else if (!isalpha(lhc) && isalpha(rhc))
3353 return NSOrderedDescending;
3356 return [lhs compare:rhs options:LaxCompareOptions_];
3359 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3360 if ((self = [self initWithName:name localize:NO]) != nil) {
3361 if (localized != nil)
3362 localized_ = localized;
3366 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3367 return [self initWithName:name row:0 localize:localize];
3370 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3371 if ((self = [super init]) != nil) {
3375 localized_ = LocalizeSection(name_);
3379 - (NSString *) name {
3383 - (void) setName:(NSString *)name {
3399 - (void) addToCount {
3403 - (void) setCount:(size_t)count {
3407 - (NSString *) localized {
3414 class CydiaLogCleaner :
3415 public pkgArchiveCleaner
3418 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3423 /* Database Implementation {{{ */
3424 @implementation Database
3426 + (Database *) sharedInstance {
3427 static _H<Database> instance;
3428 if (instance == nil)
3429 instance = [[[Database alloc] init] autorelease];
3437 - (void) releasePackages {
3441 - (bool) hasPackages {
3442 return [packages_ count] != 0;
3446 // XXX: actually implement this thing
3448 [self releasePackages];
3449 NSRecycleZone(zone_);
3453 - (void) _readCydia:(NSNumber *)fd {
3454 boost::fdistream is([fd intValue]);
3457 static RegEx finish_r("finish:([^:]*)");
3459 while (std::getline(is, line)) {
3460 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3462 const char *data(line.c_str());
3463 size_t size = line.size();
3464 lprintf("C:%s\n", data);
3466 if (finish_r(data, size)) {
3467 NSString *finish = finish_r[1];
3468 int index = [Finishes_ indexOfObject:finish];
3469 if (index != INT_MAX && index > Finish_)
3479 - (void) _readStatus:(NSNumber *)fd {
3480 boost::fdistream is([fd intValue]);
3483 static RegEx conffile_r("status: [^ ]* : conffile-prompt : (.*?) *");
3484 static RegEx pmstatus_r("([^:]*):([^:]*):([^:]*):(.*)");
3486 while (std::getline(is, line)) {
3487 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3489 const char *data(line.c_str());
3490 size_t size(line.size());
3491 lprintf("S:%s\n", data);
3493 if (conffile_r(data, size)) {
3494 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3495 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3496 } else if (strncmp(data, "status: ", 8) == 0) {
3497 // status: <package>: {unpacked,half-configured,installed}
3498 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3499 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3500 } else if (strncmp(data, "processing: ", 12) == 0) {
3501 // processing: configure: config-test
3502 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3503 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3504 } else if (pmstatus_r(data, size)) {
3505 std::string type([pmstatus_r[1] UTF8String]);
3507 NSString *package = pmstatus_r[2];
3508 if ([package isEqualToString:@"dpkg-exec"])
3511 float percent([pmstatus_r[3] floatValue]);
3512 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3514 NSString *string = pmstatus_r[4];
3516 if (type == "pmerror") {
3517 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3518 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3519 } else if (type == "pmstatus") {
3520 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3521 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3522 } else if (type == "pmconffile")
3523 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3525 lprintf("E:unknown pmstatus\n");
3527 lprintf("E:unknown status\n");
3535 - (void) _readOutput:(NSNumber *)fd {
3536 boost::fdistream is([fd intValue]);
3539 while (std::getline(is, line)) {
3540 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3542 lprintf("O:%s\n", line.c_str());
3544 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3545 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3557 - (Package *) packageWithName:(NSString *)name {
3560 @synchronized (self) {
3561 if (static_cast<pkgDepCache *>(cache_) == NULL)
3563 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]
3568 return iterator.end() ? nil : [[Package newPackageWithIterator:iterator withZone:NULL inPool:NULL database:self] autorelease];
3572 if ((self = [super init]) != nil) {
3579 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3581 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3585 _assert(pipe(fds) != -1);
3588 _config->Set("APT::Keep-Fds::", cydiafd_);
3589 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3592 detachNewThreadSelector:@selector(_readCydia:)
3594 withObject:[NSNumber numberWithInt:fds[0]]
3597 _assert(pipe(fds) != -1);
3601 detachNewThreadSelector:@selector(_readStatus:)
3603 withObject:[NSNumber numberWithInt:fds[0]]
3606 _assert(pipe(fds) != -1);
3607 _assert(dup2(fds[0], 0) != -1);
3608 _assert(close(fds[0]) != -1);
3610 input_ = fdopen(fds[1], "a");
3612 _assert(pipe(fds) != -1);
3613 _assert(dup2(fds[1], 1) != -1);
3614 _assert(close(fds[1]) != -1);
3617 detachNewThreadSelector:@selector(_readOutput:)
3619 withObject:[NSNumber numberWithInt:fds[0]]
3624 - (pkgCacheFile &) cache {
3628 - (pkgDepCache::Policy *) policy {
3632 - (pkgRecords *) records {
3636 - (pkgProblemResolver *) resolver {
3640 - (pkgAcquire &) fetcher {
3644 - (pkgSourceList &) list {
3648 - (NSArray *) packages {
3652 - (NSArray *) sources {
3656 - (Source *) sourceWithKey:(NSString *)key {
3657 for (Source *source in [self sources]) {
3658 if ([[source key] isEqualToString:key])
3663 - (bool) popErrorWithTitle:(NSString *)title {
3666 while (!_error->empty()) {
3668 bool warning(!_error->PopMessage(error));
3673 size_t size(error.size());
3674 if (size == 0 || error[size - 1] != '\n')
3676 error.resize(size - 1);
3679 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3681 static RegEx no_pubkey("GPG error:.* NO_PUBKEY .*");
3682 if (warning && no_pubkey(error.c_str()))
3685 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3691 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3692 return [self popErrorWithTitle:title] || !success;
3695 - (bool) popErrorWithTitle:(NSString *)title forReadList:(pkgSourceList &)list {
3696 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3704 if (access("/etc/apt/sources.list", F_OK) == 0)
3705 error |= [self popErrorWithTitle:title forOperation:list.ReadAppend("/etc/apt/sources.list")];
3707 std::string base("/etc/apt/sources.list.d");
3708 if (DIR *sources = opendir(base.c_str())) {
3709 while (dirent *source = readdir(sources))
3710 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)
3711 error |= [self popErrorWithTitle:title forOperation:list.ReadAppend((base + "/" + source->d_name).c_str())];
3715 error |= [self popErrorWithTitle:title forOperation:list.ReadAppend(SOURCES_LIST)];
3720 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3721 @synchronized (self) {
3724 [self releasePackages];
3727 [sourceList_ removeAllObjects];
3748 new (&pool_) CYPool();
3750 NSRecycleZone(zone_);
3751 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3753 int chk(creat("/tmp/cydia.chk", 0644));
3757 if (invocation != nil)
3758 [invocation invoke];
3760 NSString *title(UCLocalize("DATABASE"));
3762 list_ = new pkgSourceList();
3763 _profile(reloadDataWithInvocation$ReadMainList)
3764 if ([self popErrorWithTitle:title forReadList:*list_])
3768 _profile(reloadDataWithInvocation$Source$initWithMetaIndex)
3769 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3770 Source *object([[[Source alloc] initWithMetaIndex:*source forDatabase:self inPool:&pool_] autorelease]);
3771 [sourceList_ addObject:object];
3776 OpProgress progress;
3779 delock_ = GetStatusDate();
3780 _profile(reloadDataWithInvocation$pkgCacheFile)
3781 opened = cache_.Open(progress, false);
3784 // XXX: this block should probably be merged with popError: in some way
3785 while (!_error->empty()) {
3787 bool warning(!_error->PopMessage(error));
3789 lprintf("cache_.Open():[%s]\n", error.c_str());
3791 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3795 else if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3796 repair = @selector(configure);
3797 //else if (error == "The package lists or status file could not be parsed or opened.")
3798 // repair = @selector(update);
3799 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3800 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3801 // else if (error == "Malformed Status line")
3802 // else if (error == "The list of sources could not be read.")
3804 if (repair != NULL) {
3806 [delegate_ repairWithSelector:repair];
3812 } else if ([self popErrorWithTitle:title forOperation:true])
3816 unlink("/tmp/cydia.chk");
3818 now_ = [[NSDate date] timeIntervalSince1970];
3820 policy_ = new pkgDepCache::Policy();
3821 records_ = new pkgRecords(cache_);
3822 resolver_ = new pkgProblemResolver(cache_);
3823 fetcher_ = new pkgAcquire(&status_);
3826 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3827 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3831 _profile(reloadDataWithInvocation$pkgApplyStatus)
3832 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3836 if (cache_->BrokenCount() != 0) {
3837 _profile(pkgApplyStatus$pkgFixBroken)
3838 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3842 if (cache_->BrokenCount() != 0) {
3843 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3847 _profile(pkgApplyStatus$pkgMinimizeUpgrade)
3848 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3853 for (Source *object in (id) sourceList_) {
3854 metaIndex *source([object metaIndex]);
3855 std::vector<pkgIndexFile *> *indices = source->GetIndexFiles();
3856 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3857 // XXX: this could be more intelligent
3858 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3859 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3861 sourceMap_[cached->ID] = object;
3866 size_t capacity(MetaFile_->active_);
3868 capacity = 128*1024;
3872 std::vector<Package *> packages;
3873 packages.reserve(capacity);
3877 _profile(reloadDataWithInvocation$packageWithIterator)
3878 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3879 if (Package *package = [Package newPackageWithIterator:iterator withZone:zone_ inPool:&pool_ database:self]) {
3880 if (unsigned index = package.metadata->index_) {
3882 if (packages.size() == index) {
3883 packages.push_back(package);
3884 } else if (packages.size() <= index) {
3885 packages.resize(index + 1, nil);
3886 packages[index] = package;
3889 std::swap(package, packages[index]);
3890 if (package != nil) {
3891 if (package.metadata->index_ == index + 1)
3900 lost: if (last == packages.size())
3901 packages.push_back(package);
3903 packages[last] = package;
3907 for (; last != packages.size(); ++last)
3908 if (packages[last] == nil)
3913 for (size_t next(last + 1); last != packages.size(); ++last, ++next) {
3915 if (next == packages.size())
3917 if (packages[next] != nil)
3922 std::swap(packages[last], packages[next]);
3925 packages.resize(last);
3928 NSLog(@"lost = %zu", lost);
3930 _profile(reloadDataWithInvocation$radix$8)
3931 CYRadixSortUsingFunction(packages.data(), packages.size(), reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix), reinterpret_cast<void *>(8));
3934 _profile(reloadDataWithInvocation$radix$4)
3935 CYRadixSortUsingFunction(packages.data(), packages.size(), reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix), reinterpret_cast<void *>(4));
3938 _profile(reloadDataWithInvocation$radix$0)
3939 CYRadixSortUsingFunction(packages.data(), packages.size(), reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix), reinterpret_cast<void *>(0));
3943 _profile(reloadDataWithInvocation$insertion)
3944 CYArrayInsertionSortValues(packages.data(), packages.size(), &PackageNameCompare, NULL);
3947 packages_ = [[[NSArray alloc] initWithObjects:packages.data() count:packages.size()] autorelease];
3949 /*_profile(reloadDataWithInvocation$CFQSortArray)
3950 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);
3953 /*_profile(reloadDataWithInvocation$stdsort)
3954 std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3957 /*_profile(reloadDataWithInvocation$CFArraySortValues)
3958 CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3961 /*_profile(reloadDataWithInvocation$sortUsingFunction)
3962 [packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3965 MetaFile_->active_ = packages.size();
3966 for (size_t index(0), count(packages.size()); index != count; ++index) {
3967 auto package(packages[index]);
3968 [package setIndex:index];
3975 @synchronized (self) {
3977 resolver_ = new pkgProblemResolver(cache_);
3979 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3980 if (!cache_[iterator].Keep())
3981 cache_->MarkKeep(iterator, false);
3982 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3983 cache_->SetReInstall(iterator, false);
3986 - (void) configure {
3987 NSString *dpkg = [NSString stringWithFormat:@"/usr/libexec/cydo --configure -a --status-fd %u", statusfd_];
3989 system([dpkg UTF8String]);
3994 @synchronized (self) {
3995 // XXX: I don't remember this condition
4000 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
4002 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
4004 if ([self popErrorWithTitle:title])
4008 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
4010 CydiaLogCleaner cleaner;
4011 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
4018 fetcher_->Shutdown();
4020 pkgRecords records(cache_);
4022 lock_ = new FileFd();
4023 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
4025 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
4027 if ([self popErrorWithTitle:title])
4031 if ([self popErrorWithTitle:title forReadList:list])
4034 manager_ = (_system->CreatePM(cache_));
4035 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
4042 bool substrate(RestartSubstrate_);
4043 RestartSubstrate_ = false;
4045 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
4047 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
4049 if ([self popErrorWithTitle:title forReadList:list])
4051 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
4052 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
4055 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4057 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
4059 [self popErrorWithTitle:title];
4063 bool failed = false;
4064 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
4065 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
4067 if ((*item)->Status == pkgAcquire::Item::StatIdle)
4070 std::string uri = (*item)->DescURI();
4071 std::string error = (*item)->ErrorText;
4073 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
4076 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError]);
4077 [delegate_ addProgressEventOnMainThread:event forTask:title];
4080 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4088 RestartSubstrate_ = true;
4090 if (![delock_ isEqual:GetStatusDate()]) {
4091 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("DPKG_LOCKED") ofType:kCydiaProgressEventTypeError] forTask:title];
4097 pkgPackageManager::OrderResult result(manager_->DoInstall(statusfd_));
4099 NSString *oextended(@"/var/lib/apt/extended_states");
4100 NSString *nextended(Cache("extended_states"));
4103 if (stat([nextended UTF8String], &info) != -1 && (info.st_mode & S_IFMT) == S_IFREG)
4104 system([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /bin/cp --remove-destination %@ %@", ShellEscape(nextended), ShellEscape(oextended)] UTF8String]);
4106 unlink([nextended UTF8String]);
4107 symlink([oextended UTF8String], [nextended UTF8String]);
4109 if ([self popErrorWithTitle:title])
4112 if (result == pkgPackageManager::Failed) {
4117 if (result != pkgPackageManager::Completed) {
4122 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
4124 if ([self popErrorWithTitle:title forReadList:list])
4126 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
4127 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
4130 if (![before isEqualToArray:after])
4135 return ![delock_ isEqual:GetStatusDate()];
4139 NSString *title(UCLocalize("UPGRADE"));
4140 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
4146 [self updateWithStatus:status_];
4149 - (void) updateWithStatus:(CancelStatus &)status {
4150 NSString *title(UCLocalize("REFRESHING_DATA"));
4153 if ([self popErrorWithTitle:title forReadList:list])
4157 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
4158 if ([self popErrorWithTitle:title])
4161 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4163 bool success(ListUpdate(status, list, PulseInterval_));
4164 if (status.WasCancelled())
4167 [self popErrorWithTitle:title forOperation:success];
4169 [[NSDictionary dictionaryWithObjectsAndKeys:
4170 [NSDate date], @"LastUpdate",
4171 nil] writeToFile:@ CacheState_ atomically:YES];
4174 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4177 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
4178 delegate_ = delegate;
4181 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
4182 progress_ = delegate;
4183 status_.setDelegate(delegate);
4186 - (NSObject<ProgressDelegate> *) progressDelegate {
4190 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
4191 SourceMap::const_iterator i(sourceMap_.find(file->ID));
4192 return i == sourceMap_.end() ? nil : i->second;
4195 - (void) setFetch:(bool)fetch forURI:(const char *)uri {
4196 for (Source *source in (id) sourceList_)
4197 [source setFetch:fetch forURI:uri];
4200 - (void) resetFetch {
4201 for (Source *source in (id) sourceList_)
4202 [source resetFetch];
4205 - (NSString *) mappedSectionForPointer:(const char *)section {
4206 _H<NSString> *mapped;
4208 _profile(Database$mappedSectionForPointer$Cache)
4209 mapped = §ions_[section];
4212 if (*mapped == NULL) {
4213 size_t length(strlen(section));
4214 char spaced[length + 1];
4216 _profile(Database$mappedSectionForPointer$Replace)
4217 for (size_t index(0); index != length; ++index)
4218 spaced[index] = section[index] == '_' ? ' ' : section[index];
4219 spaced[length] = '\0';
4224 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
4225 string = [NSString stringWithUTF8String:spaced];
4228 _profile(Database$mappedSectionForPointer$Map)
4229 string = [SectionMap_ objectForKey:string] ?: string;
4239 @interface CydiaObject : NSObject {
4240 _H<CyteWebViewController> indirect_;
4241 _transient id delegate_;
4244 - (id) initWithDelegate:(CyteWebViewController *)indirect;
4250 @interface CydiaWebViewController : CyteWebViewController {
4251 _H<CydiaObject> cydia_;
4254 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request;
4255 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia;
4256 - (void) setDelegate:(id)delegate;
4260 /* Web Scripting {{{ */
4261 @implementation CydiaObject
4263 - (id) initWithDelegate:(CyteWebViewController *)indirect {
4264 if ((self = [super init]) != nil) {
4265 indirect_ = indirect;
4269 - (void) setDelegate:(id)delegate {
4270 delegate_ = delegate;
4273 + (NSArray *) _attributeKeys {
4274 return [NSArray arrayWithObjects:
4279 @"coreFoundationVersionNumber",
4295 - (NSArray *) attributeKeys {
4296 return [[self class] _attributeKeys];
4299 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4300 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4303 - (NSString *) version {
4307 - (unsigned) bittage {
4309 #elif defined(__arm64__)
4311 #elif defined(__arm__)
4318 - (NSString *) build {
4322 - (NSString *) coreFoundationVersionNumber {
4323 return [NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber];
4326 - (NSString *) device {
4327 return UniqueIdentifier();
4330 - (NSString *) firmware {
4331 return [[UIDevice currentDevice] systemVersion];
4334 - (NSString *) hostname {
4335 return [[UIDevice currentDevice] name];
4338 - (NSString *) idiom {
4339 return (id) Idiom_ ?: [NSNull null];
4342 - (NSArray *) cells {
4343 auto *$_CTServerConnectionCreate(reinterpret_cast<id (*)(void *, void *, void *)>(dlsym(RTLD_DEFAULT, "_CTServerConnectionCreate")));
4344 if ($_CTServerConnectionCreate == NULL)
4347 struct CTResult { int flag; int error; };
4348 auto *$_CTServerConnectionCellMonitorCopyCellInfo(reinterpret_cast<CTResult (*)(CFTypeRef, void *, CFArrayRef *)>(dlsym(RTLD_DEFAULT, "_CTServerConnectionCellMonitorCopyCellInfo")));
4349 if ($_CTServerConnectionCellMonitorCopyCellInfo == NULL)
4352 _H<const void> connection($_CTServerConnectionCreate(NULL, NULL, NULL), true);
4353 if (connection == nil)
4357 CFArrayRef cells(NULL);
4358 auto result($_CTServerConnectionCellMonitorCopyCellInfo(connection, &count, &cells));
4359 if (result.flag != 0)
4362 return [(NSArray *) cells autorelease];
4365 - (NSString *) mcc {
4366 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode")))
4367 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault) autorelease];
4371 - (NSString *) mnc {
4372 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberNetworkCode")))
4373 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault) autorelease];
4377 - (NSString *) operator {
4378 if (CFStringRef (*$CTRegistrationCopyOperatorName)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTRegistrationCopyOperatorName")))
4379 return [(NSString *) (*$CTRegistrationCopyOperatorName)(kCFAllocatorDefault) autorelease];
4383 - (NSString *) bbsnum {
4384 return (id) BBSNum_ ?: [NSNull null];
4387 - (NSString *) ecid {
4388 return (id) ChipID_ ?: [NSNull null];
4391 - (NSString *) serial {
4392 return SerialNumber_;
4395 - (NSString *) role {
4396 return (id) [NSNull null];
4399 - (NSString *) model {
4400 return [NSString stringWithUTF8String:Machine_];
4403 + (NSString *) webScriptNameForSelector:(SEL)selector {
4405 else if (selector == @selector(addBridgedHost:))
4406 return @"addBridgedHost";
4407 else if (selector == @selector(addInsecureHost:))
4408 return @"addInsecureHost";
4409 else if (selector == @selector(addInternalRedirect::))
4410 return @"addInternalRedirect";
4411 else if (selector == @selector(addSource:::))
4412 return @"addSource";
4413 else if (selector == @selector(addTrivialSource:))
4414 return @"addTrivialSource";
4415 else if (selector == @selector(close))
4417 else if (selector == @selector(du:))
4419 else if (selector == @selector(stringWithFormat:arguments:))
4421 else if (selector == @selector(getAllSources))
4422 return @"getAllSources";
4423 else if (selector == @selector(getApplicationInfo:value:))
4424 return @"getApplicationInfoValue";
4425 else if (selector == @selector(getDisplayIdentifiers))
4426 return @"getDisplayIdentifiers";
4427 else if (selector == @selector(getLocalizedNameForDisplayIdentifier:))
4428 return @"getLocalizedNameForDisplayIdentifier";
4429 else if (selector == @selector(getKernelNumber:))
4430 return @"getKernelNumber";
4431 else if (selector == @selector(getKernelString:))
4432 return @"getKernelString";
4433 else if (selector == @selector(getInstalledPackages))
4434 return @"getInstalledPackages";
4435 else if (selector == @selector(getIORegistryEntry::))
4436 return @"getIORegistryEntry";
4437 else if (selector == @selector(getLocaleIdentifier))
4438 return @"getLocaleIdentifier";
4439 else if (selector == @selector(getPreferredLanguages))
4440 return @"getPreferredLanguages";
4441 else if (selector == @selector(getPackageById:))
4442 return @"getPackageById";
4443 else if (selector == @selector(getMetadataKeys))
4444 return @"getMetadataKeys";
4445 else if (selector == @selector(getMetadataValue:))
4446 return @"getMetadataValue";
4447 else if (selector == @selector(getSessionValue:))
4448 return @"getSessionValue";
4449 else if (selector == @selector(installPackages:))
4450 return @"installPackages";
4451 else if (selector == @selector(isReachable:))
4452 return @"isReachable";
4453 else if (selector == @selector(localizedStringForKey:value:table:))
4455 else if (selector == @selector(popViewController:))
4456 return @"popViewController";
4457 else if (selector == @selector(refreshSources))
4458 return @"refreshSources";
4459 else if (selector == @selector(registerFrame:))
4460 return @"registerFrame";
4461 else if (selector == @selector(removeButton))
4462 return @"removeButton";
4463 else if (selector == @selector(saveConfig))
4464 return @"saveConfig";
4465 else if (selector == @selector(setMetadataValue::))
4466 return @"setMetadataValue";
4467 else if (selector == @selector(setSessionValue::))
4468 return @"setSessionValue";
4469 else if (selector == @selector(substitutePackageNames:))
4470 return @"substitutePackageNames";
4471 else if (selector == @selector(scrollToBottom:))
4472 return @"scrollToBottom";
4473 else if (selector == @selector(setAllowsNavigationAction:))
4474 return @"setAllowsNavigationAction";
4475 else if (selector == @selector(setBadgeValue:))
4476 return @"setBadgeValue";
4477 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4478 return @"setButtonImage";
4479 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4480 return @"setButtonTitle";
4481 else if (selector == @selector(setHidesBackButton:))
4482 return @"setHidesBackButton";
4483 else if (selector == @selector(setHidesNavigationBar:))
4484 return @"setHidesNavigationBar";
4485 else if (selector == @selector(setNavigationBarStyle:))
4486 return @"setNavigationBarStyle";
4487 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4488 return @"setNavigationBarTintColor";
4489 else if (selector == @selector(setPasteboardString:))
4490 return @"setPasteboardString";
4491 else if (selector == @selector(setPasteboardURL:))
4492 return @"setPasteboardURL";
4493 else if (selector == @selector(setScrollAlwaysBounceVertical:))
4494 return @"setScrollAlwaysBounceVertical";
4495 else if (selector == @selector(setScrollIndicatorStyle:))
4496 return @"setScrollIndicatorStyle";
4497 else if (selector == @selector(setToken:))
4499 else if (selector == @selector(setViewportWidth:))
4500 return @"setViewportWidth";
4501 else if (selector == @selector(statfs:))
4503 else if (selector == @selector(supports:))
4505 else if (selector == @selector(unload))
4511 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4512 return [self webScriptNameForSelector:selector] == nil;
4515 - (BOOL) supports:(NSString *)feature {
4516 return [feature isEqualToString:@"window.open"];
4520 [[indirect_ rootViewController] performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4523 - (void) setScrollAlwaysBounceVertical:(NSNumber *)value {
4524 [indirect_ performSelectorOnMainThread:@selector(setScrollAlwaysBounceVerticalNumber:) withObject:value waitUntilDone:NO];
4527 - (void) setScrollIndicatorStyle:(NSString *)style {
4528 [indirect_ performSelectorOnMainThread:@selector(setScrollIndicatorStyleWithName:) withObject:style waitUntilDone:NO];
4531 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4532 [CyteWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4535 - (NSDictionary *) getApplicationInfo:(NSString *)display value:(NSString *)key {
4537 if (SBBundlePathForDisplayIdentifier(SBSSpringBoardServerPort(), [display UTF8String], path) != 0)
4538 return (id) [NSNull null];
4539 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:[[NSString stringWithUTF8String:path] stringByAppendingString:@"/Info.plist"]]);
4541 return (id) [NSNull null];
4542 return [info objectForKey:key];
4545 - (NSArray *) getDisplayIdentifiers {
4546 return SBSCopyApplicationDisplayIdentifiers(false, false);
4549 - (NSString *) getLocalizedNameForDisplayIdentifier:(NSString *)identifier {
4550 return [SBSCopyLocalizedApplicationNameForDisplayIdentifier(identifier) autorelease] ?: (id) [NSNull null];
4553 - (NSNumber *) getKernelNumber:(NSString *)name {
4554 const char *string([name UTF8String]);
4557 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4558 return (id) [NSNull null];
4560 if (size != sizeof(int))
4561 return (id) [NSNull null];
4564 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4565 return (id) [NSNull null];
4567 return [NSNumber numberWithInt:value];
4570 - (NSString *) getKernelString:(NSString *)name {
4571 const char *string([name UTF8String]);
4574 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4575 return (id) [NSNull null];
4577 char value[size + 1];
4578 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4579 return (id) [NSNull null];
4581 // XXX: just in case you request something ludicrous
4584 return [NSString stringWithCString:value];
4587 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4588 NSObject *value(CYIOGetValue([path UTF8String], entry));
4591 if ([value isKindOfClass:[NSData class]])
4592 value = CYHex((NSData *) value);
4597 - (NSArray *) getMetadataKeys {
4598 @synchronized (Values_) {
4599 return [Values_ allKeys];
4602 - (void) registerFrame:(DOMHTMLIFrameElement *)iframe {
4603 WebFrame *frame([iframe contentFrame]);
4604 [indirect_ registerFrame:frame];
4607 - (id) getMetadataValue:(NSString *)key {
4608 @synchronized (Values_) {
4609 return [Values_ objectForKey:key];
4612 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4613 @synchronized (Values_) {
4614 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4615 [Values_ removeObjectForKey:key];
4617 [Values_ setObject:value forKey:key];
4620 - (id) getSessionValue:(NSString *)key {
4621 @synchronized (SessionData_) {
4622 return [SessionData_ objectForKey:key];
4625 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4626 @synchronized (SessionData_) {
4627 if (value == (id) [WebUndefined undefined])
4628 [SessionData_ removeObjectForKey:key];
4630 [SessionData_ setObject:value forKey:key];
4633 - (void) addBridgedHost:(NSString *)host {
4634 @synchronized (HostConfig_) {
4635 [BridgedHosts_ addObject:host];
4638 - (void) addInsecureHost:(NSString *)host {
4639 @synchronized (HostConfig_) {
4640 [InsecureHosts_ addObject:host];
4643 - (void) popViewController:(NSNumber *)value {
4644 if (value == (id) [WebUndefined undefined])
4645 value = [NSNumber numberWithBool:YES];
4646 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4649 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4650 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4652 for (NSString *section in sections)
4653 [array addObject:section];
4655 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4658 distribution, @"Distribution",
4660 nil] waitUntilDone:NO];
4663 - (BOOL) addTrivialSource:(NSString *)href {
4664 href = VerifySource(href);
4667 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4671 - (void) refreshSources {
4672 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4675 - (void) saveConfig {
4676 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4679 - (NSArray *) getAllSources {
4680 return [[Database sharedInstance] sources];
4683 - (NSArray *) getInstalledPackages {
4684 Database *database([Database sharedInstance]);
4685 @synchronized (database) {
4686 NSArray *packages([database packages]);
4687 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4688 for (Package *package in packages)
4689 if (![package uninstalled])
4690 [installed addObject:package];
4694 - (Package *) getPackageById:(NSString *)id {
4695 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4699 return (Package *) [NSNull null];
4702 - (NSString *) getLocaleIdentifier {
4703 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4706 - (NSArray *) getPreferredLanguages {
4710 - (NSArray *) statfs:(NSString *)path {
4713 if (path == nil || statfs([path UTF8String], &stat) == -1)
4716 return [NSArray arrayWithObjects:
4717 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4718 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4719 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4723 - (NSNumber *) du:(NSString *)path {
4724 NSNumber *value(nil);
4726 FILE *du(popen([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /usr/libexec/cydia/du -ks %@", ShellEscape(path)] UTF8String], "r"));
4729 while (fgets(line, sizeof(line), du) != NULL) {
4730 size_t length(strlen(line));
4731 while (length != 0 && line[length - 1] == '\n')
4732 line[--length] = '\0';
4733 if (char *tab = strchr(line, '\t')) {
4735 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4745 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4748 - (NSNumber *) isReachable:(NSString *)name {
4749 return [NSNumber numberWithBool:CyteIsReachable([name UTF8String])];
4752 - (void) installPackages:(NSArray *)packages {
4753 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4756 - (NSString *) substitutePackageNames:(NSString *)message {
4757 auto database([Database sharedInstance]);
4759 // XXX: this check is less racy than you'd expect, but this entire concept is a little awkward
4760 if (![database hasPackages])
4763 NSMutableArray *words([[[message componentsSeparatedByString:@" "] mutableCopy] autorelease]);
4764 for (size_t i(0), e([words count]); i != e; ++i) {
4765 NSString *word([words objectAtIndex:i]);
4766 if (Package *package = [database packageWithName:word])
4767 [words replaceObjectAtIndex:i withObject:[package name]];
4770 return [words componentsJoinedByString:@" "];
4773 - (void) removeButton {
4774 [indirect_ removeButton];
4777 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4778 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4781 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4782 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4785 - (void) setBadgeValue:(id)value {
4786 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4789 - (void) setAllowsNavigationAction:(NSString *)value {
4790 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4793 - (void) setHidesBackButton:(NSString *)value {
4794 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4797 - (void) setHidesNavigationBar:(NSString *)value {
4798 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4801 - (void) setNavigationBarStyle:(NSString *)value {
4802 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4805 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4806 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4807 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4808 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4811 - (void) setPasteboardString:(NSString *)value {
4812 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4815 - (void) setPasteboardURL:(NSString *)value {
4816 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4819 - (void) setToken:(NSString *)token {
4820 // XXX: the website expects this :/
4823 - (void) scrollToBottom:(NSNumber *)animated {
4824 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4827 - (void) setViewportWidth:(float)width {
4828 [indirect_ setViewportWidthOnMainThread:width];
4831 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4832 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4833 unsigned count([arguments count]);
4835 for (unsigned i(0); i != count; ++i)
4836 values[i] = [arguments objectAtIndex:i];
4837 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4840 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4841 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4843 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4845 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4851 @interface NSURL (CydiaSecure)
4854 @implementation NSURL (CydiaSecure)
4856 - (bool) isCydiaSecure {
4857 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4860 @synchronized (HostConfig_) {
4861 if ([InsecureHosts_ containsObject:[self host]])
4870 /* Cydia Browser Controller {{{ */
4871 @implementation CydiaWebViewController
4873 - (NSURL *) navigationURL {
4874 if (NSURLRequest *request = self.request)
4875 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request URL] absoluteString]]];
4880 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4881 [super webView:view didClearWindowObject:window forFrame:frame];
4882 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
4885 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia {
4886 WebDataSource *source([frame dataSource]);
4887 NSURLResponse *response([source response]);
4888 NSURL *url([response URL]);
4889 NSString *scheme([[url scheme] lowercaseString]);
4891 bool bridged(false);
4893 @synchronized (HostConfig_) {
4894 if ([scheme isEqualToString:@"file"])
4896 else if ([scheme isEqualToString:@"https"])
4897 if ([BridgedHosts_ containsObject:[url host]])
4902 [window setValue:cydia forKey:@"cydia"];
4905 - (void) _setupMail:(MFMailComposeViewController *)controller {
4906 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4908 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4909 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4912 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4913 return [CydiaWebViewController requestWithHeaders:[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
4916 - (NSURLRequest *) webThreadWebView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4917 return [CydiaWebViewController requestWithHeaders:[super webThreadWebView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
4920 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request {
4921 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
4923 NSURL *url([copy URL]);
4924 NSString *href([url absoluteString]);
4925 NSString *host([url host]);
4927 if ([href hasPrefix:@"https://cydia.saurik.com/TSS/"]) {
4928 if (NSString *agent = [copy valueForHTTPHeaderField:@"X-User-Agent"]) {
4929 [copy setValue:agent forHTTPHeaderField:@"User-Agent"];
4930 [copy setValue:nil forHTTPHeaderField:@"X-User-Agent"];
4933 [copy setValue:nil forHTTPHeaderField:@"Referer"];
4934 [copy setValue:nil forHTTPHeaderField:@"Origin"];
4936 [copy setURL:[NSURL URLWithString:[@"http://gs.apple.com/TSS/" stringByAppendingString:[href substringFromIndex:29]]]];
4940 if ([copy valueForHTTPHeaderField:@"X-Cydia-Cf"] == nil)
4941 [copy setValue:[NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber] forHTTPHeaderField:@"X-Cydia-Cf"];
4942 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4943 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4945 bool bridged; @synchronized (HostConfig_) {
4946 bridged = [BridgedHosts_ containsObject:host];
4949 if ([url isCydiaSecure] && bridged && UniqueID_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Id"] == nil)
4950 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
4955 - (void) setDelegate:(id)delegate {
4956 [super setDelegate:delegate];
4957 [cydia_ setDelegate:delegate];
4961 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4962 cydia_ = [[[CydiaObject alloc] initWithDelegate:self.indirect] autorelease];
4968 @interface AppCacheController : CydiaWebViewController {
4973 @implementation AppCacheController
4975 - (void) didReceiveMemoryWarning {
4976 // XXX: this doesn't work
4979 - (bool) retainsNetworkActivityIndicator {
4986 /* Confirmation Controller {{{ */
4987 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4988 if (!iterator.end())
4989 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4990 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4992 pkgCache::PkgIterator package(dep.TargetPkg());
4995 if (strcmp(package.Name(), "mobilesubstrate") == 0)
5002 @protocol ConfirmationControllerDelegate
5003 - (void) cancelAndClear:(bool)clear;
5004 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
5008 @interface ConfirmationController : CydiaWebViewController {
5009 _transient Database *database_;
5011 _H<UIAlertView> essential_;
5013 _H<NSDictionary> changes_;
5014 _H<NSMutableArray> issues_;
5015 _H<NSDictionary> sizes_;
5020 - (id) initWithDatabase:(Database *)database;
5024 @implementation ConfirmationController
5028 RestartSubstrate_ = true;
5029 [self.delegate confirmWithNavigationController:[self navigationController]];
5032 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
5033 NSString *context([alert context]);
5035 if ([context isEqualToString:@"remove"]) {
5036 if (button == [alert cancelButtonIndex])
5038 else if (button == [alert firstOtherButtonIndex]) {
5039 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
5042 [alert dismissWithClickedButtonIndex:-1 animated:YES];
5043 } else if ([context isEqualToString:@"unable"]) {
5044 [self dismissModalViewControllerAnimated:YES];
5045 [alert dismissWithClickedButtonIndex:-1 animated:YES];
5047 [super alertView:alert clickedButtonAtIndex:button];
5051 - (void) _doContinue {
5052 [self.delegate cancelAndClear:NO];
5053 [self dismissModalViewControllerAnimated:YES];
5056 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
5057 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
5061 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5062 [super webView:view didClearWindowObject:window forFrame:frame];
5064 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
5065 (id) changes_, @"changes",
5066 (id) issues_, @"issues",
5067 (id) sizes_, @"sizes",
5069 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
5072 - (id) initWithDatabase:(Database *)database {
5073 if ((self = [super init]) != nil) {
5074 database_ = database;
5076 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
5077 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
5078 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
5079 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
5080 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
5084 pkgCacheFile &cache([database_ cache]);
5085 NSArray *packages([database_ packages]);
5086 pkgDepCache::Policy *policy([database_ policy]);
5088 issues_ = [NSMutableArray arrayWithCapacity:4];
5090 for (Package *package in packages) {
5091 pkgCache::PkgIterator iterator([package iterator]);
5092 NSString *name([package id]);
5094 if ([package broken]) {
5095 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
5097 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5099 reasons, @"reasons",
5102 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
5106 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
5107 pkgCache::DepIterator start;
5108 pkgCache::DepIterator end;
5109 dep.GlobOr(start, end); // ++dep
5111 if (!cache->IsImportantDep(end))
5113 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
5116 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
5118 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5119 [NSString stringWithUTF8String:start.DepType()], @"relationship",
5120 clauses, @"clauses",
5124 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
5126 pkgCache::PkgIterator target(start.TargetPkg());
5127 if (target->ProvidesList != 0)
5128 reason = @"missing";
5130 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
5132 reason = @"installed";
5133 installed = [NSString stringWithUTF8String:ver.VerStr()];
5134 } else if (!cache[target].CandidateVerIter(cache).end())
5135 reason = @"uninstalled";
5136 else if (target->ProvidesList == 0)
5137 reason = @"uninstallable";
5139 reason = @"virtual";
5142 NSDictionary *version(start.TargetVer() == 0 ? (NSDictionary *) [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
5143 [NSString stringWithUTF8String:start.CompType()], @"operator",
5144 [NSString stringWithUTF8String:start.TargetVer()], @"value",
5147 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5148 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
5149 version, @"version",
5151 installed, @"installed",
5154 // yes, seriously. (wtf?)
5162 pkgDepCache::StateCache &state(cache[iterator]);
5164 static RegEx special_r("(firmware|gsc\\..*|cy\\+.*)");
5166 if (state.NewInstall())
5167 [installs addObject:name];
5168 // XXX: else if (state.Install())
5169 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
5170 [reinstalls addObject:name];
5171 // XXX: move before previous if
5172 else if (state.Upgrade())
5173 [upgrades addObject:name];
5174 else if (state.Downgrade())
5175 [downgrades addObject:name];
5176 else if (!state.Delete())
5177 // XXX: _assert(state.Keep());
5179 else if (special_r(name))
5180 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5181 [NSNull null], @"package",
5182 [NSArray arrayWithObjects:
5183 [NSDictionary dictionaryWithObjectsAndKeys:
5184 @"Conflicts", @"relationship",
5185 [NSArray arrayWithObjects:
5186 [NSDictionary dictionaryWithObjectsAndKeys:
5188 [NSNull null], @"version",
5189 @"installed", @"reason",
5196 if ([package essential])
5198 [removes addObject:name];
5201 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
5202 substrate_ |= DepSubstrate(iterator.CurrentVer());
5207 else if (Advanced_) {
5208 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
5210 essential_ = [[[UIAlertView alloc]
5211 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
5212 message:UCLocalize("REMOVING_ESSENTIALS_EX")
5214 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
5216 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
5220 [essential_ setContext:@"remove"];
5221 [essential_ setNumberOfRows:2];
5223 essential_ = [[[UIAlertView alloc]
5224 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
5225 message:UCLocalize("UNABLE_TO_COMPLY_EX")
5227 cancelButtonTitle:UCLocalize("OKAY")
5228 otherButtonTitles:nil
5231 [essential_ setContext:@"unable"];
5234 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5235 installs, @"installs",
5236 reinstalls, @"reinstalls",
5237 upgrades, @"upgrades",
5238 downgrades, @"downgrades",
5239 removes, @"removes",
5242 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5243 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
5244 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
5247 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
5251 - (UIBarButtonItem *) leftButton {
5252 return [[[UIBarButtonItem alloc]
5253 initWithTitle:UCLocalize("CANCEL")
5254 style:UIBarButtonItemStylePlain
5256 action:@selector(cancelButtonClicked)
5261 - (void) applyRightButton {
5262 if ([issues_ count] == 0 && ![self isLoading])
5263 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
5264 initWithTitle:UCLocalize("CONFIRM")
5265 style:UIBarButtonItemStyleDone
5267 action:@selector(confirmButtonClicked)
5270 [[self navigationItem] setRightBarButtonItem:nil];
5274 - (void) cancelButtonClicked {
5275 [self.delegate cancelAndClear:YES];
5276 [self dismissModalViewControllerAnimated:YES];
5280 - (void) confirmButtonClicked {
5281 if (essential_ != nil)
5291 /* Progress Data {{{ */
5292 @interface CydiaProgressData : NSObject {
5293 _transient id delegate_;
5302 _H<NSMutableArray> events_;
5303 _H<NSString> title_;
5305 _H<NSString> status_;
5306 _H<NSString> finish_;
5311 @implementation CydiaProgressData
5313 + (NSArray *) _attributeKeys {
5314 return [NSArray arrayWithObjects:
5326 - (NSArray *) attributeKeys {
5327 return [[self class] _attributeKeys];
5330 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5331 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5335 if ((self = [super init]) != nil) {
5336 events_ = [NSMutableArray arrayWithCapacity:32];
5344 - (void) setDelegate:(id)delegate {
5345 delegate_ = delegate;
5348 - (void) setPercent:(float)value {
5352 - (NSNumber *) percent {
5353 return [NSNumber numberWithFloat:percent_];
5356 - (void) setCurrent:(float)value {
5360 - (NSNumber *) current {
5361 return [NSNumber numberWithFloat:current_];
5364 - (void) setTotal:(float)value {
5368 - (NSNumber *) total {
5369 return [NSNumber numberWithFloat:total_];
5372 - (void) setSpeed:(float)value {
5376 - (NSNumber *) speed {
5377 return [NSNumber numberWithFloat:speed_];
5380 - (NSArray *) events {
5384 - (void) removeAllEvents {
5385 [events_ removeAllObjects];
5388 - (void) addEvent:(CydiaProgressEvent *)event {
5389 [events_ addObject:event];
5392 - (void) setTitle:(NSString *)text {
5396 - (NSString *) title {
5400 - (void) setFinish:(NSString *)text {
5404 - (NSString *) finish {
5405 return (id) finish_ ?: [NSNull null];
5408 - (void) setRunning:(bool)running {
5412 - (NSNumber *) running {
5413 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5418 /* Progress Controller {{{ */
5419 @interface ProgressController : CydiaWebViewController <
5422 _transient Database *database_;
5423 _H<CydiaProgressData, 1> progress_;
5427 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5429 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5431 - (void) setTitle:(NSString *)title;
5432 - (void) setCancellable:(bool)cancellable;
5436 @implementation ProgressController
5439 [database_ setProgressDelegate:nil];
5443 - (UIBarButtonItem *) leftButton {
5444 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5445 initWithTitle:UCLocalize("CANCEL")
5446 style:UIBarButtonItemStylePlain
5448 action:@selector(cancel)
5449 ] autorelease] : nil;
5452 - (void) updateCancel {
5453 [super applyLeftButton];
5456 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5457 if ((self = [super init]) != nil) {
5458 database_ = database;
5459 self.delegate = delegate;
5461 [database_ setProgressDelegate:self];
5463 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5464 [progress_ setDelegate:self];
5466 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5468 [self setPageColor:[UIColor blackColor]];
5470 [[self navigationItem] setHidesBackButton:YES];
5472 [self updateCancel];
5476 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5477 [super webView:view didClearWindowObject:window forFrame:frame];
5478 [window setValue:progress_ forKey:@"cydiaProgress"];
5481 - (void) updateProgress {
5482 [self dispatchEvent:@"CydiaProgressUpdate"];
5485 - (void) viewWillAppear:(BOOL)animated {
5486 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5487 [super viewWillAppear:animated];
5491 UpdateExternalStatus(0);
5494 [self.delegate saveState];
5498 [self.delegate returnToCydia];
5502 [self.delegate terminateWithSuccess];
5503 /*if ([self.delegate respondsToSelector:@selector(suspendWithAnimation:)])
5504 [self.delegate suspendWithAnimation:YES];
5506 [self.delegate suspend];*/
5518 UIProgressHUD *hud([self.delegate addProgressHUD]);
5519 [hud setText:UCLocalize("LOADING")];
5520 [self.delegate performSelector:@selector(reloadSpringBoard) withObject:nil afterDelay:0.5];
5526 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5527 SBReboot(SBSSpringBoardServerPort());
5529 reboot2(RB_AUTOBOOT);
5536 - (void) setTitle:(NSString *)title {
5537 [progress_ setTitle:title];
5538 [self updateProgress];
5541 - (UIBarButtonItem *) rightButton {
5542 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5543 initWithTitle:UCLocalize("CLOSE")
5544 style:UIBarButtonItemStylePlain
5546 action:@selector(close)
5550 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5551 UpdateExternalStatus(1);
5553 [progress_ setRunning:true];
5554 [self setTitle:title];
5555 // implicit updateProgress
5557 SHA1SumValue notifyconf; {
5559 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5562 MMap mmap(file, MMap::ReadOnly);
5564 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5565 notifyconf = sha1.Result();
5569 SHA1SumValue springlist; {
5571 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5574 MMap mmap(file, MMap::ReadOnly);
5576 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5577 springlist = sha1.Result();
5581 if (invocation != nil) {
5582 [invocation yieldToSelector:@selector(invoke)];
5583 [self setTitle:@"COMPLETE"];
5588 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5591 MMap mmap(file, MMap::ReadOnly);
5593 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5594 if (!(notifyconf == sha1.Result()))
5601 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5604 MMap mmap(file, MMap::ReadOnly);
5606 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5607 if (!(springlist == sha1.Result()))
5613 if (RestartSubstrate_)
5617 RestartSubstrate_ = false;
5620 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5621 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5622 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5623 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5624 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5627 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5629 [progress_ setRunning:false];
5630 [self updateProgress];
5632 [self applyRightButton];
5635 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5636 [progress_ addEvent:event];
5637 [self updateProgress];
5640 - (bool) isProgressCancelled {
5641 return cancel_ == 2;
5646 [self updateCancel];
5649 - (void) setCancellable:(bool)cancellable {
5650 unsigned cancel(cancel_);
5654 else if (cancel_ == 0)
5657 if (cancel != cancel_)
5658 [self updateCancel];
5661 - (void) setProgressCancellable:(NSNumber *)cancellable {
5662 [self setCancellable:[cancellable boolValue]];
5665 - (void) setProgressPercent:(NSNumber *)percent {
5666 [progress_ setPercent:[percent floatValue]];
5667 [self updateProgress];
5670 - (void) setProgressStatus:(NSDictionary *)status {
5671 if (status == nil) {
5672 [progress_ setCurrent:0];
5673 [progress_ setTotal:0];
5674 [progress_ setSpeed:0];
5676 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5678 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5679 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5680 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5683 [self updateProgress];
5689 /* Package Cell {{{ */
5690 @interface PackageCell : CyteTableViewCell <
5691 CyteTableViewCellDelegate
5695 _H<NSString> description_;
5697 _H<NSString> source_;
5699 _H<UIImage> placard_;
5703 - (PackageCell *) init;
5704 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5706 - (void) drawContentRect:(CGRect)rect;
5710 @implementation PackageCell
5712 - (PackageCell *) init {
5713 CGRect frame(CGRectMake(0, 0, 320, 74));
5714 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5715 UIView *content([self contentView]);
5716 CGRect bounds([content bounds]);
5718 self.content = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5719 [self.content setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5720 [content addSubview:self.content];
5722 [self.content setDelegate:self];
5723 [self.content setOpaque:YES];
5727 - (NSString *) accessibilityLabel {
5731 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5732 summarized_ = summary;
5742 [self.content setBackgroundColor:[UIColor whiteColor]];
5746 Source *source = [package source];
5748 icon_ = [package icon];
5750 if (NSString *name = [package name])
5751 name_ = [NSString stringWithString:name];
5753 if (NSString *description = [package shortDescription])
5754 description_ = [NSString stringWithString:description];
5756 commercial_ = [package isCommercial];
5758 NSString *label = nil;
5759 bool trusted = false;
5761 if (source != nil) {
5762 label = [source label];
5763 trusted = [source trusted];
5764 } else if ([[package id] isEqualToString:@"firmware"])
5765 label = UCLocalize("APPLE");
5767 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5769 NSString *from(label);
5771 NSString *section = [package simpleSection];
5772 if (section != nil && ![section isEqualToString:label]) {
5773 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5774 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5777 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5779 if (NSString *purpose = [package primaryPurpose])
5780 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5785 if (NSString *mode = [package mode]) {
5786 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5787 color = RemovingColor_;
5788 placard = @"removing";
5790 color = InstallingColor_;
5791 placard = @"installing";
5794 color = [UIColor whiteColor];
5796 if ([package installed] != nil)
5797 placard = @"installed";
5802 [self.content setBackgroundColor:color];
5805 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5808 [self setNeedsDisplay];
5809 [self.content setNeedsDisplay];
5812 - (void) drawSummaryContentRect:(CGRect)rect {
5813 bool highlighted(self.highlighted);
5814 float width([self bounds].size.width);
5818 rect.size = [(UIImage *) icon_ size];
5820 while (rect.size.width > 16 || rect.size.height > 16) {
5821 rect.size.width /= 2;
5822 rect.size.height /= 2;
5825 rect.origin.x = 19 - rect.size.width / 2;
5826 rect.origin.y = 19 - rect.size.height / 2;
5828 [icon_ drawInRect:Retina(rect)];
5831 if (badge_ != nil) {
5833 rect.size = [(UIImage *) badge_ size];
5835 rect.size.width /= 4;
5836 rect.size.height /= 4;
5838 rect.origin.x = 25 - rect.size.width / 2;
5839 rect.origin.y = 25 - rect.size.height / 2;
5841 [badge_ drawInRect:Retina(rect)];
5844 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5848 UISetColor(commercial_ ? Purple_ : Black_);
5849 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
5851 if (placard_ != nil)
5852 [placard_ drawAtPoint:CGPointMake(width - 52, 11)];
5855 - (void) drawNormalContentRect:(CGRect)rect {
5856 bool highlighted(self.highlighted);
5857 float width([self bounds].size.width);
5861 rect.size = [(UIImage *) icon_ size];
5863 while (rect.size.width > 32 || rect.size.height > 32) {
5864 rect.size.width /= 2;
5865 rect.size.height /= 2;
5868 rect.origin.x = 25 - rect.size.width / 2;
5869 rect.origin.y = 25 - rect.size.height / 2;
5871 [icon_ drawInRect:Retina(rect)];
5874 if (badge_ != nil) {
5876 rect.size = [(UIImage *) badge_ size];
5878 rect.size.width /= 2;
5879 rect.size.height /= 2;
5881 rect.origin.x = 36 - rect.size.width / 2;
5882 rect.origin.y = 36 - rect.size.height / 2;
5884 [badge_ drawInRect:Retina(rect)];
5887 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5891 UISetColor(commercial_ ? Purple_ : Black_);
5892 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
5893 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
5896 UISetColor(commercial_ ? Purplish_ : Gray_);
5897 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:NSLineBreakByTruncatingTail];
5899 if (placard_ != nil)
5900 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5903 - (void) drawContentRect:(CGRect)rect {
5905 [self drawSummaryContentRect:rect];
5907 [self drawNormalContentRect:rect];
5912 /* Section Cell {{{ */
5913 @interface SectionCell : CyteTableViewCell <
5914 CyteTableViewCellDelegate
5916 _H<NSString> basic_;
5917 _H<NSString> section_;
5919 _H<NSString> count_;
5921 _H<UISwitch> switch_;
5925 - (void) setSection:(Section *)section editing:(BOOL)editing;
5929 @implementation SectionCell
5931 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5932 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5933 icon_ = [UIImage imageNamed:@"folder.png"];
5934 // XXX: this initial frame is wrong, but is fixed later
5935 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5936 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5938 UIView *content([self contentView]);
5939 CGRect bounds([content bounds]);
5941 self.content = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5942 [self.content setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5943 [content addSubview:self.content];
5944 [self.content setBackgroundColor:[UIColor whiteColor]];
5946 [self.content setDelegate:self];
5950 - (void) onSwitch:(id)sender {
5951 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5952 if (metadata == nil) {
5953 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5954 [Sections_ setObject:metadata forKey:basic_];
5957 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5960 - (void) setSection:(Section *)section editing:(BOOL)editing {
5961 if (editing != editing_) {
5963 [switch_ removeFromSuperview];
5965 [self addSubview:switch_];
5974 if (section == nil) {
5975 name_ = UCLocalize("ALL_PACKAGES");
5978 basic_ = [section name];
5979 section_ = [section localized];
5981 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
5982 count_ = [NSString stringWithFormat:@"%zd", [section count]];
5985 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5988 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5989 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5991 [self.content setNeedsDisplay];
5994 - (void) setFrame:(CGRect)frame {
5995 [super setFrame:frame];
5997 CGRect rect([switch_ frame]);
5998 [switch_ setFrame:CGRectMake(frame.size.width - rect.size.width - 9, 9, rect.size.width, rect.size.height)];
6001 - (NSString *) accessibilityLabel {
6005 - (void) drawContentRect:(CGRect)rect {
6006 bool highlighted(self.highlighted && !editing_);
6008 [icon_ drawInRect:CGRectMake(7, 7, 32, 32)];
6010 if (highlighted && kCFCoreFoundationVersionNumber < 800)
6013 float width(rect.size.width);
6015 width -= 9 + [switch_ frame].size.width;
6019 [name_ drawAtPoint:CGPointMake(48, 12) forWidth:(width - 58) withFont:Font18_ lineBreakMode:NSLineBreakByTruncatingTail];
6021 CGSize size = [count_ sizeWithFont:Font14_];
6023 UISetColor(Folder_);
6025 [count_ drawAtPoint:CGPointMake(Retina(10 + (30 - size.width) / 2), 18) withFont:Font12Bold_];
6031 /* File Table {{{ */
6032 @interface FileTable : CyteViewController <
6033 UITableViewDataSource,
6036 _transient Database *database_;
6037 _H<Package> package_;
6039 _H<NSMutableArray> files_;
6040 _H<UITableView, 2> list_;
6043 - (id) initWithDatabase:(Database *)database;
6044 - (void) setPackage:(Package *)package;
6048 @implementation FileTable
6050 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6051 return files_ == nil ? 0 : [files_ count];
6054 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6058 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6059 static NSString *reuseIdentifier = @"Cell";
6061 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6063 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6064 [cell setFont:[UIFont systemFontOfSize:16]];
6066 [cell setText:[files_ objectAtIndex:indexPath.row]];
6067 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
6072 - (NSURL *) navigationURL {
6073 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
6077 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
6078 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6079 [list_ setRowHeight:24.0f];
6080 [(UITableView *) list_ setDataSource:self];
6081 [list_ setDelegate:self];
6082 [self setView:list_];
6085 - (void) viewDidLoad {
6086 [super viewDidLoad];
6088 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
6091 - (void) releaseSubviews {
6097 [super releaseSubviews];
6100 - (id) initWithDatabase:(Database *)database {
6101 if ((self = [super init]) != nil) {
6102 database_ = database;
6106 - (void) setPackage:(Package *)package {
6110 files_ = [NSMutableArray arrayWithCapacity:32];
6112 if (package != nil) {
6114 name_ = [package id];
6116 if (NSArray *files = [package files])
6117 [files_ addObjectsFromArray:files];
6119 if ([files_ count] != 0) {
6120 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
6121 [files_ removeObjectAtIndex:0];
6122 [files_ sortUsingSelector:@selector(compareByPath:)];
6124 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
6125 [stack addObject:@"/"];
6127 for (int i(0), e([files_ count]); i != e; ++i) {
6128 NSString *file = [files_ objectAtIndex:i];
6129 while (![file hasPrefix:[stack lastObject]])
6130 [stack removeLastObject];
6131 NSString *directory = [stack lastObject];
6132 [stack addObject:[file stringByAppendingString:@"/"]];
6133 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
6134 int(([stack count] - 2) * 3), "",
6135 [file substringFromIndex:[directory length]]
6144 - (void) reloadData {
6147 [self setPackage:[database_ packageWithName:name_]];
6152 /* Package Controller {{{ */
6153 @interface CYPackageController : CydiaWebViewController <
6154 UIActionSheetDelegate
6156 _transient Database *database_;
6157 _H<Package> package_;
6160 std::vector<std::pair<_H<NSString>, _H<NSString>>> buttons_;
6161 _H<UIActionSheet> sheet_;
6162 _H<UIBarButtonItem> button_;
6163 _H<NSArray> versions_;
6166 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer;
6170 @implementation CYPackageController
6172 - (NSURL *) navigationURL {
6173 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
6176 - (void) _clickButtonWithPackage:(Package *)package {
6177 [self.delegate installPackage:package];
6180 - (void) _clickButtonWithName:(NSString *)name {
6181 if ([name isEqualToString:@"CLEAR"])
6182 return [self.delegate clearPackage:package_];
6183 else if ([name isEqualToString:@"REMOVE"])
6184 return [self.delegate removePackage:package_];
6185 else if ([name isEqualToString:@"DOWNGRADE"]) {
6186 sheet_ = [[[UIActionSheet alloc]
6189 cancelButtonTitle:nil
6190 destructiveButtonTitle:nil
6191 otherButtonTitles:nil
6194 for (Package *version in (id) versions_)
6195 [sheet_ addButtonWithTitle:[version latest]];
6196 [sheet_ setContext:@"version"];
6198 [self.delegate showActionSheet:sheet_ fromItem:[[self navigationItem] rightBarButtonItem]];
6202 else if ([name isEqualToString:@"INSTALL"]);
6203 else if ([name isEqualToString:@"REINSTALL"]);
6204 else if ([name isEqualToString:@"UPGRADE"]);
6205 else _assert(false);
6207 [self.delegate installPackage:package_];
6210 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
6211 NSString *context([sheet context]);
6212 if (sheet_ == sheet)
6215 if ([context isEqualToString:@"modify"]) {
6216 if (button != [sheet cancelButtonIndex]) {
6218 [self performSelector:@selector(_clickButtonWithName:) withObject:buttons_[button].first afterDelay:0];
6220 [self _clickButtonWithName:buttons_[button].first];
6223 [sheet dismissWithClickedButtonIndex:button animated:YES];
6224 } else if ([context isEqualToString:@"version"]) {
6225 if (button != [sheet cancelButtonIndex]) {
6226 Package *version([versions_ objectAtIndex:button]);
6228 [self performSelector:@selector(_clickButtonWithPackage:) withObject:version afterDelay:0];
6230 [self _clickButtonWithPackage:version];
6233 [sheet dismissWithClickedButtonIndex:button animated:YES];
6237 - (bool) _allowJavaScriptPanel {
6242 - (void) _customButtonClicked {
6243 if (commercial_ && self.isLoading && [package_ uninstalled])
6244 return [self reloadURLWithCache:NO];
6246 size_t count(buttons_.size());
6251 [self _clickButtonWithName:buttons_[0].first];
6253 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
6254 for (const auto &button : buttons_)
6255 [buttons addObject:button.second];
6257 sheet_ = [[[UIActionSheet alloc]
6260 cancelButtonTitle:nil
6261 destructiveButtonTitle:nil
6262 otherButtonTitles:nil
6265 for (NSString *button in buttons)
6266 [sheet_ addButtonWithTitle:button];
6267 [sheet_ setContext:@"modify"];
6269 [self.delegate showActionSheet:sheet_ fromItem:[[self navigationItem] rightBarButtonItem]];
6273 - (void) applyLoadingTitle {
6274 // Don't show "Loading" as the title. Ever.
6277 - (UIBarButtonItem *) rightButton {
6282 - (void) setPageColor:(UIColor *)color {
6283 return [super setPageColor:nil];
6286 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer {
6287 if ((self = [super init]) != nil) {
6288 database_ = database;
6289 name_ = name == nil ? @"" : [NSString stringWithString:name];
6290 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]] withReferrer:referrer];
6294 - (void) reloadData {
6297 [sheet_ dismissWithClickedButtonIndex:[sheet_ cancelButtonIndex] animated:YES];
6300 package_ = [database_ packageWithName:name_];
6301 versions_ = [package_ downgrades];
6305 if (package_ != nil) {
6306 [(Package *) package_ parse];
6308 commercial_ = [package_ isCommercial];
6310 if ([package_ mode] != nil)
6311 buttons_.push_back(std::make_pair(@"CLEAR", UCLocalize("CLEAR")));
6312 if ([package_ source] == nil);
6313 else if ([package_ upgradableAndEssential:NO])
6314 buttons_.push_back(std::make_pair(@"UPGRADE", UCLocalize("UPGRADE")));
6315 else if ([package_ uninstalled])
6316 buttons_.push_back(std::make_pair(@"INSTALL", UCLocalize("INSTALL")));
6318 buttons_.push_back(std::make_pair(@"REINSTALL", UCLocalize("REINSTALL")));
6319 if (![package_ uninstalled])
6320 buttons_.push_back(std::make_pair(@"REMOVE", UCLocalize("REMOVE")));
6321 if ([versions_ count] != 0)
6322 buttons_.push_back(std::make_pair(@"DOWNGRADE", UCLocalize("DOWNGRADE")));
6326 switch (buttons_.size()) {
6327 case 0: title = nil; break;
6328 case 1: title = buttons_[0].second; break;
6329 default: title = UCLocalize("MODIFY"); break;
6332 button_ = [[[UIBarButtonItem alloc]
6334 style:UIBarButtonItemStylePlain
6336 action:@selector(customButtonClicked)
6340 - (bool) isLoading {
6341 return commercial_ ? [super isLoading] : false;
6347 /* Package List Controller {{{ */
6348 @interface PackageListController : CyteViewController <
6349 UITableViewDataSource,
6352 _transient Database *database_;
6354 _H<NSArray> packages_;
6355 _H<NSArray> sections_;
6356 _H<UITableView, 2> list_;
6358 _H<NSArray> thumbs_;
6359 std::vector<NSInteger> offset_;
6361 _H<NSString> title_;
6362 unsigned reloading_;
6365 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6366 - (void) resetCursor;
6369 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages;
6373 @implementation PackageListController
6375 - (NSURL *) referrerURL {
6376 return [self navigationURL];
6379 - (bool) isSummarized {
6383 - (bool) showsSections {
6387 - (void) deselectWithAnimation:(BOOL)animated {
6388 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6391 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6392 CGRect base = [[self view] bounds];
6393 base.size.height -= bounds.size.height;
6394 base.origin = [list_ frame].origin;
6396 [UIView beginAnimations:nil context:NULL];
6397 [UIView setAnimationBeginsFromCurrentState:YES];
6398 [UIView setAnimationCurve:curve];
6399 [UIView setAnimationDuration:duration];
6400 [list_ setFrame:base];
6401 [UIView commitAnimations];
6404 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6405 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6408 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6409 [self resizeForKeyboardBounds:bounds duration:0];
6412 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6413 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6414 *curve = UIViewAnimationCurveEaseInOut;
6416 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6418 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6421 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6424 - (void) keyboardWillShow:(NSNotification *)notification {
6427 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6428 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6430 NSTimeInterval duration;
6431 UIViewAnimationCurve curve;
6432 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6434 CGRect kbframe = CGRectMake(Retina(center.x - bounds.size.width / 2), Retina(center.y - bounds.size.height / 2), bounds.size.width, bounds.size.height);
6435 UIViewController *base([self rootViewController]);
6436 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6437 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6439 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6440 intersection.size.height += CYStatusBarHeight();
6442 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6445 - (void) keyboardWillHide:(NSNotification *)notification {
6446 NSTimeInterval duration;
6447 UIViewAnimationCurve curve;
6448 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6450 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6453 - (void) viewWillAppear:(BOOL)animated {
6454 [super viewWillAppear:animated];
6456 [self resizeForKeyboardBounds:CGRectZero];
6457 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6458 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6461 - (void) viewWillDisappear:(BOOL)animated {
6462 [super viewWillDisappear:animated];
6464 [self resizeForKeyboardBounds:CGRectZero];
6465 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6466 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6469 - (void) viewDidAppear:(BOOL)animated {
6470 [super viewDidAppear:animated];
6471 [self deselectWithAnimation:animated];
6474 - (void) didSelectPackage:(Package *)package {
6475 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[[self referrerURL] absoluteString]] autorelease]);
6476 [view setDelegate:self.delegate];
6477 [[self navigationController] pushViewController:view animated:YES];
6480 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6481 NSInteger count([sections_ count]);
6482 return count == 0 ? 1 : count;
6485 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6486 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6488 return [[sections_ objectAtIndex:section] name];
6491 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6492 if ([sections_ count] == 0)
6494 return [[sections_ objectAtIndex:section] count];
6497 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6498 @synchronized (database_) {
6499 if ([database_ era] != era_)
6502 Section *section([sections_ objectAtIndex:[path section]]);
6503 NSInteger row([path row]);
6504 Package *package([packages_ objectAtIndex:([section row] + row)]);
6505 return [[package retain] autorelease];
6508 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6509 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6511 cell = [[[PackageCell alloc] init] autorelease];
6513 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6514 [cell setPackage:package asSummary:[self isSummarized]];
6518 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6519 Package *package([self packageAtIndexPath:path]);
6520 package = [database_ packageWithName:[package id]];
6521 [self didSelectPackage:package];
6524 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6528 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6529 return offset_[index];
6532 - (void) updateHeight {
6533 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6536 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6537 if ((self = [super init]) != nil) {
6538 database_ = database;
6539 title_ = [title copy];
6540 [[self navigationItem] setTitle:title_];
6545 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
6546 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
6547 [self setView:view];
6549 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6550 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6551 [view addSubview:list_];
6553 // XXX: is 20 the most optimal number here?
6554 [list_ setSectionIndexMinimumDisplayRowCount:20];
6556 [(UITableView *) list_ setDataSource:self];
6557 [list_ setDelegate:self];
6559 [self updateHeight];
6562 - (void) releaseSubviews {
6571 [super releaseSubviews];
6574 - (bool) shouldYield {
6578 - (bool) shouldBlock {
6582 - (NSMutableArray *) _reloadPackages {
6583 @synchronized (database_) {
6584 era_ = [database_ era];
6585 NSArray *packages([database_ packages]);
6587 return [NSMutableArray arrayWithArray:packages];
6590 - (void) _reloadData {
6591 if (reloading_ != 0) {
6596 NSMutableArray *packages;
6599 if ([self shouldYield]) {
6603 if (![self shouldBlock])
6606 hud = [self.delegate addProgressHUD];
6607 [hud setText:UCLocalize("LOADING")];
6611 packages = [self yieldToSelector:@selector(_reloadPackages)];
6614 [self.delegate removeProgressHUD:hud];
6615 } while (reloading_ == 2);
6617 packages = [self _reloadPackages];
6620 @synchronized (database_) {
6621 if (era_ != [database_ era])
6628 packages_ = packages;
6630 if ([self showsSections])
6631 sections_ = [self sectionsForPackages:packages];
6633 Section *section([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6634 [section setCount:[packages_ count]];
6635 sections_ = [NSArray arrayWithObject:section];
6638 [self updateHeight];
6640 _profile(PackageTable$reloadData$List)
6641 [(UITableView *) list_ setDataSource:self];
6649 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
6650 Section *prefix([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6651 size_t end([packages count]);
6653 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
6654 Section *section(prefix);
6656 thumbs_ = CollationThumbs_;
6657 offset_ = CollationOffset_;
6660 size_t offsets([CollationStarts_ count]);
6662 NSString *start([CollationStarts_ objectAtIndex:offset]);
6663 size_t length([start length]);
6665 for (size_t index(0); index != end; ++index) {
6667 Package *package([packages objectAtIndex:index]);
6668 NSString *name(PackageName(package, @selector(cyname)));
6670 //while ([start compare:name options:NSNumericSearch range:NSMakeRange(0, length) locale:CollationLocale_] != NSOrderedDescending) {
6671 while (StringNameCompare(start, name, length) != kCFCompareGreaterThan) {
6672 NSString *title([CollationTitles_ objectAtIndex:offset]);
6673 section = [[[Section alloc] initWithName:title row:index localize:NO] autorelease];
6674 [sections addObject:section];
6676 start = ++offset == offsets ? nil : [CollationStarts_ objectAtIndex:offset];
6679 length = [start length];
6683 [section addToCount];
6686 for (; offset != offsets; ++offset) {
6687 NSString *title([CollationTitles_ objectAtIndex:offset]);
6688 Section *section([[[Section alloc] initWithName:title row:end localize:NO] autorelease]);
6689 [sections addObject:section];
6692 if ([prefix count] != 0) {
6693 Section *suffix([sections lastObject]);
6694 [prefix setName:[suffix name]];
6695 [suffix setName:nil];
6696 [sections insertObject:prefix atIndex:(offsets - 1)];
6702 - (void) reloadData {
6705 if ([self shouldYield])
6706 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6711 - (void) resetCursor {
6712 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6715 - (void) clearData {
6716 [self updateHeight];
6718 [list_ setDataSource:nil];
6726 /* Filtered Package List Controller {{{ */
6727 typedef Function<bool, Package *> PackageFilter;
6728 typedef Function<void, NSMutableArray *> PackageSorter;
6729 @interface FilteredPackageListController : PackageListController {
6730 PackageFilter filter_;
6731 PackageSorter sorter_;
6734 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter;
6736 - (void) setFilter:(PackageFilter)filter;
6737 - (void) setSorter:(PackageSorter)sorter;
6741 @implementation FilteredPackageListController
6743 - (void) setFilter:(PackageFilter)filter {
6744 @synchronized (self) {
6748 - (void) setSorter:(PackageSorter)sorter {
6749 @synchronized (self) {
6753 - (NSMutableArray *) _reloadPackages {
6754 @synchronized (database_) {
6755 era_ = [database_ era];
6757 NSArray *packages([database_ packages]);
6758 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6760 PackageFilter filter;
6761 PackageSorter sorter;
6763 @synchronized (self) {
6768 _profile(PackageTable$reloadData$Filter)
6769 for (Package *package in packages)
6770 if (filter(package))
6771 [filtered addObject:package];
6779 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter {
6780 if ((self = [super initWithDatabase:database title:title]) != nil) {
6781 [self setFilter:filter];
6788 /* Home Controller {{{ */
6789 @interface HomeController : CydiaWebViewController {
6790 CFRunLoopRef runloop_;
6791 SCNetworkReachabilityRef reachability_;
6796 @implementation HomeController
6798 static void HomeControllerReachabilityCallback(SCNetworkReachabilityRef reachability, SCNetworkReachabilityFlags flags, void *info) {
6799 [(HomeController *) info dispatchEvent:@"CydiaReachabilityCallback"];
6803 if ((self = [super init]) != nil) {
6804 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6807 reachability_ = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "cydia.saurik.com");
6808 if (reachability_ != NULL) {
6809 SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
6810 SCNetworkReachabilitySetCallback(reachability_, HomeControllerReachabilityCallback, &context);
6812 CFRunLoopRef runloop(CFRunLoopGetCurrent());
6813 if (SCNetworkReachabilityScheduleWithRunLoop(reachability_, runloop, kCFRunLoopDefaultMode))
6820 if (reachability_ != NULL && runloop_ != NULL)
6821 SCNetworkReachabilityUnscheduleFromRunLoop(reachability_, runloop_, kCFRunLoopDefaultMode);
6825 - (NSURL *) navigationURL {
6826 return [NSURL URLWithString:@"cydia://home"];
6829 - (void) aboutButtonClicked {
6830 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6832 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6833 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6834 [alert setCancelButtonIndex:0];
6837 @"Copyright \u00a9 2008-2015\n"
6840 "Jay Freeman (saurik)\n"
6841 "saurik@saurik.com\n"
6842 "http://www.saurik.com/"
6848 - (UIBarButtonItem *) leftButton {
6849 return [[[UIBarButtonItem alloc]
6850 initWithTitle:UCLocalize("ABOUT")
6851 style:UIBarButtonItemStylePlain
6853 action:@selector(aboutButtonClicked)
6860 /* Cydia Tab Bar Controller {{{ */
6861 @interface CydiaTabBarController : CyteTabBarController <
6862 UITabBarControllerDelegate,
6865 _transient Database *database_;
6867 _H<UIActivityIndicatorView> indicator_;
6870 // XXX: ok, "updatedelegate_"?...
6871 _transient NSObject<CydiaDelegate> *updatedelegate_;
6874 - (void) beginUpdate;
6879 @implementation CydiaTabBarController
6881 - (id) initWithDatabase:(Database *)database {
6882 if ((self = [super init]) != nil) {
6883 database_ = database;
6884 [self setDelegate:self];
6886 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteTiny] autorelease];
6887 [indicator_ setOrigin:CGPointMake(kCFCoreFoundationVersionNumber >= 800 ? 2 : 4, 2)];
6889 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6893 - (void) beginUpdate {
6897 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
6898 UITabBarItem *item([controller tabBarItem]);
6900 [item setBadgeValue:@""];
6901 UIView *badge(MSHookIvar<UIView *>([item view], "_badge"));
6903 [indicator_ startAnimating];
6904 [badge addSubview:indicator_];
6906 [updatedelegate_ retainNetworkActivityIndicator];
6910 detachNewThreadSelector:@selector(performUpdate)
6916 - (void) performUpdate {
6917 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
6919 SourceStatus status(self, database_);
6920 [database_ updateWithStatus:status];
6923 performSelectorOnMainThread:@selector(completeUpdate)
6931 - (void) stopUpdateWithSelector:(SEL)selector {
6933 [updatedelegate_ releaseNetworkActivityIndicator];
6935 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
6936 [[controller tabBarItem] setBadgeValue:nil];
6938 [indicator_ removeFromSuperview];
6939 [indicator_ stopAnimating];
6941 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6944 - (void) completeUpdate {
6947 [self stopUpdateWithSelector:@selector(reloadData)];
6950 - (void) cancelUpdate {
6951 [self stopUpdateWithSelector:@selector(updateDataAndLoad)];
6954 - (void) cancelPressed {
6955 [self cancelUpdate];
6962 - (bool) isSourceCancelled {
6966 - (void) startSourceFetch:(NSString *)uri {
6969 - (void) stopSourceFetch:(NSString *)uri {
6972 - (void) setUpdateDelegate:(id)delegate {
6973 updatedelegate_ = delegate;
6979 /* Cydia:// Protocol {{{ */
6980 @interface CydiaURLProtocol : NSURLProtocol {
6985 @implementation CydiaURLProtocol
6987 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6988 NSURL *url([request URL]);
6992 NSString *scheme([[url scheme] lowercaseString]);
6993 if (scheme != nil && [scheme isEqualToString:@"cydia"])
6995 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7001 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7005 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7006 id<NSURLProtocolClient> client([self client]);
7008 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7010 NSData *data(UIImagePNGRepresentation(icon));
7012 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7013 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7014 [client URLProtocol:self didLoadData:data];
7015 [client URLProtocolDidFinishLoading:self];
7019 - (void) startLoading {
7020 id<NSURLProtocolClient> client([self client]);
7021 NSURLRequest *request([self request]);
7023 NSURL *url([request URL]);
7024 NSString *href([url absoluteString]);
7025 NSString *scheme([[url scheme] lowercaseString]);
7029 if ([scheme isEqualToString:@"cydia"])
7030 path = [href substringFromIndex:8];
7031 else if ([scheme isEqualToString:@"about"])
7032 path = [href substringFromIndex:12];
7033 else _assert(false);
7035 NSRange slash([path rangeOfString:@"/"]);
7038 if (slash.location == NSNotFound) {
7042 command = [path substringToIndex:slash.location];
7043 path = [path substringFromIndex:(slash.location + 1)];
7046 Database *database([Database sharedInstance]);
7049 else if ([command isEqualToString:@"application-icon"]) {
7052 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7056 if (icon == nil && $SBSCopyIconImagePNGDataForDisplayIdentifier != NULL) {
7057 NSData *data([$SBSCopyIconImagePNGDataForDisplayIdentifier(path) autorelease]);
7058 icon = [UIImage imageWithData:data];
7062 if (NSString *file = SBSCopyIconImagePathForDisplayIdentifier(path))
7063 icon = [UIImage imageAtPath:file];
7066 icon = [UIImage imageNamed:@"unknown.png"];
7068 [self _returnPNGWithImage:icon forRequest:request];
7069 } else if ([command isEqualToString:@"package-icon"]) {
7072 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7073 Package *package([database packageWithName:path]);
7077 UIImage *icon([package icon]);
7078 [self _returnPNGWithImage:icon forRequest:request];
7079 } else if ([command isEqualToString:@"uikit-image"]) {
7082 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7083 UIImage *icon(_UIImageWithName(path));
7084 [self _returnPNGWithImage:icon forRequest:request];
7085 } else if ([command isEqualToString:@"section-icon"]) {
7088 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7089 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7091 icon = [UIImage imageNamed:@"unknown.png"];
7092 [self _returnPNGWithImage:icon forRequest:request];
7094 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7098 - (void) stopLoading {
7104 /* Section Controller {{{ */
7105 @interface SectionController : FilteredPackageListController {
7107 _H<NSString> section_;
7110 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section;
7114 @implementation SectionController
7116 - (NSURL *) referrerURL {
7117 NSString *name(section_);
7118 name = name ?: @"*";
7119 NSString *key(key_);
7121 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sections/%@/%@", UI_, [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7124 - (NSURL *) navigationURL {
7125 NSString *name(section_);
7126 name = name ?: @"*";
7127 NSString *key(key_);
7129 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@/%@", [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7132 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section {
7135 title = UCLocalize("ALL_PACKAGES");
7136 else if (![section isEqual:@""])
7137 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(section) value:nil table:@"Sections"];
7139 title = UCLocalize("NO_SECTION");
7141 if ((self = [super initWithDatabase:database title:title]) != nil) {
7142 key_ = [source key];
7147 - (void) reloadData {
7148 Source *source([database_ sourceWithKey:key_]);
7149 _H<NSString> name(section_);
7151 [self setFilter:[=](Package *package) {
7152 NSString *section([package section]);
7156 section == nil && [name length] == 0 ||
7157 [name isEqualToString:section]
7160 [package source] == source
7161 ) && [package visible];
7169 /* Sections Controller {{{ */
7170 @interface SectionsController : CyteViewController <
7171 UITableViewDataSource,
7174 _transient Database *database_;
7176 _H<NSMutableArray> sections_;
7177 _H<NSMutableArray> filtered_;
7178 _H<UITableView, 2> list_;
7181 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7182 - (void) editButtonClicked;
7186 @implementation SectionsController
7188 - (NSURL *) navigationURL {
7189 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
7192 - (Source *) source {
7195 return [database_ sourceWithKey:key_];
7198 - (void) updateNavigationItem {
7199 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7200 if ([sections_ count] == 0) {
7201 [[self navigationItem] setRightBarButtonItem:nil];
7203 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7204 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7206 action:@selector(editButtonClicked)
7207 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7211 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7212 [super setEditing:editing animated:animated];
7217 [self.delegate updateData];
7219 [self updateNavigationItem];
7222 - (void) viewDidAppear:(BOOL)animated {
7223 [super viewDidAppear:animated];
7224 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7227 - (void) viewWillDisappear:(BOOL)animated {
7228 [super viewWillDisappear:animated];
7229 [self setEditing:NO];
7232 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7233 Section *section = nil;
7234 int index = [indexPath row];
7235 if (![self isEditing]) {
7238 section = [filtered_ objectAtIndex:index];
7240 section = [sections_ objectAtIndex:index];
7245 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7246 if ([self isEditing])
7247 return [sections_ count];
7249 return [filtered_ count] + 1;
7252 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7256 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7257 static NSString *reuseIdentifier = @"SectionCell";
7259 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7261 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7263 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7268 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7269 if ([self isEditing])
7272 Section *section = [self sectionAtIndexPath:indexPath];
7274 SectionController *controller = [[[SectionController alloc]
7275 initWithDatabase:database_
7276 source:[self source]
7277 section:[section name]
7279 [controller setDelegate:self.delegate];
7281 [[self navigationController] pushViewController:controller animated:YES];
7285 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
7286 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7287 [list_ setRowHeight:46];
7288 [(UITableView *) list_ setDataSource:self];
7289 [list_ setDelegate:self];
7290 [self setView:list_];
7293 - (void) viewDidLoad {
7294 [super viewDidLoad];
7296 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7299 - (void) releaseSubviews {
7305 [super releaseSubviews];
7308 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7309 if ((self = [super init]) != nil) {
7310 database_ = database;
7311 key_ = [source key];
7315 - (void) reloadData {
7318 NSArray *packages = [database_ packages];
7320 sections_ = [NSMutableArray arrayWithCapacity:16];
7321 filtered_ = [NSMutableArray arrayWithCapacity:16];
7323 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7325 Source *source([self source]);
7328 for (Package *package in packages) {
7329 if (source != nil && [package source] != source)
7332 NSString *name([package section]);
7333 NSString *key(name == nil ? @"" : name);
7337 _profile(SectionsView$reloadData$Section)
7338 section = [sections objectForKey:key];
7339 if (section == nil) {
7340 _profile(SectionsView$reloadData$Section$Allocate)
7341 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7342 [sections setObject:section forKey:key];
7347 [section addToCount];
7349 _profile(SectionsView$reloadData$Filter)
7350 if (![package visible])
7358 [sections_ addObjectsFromArray:[sections allValues]];
7360 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7362 for (Section *section in (id) sections_) {
7363 size_t count([section row]);
7367 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7368 [section setCount:count];
7369 [filtered_ addObject:section];
7372 [self updateNavigationItem];
7377 - (void) editButtonClicked {
7378 [self setEditing:![self isEditing] animated:YES];
7384 /* Changes Controller {{{ */
7385 @interface ChangesController : FilteredPackageListController {
7389 - (id) initWithDatabase:(Database *)database;
7393 @implementation ChangesController
7395 - (NSURL *) referrerURL {
7396 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/changes/", UI_]];
7399 - (NSURL *) navigationURL {
7400 return [NSURL URLWithString:@"cydia://changes"];
7403 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7404 @synchronized (database_) {
7405 if ([database_ era] != era_)
7408 NSUInteger sectionIndex([path section]);
7409 if (sectionIndex >= [sections_ count])
7411 Section *section([sections_ objectAtIndex:sectionIndex]);
7412 NSInteger row([path row]);
7413 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7416 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7417 NSString *context([alert context]);
7419 if ([context isEqualToString:@"norefresh"])
7420 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7423 - (void) setLeftBarButtonItem {
7424 if ([self.delegate updating])
7425 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7426 initWithTitle:UCLocalize("CANCEL")
7427 style:UIBarButtonItemStyleDone
7429 action:@selector(cancelButtonClicked)
7430 ] autorelease] animated:YES];
7432 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7433 initWithTitle:UCLocalize("REFRESH")
7434 style:UIBarButtonItemStylePlain
7436 action:@selector(refreshButtonClicked)
7437 ] autorelease] animated:YES];
7440 - (void) refreshButtonClicked {
7441 if ([self.delegate requestUpdate])
7442 [self setLeftBarButtonItem];
7445 - (void) cancelButtonClicked {
7446 [self.delegate cancelUpdate];
7449 - (void) upgradeButtonClicked {
7450 [self.delegate distUpgrade];
7451 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7454 - (bool) shouldYield {
7458 - (bool) shouldBlock {
7462 - (void) useFilter {
7463 @synchronized (self) {
7464 [self setFilter:[](Package *package) {
7465 return [package upgradableAndEssential:YES] || [package visible];
7468 [self setSorter:[](NSMutableArray *packages) {
7469 [packages radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7473 - (id) initWithDatabase:(Database *)database {
7474 if ((self = [super initWithDatabase:database title:UCLocalize("CHANGES")]) != nil) {
7479 - (void) viewDidLoad {
7480 [super viewDidLoad];
7481 [self setLeftBarButtonItem];
7484 - (void) viewWillAppear:(BOOL)animated {
7485 [super viewWillAppear:animated];
7486 [self setLeftBarButtonItem];
7489 - (void) reloadData {
7490 [self setLeftBarButtonItem];
7494 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
7495 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
7497 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7498 Section *ignored = nil;
7499 Section *section = nil;
7503 bool unseens = false;
7505 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7507 for (size_t offset = 0, count = [packages count]; offset != count; ++offset) {
7508 Package *package = [packages objectAtIndex:offset];
7510 BOOL uae = [package upgradableAndEssential:YES];
7514 time_t seen([package seen]);
7516 if (section == nil || last != seen) {
7520 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7523 _profile(ChangesController$reloadData$Allocate)
7524 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7525 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7526 [sections addObject:section];
7530 [section addToCount];
7531 } else if ([package ignored]) {
7532 if (ignored == nil) {
7533 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7535 [ignored addToCount];
7538 [upgradable addToCount];
7543 CFRelease(formatter);
7546 Section *last = [sections lastObject];
7547 size_t count = [last count];
7548 [packages removeObjectsInRange:NSMakeRange([packages count] - count, count)];
7549 [sections removeLastObject];
7552 if ([ignored count] != 0)
7553 [sections insertObject:ignored atIndex:0];
7555 [sections insertObject:upgradable atIndex:0];
7559 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7560 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7561 style:UIBarButtonItemStylePlain
7563 action:@selector(upgradeButtonClicked)
7564 ] autorelease]) animated:YES];
7571 /* Search Controller {{{ */
7572 @interface SearchController : FilteredPackageListController <
7575 _H<UISearchBar, 1> search_;
7580 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7581 - (void) reloadData;
7585 @implementation SearchController
7587 - (NSURL *) referrerURL {
7588 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/search?q=%@", UI_, [([search_ text] ?: @"") stringByAddingPercentEscapesIncludingReserved]]];
7591 - (NSURL *) navigationURL {
7592 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7593 return [NSURL URLWithString:@"cydia://search"];
7595 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [[search_ text] stringByAddingPercentEscapesIncludingReserved]]];
7598 - (NSArray *) termsForQuery:(NSString *)query {
7599 NSMutableArray *terms([NSMutableArray arrayWithCapacity:2]);
7600 for (NSString *component in [query componentsSeparatedByString:@" "])
7601 if ([component length] != 0)
7602 [terms addObject:component];
7607 - (void) useSearch {
7608 _H<NSArray> query([self termsForQuery:[search_ text]]);
7611 @synchronized (self) {
7612 [self setFilter:[=](Package *package) {
7613 if (![package unfiltered])
7615 if (![package matches:query])
7620 [self setSorter:[](NSMutableArray *packages) {
7621 [packages radixSortUsingSelector:@selector(rank)];
7629 - (void) usePrefix:(NSString *)prefix {
7630 _H<NSString> query(prefix);
7633 @synchronized (self) {
7634 [self setFilter:[=](Package *package) {
7635 if ([query length] == 0)
7637 if (![package unfiltered])
7639 if ([[package name] compare:query options:MatchCompareOptions_ range:NSMakeRange(0, [query length])] != NSOrderedSame)
7644 [self setSorter:nullptr];
7650 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7652 [self usePrefix:[search_ text]];
7655 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7656 [search_ resignFirstResponder];
7660 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7661 [search_ setText:@""];
7662 [self searchBarButtonClicked:searchBar];
7665 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7666 [self searchBarButtonClicked:searchBar];
7669 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7670 [self usePrefix:text];
7673 - (bool) shouldYield {
7677 - (bool) shouldBlock {
7681 - (bool) isSummarized {
7685 - (bool) showsSections {
7689 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7690 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH")])) {
7691 search_ = [[[UISearchBar alloc] init] autorelease];
7692 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7693 [search_ setDelegate:self];
7695 UITextField *textField;
7696 if ([search_ respondsToSelector:@selector(searchField)])
7697 textField = [search_ searchField];
7699 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7701 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7702 [textField setEnablesReturnKeyAutomatically:NO];
7703 [[self navigationItem] setTitleView:textField];
7706 [search_ setText:query];
7711 - (void) viewDidAppear:(BOOL)animated {
7712 [super viewDidAppear:animated];
7714 if (!searchloaded_) {
7715 searchloaded_ = YES;
7716 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7717 [search_ layoutSubviews];
7720 if ([self isSummarized])
7721 [search_ becomeFirstResponder];
7724 - (void) reloadData {
7729 - (void) didSelectPackage:(Package *)package {
7730 [search_ resignFirstResponder];
7731 [super didSelectPackage:package];
7736 /* Package Settings Controller {{{ */
7737 @interface PackageSettingsController : CyteViewController <
7738 UITableViewDataSource,
7741 _transient Database *database_;
7743 _H<Package> package_;
7744 _H<UITableView, 2> table_;
7745 _H<UISwitch> subscribedSwitch_;
7746 _H<UISwitch> ignoredSwitch_;
7747 _H<UITableViewCell> subscribedCell_;
7748 _H<UITableViewCell> ignoredCell_;
7751 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7755 @implementation PackageSettingsController
7757 - (NSURL *) navigationURL {
7758 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
7761 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7762 if (package_ == nil)
7765 if ([package_ installed] == nil)
7771 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7772 if (package_ == nil)
7775 // both sections contain just one item right now.
7779 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7783 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7785 return UCLocalize("SHOW_ALL_CHANGES_EX");
7787 return UCLocalize("IGNORE_UPGRADES_EX");
7790 - (void) onSubscribed:(id)control {
7791 bool value([control isOn]);
7792 if (package_ == nil)
7794 if ([package_ setSubscribed:value])
7795 [self.delegate updateData];
7798 - (void) _updateIgnored {
7799 const char *package([name_ UTF8String]);
7800 bool on([ignoredSwitch_ isOn]);
7802 FILE *dpkg(popen("/usr/libexec/cydia/cydo --set-selections", "w"));
7803 fwrite(package, strlen(package), 1, dpkg);
7806 fwrite(" hold\n", 6, 1, dpkg);
7808 fwrite(" install\n", 9, 1, dpkg);
7813 - (void) onIgnored:(id)control {
7814 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7815 [invocation setTarget:self];
7816 [invocation setSelector:@selector(_updateIgnored)];
7818 [self.delegate reloadDataWithInvocation:invocation];
7821 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7822 if (package_ == nil)
7825 switch ([indexPath section]) {
7826 case 0: return subscribedCell_;
7827 case 1: return ignoredCell_;
7836 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
7837 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
7838 [self setView:view];
7840 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7841 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7842 [(UITableView *) table_ setDataSource:self];
7843 [table_ setDelegate:self];
7844 [view addSubview:table_];
7846 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7847 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7848 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7850 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7851 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7852 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7854 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7855 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7856 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7857 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7859 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7860 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7861 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7862 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7865 - (void) viewDidLoad {
7866 [super viewDidLoad];
7868 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7871 - (void) releaseSubviews {
7873 subscribedCell_ = nil;
7875 ignoredSwitch_ = nil;
7876 subscribedSwitch_ = nil;
7878 [super releaseSubviews];
7881 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7882 if ((self = [super init]) != nil) {
7883 database_ = database;
7888 - (void) reloadData {
7891 package_ = [database_ packageWithName:name_];
7893 if (package_ != nil) {
7894 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7895 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7896 } // XXX: what now, G?
7898 [table_ reloadData];
7904 /* Installed Controller {{{ */
7905 @interface InstalledController : FilteredPackageListController {
7909 - (id) initWithDatabase:(Database *)database;
7910 - (void) queueStatusDidChange;
7914 @implementation InstalledController
7916 - (NSURL *) referrerURL {
7917 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/installed/", UI_]];
7920 - (NSURL *) navigationURL {
7921 return [NSURL URLWithString:@"cydia://installed"];
7924 - (void) useRecent {
7927 @synchronized (self) {
7928 [self setFilter:[](Package *package) {
7929 return ![package uninstalled] && package->role_ < 7;
7932 [self setSorter:[](NSMutableArray *packages) {
7933 [packages radixSortUsingSelector:@selector(recent)];
7937 - (void) useFilter:(UISegmentedControl *)segmented {
7938 NSInteger selected([segmented selectedSegmentIndex]);
7940 return [self useRecent];
7941 bool simple(selected == 0);
7944 @synchronized (self) {
7945 [self setFilter:[=](Package *package) {
7946 return ![package uninstalled] && package->role_ <= (simple ? 1 : 3);
7949 [self setSorter:nullptr];
7952 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
7954 return [super sectionsForPackages:packages];
7956 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterLongStyle, kCFDateFormatterNoStyle));
7958 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
7959 Section *section(nil);
7962 for (size_t offset(0), count([packages count]); offset != count; ++offset) {
7963 Package *package([packages objectAtIndex:offset]);
7965 time_t upgraded([package upgraded]);
7966 if (upgraded < 1168364520)
7969 upgraded -= upgraded % (60 * 60 * 24);
7971 if (section == nil || upgraded != last) {
7976 continue; // XXX: name = UCLocalize("...");
7978 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:upgraded]);
7982 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7983 [sections addObject:section];
7986 [section addToCount];
7989 CFRelease(formatter);
7993 - (id) initWithDatabase:(Database *)database {
7994 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED")]) != nil) {
7995 UISegmentedControl *segmented([[[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:UCLocalize("USER"), UCLocalize("EXPERT"), UCLocalize("RECENT"), nil]] autorelease]);
7996 [segmented setSelectedSegmentIndex:0];
7997 [segmented setSegmentedControlStyle:UISegmentedControlStyleBar];
7998 [[self navigationItem] setTitleView:segmented];
8000 [segmented addTarget:self action:@selector(modeChanged:) forEvents:UIControlEventValueChanged];
8001 [self useFilter:segmented];
8003 [self queueStatusDidChange];
8008 - (void) queueButtonClicked {
8009 [self.delegate queue];
8013 - (void) queueStatusDidChange {
8016 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8017 initWithTitle:UCLocalize("QUEUE")
8018 style:UIBarButtonItemStyleDone
8020 action:@selector(queueButtonClicked)
8023 [[self navigationItem] setRightBarButtonItem:nil];
8028 - (void) modeChanged:(UISegmentedControl *)segmented {
8029 [self useFilter:segmented];
8036 /* Source Cell {{{ */
8037 @interface SourceCell : CyteTableViewCell <
8038 CyteTableViewCellDelegate,
8041 _H<Source, 1> source_;
8044 _H<NSString> origin_;
8045 _H<NSString> label_;
8046 _H<UIActivityIndicatorView> indicator_;
8049 - (void) setSource:(Source *)source;
8050 - (void) setFetch:(NSNumber *)fetch;
8054 @implementation SourceCell
8056 - (void) _setImage:(NSArray *)data {
8057 if ([url_ isEqual:[data objectAtIndex:0]]) {
8058 icon_ = [data objectAtIndex:1];
8059 [self.content setNeedsDisplay];
8063 - (void) _setSource:(NSURL *) url {
8064 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8066 if (NSData *data = [NSURLConnection
8067 sendSynchronousRequest:[NSURLRequest
8069 cachePolicy:NSURLRequestUseProtocolCachePolicy
8073 returningResponse:NULL
8076 if (UIImage *image = [UIImage imageWithData:data])
8077 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
8082 - (void) setSource:(Source *)source {
8084 [source_ setDelegate:self];
8086 [self setFetch:[NSNumber numberWithBool:[source_ fetch]]];
8088 icon_ = [UIImage imageNamed:@"unknown.png"];
8090 origin_ = [source name];
8091 label_ = [source rooturi];
8093 [self.content setNeedsDisplay];
8095 url_ = [source iconURL];
8096 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
8099 - (void) setAllSource {
8101 [indicator_ stopAnimating];
8103 icon_ = [UIImage imageNamed:@"folder.png"];
8104 origin_ = UCLocalize("ALL_SOURCES");
8105 label_ = UCLocalize("ALL_SOURCES_EX");
8106 [self.content setNeedsDisplay];
8109 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8110 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8111 UIView *content([self contentView]);
8112 CGRect bounds([content bounds]);
8114 self.content = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8115 [self.content setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8116 [self.content setBackgroundColor:[UIColor whiteColor]];
8117 [content addSubview:self.content];
8119 [self.content setDelegate:self];
8120 [self.content setOpaque:YES];
8122 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGraySmall] autorelease];
8123 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin];// | UIViewAutoresizingFlexibleBottomMargin];
8124 [content addSubview:indicator_];
8126 [[self.content layer] setContentsGravity:kCAGravityTopLeft];
8130 - (void) layoutSubviews {
8131 [super layoutSubviews];
8133 UIView *content([self contentView]);
8134 CGRect bounds([content bounds]);
8136 CGRect frame([indicator_ frame]);
8137 frame.origin.x = bounds.size.width - frame.size.width;
8138 frame.origin.y = Retina((bounds.size.height - frame.size.height) / 2);
8140 if (kCFCoreFoundationVersionNumber < 800)
8141 frame.origin.x -= 8;
8142 [indicator_ setFrame:frame];
8145 - (NSString *) accessibilityLabel {
8149 - (void) drawContentRect:(CGRect)rect {
8150 bool highlighted(self.highlighted);
8151 float width(rect.size.width);
8155 rect.size = [(UIImage *) icon_ size];
8157 while (rect.size.width > 32 || rect.size.height > 32) {
8158 rect.size.width /= 2;
8159 rect.size.height /= 2;
8162 rect.origin.x = 26 - rect.size.width / 2;
8163 rect.origin.y = 26 - rect.size.height / 2;
8165 [icon_ drawInRect:Retina(rect)];
8168 if (highlighted && kCFCoreFoundationVersionNumber < 800)
8173 [origin_ drawAtPoint:CGPointMake(52, 8) forWidth:(width - 49) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
8177 [label_ drawAtPoint:CGPointMake(52, 29) forWidth:(width - 49) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
8180 - (void) setFetch:(NSNumber *)fetch {
8181 if ([fetch boolValue])
8182 [indicator_ startAnimating];
8184 [indicator_ stopAnimating];
8189 /* Sources Controller {{{ */
8190 @interface SourcesController : CyteViewController <
8191 UITableViewDataSource,
8194 _transient Database *database_;
8197 _H<UITableView, 2> list_;
8198 _H<NSMutableArray> sources_;
8202 _H<UIProgressHUD> hud_;
8205 NSURLConnection *trivial_bz2_;
8206 NSURLConnection *trivial_gz_;
8211 - (id) initWithDatabase:(Database *)database;
8212 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated;
8216 @implementation SourcesController
8218 - (void) _releaseConnection:(NSURLConnection *)connection {
8219 if (connection != nil) {
8220 [connection cancel];
8221 //[connection setDelegate:nil];
8222 [connection release];
8227 [self _releaseConnection:trivial_gz_];
8228 [self _releaseConnection:trivial_bz2_];
8233 - (NSURL *) navigationURL {
8234 return [NSURL URLWithString:@"cydia://sources"];
8237 - (void) viewDidAppear:(BOOL)animated {
8238 [super viewDidAppear:animated];
8239 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8242 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8246 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8248 return UCLocalize("INDIVIDUAL_SOURCES");
8252 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8255 case 1: return [sources_ count];
8260 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8261 @synchronized (database_) {
8262 if ([database_ era] != era_)
8264 if ([indexPath section] != 1)
8266 NSUInteger index([indexPath row]);
8267 if (index >= [sources_ count])
8269 return [sources_ objectAtIndex:index];
8272 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8273 static NSString *cellIdentifier = @"SourceCell";
8275 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8276 if (cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8277 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8279 Source *source([self sourceAtIndexPath:indexPath]);
8281 [cell setAllSource];
8283 [cell setSource:source];
8288 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8289 SectionsController *controller([[[SectionsController alloc]
8290 initWithDatabase:database_
8291 source:[self sourceAtIndexPath:indexPath]
8294 [controller setDelegate:self.delegate];
8295 [[self navigationController] pushViewController:controller animated:YES];
8298 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8299 if ([indexPath section] != 1)
8301 Source *source = [self sourceAtIndexPath:indexPath];
8302 return [source record] != nil;
8305 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8306 _assert([indexPath section] == 1);
8307 if (editingStyle == UITableViewCellEditingStyleDelete) {
8308 Source *source = [self sourceAtIndexPath:indexPath];
8309 if (source == nil) return;
8311 [Sources_ removeObjectForKey:[source key]];
8313 [self.delegate syncData];
8317 - (void) tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath {
8318 [self updateButtonsForEditingStatusAnimated:YES];
8322 [self.delegate addTrivialSource:href_];
8325 [self.delegate syncData];
8328 - (NSString *) getWarning {
8329 NSString *href(href_);
8330 NSRange colon([href rangeOfString:@"://"]);
8331 if (colon.location != NSNotFound)
8332 href = [href substringFromIndex:(colon.location + 3)];
8333 href = [href stringByAddingPercentEscapes];
8334 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8336 NSURL *url([NSURL URLWithString:href]);
8338 NSStringEncoding encoding;
8339 NSError *error(nil);
8341 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8342 return [warning length] == 0 ? nil : warning;
8346 - (void) _endConnection:(NSURLConnection *)connection {
8347 // XXX: the memory management in this method is horribly awkward
8349 NSURLConnection **field = NULL;
8350 if (connection == trivial_bz2_)
8351 field = &trivial_bz2_;
8352 else if (connection == trivial_gz_)
8353 field = &trivial_gz_;
8354 _assert(field != NULL);
8355 [connection release];
8359 trivial_bz2_ == nil &&
8362 NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil);
8364 [self.delegate releaseNetworkActivityIndicator];
8366 [self.delegate removeProgressHUD:hud_];
8370 if (warning != nil) {
8371 UIAlertView *alert = [[[UIAlertView alloc]
8372 initWithTitle:UCLocalize("SOURCE_WARNING")
8375 cancelButtonTitle:UCLocalize("CANCEL")
8377 UCLocalize("ADD_ANYWAY"),
8381 [alert setContext:@"warning"];
8382 [alert setNumberOfRows:1];
8385 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
8391 } else if (error_ != nil) {
8392 UIAlertView *alert = [[[UIAlertView alloc]
8393 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8394 message:[error_ localizedDescription]
8396 cancelButtonTitle:UCLocalize("OK")
8397 otherButtonTitles:nil
8400 [alert setContext:@"urlerror"];
8405 UIAlertView *alert = [[[UIAlertView alloc]
8406 initWithTitle:UCLocalize("NOT_REPOSITORY")
8407 message:UCLocalize("NOT_REPOSITORY_EX")
8409 cancelButtonTitle:UCLocalize("OK")
8410 otherButtonTitles:nil
8413 [alert setContext:@"trivial"];
8423 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8424 switch ([response statusCode]) {
8430 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8431 lprintf("connection:\"%s\" didFailWithError:\"%s\"\n", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8433 [self _endConnection:connection];
8436 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8437 [self _endConnection:connection];
8440 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8441 NSURL *url([NSURL URLWithString:href]);
8443 NSMutableURLRequest *request = [NSMutableURLRequest
8445 cachePolicy:NSURLRequestUseProtocolCachePolicy
8449 [request setHTTPMethod:method];
8451 if (Machine_ != NULL)
8452 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8454 if (UniqueID_ != nil)
8455 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8457 if ([url isCydiaSecure]) {
8458 if (UniqueID_ != nil)
8459 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
8462 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8465 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8466 NSString *context([alert context]);
8468 if ([context isEqualToString:@"source"]) {
8471 NSString *href = [[alert textField] text];
8472 href = VerifySource(href);
8477 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8478 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8482 // XXX: this is stupid
8483 hud_ = [self.delegate addProgressHUD];
8484 [hud_ setText:UCLocalize("VERIFYING_URL")];
8485 [self.delegate retainNetworkActivityIndicator];
8494 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8495 } else if ([context isEqualToString:@"trivial"])
8496 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8497 else if ([context isEqualToString:@"urlerror"])
8498 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8499 else if ([context isEqualToString:@"warning"]) {
8502 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
8511 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8515 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated {
8516 BOOL editing([list_ isEditing]);
8519 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8520 initWithTitle:UCLocalize("ADD")
8521 style:UIBarButtonItemStylePlain
8523 action:@selector(addButtonClicked)
8524 ] autorelease] animated:animated];
8525 else if ([self.delegate updating])
8526 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8527 initWithTitle:UCLocalize("CANCEL")
8528 style:UIBarButtonItemStyleDone
8530 action:@selector(cancelButtonClicked)
8531 ] autorelease] animated:animated];
8533 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8534 initWithTitle:UCLocalize("REFRESH")
8535 style:UIBarButtonItemStylePlain
8537 action:@selector(refreshButtonClicked)
8538 ] autorelease] animated:animated];
8540 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8541 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8542 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8544 action:@selector(editButtonClicked)
8545 ] autorelease] animated:animated];
8549 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease];
8550 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8551 [list_ setRowHeight:53];
8552 [(UITableView *) list_ setDataSource:self];
8553 [list_ setDelegate:self];
8554 [self setView:list_];
8557 - (void) viewDidLoad {
8558 [super viewDidLoad];
8560 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8561 [self updateButtonsForEditingStatusAnimated:NO];
8564 - (void) viewWillAppear:(BOOL)animated {
8565 [super viewWillAppear:animated];
8567 [list_ setEditing:NO];
8568 [self updateButtonsForEditingStatusAnimated:NO];
8571 - (void) releaseSubviews {
8576 [super releaseSubviews];
8579 - (id) initWithDatabase:(Database *)database {
8580 if ((self = [super init]) != nil) {
8581 database_ = database;
8585 - (void) reloadData {
8587 [self updateButtonsForEditingStatusAnimated:YES];
8589 @synchronized (database_) {
8590 era_ = [database_ era];
8592 sources_ = [NSMutableArray arrayWithCapacity:16];
8593 [sources_ addObjectsFromArray:[database_ sources]];
8595 [sources_ sortUsingSelector:@selector(compareByName:)];
8598 int count([sources_ count]);
8600 for (int i = 0; i != count; i++) {
8601 if ([[sources_ objectAtIndex:i] record] == nil)
8609 - (void) showAddSourcePrompt {
8610 UIAlertView *alert = [[[UIAlertView alloc]
8611 initWithTitle:UCLocalize("ENTER_APT_URL")
8614 cancelButtonTitle:UCLocalize("CANCEL")
8616 UCLocalize("ADD_SOURCE"),
8620 [alert setContext:@"source"];
8622 [alert setNumberOfRows:1];
8623 [alert addTextFieldWithValue:@"http://" label:@""];
8625 NSObject<UITextInputTraits> *traits = [[alert textField] textInputTraits];
8626 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8627 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8628 [traits setKeyboardType:UIKeyboardTypeURL];
8629 // XXX: UIReturnKeyDone
8630 [traits setReturnKeyType:UIReturnKeyNext];
8635 - (void) addButtonClicked {
8636 [self showAddSourcePrompt];
8639 - (void) refreshButtonClicked {
8640 if ([self.delegate requestUpdate])
8641 [self updateButtonsForEditingStatusAnimated:YES];
8644 - (void) cancelButtonClicked {
8645 [self.delegate cancelUpdate];
8648 - (void) editButtonClicked {
8649 [list_ setEditing:![list_ isEditing] animated:YES];
8650 [self updateButtonsForEditingStatusAnimated:YES];
8656 /* Stash Controller {{{ */
8657 @interface StashController : CyteViewController {
8658 _H<UIActivityIndicatorView> spinner_;
8659 _H<UILabel> status_;
8660 _H<UILabel> caption_;
8665 @implementation StashController
8668 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8669 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8670 [self setView:view];
8672 [view setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8674 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8675 CGRect spinrect = [spinner_ frame];
8676 spinrect.origin.x = Retina([[self view] frame].size.width / 2 - spinrect.size.width / 2);
8677 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8678 [spinner_ setFrame:spinrect];
8679 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8680 [view addSubview:spinner_];
8681 [spinner_ startAnimating];
8684 captrect.size.width = [[self view] frame].size.width;
8685 captrect.size.height = 40.0f;
8686 captrect.origin.x = 0;
8687 captrect.origin.y = Retina([[self view] frame].size.height / 2 - captrect.size.height * 2);
8688 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8689 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8690 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8691 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8692 [caption_ setTextColor:[UIColor whiteColor]];
8693 [caption_ setBackgroundColor:[UIColor clearColor]];
8694 [caption_ setShadowColor:[UIColor blackColor]];
8695 [caption_ setTextAlignment:NSTextAlignmentCenter];
8696 [view addSubview:caption_];
8699 statusrect.size.width = [[self view] frame].size.width;
8700 statusrect.size.height = 30.0f;
8701 statusrect.origin.x = 0;
8702 statusrect.origin.y = Retina([[self view] frame].size.height / 2 - statusrect.size.height);
8703 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8704 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8705 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8706 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8707 [status_ setTextColor:[UIColor whiteColor]];
8708 [status_ setBackgroundColor:[UIColor clearColor]];
8709 [status_ setShadowColor:[UIColor blackColor]];
8710 [status_ setTextAlignment:NSTextAlignmentCenter];
8711 [view addSubview:status_];
8714 - (void) releaseSubviews {
8719 [super releaseSubviews];
8725 @interface Cydia : CyteApplication <
8726 ConfirmationControllerDelegate,
8730 _H<CyteWindow> window_;
8731 _H<CydiaTabBarController> tabbar_;
8732 _H<CyteTabBarController> emulated_;
8733 _H<AppCacheController> appcache_;
8735 _H<NSMutableArray> essential_;
8736 _H<NSMutableArray> broken_;
8738 Database *database_;
8740 _H<NSURL> starturl_;
8745 _H<StashController> stash_;
8754 @implementation Cydia
8756 - (void) lockSuspend {
8757 if (locked_++ == 0) {
8758 if ($SBSSetInterceptsMenuButtonForever != NULL)
8759 (*$SBSSetInterceptsMenuButtonForever)(true);
8761 [self setIdleTimerDisabled:YES];
8765 - (void) unlockSuspend {
8766 if (--locked_ == 0) {
8767 [self setIdleTimerDisabled:NO];
8769 if ($SBSSetInterceptsMenuButtonForever != NULL)
8770 (*$SBSSetInterceptsMenuButtonForever)(false);
8774 - (void) beginUpdate {
8775 [tabbar_ beginUpdate];
8778 - (void) cancelUpdate {
8779 [tabbar_ cancelUpdate];
8782 - (bool) requestUpdate {
8783 if (CyteIsReachable("cydia.saurik.com")) {
8787 UIAlertView *alert = [[[UIAlertView alloc]
8788 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("REFRESH")]
8789 message:@"Host Unreachable" // XXX: Localize
8791 cancelButtonTitle:UCLocalize("OK")
8792 otherButtonTitles:nil
8795 [alert setContext:@"norefresh"];
8803 return [tabbar_ updating];
8807 if ([broken_ count] != 0) {
8808 int count = [broken_ count];
8810 UIAlertView *alert = [[[UIAlertView alloc]
8811 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8812 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8814 cancelButtonTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("FORCIBLY_CLEAR"), UCLocalize("UNSAFE")]
8816 UCLocalize("TEMPORARY_IGNORE"),
8820 [alert setContext:@"fixhalf"];
8821 [alert setNumberOfRows:2];
8823 } else if (!Ignored_ && [essential_ count] != 0) {
8824 int count = [essential_ count];
8826 UIAlertView *alert = [[[UIAlertView alloc]
8827 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8828 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8830 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8832 UCLocalize("UPGRADE_ESSENTIAL"),
8833 UCLocalize("COMPLETE_UPGRADE"),
8837 [alert setContext:@"upgrade"];
8842 - (void) returnToCydia {
8846 - (void) reloadSpringBoard {
8847 if (kCFCoreFoundationVersionNumber >= 700) // XXX: iOS 6.x
8848 system("/usr/libexec/cydia/cydo /bin/launchctl stop com.apple.backboardd");
8850 system("/usr/libexec/cydia/cydo /bin/launchctl stop com.apple.SpringBoard");
8852 system("/usr/bin/killall backboardd SpringBoard");
8855 - (void) _saveConfig {
8856 SaveConfig(database_);
8859 // Navigation controller for the queuing badge.
8860 - (UINavigationController *) queueNavigationController {
8861 NSArray *controllers = [tabbar_ viewControllers];
8862 return [controllers objectAtIndex:3];
8865 - (void) _updateData {
8867 [window_ unloadData];
8869 UINavigationController *navigation = [self queueNavigationController];
8871 id queuedelegate = nil;
8872 if ([[navigation viewControllers] count] > 0)
8873 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8875 [queuedelegate queueStatusDidChange];
8876 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8879 - (void) _refreshIfPossible {
8880 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8882 NSDate *update([[NSDictionary dictionaryWithContentsOfFile:@ CacheState_] objectForKey:@"LastUpdate"]);
8884 bool recently = false;
8885 if (update != nil) {
8886 NSTimeInterval interval([update timeIntervalSinceNow]);
8887 if (interval > -(15*60))
8891 // Don't automatic refresh if:
8892 // - We already refreshed recently.
8893 // - We already auto-refreshed this launch.
8894 // - Auto-refresh is disabled.
8895 // - Cydia's server is not reachable
8896 if (recently || loaded_ || ManualRefresh || !CyteIsReachable("cydia.saurik.com")) {
8897 // If we are cancelling, we need to make sure it knows it's already loaded.
8900 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8902 // We are going to load, so remember that.
8905 [tabbar_ performSelectorOnMainThread:@selector(beginUpdate) withObject:nil waitUntilDone:NO];
8911 - (void) refreshIfPossible {
8912 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
8915 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
8916 _profile(reloadDataWithInvocation)
8917 @synchronized (self) {
8918 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8920 [hud setText:UCLocalize("RELOADING_DATA")];
8922 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
8926 [essential_ removeAllObjects];
8927 [broken_ removeAllObjects];
8929 _profile(reloadDataWithInvocation$Essential)
8930 NSArray *packages([database_ packages]);
8931 for (Package *package in packages) {
8933 [broken_ addObject:package];
8934 if ([package upgradableAndEssential:YES] && ![package ignored]) {
8935 if ([package essential] && [package installed] != nil)
8936 [essential_ addObject:package];
8942 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
8945 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8946 [changesItem setBadgeValue:badge];
8947 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8948 [self setApplicationIconBadgeNumber:changes];
8951 [changesItem setBadgeValue:nil];
8952 [changesItem setAnimatedBadge:NO];
8953 [self setApplicationIconBadgeNumber:0];
8960 [self removeProgressHUD:hud];
8967 - (void) updateData {
8971 - (void) updateDataAndLoad {
8973 if ([database_ progressDelegate] == nil)
8979 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
8982 - (void) disemulate {
8983 if (emulated_ == nil)
8986 [window_ setRootViewController:tabbar_];
8989 [window_ setUserInteractionEnabled:YES];
8992 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
8993 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
8995 UIViewController *parent;
8996 if (emulated_ == nil)
9006 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9007 [parent presentModalViewController:navigation animated:YES];
9010 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9011 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9013 if (navigation != nil)
9014 [navigation pushViewController:progress animated:YES];
9016 [self presentModalViewController:progress force:YES];
9018 [progress invoke:invocation withTitle:title];
9022 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9023 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9026 - (void) repairWithInvocation:(NSInvocation *)invocation {
9028 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9032 - (void) repairWithSelector:(SEL)selector {
9033 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9036 - (void) reloadData {
9037 [self reloadDataWithInvocation:nil];
9038 if ([database_ progressDelegate] == nil)
9044 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9047 - (void) addSource:(NSDictionary *) source {
9048 CydiaAddSource(source);
9051 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9052 CydiaAddSource(href, distribution, sections);
9055 // XXX: this method should not return anything
9056 - (BOOL) addTrivialSource:(NSString *)href {
9057 CydiaAddSource(href, @"./");
9062 pkgProblemResolver *resolver = [database_ resolver];
9064 resolver->InstallProtect();
9065 if (!resolver->Resolve(true))
9070 // XXX: this is a really crappy way of doing this.
9071 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9072 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9073 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9074 if ([tabbar_ updating])
9075 [tabbar_ cancelUpdate];
9077 if (![database_ prepare])
9080 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9081 [page setDelegate:self];
9082 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9085 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9086 [tabbar_ presentModalViewController:confirm_ animated:YES];
9092 @synchronized (self) {
9097 - (void) clearPackage:(Package *)package {
9098 @synchronized (self) {
9105 - (void) installPackages:(NSArray *)packages {
9106 @synchronized (self) {
9107 for (Package *package in packages)
9114 - (void) installPackage:(Package *)package {
9115 @synchronized (self) {
9122 - (void) removePackage:(Package *)package {
9123 @synchronized (self) {
9130 - (void) distUpgrade {
9131 @synchronized (self) {
9132 if (![database_ upgrade])
9140 system("/usr/bin/uicache");
9145 UIProgressHUD *hud([self addProgressHUD]);
9146 [hud setText:UCLocalize("LOADING")];
9147 [self yieldToSelector:@selector(_uicache)];
9148 [self removeProgressHUD:hud];
9152 [database_ perform];
9153 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9154 [self performSelectorOnMainThread:@selector(uicache) withObject:nil waitUntilDone:YES];
9157 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9160 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9161 [self unlockSuspend];
9164 - (void) retainNetworkActivityIndicator {
9165 if (activity_++ == 0)
9166 [self setNetworkActivityIndicatorVisible:YES];
9169 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9173 - (void) releaseNetworkActivityIndicator {
9174 if (--activity_ == 0)
9175 [self setNetworkActivityIndicatorVisible:NO];
9178 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9183 - (void) cancelAndClear:(bool)clear {
9184 @synchronized (self) {
9196 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9197 NSString *context([alert context]);
9199 if ([context isEqualToString:@"conffile"]) {
9200 FILE *input = [database_ input];
9201 if (button == [alert cancelButtonIndex])
9202 fprintf(input, "N\n");
9203 else if (button == [alert firstOtherButtonIndex])
9204 fprintf(input, "Y\n");
9207 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9208 } else if ([context isEqualToString:@"fixhalf"]) {
9209 if (button == [alert cancelButtonIndex]) {
9210 @synchronized (self) {
9211 for (Package *broken in (id) broken_) {
9213 NSString *id(ShellEscape([broken id]));
9214 system([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /bin/rm -f"
9215 " /var/lib/dpkg/info/%@.prerm"
9216 " /var/lib/dpkg/info/%@.postrm"
9217 " /var/lib/dpkg/info/%@.preinst"
9218 " /var/lib/dpkg/info/%@.postinst"
9219 " /var/lib/dpkg/info/%@.extrainst_"
9220 "", id, id, id, id, id] UTF8String]);
9226 } else if (button == [alert firstOtherButtonIndex]) {
9227 [broken_ removeAllObjects];
9231 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9232 } else if ([context isEqualToString:@"upgrade"]) {
9233 if (button == [alert firstOtherButtonIndex]) {
9234 @synchronized (self) {
9235 for (Package *essential in (id) essential_)
9236 [essential install];
9241 } else if (button == [alert firstOtherButtonIndex] + 1) {
9243 } else if (button == [alert cancelButtonIndex]) {
9247 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9251 - (void) system:(NSString *)command {
9252 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9255 system([command UTF8String]);
9261 - (void) applicationWillSuspend {
9263 [super applicationWillSuspend];
9266 - (BOOL) isSafeToSuspend {
9269 NSLog(@"isSafeToSuspend: locked_ != 0");
9274 if ([tabbar_ modalViewController] != nil)
9277 // Use external process status API internally.
9278 // This is probably a really bad idea.
9279 // XXX: what is the point of this? does this solve anything at all?
9280 uint64_t status = 0;
9282 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9283 notify_get_state(notify_token, &status);
9284 notify_cancel(notify_token);
9289 NSLog(@"isSafeToSuspend: status != 0");
9295 NSLog(@"isSafeToSuspend: -> true");
9300 - (void) suspendReturningToLastApp:(BOOL)returning {
9301 if ([self isSafeToSuspend])
9302 [super suspendReturningToLastApp:returning];
9306 if ([self isSafeToSuspend])
9310 - (void) applicationSuspend {
9311 if ([self isSafeToSuspend])
9312 [super applicationSuspend];
9315 - (void) applicationSuspend:(GSEventRef)event {
9316 if ([self isSafeToSuspend])
9317 [super applicationSuspend:event];
9320 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9321 if ([self isSafeToSuspend])
9322 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9325 - (void) _setSuspended:(BOOL)value {
9326 if ([self isSafeToSuspend])
9327 [super _setSuspended:value];
9330 - (UIProgressHUD *) addProgressHUD {
9331 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9332 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9334 [window_ setUserInteractionEnabled:NO];
9336 UIViewController *target(tabbar_);
9337 if (UIViewController *modal = [target modalViewController])
9340 [hud showInView:[target view]];
9346 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9347 [self unlockSuspend];
9349 [hud removeFromSuperview];
9350 [window_ setUserInteractionEnabled:YES];
9353 - (CyteViewController *) pageForPackage:(NSString *)name withReferrer:(NSString *)referrer {
9354 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name withReferrer:referrer] autorelease];
9357 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external withReferrer:(NSString *)referrer {
9358 NSString *scheme([[url scheme] lowercaseString]);
9359 if ([[url absoluteString] length] <= [scheme length] + 3)
9361 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9362 NSArray *components([path componentsSeparatedByString:@"/"]);
9364 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"]) {
9365 CyteViewController *controller([self pageForPackage:[components objectAtIndex:1] withReferrer:referrer]);
9366 if (controller != nil)
9367 [controller setDelegate:self];
9371 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9374 NSString *base([components objectAtIndex:0]);
9376 CyteViewController *controller = nil;
9378 if ([base isEqualToString:@"url"]) {
9379 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9380 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9381 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9382 } else if (!external && [components count] == 1) {
9383 if ([base isEqualToString:@"sources"]) {
9384 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9387 if ([base isEqualToString:@"home"]) {
9388 controller = [[[HomeController alloc] init] autorelease];
9391 if ([base isEqualToString:@"sections"]) {
9392 controller = [[[SectionsController alloc] initWithDatabase:database_ source:nil] autorelease];
9395 if ([base isEqualToString:@"search"]) {
9396 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9399 if ([base isEqualToString:@"changes"]) {
9400 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9403 if ([base isEqualToString:@"installed"]) {
9404 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9406 } else if ([components count] == 2) {
9407 NSString *argument = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9409 if ([base isEqualToString:@"package"]) {
9410 controller = [self pageForPackage:argument withReferrer:referrer];
9413 if (!external && [base isEqualToString:@"search"]) {
9414 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9417 if (!external && [base isEqualToString:@"sections"]) {
9418 if ([argument isEqualToString:@"all"] || [argument isEqualToString:@"*"])
9420 controller = [[[SectionController alloc] initWithDatabase:database_ source:nil section:argument] autorelease];
9423 if ([base isEqualToString:@"sources"]) {
9424 if ([argument isEqualToString:@"add"]) {
9425 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9426 [(SourcesController *)controller showAddSourcePrompt];
9428 Source *source([database_ sourceWithKey:argument]);
9429 controller = [[[SectionsController alloc] initWithDatabase:database_ source:source] autorelease];
9433 if (!external && [base isEqualToString:@"launch"]) {
9434 [self launchApplicationWithIdentifier:argument suspended:NO];
9437 } else if (!external && [components count] == 3) {
9438 NSString *arg1 = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9439 NSString *arg2 = [[components objectAtIndex:2] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9441 if ([base isEqualToString:@"package"]) {
9442 if ([arg2 isEqualToString:@"settings"]) {
9443 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9444 } else if ([arg2 isEqualToString:@"files"]) {
9445 if (Package *package = [database_ packageWithName:arg1]) {
9446 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9447 [(FileTable *)controller setPackage:package];
9452 if ([base isEqualToString:@"sections"]) {
9453 Source *source([arg1 isEqualToString:@"*"] ? nil : [database_ sourceWithKey:arg1]);
9454 NSString *section([arg2 isEqualToString:@"*"] ? nil : arg2);
9455 controller = [[[SectionController alloc] initWithDatabase:database_ source:source section:section] autorelease];
9459 [controller setDelegate:self];
9463 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9464 CyteViewController *page([self pageForURL:url forExternal:external withReferrer:nil]);
9467 [tabbar_ setUnselectedViewController:page];
9472 - (void) applicationOpenURL:(NSURL *)url {
9473 [super applicationOpenURL:url];
9478 [self openCydiaURL:url forExternal:YES];
9481 - (void) applicationWillResignActive:(UIApplication *)application {
9482 // Stop refreshing if you get a phone call or lock the device.
9483 if ([tabbar_ updating])
9484 [tabbar_ cancelUpdate];
9486 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9487 [super applicationWillResignActive:application];
9490 - (void) saveState {
9491 [[NSDictionary dictionaryWithObjectsAndKeys:
9492 @"InterfaceState", [tabbar_ navigationURLCollection],
9493 @"LastClosed", [NSDate date],
9494 @"InterfaceIndex", [NSNumber numberWithInt:[tabbar_ selectedIndex]],
9495 nil] writeToFile:@ SavedState_ atomically:YES];
9500 - (void) applicationWillTerminate:(UIApplication *)application {
9504 - (void) applicationDidEnterBackground:(UIApplication *)application {
9505 if (kCFCoreFoundationVersionNumber < 1000 && [self isSafeToSuspend])
9506 return [self terminateWithSuccess];
9507 Backgrounded_ = [NSDate date];
9511 - (void) applicationWillEnterForeground:(UIApplication *)application {
9512 if (Backgrounded_ == nil)
9515 NSTimeInterval interval([Backgrounded_ timeIntervalSinceNow]);
9517 if (interval <= -(30*60)) {
9518 [tabbar_ setSelectedIndex:0];
9519 [[[tabbar_ viewControllers] objectAtIndex:0] popToRootViewControllerAnimated:NO];
9522 if (interval <= -(15*60)) {
9523 if (CyteIsReachable("cydia.saurik.com")) {
9524 [tabbar_ beginUpdate];
9525 [appcache_ reloadURLWithCache:YES];
9529 if ([database_ delocked])
9533 - (void) setConfigurationData:(NSString *)data {
9534 static RegEx conffile_r("'(.*)' '(.*)' ([01]) ([01])");
9536 if (!conffile_r(data)) {
9537 lprintf("E:invalid conffile\n");
9541 NSString *ofile = conffile_r[1];
9542 //NSString *nfile = conffile_r[2];
9544 UIAlertView *alert = [[[UIAlertView alloc]
9545 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9546 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9548 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9550 UCLocalize("ACCEPT_NEW_COPY"),
9551 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9555 [alert setContext:@"conffile"];
9556 [alert setNumberOfRows:2];
9560 - (void) addStashController {
9562 stash_ = [[[StashController alloc] init] autorelease];
9563 [window_ addSubview:[stash_ view]];
9566 - (void) removeStashController {
9567 [[stash_ view] removeFromSuperview];
9569 [self unlockSuspend];
9573 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9574 UpdateExternalStatus(1);
9575 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/cydo /usr/libexec/cydia/free.sh"];
9576 UpdateExternalStatus(0);
9578 [self removeStashController];
9579 [self reloadSpringBoard];
9582 - (void) applicationDidFinishLaunching:(id)unused {
9583 [super applicationDidFinishLaunching:unused];
9586 @synchronized (HostConfig_) {
9587 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9590 [CyteWebViewController _initialize];
9592 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9594 // this would disallow http{,s} URLs from accessing this data
9595 //[WebView registerURLSchemeAsLocal:@"cydia"];
9597 Font12_ = [UIFont systemFontOfSize:12];
9598 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9599 Font14_ = [UIFont systemFontOfSize:14];
9600 Font18_ = [UIFont systemFontOfSize:18];
9601 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9602 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9604 essential_ = [NSMutableArray arrayWithCapacity:4];
9605 broken_ = [NSMutableArray arrayWithCapacity:4];
9607 // XXX: I really need this thing... like, seriously... I'm sorry
9608 appcache_ = [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] autorelease];
9609 [appcache_ reloadData];
9611 window_ = [[[CyteWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9612 [window_ orderFront:self];
9613 [window_ makeKey:self];
9614 [window_ setHidden:NO];
9616 if (access("/.cydia_no_stash", F_OK) == 0);
9620 [self addStashController];
9621 // XXX: this would be much cleaner as a yieldToSelector:
9622 // that way the removeStashController could happen right here inline
9623 // we also could no longer require the useless stash_ field anymore
9624 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9629 int error(stat("/", &root));
9630 _assert(error != -1);
9632 #define Stash_(path) do { \
9633 struct stat folder; \
9634 int error(lstat((path), &folder)); \
9635 if (error != -1 && ( \
9636 folder.st_dev == root.st_dev && \
9637 S_ISDIR(folder.st_mode) \
9638 ) || error == -1 && ( \
9639 errno == ENOENT || \
9644 Stash_("/Applications");
9645 Stash_("/Library/Ringtones");
9646 Stash_("/Library/Wallpaper");
9647 //Stash_("/usr/bin");
9648 Stash_("/usr/include");
9649 Stash_("/usr/share");
9650 //Stash_("/var/lib");
9654 database_ = [Database sharedInstance];
9655 [database_ setDelegate:self];
9657 [window_ setUserInteractionEnabled:NO];
9659 tabbar_ = [[[CydiaTabBarController alloc] initWithDatabase:database_] autorelease];
9661 [tabbar_ addViewControllers:nil,
9662 @"Cydia", @"home.png", @"home7.png", @"home7s.png",
9663 UCLocalize("SOURCES"), @"install.png", @"install7.png", @"install7s.png",
9664 UCLocalize("CHANGES"), @"changes.png", @"changes7.png", @"changes7s.png",
9665 UCLocalize("INSTALLED"), @"manage.png", @"manage7.png", @"manage7s.png",
9666 UCLocalize("SEARCH"), @"search.png", @"search7.png", @"search7s.png",
9669 [tabbar_ setUpdateDelegate:self];
9671 CydiaLoadingViewController *loading([[[CydiaLoadingViewController alloc] init] autorelease]);
9672 UINavigationController *navigation([[[UINavigationController alloc] init] autorelease]);
9673 [navigation setViewControllers:[NSArray arrayWithObject:loading]];
9675 emulated_ = [[[CyteTabBarController alloc] init] autorelease];
9676 [emulated_ setViewControllers:[NSArray arrayWithObject:navigation]];
9677 [emulated_ setSelectedIndex:0];
9679 if ([emulated_ respondsToSelector:@selector(concealTabBarSelection)])
9680 [emulated_ concealTabBarSelection];
9682 [window_ setRootViewController:emulated_];
9684 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9688 - (NSArray *) defaultStartPages {
9689 NSMutableArray *standard = [NSMutableArray array];
9690 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9691 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9692 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9693 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9694 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9700 if ([emulated_ modalViewController] != nil)
9701 [emulated_ dismissModalViewControllerAnimated:YES];
9702 [window_ setUserInteractionEnabled:NO];
9704 [self reloadDataWithInvocation:nil];
9705 [self refreshIfPossible];
9708 NSDictionary *state([NSDictionary dictionaryWithContentsOfFile:@ SavedState_]);
9710 int savedIndex = [[state objectForKey:@"InterfaceIndex"] intValue];
9711 NSArray *saved = [[[state objectForKey:@"InterfaceState"] mutableCopy] autorelease];
9712 int standardIndex = 0;
9713 NSArray *standard = [self defaultStartPages];
9720 NSDate *closed = [state objectForKey:@"LastClosed"];
9721 if (valid && closed != nil) {
9722 NSTimeInterval interval([closed timeIntervalSinceNow]);
9723 if (interval <= -(30*60))
9727 if (valid && [saved count] != [standard count])
9731 for (unsigned int i = 0; i < [standard count]; i++) {
9732 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9733 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9734 // but it's good enough for now.
9735 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9742 NSArray *items = nil;
9744 [tabbar_ setSelectedIndex:savedIndex];
9747 [tabbar_ setSelectedIndex:standardIndex];
9751 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9752 NSArray *stack = [items objectAtIndex:tab];
9753 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9754 NSMutableArray *current = [NSMutableArray array];
9756 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9757 NSString *addr = [stack objectAtIndex:nav];
9758 NSURL *url = [NSURL URLWithString:addr];
9759 CyteViewController *page = [self pageForURL:url forExternal:NO withReferrer:nil];
9761 [current addObject:page];
9764 [navigation setViewControllers:current];
9767 // (Try to) show the startup URL.
9768 if (starturl_ != nil) {
9769 [self openCydiaURL:starturl_ forExternal:YES];
9774 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9776 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
9777 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
9780 if (item != nil && IsWildcat_) {
9781 [sheet showFromBarButtonItem:item animated:YES];
9783 [sheet showInView:window_];
9787 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9788 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9789 [progress setTitle:task];
9790 [progress addProgressEvent:event];
9793 - (void) addProgressEventForTask:(NSArray *)data {
9794 CydiaProgressEvent *event([data objectAtIndex:0]);
9795 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9796 [self addProgressEvent:event forTask:task];
9799 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9800 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9806 id Alloc_(id self, SEL selector) {
9807 id object = alloc_(self, selector);
9808 lprintf("[%s]A-%p\n", self->isa->name, object);
9813 id Dealloc_(id self, SEL selector) {
9814 id object = dealloc_(self, selector);
9815 lprintf("[%s]D-%p\n", self->isa->name, object);
9819 static NSMutableDictionary *AutoreleaseDeepMutableCopyOfDictionary(CFTypeRef type) {
9822 if (CFGetTypeID(type) != CFDictionaryGetTypeID())
9824 CFTypeRef copy(CFPropertyListCreateDeepCopy(kCFAllocatorDefault, type, kCFPropertyListMutableContainers));
9826 return [(NSMutableDictionary *) copy autorelease];
9829 int main_store(int, char *argv[]);
9831 int main(int argc, char *argv[]) {
9833 const char *argv0(argv[0]);
9834 if (const char *slash = strrchr(argv0, '/'))
9837 else if (!strcmp(argv0, "store"))
9838 return main_store(argc, argv);
9841 int fd(open("/tmp/cydia.log", O_WRONLY | O_APPEND | O_CREAT, 0644));
9845 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9849 UpdateExternalStatus(0);
9851 Idiom_ = IsWildcat_ ? @"ipad" : @"iphone";
9853 RegEx pattern("([0-9]+\\.[0-9]+).*");
9855 UIDevice *device([UIDevice currentDevice]);
9856 if (pattern([device systemVersion]))
9857 Firmware_ = pattern[1];
9859 if (pattern(Cydia_))
9860 Major_ = pattern[1];
9862 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
9864 HostConfig_ = [[[NSObject alloc] init] autorelease];
9865 @synchronized (HostConfig_) {
9866 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
9867 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
9870 NSString *ui(@"ui/ios");
9872 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
9873 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"/%@", Major_]];
9876 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9878 /* Set Locale {{{ */
9879 Locale_ = CFLocaleCopyCurrent();
9880 Languages_ = [NSLocale preferredLanguages];
9882 std::string languages;
9883 const char *translation(NULL);
9885 // XXX: this isn't really a language, but this is compatible with older Cydia builds
9886 if (Locale_ != NULL)
9887 if (const char *language = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String]) {
9888 RegEx pattern("([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?");
9889 if (pattern(language)) {
9890 translation = strdup([pattern->*@"%1$@%2$@" UTF8String]);
9891 languages += translation;
9896 if (Languages_ != nil)
9897 for (NSString *locale : Languages_) {
9898 auto components([NSLocale componentsFromLocaleIdentifier:locale]);
9899 NSString *language([components objectForKey:(id)kCFLocaleLanguageCode]);
9900 if (NSString *script = [components objectForKey:(id)kCFLocaleScriptCode])
9901 language = [NSString stringWithFormat:@"%@-%@", language, script];
9902 languages += [language UTF8String];
9907 NSLog(@"Setting Language: [%s] %s", translation, languages.c_str());
9909 /* Index Collation {{{ */
9910 if (Class $UILocalizedIndexedCollation = objc_getClass("UILocalizedIndexedCollation")) { @try {
9911 NSBundle *bundle([NSBundle bundleForClass:$UILocalizedIndexedCollation]);
9912 NSString *path([bundle pathForResource:@"UITableViewLocalizedSectionIndex" ofType:@"plist"]);
9913 //path = @"/System/Library/Frameworks/UIKit.framework/.lproj/UITableViewLocalizedSectionIndex.plist";
9914 NSDictionary *dictionary([NSDictionary dictionaryWithContentsOfFile:path]);
9915 _H<UILocalizedIndexedCollation> collation([[[$UILocalizedIndexedCollation alloc] initWithDictionary:dictionary] autorelease]);
9917 CollationLocale_ = MSHookIvar<NSLocale *>(collation, "_locale");
9919 if (kCFCoreFoundationVersionNumber >= 800 && [[CollationLocale_ localeIdentifier] isEqualToString:@"zh@collation=stroke"]) {
9920 CollationThumbs_ = [NSArray arrayWithObjects:@"1",@"•",@"4",@"•",@"7",@"•",@"10",@"•",@"13",@"•",@"16",@"•",@"19",@"A",@"•",@"E",@"•",@"I",@"•",@"M",@"•",@"R",@"•",@"V",@"•",@"Z",@"#",nil];
9921 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})
9922 CollationOffset_.push_back(offset);
9923 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];
9924 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];
9927 CollationThumbs_ = [collation sectionIndexTitles];
9928 for (size_t index(0), end([CollationThumbs_ count]); index != end; ++index)
9929 CollationOffset_.push_back([collation sectionForSectionIndexTitleAtIndex:index]);
9931 CollationTitles_ = [collation sectionTitles];
9932 CollationStarts_ = MSHookIvar<NSArray *>(collation, "_sectionStartStrings");
9934 NSString *&transform(MSHookIvar<NSString *>(collation, "_transform"));
9935 if (&transform != NULL && transform != nil) {
9936 /*if ([collation respondsToSelector:@selector(transformedCollationStringForString:)])
9937 CollationModify_ = [=](NSString *value) { return [collation transformedCollationStringForString:value]; };*/
9938 const UChar *uid(reinterpret_cast<const UChar *>([transform cStringUsingEncoding:NSUnicodeStringEncoding]));
9939 UErrorCode code(U_ZERO_ERROR);
9940 CollationTransl_ = utrans_openU(uid, -1, UTRANS_FORWARD, NULL, 0, NULL, &code);
9941 if (!U_SUCCESS(code))
9942 NSLog(@"%s", u_errorName(code));
9946 } @catch (NSException *e) {
9950 CollationLocale_ = [[[NSLocale alloc] initWithLocaleIdentifier:@"en@collation=dictionary"] autorelease];
9952 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];
9953 for (NSInteger offset(0); offset != 28; ++offset)
9954 CollationOffset_.push_back(offset);
9956 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];
9957 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];
9961 App_ = [[NSBundle mainBundle] bundlePath];
9964 Cache_ = [[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia", @"/var/mobile"] retain];
9965 mkdir([Cache_ UTF8String], 0755);
9967 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
9968 alloc_ = alloc->method_imp;
9969 alloc->method_imp = (IMP) &Alloc_;*/
9971 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
9972 dealloc_ = dealloc->method_imp;
9973 dealloc->method_imp = (IMP) &Dealloc_;*/
9975 void *gestalt(dlopen("/usr/lib/libMobileGestalt.dylib", RTLD_GLOBAL | RTLD_LAZY));
9976 $MGCopyAnswer = reinterpret_cast<CFStringRef (*)(CFStringRef)>(dlsym(gestalt, "MGCopyAnswer"));
9978 /* System Information {{{ */
9982 size = sizeof(maxproc);
9983 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9984 perror("sysctlbyname(\"kern.maxproc\", ?)");
9985 else if (maxproc < 64) {
9987 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9988 perror("sysctlbyname(\"kern.maxproc\", #)");
9991 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
9992 char *osversion = new char[size];
9993 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
9994 perror("sysctlbyname(\"kern.osversion\", ?)");
9996 System_ = [NSString stringWithUTF8String:osversion];
9998 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
9999 char *machine = new char[size];
10000 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10001 perror("sysctlbyname(\"hw.machine\", ?)");
10003 Machine_ = machine;
10005 int64_t usermem(0);
10006 size = sizeof(usermem);
10007 if (sysctlbyname("hw.usermem", &usermem, &size, NULL, 0) == -1)
10010 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10011 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10012 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10014 UniqueID_ = UniqueIdentifier(device);
10016 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10017 Product_ = [info objectForKey:@"SafariProductVersion"];
10018 Safari_ = [info objectForKey:@"CFBundleVersion"];
10021 NSString *agent([NSString stringWithFormat:@"Cydia/%@ CyF/%.2f", Cydia_, kCFCoreFoundationVersionNumber]);
10023 if (RegEx match = RegEx("([0-9]+(\\.[0-9]+)+).*", Safari_))
10024 agent = [NSString stringWithFormat:@"Safari/%@ %@", match[1], agent];
10025 if (RegEx match = RegEx("([0-9]+[A-Z][0-9]+[a-z]?).*", System_))
10026 agent = [NSString stringWithFormat:@"Mobile/%@ %@", match[1], agent];
10027 if (RegEx match = RegEx("([0-9]+(\\.[0-9]+)+).*", Product_))
10028 agent = [NSString stringWithFormat:@"Version/%@ %@", match[1], agent];
10030 [CyteWebViewController setApplicationNameForUserAgent:agent];
10032 /* Load Database {{{ */
10033 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10036 mkdir("/var/mobile/Library/Cydia", 0755);
10037 MetaFile_.Open("/var/mobile/Library/Cydia/metadata.cb0");
10040 Values_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaValues"), CFSTR("com.saurik.Cydia")));
10041 Sections_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaSections"), CFSTR("com.saurik.Cydia")));
10042 Sources_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaSources"), CFSTR("com.saurik.Cydia")));
10043 Version_ = [(NSNumber *) CFPreferencesCopyAppValue(CFSTR("CydiaVersion"), CFSTR("com.saurik.Cydia")) autorelease];
10046 NSDictionary *metadata([[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease]);
10048 if (Values_ == nil)
10049 Values_ = [metadata objectForKey:@"Values"];
10050 if (Values_ == nil)
10051 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10053 if (Sections_ == nil)
10054 Sections_ = [metadata objectForKey:@"Sections"];
10055 if (Sections_ == nil)
10056 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10058 if (Sources_ == nil)
10059 Sources_ = [metadata objectForKey:@"Sources"];
10060 if (Sources_ == nil)
10061 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10063 // XXX: this wrong, but in a way that doesn't matter :/
10064 if (Version_ == nil)
10065 Version_ = [metadata objectForKey:@"Version"];
10066 if (Version_ == nil)
10067 Version_ = [NSNumber numberWithUnsignedInt:0];
10069 if (NSDictionary *packages = [metadata objectForKey:@"Packages"]) {
10071 CFDictionaryApplyFunction((CFDictionaryRef) packages, &PackageImport, &fail);
10074 NSLog(@"unable to import package preferences... from 2010? oh well :/");
10077 if ([Version_ unsignedIntValue] == 0) {
10078 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10079 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10080 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10081 CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./");
10083 Version_ = [NSNumber numberWithUnsignedInt:1];
10085 if (NSMutableDictionary *cache = [NSMutableDictionary dictionaryWithContentsOfFile:@ CacheState_]) {
10086 [cache removeObjectForKey:@"LastUpdate"];
10087 [cache writeToFile:@ CacheState_ atomically:YES];
10091 _H<NSMutableArray> broken([NSMutableArray array]);
10092 for (NSString *key in (id) Sources_)
10093 if ([key rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"# "]].location != NSNotFound || ![([[Sources_ objectForKey:key] objectForKey:@"URI"] ?: @"/") hasSuffix:@"/"])
10094 [broken addObject:key];
10095 if ([broken count] != 0)
10096 for (NSString *key in (id) broken)
10097 [Sources_ removeObjectForKey:key];
10101 system("/usr/libexec/cydia/cydo /bin/rm -f /var/lib/cydia/metadata.plist");
10104 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10106 if (kCFCoreFoundationVersionNumber > 1000)
10107 system("/usr/libexec/cydia/cydo /usr/libexec/cydia/setnsfpn /var/lib");
10109 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10111 if (access("/User", F_OK) != 0 || version != 6) {
10113 system("/usr/libexec/cydia/cydo /usr/libexec/cydia/firmware.sh");
10117 if (access("/tmp/cydia.chk", F_OK) == 0) {
10118 if (unlink([Cache("pkgcache.bin") UTF8String]) == -1)
10119 _assert(errno == ENOENT);
10120 if (unlink([Cache("srcpkgcache.bin") UTF8String]) == -1)
10121 _assert(errno == ENOENT);
10124 system("/usr/libexec/cydia/cydo /bin/ln -sf /var/mobile/Library/Caches/com.saurik.Cydia/sources.list /etc/apt/sources.list.d/cydia.list");
10126 /* APT Initialization {{{ */
10127 _assert(pkgInitConfig(*_config));
10128 _assert(pkgInitSystem(*_config, _system));
10130 _config->Set("Acquire::AllowInsecureRepositories", true);
10131 _config->Set("Acquire::Check-Valid-Until", false);
10132 _config->Set("Dir::Bin::Methods::store", "/Applications/Cydia.app/store");
10134 _config->Set("pkgCacheGen::ForceEssential", "");
10136 if (translation != NULL)
10137 _config->Set("APT::Acquire::Translation", translation);
10138 _config->Set("Acquire::Languages", languages);
10140 // XXX: this timeout might be important :(
10141 //_config->Set("Acquire::http::Timeout", 15);
10143 _config->Set("Acquire::http::MaxParallel", usermem >= 384 * 1024 * 1024 ? 16 : 3);
10145 mkdir([Cache("archives") UTF8String], 0755);
10146 mkdir([Cache("archives/partial") UTF8String], 0755);
10147 _config->Set("Dir::Cache", [Cache_ UTF8String]);
10149 symlink("/var/lib/apt/extended_states", [Cache("extended_states") UTF8String]);
10150 _config->Set("Dir::State", [Cache_ UTF8String]);
10152 mkdir([Cache("lists") UTF8String], 0755);
10153 mkdir([Cache("lists/partial") UTF8String], 0755);
10154 mkdir([Cache("periodic") UTF8String], 0755);
10155 _config->Set("Dir::State::Lists", [Cache("lists") UTF8String]);
10157 std::string logs("/var/mobile/Library/Logs/Cydia");
10158 mkdir(logs.c_str(), 0755);
10159 _config->Set("Dir::Log", logs);
10161 _config->Set("Dir::Bin::dpkg", "/usr/libexec/cydia/cydo");
10163 /* Color Choices {{{ */
10164 space_ = CGColorSpaceCreateDeviceRGB();
10166 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10167 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10168 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10169 Folder_.Set(space_, 0x8e/255.f, 0x8e/255.f, 0x93/255.f, 1.0);
10170 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10171 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10172 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10173 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10174 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10175 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10177 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10178 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10180 /* UIKit Configuration {{{ */
10181 // XXX: I have a feeling this was important
10182 //UIKeyboardDisableAutomaticAppearance();
10185 $SBSSetInterceptsMenuButtonForever = reinterpret_cast<void (*)(bool)>(dlsym(RTLD_DEFAULT, "SBSSetInterceptsMenuButtonForever"));
10186 $SBSCopyIconImagePNGDataForDisplayIdentifier = reinterpret_cast<NSData *(*)(NSString *)>(dlsym(RTLD_DEFAULT, "SBSCopyIconImagePNGDataForDisplayIdentifier"));
10188 const char *symbol(kCFCoreFoundationVersionNumber >= 800 ? "MGGetBoolAnswer" : "GSSystemHasCapability");
10189 BOOL (*GSSystemHasCapability)(CFStringRef) = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, symbol));
10190 bool fast = GSSystemHasCapability != NULL && GSSystemHasCapability(CFSTR("armv7"));
10192 PulseInterval_ = fast ? 50000 : 500000;
10194 Colon_ = UCLocalize("COLON_DELIMITED");
10195 Elision_ = UCLocalize("ELISION");
10196 Error_ = UCLocalize("ERROR");
10197 Warning_ = UCLocalize("WARNING");
10200 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10202 CGColorSpaceRelease(space_);
10203 CFRelease(Locale_);