1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2015 Jay Freeman (saurik)
5 /* GNU General Public License, Version 3 {{{ */
7 * Cydia is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published
9 * by the Free Software Foundation, either version 3 of the License,
10 * or (at your option) any later version.
12 * Cydia is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Cydia. If not, see <http://www.gnu.org/licenses/>.
22 // XXX: wtf/FastMalloc.h... wtf?
23 #define USE_SYSTEM_MALLOC 1
25 /* #include Directives {{{ */
26 #include "CyteKit/UCPlatform.h"
27 #include "CyteKit/Localize.h"
29 #include <unicode/ustring.h>
30 #include <unicode/utrans.h>
32 #include <objc/objc.h>
33 #include <objc/runtime.h>
35 #include <CoreGraphics/CoreGraphics.h>
36 #include <Foundation/Foundation.h>
39 #define DEPLOYMENT_TARGET_MACOSX 1
40 #define CF_BUILDING_CF 1
41 #include <CoreFoundation/CFInternal.h>
44 #include <CoreFoundation/CFUniChar.h>
46 #include <SystemConfiguration/SystemConfiguration.h>
48 #include <UIKit/UIKit.h>
49 #include "iPhonePrivate.h"
51 #include <IOKit/IOKitLib.h>
53 #include <QuartzCore/CALayer.h>
55 #include <WebCore/WebCoreThread.h>
56 #include <WebKit/DOMHTMLIFrameElement.h>
65 #include "fdstream.hpp"
70 #include <apt-pkg/acquire.h>
71 #include <apt-pkg/acquire-item.h>
72 #include <apt-pkg/algorithms.h>
73 #include <apt-pkg/cachefile.h>
74 #include <apt-pkg/clean.h>
75 #include <apt-pkg/configuration.h>
76 #include <apt-pkg/debindexfile.h>
77 #include <apt-pkg/debmetaindex.h>
78 #include <apt-pkg/error.h>
79 #include <apt-pkg/init.h>
80 #include <apt-pkg/mmap.h>
81 #include <apt-pkg/pkgrecords.h>
82 #include <apt-pkg/sha1.h>
83 #include <apt-pkg/sourcelist.h>
84 #include <apt-pkg/sptr.h>
85 #include <apt-pkg/strutl.h>
86 #include <apt-pkg/tagfile.h>
88 #include <sys/types.h>
90 #include <sys/sysctl.h>
91 #include <sys/param.h>
92 #include <sys/mount.h>
93 #include <sys/reboot.h>
101 #include <mach-o/nlist.h>
110 #include <Cytore.hpp>
113 #include "Substrate.hpp"
114 #include "Menes/Menes.h"
116 #include "CyteKit/IndirectDelegate.h"
117 #include "CyteKit/RegEx.hpp"
118 #include "CyteKit/TableViewCell.h"
119 #include "CyteKit/TabBarController.h"
120 #include "CyteKit/WebScriptObject-Cyte.h"
121 #include "CyteKit/WebViewController.h"
122 #include "CyteKit/WebViewTableViewCell.h"
123 #include "CyteKit/stringWithUTF8Bytes.h"
125 #include "Cydia/MIMEAddress.h"
126 #include "Cydia/LoadingViewController.h"
127 #include "Cydia/ProgressEvent.h"
129 #include "SDURLCache/SDURLCache.h"
136 #define _timestamp ({ \
138 gettimeofday(&tv, NULL); \
139 tv.tv_sec * 1000000 + tv.tv_usec; \
142 typedef std::vector<class ProfileTime *> TimeList;
152 ProfileTime(const char *name) :
156 times_.push_back(this);
159 void AddTime(uint64_t time) {
166 std::cerr << std::setw(7) << count_ << ", " << std::setw(8) << total_ << " : " << name_ << std::endl;
178 ProfileTimer(ProfileTime &time) :
185 time_.AddTime(_timestamp - start_);
190 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
192 std::cerr << "========" << std::endl;
195 #define _profile(name) { \
196 static ProfileTime name(#name); \
197 ProfileTimer _ ## name(name);
202 // XXX: I hate clang. Apple: please get over your petty hatred of GPL and fix your gcc fork
203 #define synchronized(lock) \
204 synchronized(static_cast<NSObject *>(lock))
206 extern NSString *Cydia_;
208 #define lprintf(args...) fprintf(stderr, args)
211 #define TraceLogging (1 && !ForRelease)
212 #define HistogramInsertionSort (0 && !ForRelease)
213 #define ProfileTimes (0 && !ForRelease)
214 #define ForSaurik (0 && !ForRelease)
215 #define LogBrowser (0 && !ForRelease)
216 #define TrackResize (0 && !ForRelease)
217 #define ManualRefresh (1 && !ForRelease)
218 #define ShowInternals (0 && !ForRelease)
219 #define AlwaysReload (0 && !ForRelease)
223 #define _trace(args...)
228 #define _profile(name) {
231 #define PrintTimes() do {} while (false)
234 // Hash Functions/Structures {{{
235 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
243 @implementation NSDictionary (Cydia)
244 - (id) invokeUndefinedMethodFromWebScript:(NSString *)name withArguments:(NSArray *)arguments {
246 else if ([name isEqualToString:@"get"])
247 return [self objectForKey:[arguments objectAtIndex:0]];
248 else if ([name isEqualToString:@"keys"])
249 return [self allKeys];
253 static NSString *Colon_;
255 static NSString *Error_;
256 static NSString *Warning_;
258 static NSString *Cache_;
259 #define Cache(file) \
260 [NSString stringWithFormat:@"%@/%s", Cache_, file]
262 static void (*$SBSSetInterceptsMenuButtonForever)(bool);
263 static NSData *(*$SBSCopyIconImagePNGDataForDisplayIdentifier)(NSString *);
265 static CFStringRef (*$MGCopyAnswer)(CFStringRef);
267 static NSString *UniqueIdentifier(UIDevice *device = nil) {
268 if (kCFCoreFoundationVersionNumber < 800) // iOS 7.x
269 return [device ?: [UIDevice currentDevice] uniqueIdentifier];
271 return [(id)$MGCopyAnswer(CFSTR("UniqueDeviceID")) autorelease];
274 static bool IsReachable(const char *name) {
275 SCNetworkReachabilityFlags flags; {
276 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, name));
277 SCNetworkReachabilityGetFlags(reachability, &flags);
278 CFRelease(reachability);
281 // XXX: this elaborate mess is what Apple is using to determine this? :(
282 // XXX: do we care if the user has to intervene? maybe that's ok?
284 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
285 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
286 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
287 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
288 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
289 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
294 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
296 static _finline NSString *CydiaURL(NSString *path) {
298 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
299 page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
300 page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
301 page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
302 page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
304 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
307 static NSString *ShellEscape(NSString *value) {
308 return [NSString stringWithFormat:@"'%@'", [value stringByReplacingOccurrencesOfString:@"'" withString:@"'\\''"]];
311 static _finline void UpdateExternalStatus(uint64_t newStatus) {
313 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
314 notify_set_state(notify_token, newStatus);
315 notify_cancel(notify_token);
317 notify_post("com.saurik.Cydia.status");
320 static CGFloat CYStatusBarHeight() {
321 CGSize size([[UIApplication sharedApplication] statusBarFrame].size);
322 return UIInterfaceOrientationIsPortrait([[UIApplication sharedApplication] statusBarOrientation]) ? size.height : size.width;
325 /* NSForcedOrderingSearch doesn't work on the iPhone */
326 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
327 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
328 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
330 /* Insertion Sort {{{ */
332 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
333 const char *ptr = (const char *)list;
335 CFIndex half = count / 2;
336 const char *probe = ptr + elementSize * half;
337 CFComparisonResult cr = comparator(element, probe, context);
338 if (0 == cr) return (probe - (const char *)list) / elementSize;
339 ptr = (cr < 0) ? ptr : probe + elementSize;
340 count = (cr < 0) ? half : (half + (count & 1) - 1);
342 return (ptr - (const char *)list) / elementSize;
345 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
346 const char *ptr = (const char *)list;
348 CFIndex half = count / 2;
349 const char *probe = ptr + elementSize * half;
350 CFComparisonResult cr = comparator(element, probe, context);
351 if (0 == cr) return (probe - (const char *)list) / elementSize;
352 ptr = (cr < 0) ? ptr : probe + elementSize;
353 count = (cr < 0) ? half : (half + (count & 1) - 1);
355 return (ptr - (const char *)list) / elementSize;
358 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
359 if (range.length == 0)
361 const void **values(new const void *[range.length]);
362 CFArrayGetValues(array, range, values);
364 #if HistogramInsertionSort > 0
365 uint32_t total(0), *offsets(new uint32_t[range.length]);
368 for (CFIndex index(1); index != range.length; ++index) {
369 const void *value(values[index]);
370 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
371 CFIndex correct(index);
372 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
373 #if HistogramInsertionSort > 1
374 NSLog(@"%@ < %@", value, values[correct - 1]);
379 if (correct != index) {
380 size_t offset(index - correct);
381 #if HistogramInsertionSort
385 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
387 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
388 values[correct] = value;
392 CFArrayReplaceValues(array, range, values, range.length);
395 #if HistogramInsertionSort > 0
396 for (CFIndex index(0); index != range.length; ++index)
397 if (offsets[index] != 0)
398 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
399 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
406 /* Apple Bug Fixes {{{ */
407 @implementation UIWebDocumentView (Cydia)
409 - (void) _setScrollerOffset:(CGPoint)offset {
410 UIScroller *scroller([self _scroller]);
412 CGSize size([scroller contentSize]);
413 CGSize bounds([scroller bounds].size);
416 max.x = size.width - bounds.width;
417 max.y = size.height - bounds.height;
425 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
426 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
428 [scroller setOffset:offset];
434 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
435 size_t length([self length] - state->state);
438 else if (length > count)
440 for (size_t i(0); i != length; ++i)
441 objects[i] = [self item:state->state++];
442 state->itemsPtr = objects;
443 state->mutationsPtr = (unsigned long *) self;
447 /* Cydia NSString Additions {{{ */
448 @interface NSString (Cydia)
449 - (NSComparisonResult) compareByPath:(NSString *)other;
450 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
453 @implementation NSString (Cydia)
455 - (NSComparisonResult) compareByPath:(NSString *)other {
456 NSString *prefix = [self commonPrefixWithString:other options:0];
457 size_t length = [prefix length];
459 NSRange lrange = NSMakeRange(length, [self length] - length);
460 NSRange rrange = NSMakeRange(length, [other length] - length);
462 lrange = [self rangeOfString:@"/" options:0 range:lrange];
463 rrange = [other rangeOfString:@"/" options:0 range:rrange];
465 NSComparisonResult value;
467 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
468 value = NSOrderedSame;
469 else if (lrange.location == NSNotFound)
470 value = NSOrderedAscending;
471 else if (rrange.location == NSNotFound)
472 value = NSOrderedDescending;
474 value = NSOrderedSame;
476 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
477 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
478 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
479 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
481 NSComparisonResult result = [lpath compare:rpath];
482 return result == NSOrderedSame ? value : result;
485 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
486 return [(id)CFURLCreateStringByAddingPercentEscapes(
491 kCFStringEncodingUTF8
498 /* C++ NSString Wrapper Cache {{{ */
499 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
500 return size == 0 ? NULL :
501 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
502 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
505 static _finline CFStringRef CYStringCreate(const std::string &data) {
506 return CYStringCreate(data.data(), data.size());
509 static _finline CFStringRef CYStringCreate(const char *data) {
510 return CYStringCreate(data, strlen(data));
519 _finline void clear_() {
520 if (cache_ != NULL) {
527 _finline bool empty() const {
531 _finline size_t size() const {
535 _finline char *data() const {
539 _finline void clear() {
544 _finline CYString() :
551 _finline ~CYString() {
555 void operator =(const CYString &rhs) {
559 if (rhs.cache_ == nil)
562 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
565 void copy(CYPool *pool) {
566 char *temp(pool->malloc<char>(size_ + 1));
567 memcpy(temp, data_, size_);
572 void set(CYPool *pool, const char *data, size_t size) {
578 data_ = const_cast<char *>(data);
586 _finline void set(CYPool *pool, const char *data) {
587 set(pool, data, data == NULL ? 0 : strlen(data));
590 _finline void set(CYPool *pool, const std::string &rhs) {
591 set(pool, rhs.data(), rhs.size());
594 bool operator ==(const CYString &rhs) const {
595 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
598 _finline operator CFStringRef() {
600 cache_ = CYStringCreate(data_, size_);
604 _finline operator id() {
605 return (NSString *) static_cast<CFStringRef>(*this);
608 _finline operator const char *() {
609 return reinterpret_cast<const char *>(data_);
613 /* C++ NSString Algorithm Adapters {{{ */
615 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
618 struct NSStringMapHash :
619 std::unary_function<NSString *, size_t>
621 _finline size_t operator ()(NSString *value) const {
622 return CFStringHashNSString((CFStringRef) value);
626 struct NSStringMapLess :
627 std::binary_function<NSString *, NSString *, bool>
629 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
630 return [lhs compare:rhs] == NSOrderedAscending;
634 struct NSStringMapEqual :
635 std::binary_function<NSString *, NSString *, bool>
637 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
638 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
639 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
640 //[lhs isEqualToString:rhs];
645 /* CoreGraphics Primitives {{{ */
650 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
651 CGFloat color[] = {red, green, blue, alpha};
652 return CGColorCreate(space, color);
661 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
662 color_(Create_(space, red, green, blue, alpha))
664 Set(space, red, green, blue, alpha);
669 CGColorRelease(color_);
676 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
678 color_ = Create_(space, red, green, blue, alpha);
681 operator CGColorRef() {
687 /* Random Global Variables {{{ */
688 static int PulseInterval_ = 500000;
690 static const NSString *UI_;
693 static bool RestartSubstrate_;
694 static NSArray *Finishes_;
696 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
697 #define NotifyConfig_ "/etc/notify.conf"
699 static bool Queuing_;
701 static CYColor Blue_;
702 static CYColor Blueish_;
703 static CYColor Black_;
704 static CYColor Folder_;
706 static CYColor White_;
707 static CYColor Gray_;
708 static CYColor Green_;
709 static CYColor Purple_;
710 static CYColor Purplish_;
712 static UIColor *InstallingColor_;
713 static UIColor *RemovingColor_;
715 static NSString *App_;
717 static BOOL Advanced_;
718 static BOOL Ignored_;
720 static _H<UIFont> Font12_;
721 static _H<UIFont> Font12Bold_;
722 static _H<UIFont> Font14_;
723 static _H<UIFont> Font18_;
724 static _H<UIFont> Font18Bold_;
725 static _H<UIFont> Font22Bold_;
727 static const char *Machine_ = NULL;
728 static _H<NSString> System_;
729 static NSString *SerialNumber_ = nil;
730 static NSString *ChipID_ = nil;
731 static NSString *BBSNum_ = nil;
732 static _H<NSString> UniqueID_;
733 static _H<NSString> UserAgent_;
734 static _H<NSString> Product_;
735 static _H<NSString> Safari_;
737 static _H<NSLocale> CollationLocale_;
738 static _H<NSArray> CollationThumbs_;
739 static std::vector<NSInteger> CollationOffset_;
740 static _H<NSArray> CollationTitles_;
741 static _H<NSArray> CollationStarts_;
742 static UTransliterator *CollationTransl_;
743 //static Function<NSString *, NSString *> CollationModify_;
745 typedef std::basic_string<UChar> ustring;
746 static ustring CollationString_;
748 #define CUC const ustring &str(*reinterpret_cast<const ustring *>(rep))
749 #define UC ustring &str(*reinterpret_cast<ustring *>(rep))
750 static struct UReplaceableCallbacks CollationUCalls_ = {
751 .length = [](const UReplaceable *rep) -> int32_t { CUC;
755 .charAt = [](const UReplaceable *rep, int32_t offset) -> UChar { CUC;
756 //fprintf(stderr, "charAt(%d) : %d\n", offset, str.size());
757 if (offset >= str.size())
762 .char32At = [](const UReplaceable *rep, int32_t offset) -> UChar32 { CUC;
763 //fprintf(stderr, "char32At(%d) : %d\n", offset, str.size());
764 if (offset >= str.size())
767 U16_GET(str.data(), 0, offset, str.size(), c);
771 .replace = [](UReplaceable *rep, int32_t start, int32_t limit, const UChar *text, int32_t length) -> void { UC;
772 //fprintf(stderr, "replace(%d, %d, %d) : %d\n", start, limit, length, str.size());
773 str.replace(start, limit - start, text, length);
776 .extract = [](UReplaceable *rep, int32_t start, int32_t limit, UChar *dst) -> void { UC;
777 //fprintf(stderr, "extract(%d, %d) : %d\n", start, limit, str.size());
778 str.copy(dst, limit - start, start);
781 .copy = [](UReplaceable *rep, int32_t start, int32_t limit, int32_t dest) -> void { UC;
782 //fprintf(stderr, "copy(%d, %d, %d) : %d\n", start, limit, dest, str.size());
783 str.replace(dest, 0, str, start, limit - start);
787 static CFLocaleRef Locale_;
788 static NSArray *Languages_;
789 static CGColorSpaceRef space_;
791 #define CacheState_ "/var/mobile/Library/Caches/com.saurik.Cydia/CacheState.plist"
792 #define SavedState_ "/var/mobile/Library/Caches/com.saurik.Cydia/SavedState.plist"
794 static NSDictionary *SectionMap_;
795 static _H<NSDate> Backgrounded_;
796 static _transient NSMutableDictionary *Values_;
797 static _transient NSMutableDictionary *Sections_;
798 _H<NSMutableDictionary> Sources_;
799 static _transient NSNumber *Version_;
803 CGFloat ScreenScale_;
804 static NSString *Idiom_;
805 static _H<NSString> Firmware_;
806 static NSString *Major_;
808 static _H<NSMutableDictionary> SessionData_;
809 static _H<NSObject> HostConfig_;
810 static _H<NSMutableSet> BridgedHosts_;
811 static _H<NSMutableSet> InsecureHosts_;
812 static _H<NSMutableSet> PipelinedHosts_;
813 static _H<NSMutableSet> CachedURLs_;
815 static NSString *kCydiaProgressEventTypeError = @"Error";
816 static NSString *kCydiaProgressEventTypeInformation = @"Information";
817 static NSString *kCydiaProgressEventTypeStatus = @"Status";
818 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
821 /* Display Helpers {{{ */
822 inline float Interpolate(float begin, float end, float fraction) {
823 return (end - begin) * fraction + begin;
826 static inline double Retina(double value) {
827 value *= ScreenScale_;
828 value = round(value);
829 value /= ScreenScale_;
833 static inline CGRect Retina(CGRect value) {
834 value.origin.x *= ScreenScale_;
835 value.origin.y *= ScreenScale_;
836 value.size.width *= ScreenScale_;
837 value.size.height *= ScreenScale_;
838 value = CGRectIntegral(value);
839 value.origin.x /= ScreenScale_;
840 value.origin.y /= ScreenScale_;
841 value.size.width /= ScreenScale_;
842 value.size.height /= ScreenScale_;
846 static _finline const char *StripVersion_(const char *version) {
847 const char *colon(strchr(version, ':'));
848 return colon == NULL ? version : colon + 1;
851 NSString *LocalizeSection(NSString *section) {
852 static RegEx title_r("(.*?) \\((.*)\\)");
853 if (title_r(section)) {
854 NSString *parent(title_r[1]);
855 NSString *child(title_r[2]);
857 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
858 LocalizeSection(parent),
859 LocalizeSection(child)
863 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
866 NSString *Simplify(NSString *title) {
867 const char *data = [title UTF8String];
868 size_t size = [title lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
870 static RegEx square_r("\\[(.*)\\]");
871 if (square_r(data, size))
872 return Simplify(square_r[1]);
874 static RegEx paren_r("\\((.*)\\)");
875 if (paren_r(data, size))
876 return Simplify(paren_r[1]);
878 static RegEx title_r("(.*?) \\((.*)\\)");
879 if (title_r(data, size))
880 return Simplify(title_r[1]);
886 bool isSectionVisible(NSString *section) {
887 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
888 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
889 return hidden == nil || ![hidden boolValue];
892 static NSObject *CYIOGetValue(const char *path, NSString *property) {
893 io_registry_entry_t entry(IORegistryEntryFromPath(kIOMasterPortDefault, path));
894 if (entry == MACH_PORT_NULL)
897 CFTypeRef value(IORegistryEntryCreateCFProperty(entry, (CFStringRef) property, kCFAllocatorDefault, 0));
898 IOObjectRelease(entry);
902 return [(id) value autorelease];
905 static NSString *CYHex(NSData *data, bool reverse = false) {
909 size_t length([data length]);
910 uint8_t bytes[length];
911 [data getBytes:bytes];
913 char string[length * 2 + 1];
914 for (size_t i(0); i != length; ++i)
915 sprintf(string + i * 2, "%.2x", bytes[reverse ? length - i - 1 : i]);
917 return [NSString stringWithUTF8String:string];
920 static NSString *VerifySource(NSString *href) {
921 static RegEx href_r("(http(s?)://|file:///)[^# ]*");
923 [[[[UIAlertView alloc]
924 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("INVALID_URL")]
925 message:UCLocalize("INVALID_URL_EX")
927 cancelButtonTitle:UCLocalize("OK")
928 otherButtonTitles:nil
929 ] autorelease] show];
934 if (![href hasSuffix:@"/"])
935 href = [href stringByAppendingString:@"/"];
941 /* Delegate Prototypes {{{ */
944 @class CydiaProgressEvent;
946 @protocol DatabaseDelegate
947 - (void) repairWithSelector:(SEL)selector;
948 - (void) setConfigurationData:(NSString *)data;
949 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
952 @class CYPackageController;
954 @protocol SourceDelegate
955 - (void) setFetch:(NSNumber *)fetch;
958 @protocol FetchDelegate
959 - (bool) isSourceCancelled;
960 - (void) startSourceFetch:(NSString *)uri;
961 - (void) stopSourceFetch:(NSString *)uri;
964 @protocol CydiaDelegate
965 - (void) returnToCydia;
967 - (void) retainNetworkActivityIndicator;
968 - (void) releaseNetworkActivityIndicator;
969 - (void) clearPackage:(Package *)package;
970 - (void) installPackage:(Package *)package;
971 - (void) installPackages:(NSArray *)packages;
972 - (void) removePackage:(Package *)package;
973 - (void) beginUpdate;
975 - (bool) requestUpdate;
976 - (void) distUpgrade;
979 - (void) _saveConfig;
981 - (void) addSource:(NSDictionary *)source;
982 - (BOOL) addTrivialSource:(NSString *)href;
983 - (UIProgressHUD *) addProgressHUD;
984 - (void) removeProgressHUD:(UIProgressHUD *)hud;
985 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
986 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
990 /* CancelStatus {{{ */
992 public pkgAcquireStatus
1003 virtual bool MediaChange(std::string media, std::string drive) {
1007 virtual void IMSHit(pkgAcquire::ItemDesc &desc) {
1011 virtual bool Pulse_(pkgAcquire *Owner) = 0;
1013 virtual bool Pulse(pkgAcquire *Owner) {
1014 if (pkgAcquireStatus::Pulse(Owner) && Pulse_(Owner))
1022 _finline bool WasCancelled() const {
1027 /* DelegateStatus {{{ */
1032 _transient NSObject<ProgressDelegate> *delegate_;
1040 void setDelegate(NSObject<ProgressDelegate> *delegate) {
1041 delegate_ = delegate;
1044 virtual void Fetch(pkgAcquire::ItemDesc &desc) {
1045 NSString *name([NSString stringWithUTF8String:desc.ShortDesc.c_str()]);
1046 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItemDesc:desc]);
1047 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1050 virtual void Done(pkgAcquire::ItemDesc &desc) {
1051 NSString *name([NSString stringWithUTF8String:desc.ShortDesc.c_str()]);
1052 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:Colon_, UCLocalize("DONE"), name] ofType:kCydiaProgressEventTypeStatus forItemDesc:desc]);
1053 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1056 virtual void Fail(pkgAcquire::ItemDesc &desc) {
1058 desc.Owner->Status == pkgAcquire::Item::StatIdle ||
1059 desc.Owner->Status == pkgAcquire::Item::StatDone
1063 std::string &error(desc.Owner->ErrorText);
1067 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItemDesc:desc]);
1068 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1071 virtual bool Pulse_(pkgAcquire *Owner) {
1073 double(CurrentBytes + CurrentItems) /
1074 double(TotalBytes + TotalItems)
1077 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
1078 [NSNumber numberWithDouble:percent], @"Percent",
1080 [NSNumber numberWithDouble:CurrentBytes], @"Current",
1081 [NSNumber numberWithDouble:TotalBytes], @"Total",
1082 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
1083 nil] waitUntilDone:YES];
1085 return ![delegate_ isProgressCancelled];
1088 virtual void Start() {
1089 pkgAcquireStatus::Start();
1090 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
1093 virtual void Stop() {
1094 pkgAcquireStatus::Stop();
1095 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
1096 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
1100 /* Database Interface {{{ */
1101 typedef std::map< unsigned long, _H<Source> > SourceMap;
1103 @interface Database : NSObject {
1110 pkgCacheFile cache_;
1111 pkgDepCache::Policy *policy_;
1112 pkgRecords *records_;
1113 pkgProblemResolver *resolver_;
1114 pkgAcquire *fetcher_;
1116 SPtr<pkgPackageManager> manager_;
1117 pkgSourceList *list_;
1119 SourceMap sourceMap_;
1120 _H<NSMutableArray> sourceList_;
1122 CFMutableArrayRef packages_;
1124 _transient NSObject<DatabaseDelegate> *delegate_;
1125 _transient NSObject<ProgressDelegate> *progress_;
1127 CydiaStatus status_;
1133 std::map<const char *, _H<NSString> > sections_;
1136 + (Database *) sharedInstance;
1139 - (void) _readCydia:(NSNumber *)fd;
1140 - (void) _readStatus:(NSNumber *)fd;
1141 - (void) _readOutput:(NSNumber *)fd;
1145 - (Package *) packageWithName:(NSString *)name;
1147 - (pkgCacheFile &) cache;
1148 - (pkgDepCache::Policy *) policy;
1149 - (pkgRecords *) records;
1150 - (pkgProblemResolver *) resolver;
1151 - (pkgAcquire &) fetcher;
1152 - (pkgSourceList &) list;
1153 - (NSArray *) packages;
1154 - (NSArray *) sources;
1155 - (Source *) sourceWithKey:(NSString *)key;
1156 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1164 - (void) updateWithStatus:(CancelStatus &)status;
1166 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1168 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1169 - (NSObject<ProgressDelegate> *) progressDelegate;
1171 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1172 - (void) setFetch:(bool)fetch forURI:(const char *)uri;
1173 - (void) resetFetch;
1175 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1179 /* SourceStatus {{{ */
1180 class SourceStatus :
1184 _transient NSObject<FetchDelegate> *delegate_;
1185 _transient Database *database_;
1186 std::set<std::string> fetches_;
1189 SourceStatus(NSObject<FetchDelegate> *delegate, Database *database) :
1190 delegate_(delegate),
1195 void Set(bool fetch, const std::string &uri) {
1197 if (!fetches_.insert(uri).second)
1200 if (fetches_.erase(uri) == 0)
1204 //printf("Set(%s, %s)\n", fetch ? "true" : "false", uri.c_str());
1205 [database_ setFetch:fetch forURI:uri.c_str()];
1208 _finline void Set(bool fetch, pkgAcquire::Item *item) {
1209 /*unsigned long ID(fetch ? 1 : 0);
1213 Set(fetch, item->DescURI());
1216 void Log(const char *tag, pkgAcquire::Item *item) {
1217 //printf("%s(%s) S:%u Q:%u\n", tag, item->DescURI().c_str(), item->Status, item->QueueCounter);
1220 virtual void Fetch(pkgAcquire::ItemDesc &desc) {
1221 Log("Fetch", desc.Owner);
1222 Set(true, desc.Owner);
1225 virtual void Done(pkgAcquire::ItemDesc &desc) {
1226 Log("Done", desc.Owner);
1227 Set(false, desc.Owner);
1230 virtual void Fail(pkgAcquire::ItemDesc &desc) {
1231 Log("Fail", desc.Owner);
1232 Set(false, desc.Owner);
1235 virtual bool Pulse_(pkgAcquire *Owner) {
1236 std::set<std::string> fetches;
1237 for (pkgAcquire::ItemCIterator item(Owner->ItemsBegin()); item != Owner->ItemsEnd(); ++item) {
1239 if ((*item)->QueueCounter == 0)
1241 else switch ((*item)->Status) {
1242 case pkgAcquire::Item::StatFetching:
1243 fetches.insert((*item)->DescURI());
1252 Log(fetch ? "Pulse<true>" : "Pulse<false>", *item);
1256 std::vector<std::string> stops;
1257 std::set_difference(fetches_.begin(), fetches_.end(), fetches.begin(), fetches.end(), std::back_insert_iterator<std::vector<std::string>>(stops));
1258 for (std::vector<std::string>::const_iterator stop(stops.begin()); stop != stops.end(); ++stop) {
1259 //printf("Stop(%s)\n", stop->c_str());
1263 return ![delegate_ isSourceCancelled];
1266 virtual void Stop() {
1267 pkgAcquireStatus::Stop();
1268 [database_ resetFetch];
1272 /* ProgressEvent Implementation {{{ */
1273 @implementation CydiaProgressEvent
1275 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1276 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1279 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1280 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1281 [event setPackage:package];
1285 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItemDesc:(pkgAcquire::ItemDesc &)desc {
1286 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1288 NSString *description([NSString stringWithUTF8String:desc.Description.c_str()]);
1289 NSArray *fields([description componentsSeparatedByString:@" "]);
1290 [event setItem:fields];
1292 if ([fields count] > 3) {
1293 [event setPackage:[fields objectAtIndex:2]];
1294 [event setVersion:[fields objectAtIndex:3]];
1297 [event setURL:[NSString stringWithUTF8String:desc.URI.c_str()]];
1302 + (NSArray *) _attributeKeys {
1303 return [NSArray arrayWithObjects:
1313 - (NSArray *) attributeKeys {
1314 return [[self class] _attributeKeys];
1317 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1318 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1321 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1322 if ((self = [super init]) != nil) {
1328 - (NSString *) message {
1332 - (NSString *) type {
1336 - (NSArray *) item {
1337 return (id) item_ ?: [NSNull null];
1340 - (void) setItem:(NSArray *)item {
1344 - (NSString *) package {
1345 return (id) package_ ?: [NSNull null];
1348 - (void) setPackage:(NSString *)package {
1352 - (NSString *) url {
1353 return (id) url_ ?: [NSNull null];
1356 - (void) setURL:(NSString *)url {
1360 - (void) setVersion:(NSString *)version {
1364 - (NSString *) version {
1365 return (id) version_ ?: [NSNull null];
1368 - (NSString *) compound:(NSString *)value {
1370 NSString *mode(nil); {
1371 NSString *type([self type]);
1372 if ([type isEqualToString:kCydiaProgressEventTypeError])
1373 mode = UCLocalize("ERROR");
1374 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1375 mode = UCLocalize("WARNING");
1379 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1385 - (NSString *) compoundMessage {
1386 return [self compound:[self message]];
1389 - (NSString *) compoundTitle {
1392 if (package_ == nil)
1394 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1395 title = [package name];
1399 return [self compound:title];
1405 // Cytore Definitions {{{
1406 struct PackageValue :
1409 Cytore::Offset<PackageValue> next_;
1411 uint32_t index_ : 23;
1412 uint32_t subscribed_ : 1;
1429 Cytore::Offset<PackageValue> packages_[1 << 16];
1432 static Cytore::File<MetaValue> MetaFile_;
1434 // Cytore Helper Functions {{{
1435 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1436 SplitHash nhash = { hashlittle(name, length) };
1438 PackageValue *metadata;
1440 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1441 for (;; offset = &metadata->next_) { if (offset->IsNull()) {
1442 *offset = MetaFile_.New<PackageValue>(length + 1);
1443 metadata = &MetaFile_.Get(*offset);
1445 if (metadata == NULL) {
1449 metadata = new PackageValue();
1450 memset(metadata, 0, sizeof(*metadata));
1453 memcpy(metadata->name_, name, length);
1454 metadata->name_[length] = '\0';
1455 metadata->nhash_ = nhash.u16[1];
1457 metadata = &MetaFile_.Get(*offset);
1458 if (metadata->nhash_ != nhash.u16[1])
1460 if (strncmp(metadata->name_, name, length) != 0)
1462 if (metadata->name_[length] != '\0')
1469 static void PackageImport(const void *key, const void *value, void *context) {
1470 bool &fail(*reinterpret_cast<bool *>(context));
1473 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1474 NSLog(@"failed to import package %@", key);
1478 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1479 NSDictionary *package((NSDictionary *) value);
1481 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1482 if ([subscribed boolValue] && !metadata->subscribed_)
1483 metadata->subscribed_ = true;
1485 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1486 time_t time([date timeIntervalSince1970]);
1487 if (metadata->first_ > time || metadata->first_ == 0)
1488 metadata->first_ = time;
1491 NSDate *date([package objectForKey:@"LastSeen"]);
1492 NSString *version([package objectForKey:@"LastVersion"]);
1494 if (date != nil && version != nil) {
1495 time_t time([date timeIntervalSince1970]);
1496 if (metadata->last_ < time || metadata->last_ == 0)
1497 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1498 size_t length(strlen(buffer));
1499 uint16_t vhash(hashlittle(buffer, length));
1501 size_t capped(std::min<size_t>(8, length));
1502 char *latest(buffer + length - capped);
1504 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1505 metadata->vhash_ = vhash;
1507 metadata->last_ = time;
1513 static NSDate *GetStatusDate() {
1514 return [[[NSFileManager defaultManager] attributesOfItemAtPath:@"/var/lib/dpkg/status" error:NULL] fileModificationDate];
1517 static void SaveConfig(NSObject *lock) {
1518 @synchronized (lock) {
1524 CFPreferencesSetMultiple((CFDictionaryRef) [NSDictionary dictionaryWithObjectsAndKeys:
1525 Values_, @"CydiaValues",
1526 Sections_, @"CydiaSections",
1527 (id) Sources_, @"CydiaSources",
1528 Version_, @"CydiaVersion",
1529 nil], NULL, CFSTR("com.saurik.Cydia"), kCFPreferencesCurrentUser, kCFPreferencesCurrentHost);
1531 if (!CFPreferencesAppSynchronize(CFSTR("com.saurik.Cydia")))
1532 NSLog(@"CFPreferencesAppSynchronize(com.saurik.Cydia) == false");
1534 CydiaWriteSources();
1537 /* Source Class {{{ */
1538 @interface Source : NSObject {
1540 Database *database_;
1543 CYString depiction_;
1544 CYString description_;
1550 CYString distribution_;
1556 _H<NSString> authority_;
1558 CYString defaultIcon_;
1560 _H<NSMutableDictionary> record_;
1563 std::set<std::string> fetches_;
1564 std::set<std::string> files_;
1565 _transient NSObject<SourceDelegate> *delegate_;
1568 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(CYPool *)pool;
1570 - (NSComparisonResult) compareByName:(Source *)source;
1572 - (NSString *) depictionForPackage:(NSString *)package;
1573 - (NSString *) supportForPackage:(NSString *)package;
1575 - (metaIndex *) metaIndex;
1576 - (NSDictionary *) record;
1579 - (NSString *) rooturi;
1580 - (NSString *) distribution;
1581 - (NSString *) type;
1584 - (NSString *) host;
1586 - (NSString *) name;
1587 - (NSString *) shortDescription;
1588 - (NSString *) label;
1589 - (NSString *) origin;
1590 - (NSString *) version;
1592 - (NSString *) defaultIcon;
1593 - (NSURL *) iconURL;
1595 - (void) setFetch:(bool)fetch forURI:(const char *)uri;
1596 - (void) resetFetch;
1600 @implementation Source
1602 + (NSString *) webScriptNameForSelector:(SEL)selector {
1604 else if (selector == @selector(addSection:))
1605 return @"addSection";
1606 else if (selector == @selector(getField:))
1608 else if (selector == @selector(removeSection:))
1609 return @"removeSection";
1610 else if (selector == @selector(remove))
1616 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1617 return [self webScriptNameForSelector:selector] == nil;
1620 + (NSArray *) _attributeKeys {
1621 return [NSArray arrayWithObjects:
1632 @"shortDescription",
1639 - (NSArray *) attributeKeys {
1640 return [[self class] _attributeKeys];
1643 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1644 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1647 - (metaIndex *) metaIndex {
1651 - (void) setMetaIndex:(metaIndex *)index inPool:(CYPool *)pool {
1652 trusted_ = index->IsTrusted();
1654 uri_.set(pool, index->GetURI());
1655 distribution_.set(pool, index->GetDist());
1656 type_.set(pool, index->GetType());
1658 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1659 if (dindex != NULL) {
1660 std::string file(dindex->MetaIndexURI(""));
1661 base_.set(pool, file);
1664 _profile(Source$setMetaIndex$GetIndexes)
1665 dindex->GetIndexes(&acquire, true);
1667 _profile(Source$setMetaIndex$DescURI)
1668 for (pkgAcquire::ItemIterator item(acquire.ItemsBegin()); item != acquire.ItemsEnd(); item++) {
1669 std::string file((*item)->DescURI());
1670 files_.insert(file);
1671 if (file.length() < sizeof("Packages.bz2") || file.substr(file.length() - sizeof("Packages.bz2")) != "/Packages.bz2")
1673 file = file.substr(0, file.length() - 4);
1674 files_.insert(file);
1675 files_.insert(file + ".gz");
1676 files_.insert(file + "Index");
1681 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1684 pkgTagFile tags(&fd);
1686 pkgTagSection section;
1693 {"default-icon", &defaultIcon_},
1694 {"depiction", &depiction_},
1695 {"description", &description_},
1697 {"origin", &origin_},
1698 {"support", &support_},
1699 {"version", &version_},
1702 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1703 const char *start, *end;
1705 if (section.Find(names[i].name_, start, end)) {
1706 CYString &value(*names[i].value_);
1707 value.set(pool, start, end - start);
1713 record_ = [Sources_ objectForKey:[self key]];
1715 NSURL *url([NSURL URLWithString:uri_]);
1719 host_ = [host_ lowercaseString];
1724 authority_ = [url path];
1727 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(CYPool *)pool {
1728 if ((self = [super init]) != nil) {
1729 era_ = [database era];
1730 database_ = database;
1733 _profile(Source$initWithMetaIndex$setMetaIndex)
1734 [self setMetaIndex:index inPool:pool];
1739 - (NSString *) getField:(NSString *)name {
1740 @synchronized (database_) {
1741 if ([database_ era] != era_ || index_ == NULL)
1744 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index_));
1749 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly)) {
1754 pkgTagFile tags(&fd);
1756 pkgTagSection section;
1759 const char *start, *end;
1760 if (!section.Find([name UTF8String], start, end))
1761 return (NSString *) [NSNull null];
1763 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
1766 - (NSComparisonResult) compareByName:(Source *)source {
1767 NSString *lhs = [self name];
1768 NSString *rhs = [source name];
1770 if ([lhs length] != 0 && [rhs length] != 0) {
1771 unichar lhc = [lhs characterAtIndex:0];
1772 unichar rhc = [rhs characterAtIndex:0];
1774 if (isalpha(lhc) && !isalpha(rhc))
1775 return NSOrderedAscending;
1776 else if (!isalpha(lhc) && isalpha(rhc))
1777 return NSOrderedDescending;
1780 return [lhs compare:rhs options:LaxCompareOptions_];
1783 - (NSString *) depictionForPackage:(NSString *)package {
1784 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1787 - (NSString *) supportForPackage:(NSString *)package {
1788 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1791 - (NSArray *) sections {
1792 return record_ == nil ? (id) [NSNull null] : [record_ objectForKey:@"Sections"] ?: [NSArray array];
1795 - (void) _addSection:(NSString *)section {
1798 else if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) {
1799 if (![sections containsObject:section])
1800 [sections addObject:section];
1802 [record_ setObject:[NSMutableArray arrayWithObject:section] forKey:@"Sections"];
1805 - (bool) addSection:(NSString *)section {
1809 [self performSelectorOnMainThread:@selector(_addSection:) withObject:section waitUntilDone:NO];
1813 - (void) _removeSection:(NSString *)section {
1817 if (NSMutableArray *sections = [record_ objectForKey:@"Sections"])
1818 if ([sections containsObject:section])
1819 [sections removeObject:section];
1822 - (bool) removeSection:(NSString *)section {
1826 [self performSelectorOnMainThread:@selector(_removeSection:) withObject:section waitUntilDone:NO];
1831 [Sources_ removeObjectForKey:[self key]];
1835 bool value(record_ != nil);
1836 [self performSelectorOnMainThread:@selector(_remove) withObject:nil waitUntilDone:NO];
1840 - (NSDictionary *) record {
1848 - (NSString *) rooturi {
1852 - (NSString *) distribution {
1853 return distribution_;
1856 - (NSString *) type {
1860 - (NSString *) baseuri {
1861 return base_.empty() ? nil : (id) base_;
1864 - (NSString *) iconuri {
1865 if (NSString *base = [self baseuri])
1866 return [base stringByAppendingString:@"CydiaIcon.png"];
1871 - (NSURL *) iconURL {
1872 if (NSString *uri = [self iconuri])
1873 return [NSURL URLWithString:uri];
1877 - (NSString *) key {
1878 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1881 - (NSString *) host {
1885 - (NSString *) name {
1886 return origin_.empty() ? (id) authority_ : origin_;
1889 - (NSString *) shortDescription {
1890 return description_;
1893 - (NSString *) label {
1894 return label_.empty() ? (id) authority_ : label_;
1897 - (NSString *) origin {
1901 - (NSString *) version {
1905 - (NSString *) defaultIcon {
1906 return defaultIcon_;
1909 - (void) setDelegate:(NSObject<SourceDelegate> *)delegate {
1910 delegate_ = delegate;
1914 return !fetches_.empty();
1917 - (void) setFetch:(bool)fetch forURI:(const char *)uri {
1919 if (fetches_.erase(uri) == 0)
1921 } else if (files_.find(uri) == files_.end())
1923 else if (!fetches_.insert(uri).second)
1926 [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:[self fetch]] waitUntilDone:NO];
1929 - (void) resetFetch {
1931 [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:NO];
1936 /* CydiaOperation Class {{{ */
1937 @interface CydiaOperation : NSObject {
1938 _H<NSString> operator_;
1939 _H<NSString> value_;
1942 - (NSString *) operator;
1943 - (NSString *) value;
1947 @implementation CydiaOperation
1949 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1950 if ((self = [super init]) != nil) {
1951 operator_ = [NSString stringWithUTF8String:_operator];
1952 value_ = [NSString stringWithUTF8String:value];
1956 + (NSArray *) _attributeKeys {
1957 return [NSArray arrayWithObjects:
1963 - (NSArray *) attributeKeys {
1964 return [[self class] _attributeKeys];
1967 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1968 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1971 - (NSString *) operator {
1975 - (NSString *) value {
1981 /* CydiaClause Class {{{ */
1982 @interface CydiaClause : NSObject {
1983 _H<NSString> package_;
1984 _H<CydiaOperation> version_;
1987 - (NSString *) package;
1988 - (CydiaOperation *) version;
1992 @implementation CydiaClause
1994 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1995 if ((self = [super init]) != nil) {
1996 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1998 if (const char *version = dep.TargetVer())
1999 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
2001 version_ = (id) [NSNull null];
2005 + (NSArray *) _attributeKeys {
2006 return [NSArray arrayWithObjects:
2012 - (NSArray *) attributeKeys {
2013 return [[self class] _attributeKeys];
2016 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2017 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2020 - (NSString *) package {
2024 - (CydiaOperation *) version {
2030 /* CydiaRelation Class {{{ */
2031 @interface CydiaRelation : NSObject {
2032 _H<NSString> relationship_;
2033 _H<NSMutableArray> clauses_;
2036 - (NSString *) relationship;
2037 - (NSArray *) clauses;
2041 @implementation CydiaRelation
2043 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
2044 if ((self = [super init]) != nil) {
2045 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
2046 clauses_ = [NSMutableArray arrayWithCapacity:8];
2048 pkgCache::DepIterator start;
2049 pkgCache::DepIterator end;
2050 dep.GlobOr(start, end); // ++dep
2053 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
2055 // yes, seriously. (wtf?)
2063 + (NSArray *) _attributeKeys {
2064 return [NSArray arrayWithObjects:
2070 - (NSArray *) attributeKeys {
2071 return [[self class] _attributeKeys];
2074 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2075 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2078 - (NSString *) relationship {
2079 return relationship_;
2082 - (NSArray *) clauses {
2086 - (void) addClause:(CydiaClause *)clause {
2087 [clauses_ addObject:clause];
2092 /* Package Class {{{ */
2093 struct ParsedPackage {
2097 CYString architecture_;
2100 CYString depiction_;
2107 @interface Package : NSObject {
2109 @public uint32_t role_ : 3;
2110 uint32_t essential_ : 1;
2111 uint32_t obsolete_ : 1;
2112 uint32_t ignored_ : 1;
2113 uint32_t pooled_ : 1;
2119 _transient Database *database_;
2121 pkgCache::VerIterator version_;
2122 pkgCache::PkgIterator iterator_;
2123 pkgCache::VerFileIterator file_;
2127 CYString transform_;
2130 CYString installed_;
2133 const char *section_;
2134 _transient NSString *section$_;
2138 PackageValue *metadata_;
2139 ParsedPackage *parsed_;
2141 _H<NSMutableArray> tags_;
2144 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database;
2145 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database;
2147 - (pkgCache::PkgIterator) iterator;
2150 - (NSString *) section;
2151 - (NSString *) simpleSection;
2153 - (NSString *) longSection;
2154 - (NSString *) shortSection;
2158 - (MIMEAddress *) maintainer;
2160 - (NSString *) longDescription;
2161 - (NSString *) shortDescription;
2164 - (PackageValue *) metadata;
2167 - (bool) subscribed;
2168 - (bool) setSubscribed:(bool)subscribed;
2172 - (NSString *) latest;
2173 - (NSString *) installed;
2174 - (BOOL) uninstalled;
2176 - (BOOL) upgradableAndEssential:(BOOL)essential;
2179 - (BOOL) unfiltered;
2183 - (BOOL) halfConfigured;
2184 - (BOOL) halfInstalled;
2186 - (NSString *) mode;
2189 - (NSString *) name;
2191 - (NSString *) homepage;
2192 - (NSString *) depiction;
2193 - (MIMEAddress *) author;
2195 - (NSString *) support;
2197 - (NSArray *) files;
2198 - (NSArray *) warnings;
2199 - (NSArray *) applications;
2201 - (Source *) source;
2204 - (BOOL) matches:(NSArray *)query;
2206 - (BOOL) hasTag:(NSString *)tag;
2207 - (NSString *) primaryPurpose;
2208 - (NSArray *) purposes;
2209 - (bool) isCommercial;
2211 - (void) setIndex:(size_t)index;
2213 - (CYString &) cyname;
2215 - (uint32_t) compareBySection:(NSArray *)sections;
2222 uint32_t PackageChangesRadix(Package *self, void *) {
2227 uint32_t timestamp : 30;
2228 uint32_t ignored : 1;
2229 uint32_t upgradable : 1;
2233 bool upgradable([self upgradableAndEssential:YES]);
2234 value.bits.upgradable = upgradable ? 1 : 0;
2237 value.bits.timestamp = 0;
2238 value.bits.ignored = [self ignored] ? 0 : 1;
2239 value.bits.upgradable = 1;
2241 value.bits.timestamp = [self seen] >> 2;
2242 value.bits.ignored = 0;
2243 value.bits.upgradable = 0;
2246 return _not(uint32_t) - value.key;
2249 CYString &(*PackageName)(Package *self, SEL sel);
2251 uint32_t PackagePrefixRadix(Package *self, void *context) {
2252 size_t offset(reinterpret_cast<size_t>(context));
2253 CYString &name(PackageName(self, @selector(cyname)));
2255 size_t size(name.size());
2258 char *text(name.data());
2261 if (!isdigit(text[0]))
2265 while (size != digits && isdigit(text[digits]))
2273 if (offset == 0 && zeros != 0) {
2274 memset(data, '0', zeros);
2275 memcpy(data + zeros, text, 4 - zeros);
2277 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2278 if (size <= offset - zeros)
2281 text += offset - zeros;
2282 size -= offset - zeros;
2285 memcpy(data, text, 4);
2287 memcpy(data, text, size);
2288 memset(data + size, 0, 4 - size);
2291 for (size_t i(0); i != 4; ++i)
2292 if (isalpha(data[i]))
2300 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2302 /* XXX: ntohl may be more honest */
2303 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2306 CFComparisonResult StringNameCompare(CFStringRef lhn, CFStringRef rhn, size_t length) {
2307 _profile(PackageNameCompare)
2309 return rhn == NULL ? kCFCompareEqualTo : kCFCompareLessThan;
2310 else if (rhn == NULL)
2311 return kCFCompareGreaterThan;
2313 CFIndex length(CFStringGetLength(lhn));
2315 _profile(PackageNameCompare$NumbersLast)
2316 if (length != 0 && CFStringGetLength(rhn) != 0) {
2317 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2318 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2319 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2320 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2321 return lha ? kCFCompareLessThan : kCFCompareGreaterThan;
2325 _profile(PackageNameCompare$Compare)
2326 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, (CFLocaleRef) (id) CollationLocale_);
2331 _finline CFComparisonResult StringNameCompare(NSString *lhn, NSString*rhn, size_t length) {
2332 return StringNameCompare((CFStringRef) lhn, (CFStringRef) rhn, length);
2335 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2336 CYString &lhn(PackageName(lhs, @selector(cyname)));
2337 NSString *rhn(PackageName(rhs, @selector(cyname)));
2338 return StringNameCompare(lhn, rhn, lhn.size());
2341 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *arg) {
2342 return PackageNameCompare(*lhs, *rhs, arg);
2345 struct PackageNameOrdering :
2346 std::binary_function<Package *, Package *, bool>
2348 _finline bool operator ()(Package *lhs, Package *rhs) const {
2349 return PackageNameCompare(lhs, rhs, NULL) == kCFCompareLessThan;
2353 @implementation Package
2355 - (NSString *) description {
2356 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2362 if (parsed_ != NULL)
2367 + (NSString *) webScriptNameForSelector:(SEL)selector {
2369 else if (selector == @selector(clear))
2371 else if (selector == @selector(getField:))
2373 else if (selector == @selector(getRecord))
2374 return @"getRecord";
2375 else if (selector == @selector(hasTag:))
2377 else if (selector == @selector(install))
2379 else if (selector == @selector(remove))
2385 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2386 return [self webScriptNameForSelector:selector] == nil;
2389 + (NSArray *) _attributeKeys {
2390 return [NSArray arrayWithObjects:
2411 @"shortDescription",
2424 - (NSArray *) attributeKeys {
2425 return [[self class] _attributeKeys];
2428 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2429 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2432 - (NSArray *) relations {
2433 @synchronized (database_) {
2434 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2435 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2436 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2440 - (NSString *) architecture {
2442 @synchronized (database_) {
2443 return parsed_->architecture_.empty() ? [NSNull null] : (id) parsed_->architecture_;
2446 - (NSString *) getField:(NSString *)name {
2447 @synchronized (database_) {
2448 if ([database_ era] != era_ || file_.end())
2451 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2453 const char *start, *end;
2454 if (!parser.Find([name UTF8String], start, end))
2455 return (NSString *) [NSNull null];
2457 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2460 - (NSString *) getRecord {
2461 @synchronized (database_) {
2462 if ([database_ era] != era_ || file_.end())
2465 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2467 const char *start, *end;
2468 parser.GetRec(start, end);
2470 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2474 if (parsed_ != NULL)
2476 @synchronized (database_) {
2477 if ([database_ era] != era_ || file_.end())
2480 ParsedPackage *parsed(new ParsedPackage);
2483 _profile(Package$parse)
2484 pkgRecords::Parser *parser;
2486 _profile(Package$parse$Lookup)
2487 parser = &[database_ records]->Lookup(file_);
2493 _profile(Package$parse$Find)
2498 {"architecture", &parsed->architecture_},
2499 {"icon", &parsed->icon_},
2500 {"depiction", &parsed->depiction_},
2501 {"homepage", &parsed->homepage_},
2502 {"website", &website},
2504 {"support", &parsed->support_},
2505 {"author", &parsed->author_},
2506 {"md5sum", &parsed->md5sum_},
2509 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2510 const char *start, *end;
2512 if (parser->Find(names[i].name_, start, end)) {
2513 CYString &value(*names[i].value_);
2514 _profile(Package$parse$Value)
2515 value.set(pool_, start, end - start);
2521 _profile(Package$parse$Tagline)
2522 parsed->tagline_.set(pool_, parser->ShortDesc());
2525 _profile(Package$parse$Retain)
2526 if (parsed->homepage_.empty())
2527 parsed->homepage_ = website;
2528 if (parsed->homepage_ == parsed->depiction_)
2529 parsed->homepage_.clear();
2530 if (parsed->support_.empty())
2531 parsed->support_ = bugs;
2536 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database {
2537 if ((self = [super init]) != nil) {
2538 _profile(Package$initWithVersion)
2540 pool_ = new CYPool();
2546 database_ = database;
2547 era_ = [database era];
2551 pkgCache::PkgIterator iterator(version_.ParentPkg());
2552 iterator_ = iterator;
2554 _profile(Package$initWithVersion$Version)
2555 file_ = version_.FileList();
2558 _profile(Package$initWithVersion$Cache)
2559 name_.set(NULL, version_.Display());
2561 latest_.set(NULL, StripVersion_(version_.VerStr()));
2563 pkgCache::VerIterator current(iterator.CurrentVer());
2565 installed_.set(NULL, StripVersion_(current.VerStr()));
2568 _profile(Package$initWithVersion$Transliterate) do {
2569 if (CollationTransl_ == NULL)
2574 _profile(Package$initWithVersion$Transliterate$utf8)
2575 const uint8_t *data(reinterpret_cast<const uint8_t *>(name_.data()));
2576 for (size_t i(0), e(name_.size()); i != e; ++i)
2577 if (data[i] >= 0x80)
2582 UErrorCode code(U_ZERO_ERROR);
2585 _profile(Package$initWithVersion$Transliterate$u_strFromUTF8WithSub)
2586 CollationString_.resize(name_.size());
2587 u_strFromUTF8WithSub(&CollationString_[0], CollationString_.size(), &length, name_.data(), name_.size(), 0xfffd, NULL, &code);
2588 if (!U_SUCCESS(code))
2590 CollationString_.resize(length);
2593 _profile(Package$initWithVersion$Transliterate$utrans_trans)
2594 length = CollationString_.size();
2595 utrans_trans(CollationTransl_, reinterpret_cast<UReplaceable *>(&CollationString_), &CollationUCalls_, 0, &length, &code);
2596 if (!U_SUCCESS(code))
2598 _assert(CollationString_.size() == length);
2601 _profile(Package$initWithVersion$Transliterate$u_strToUTF8WithSub$preflight)
2602 u_strToUTF8WithSub(NULL, 0, &length, CollationString_.data(), CollationString_.size(), 0xfffd, NULL, &code);
2603 if (code == U_BUFFER_OVERFLOW_ERROR)
2604 code = U_ZERO_ERROR;
2605 else if (!U_SUCCESS(code))
2610 _profile(Package$initWithVersion$Transliterate$apr_palloc)
2611 transform = pool_->malloc<char>(length);
2613 _profile(Package$initWithVersion$Transliterate$u_strToUTF8WithSub$transform)
2614 u_strToUTF8WithSub(transform, length, NULL, CollationString_.data(), CollationString_.size(), 0xfffd, NULL, &code);
2615 if (!U_SUCCESS(code))
2619 transform_.set(NULL, transform, length);
2620 } while (false); _end
2622 _profile(Package$initWithVersion$Tags)
2624 pkgCache::TagIterator tag(version_.TagList());
2626 pkgCache::TagIterator tag(iterator.TagList());
2629 tags_ = [NSMutableArray arrayWithCapacity:8];
2631 goto tag; for (; !tag.end(); ++tag) tag: {
2632 const char *name(tag.Name());
2633 NSString *string((NSString *) CYStringCreate(name));
2637 [tags_ addObject:[string autorelease]];
2639 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2640 if (strcmp(name + 6, "enduser") == 0)
2642 else if (strcmp(name + 6, "hacker") == 0)
2644 else if (strcmp(name + 6, "developer") == 0)
2646 else if (strcmp(name + 6, "cydia") == 0)
2652 if (strncmp(name, "cydia::", 7) == 0) {
2653 if (strcmp(name + 7, "essential") == 0)
2655 else if (strcmp(name + 7, "obsolete") == 0)
2662 _profile(Package$initWithVersion$Metadata)
2663 const char *mixed(iterator.Name());
2664 size_t size(strlen(mixed));
2665 static const size_t prefix(sizeof("/var/lib/dpkg/info/") - 1);
2666 char lower[prefix + size + 5 + 1];
2668 for (size_t i(0); i != size; ++i)
2669 lower[prefix + i] = mixed[i] | 0x20;
2671 if (!installed_.empty()) {
2672 memcpy(lower, "/var/lib/dpkg/info/", prefix);
2673 memcpy(lower + prefix + size, ".list", 6);
2675 if (stat(lower, &info) != -1)
2676 upgraded_ = info.st_birthtime;
2679 PackageValue *metadata(PackageFind(lower + prefix, size));
2680 metadata_ = metadata;
2682 id_.set(NULL, metadata->name_, size);
2684 const char *latest(version_.VerStr());
2685 size_t length(strlen(latest));
2687 uint16_t vhash(hashlittle(latest, length));
2689 size_t capped(std::min<size_t>(8, length));
2690 latest = latest + length - capped;
2692 if (metadata->first_ == 0)
2693 metadata->first_ = now_;
2695 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2696 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2697 metadata->vhash_ = vhash;
2698 metadata->last_ = now_;
2699 } else if (metadata->last_ == 0)
2700 metadata->last_ = metadata->first_;
2703 _profile(Package$initWithVersion$Section)
2704 section_ = version_.Section();
2707 _profile(Package$initWithVersion$Flags)
2708 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2709 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2714 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database {
2715 pkgCache::VerIterator version;
2717 _profile(Package$packageWithIterator$GetCandidateVer)
2718 version = [database policy]->GetCandidateVer(iterator);
2726 _profile(Package$packageWithIterator$Allocate)
2727 package = [Package allocWithZone:zone];
2730 _profile(Package$packageWithIterator$Initialize)
2732 initWithVersion:version
2739 _profile(Package$packageWithIterator$Autorelease)
2740 package = [package autorelease];
2746 - (pkgCache::PkgIterator) iterator {
2750 - (NSArray *) downgrades {
2751 NSMutableArray *versions([NSMutableArray arrayWithCapacity:4]);
2753 for (auto version(iterator_.VersionList()); !version.end(); ++version) {
2754 if (version == version_)
2756 Package *package([[[Package allocWithZone:NULL] initWithVersion:version withZone:NULL inPool:NULL database:database_] autorelease]);
2757 if ([package source] == nil)
2759 [versions addObject:package];
2765 - (NSString *) section {
2766 if (section$_ == nil) {
2767 if (section_ == NULL)
2770 _profile(Package$section$mappedSectionForPointer)
2771 section$_ = [database_ mappedSectionForPointer:section_];
2776 - (NSString *) simpleSection {
2777 if (NSString *section = [self section])
2778 return Simplify(section);
2783 - (NSString *) longSection {
2784 if (NSString *section = [self section])
2785 return LocalizeSection(section);
2790 - (NSString *) shortSection {
2791 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2794 - (NSString *) uri {
2797 pkgIndexFile *index;
2798 pkgCache::PkgFileIterator file(file_.File());
2799 if (![database_ list].FindIndex(file, index))
2801 return [NSString stringWithUTF8String:iterator_->Path];
2802 //return [NSString stringWithUTF8String:file.Site()];
2803 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2807 - (MIMEAddress *) maintainer {
2808 @synchronized (database_) {
2809 if ([database_ era] != era_ || file_.end())
2812 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2813 const std::string &maintainer(parser->Maintainer());
2814 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2817 - (NSString *) md5sum {
2818 return parsed_ == NULL ? nil : (id) parsed_->md5sum_;
2822 @synchronized (database_) {
2823 if ([database_ era] != era_ || version_.end())
2826 return version_->InstalledSize;
2829 - (NSString *) longDescription {
2830 @synchronized (database_) {
2831 if ([database_ era] != era_ || file_.end())
2834 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2835 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2837 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2838 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2839 if ([lines count] < 2)
2842 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2843 for (size_t i(1), e([lines count]); i != e; ++i) {
2844 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2845 [trimmed addObject:trim];
2848 return [trimmed componentsJoinedByString:@"\n"];
2851 - (NSString *) shortDescription {
2852 if (parsed_ != NULL)
2853 return static_cast<NSString *>(parsed_->tagline_);
2855 @synchronized (database_) {
2856 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2857 std::string value(parser.ShortDesc());
2860 if (value.size() > 200)
2862 return [(id) CYStringCreate(value) autorelease];
2866 _profile(Package$index)
2867 CFStringRef name((CFStringRef) [self name]);
2868 if (CFStringGetLength(name) == 0)
2870 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2871 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2873 return toupper(character);
2877 - (PackageValue *) metadata {
2882 PackageValue *metadata([self metadata]);
2883 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2886 - (bool) subscribed {
2887 return [self metadata]->subscribed_;
2890 - (bool) setSubscribed:(bool)subscribed {
2891 PackageValue *metadata([self metadata]);
2892 if (metadata->subscribed_ == subscribed)
2894 metadata->subscribed_ = subscribed;
2902 - (NSString *) latest {
2906 - (NSString *) installed {
2910 - (BOOL) uninstalled {
2911 return installed_.empty();
2914 - (BOOL) upgradableAndEssential:(BOOL)essential {
2915 _profile(Package$upgradableAndEssential)
2916 pkgCache::VerIterator current(iterator_.CurrentVer());
2918 return essential && essential_;
2920 return version_ != current;
2924 - (BOOL) essential {
2929 return [database_ cache][iterator_].InstBroken();
2932 - (BOOL) unfiltered {
2933 _profile(Package$unfiltered$obsolete)
2934 if (_unlikely(obsolete_))
2938 _profile(Package$unfiltered$role)
2939 if (_unlikely(role_ > 3))
2947 if (![self unfiltered])
2952 _profile(Package$visible$section)
2953 section = [self section];
2956 _profile(Package$visible$isSectionVisible)
2957 if (!isSectionVisible(section))
2965 unsigned char current(iterator_->CurrentState);
2966 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2969 - (BOOL) halfConfigured {
2970 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2973 - (BOOL) halfInstalled {
2974 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2978 @synchronized (database_) {
2979 if ([database_ era] != era_ || iterator_.end())
2982 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2983 return state.Mode != pkgDepCache::ModeKeep;
2986 - (NSString *) mode {
2987 @synchronized (database_) {
2988 if ([database_ era] != era_ || iterator_.end())
2991 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2993 switch (state.Mode) {
2994 case pkgDepCache::ModeDelete:
2995 if ((state.iFlags & pkgDepCache::Purge) != 0)
2999 case pkgDepCache::ModeKeep:
3000 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
3001 return @"REINSTALL";
3002 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
3006 case pkgDepCache::ModeInstall:
3007 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
3008 return @"REINSTALL";
3009 else*/ switch (state.Status) {
3011 return @"DOWNGRADE";
3017 return @"NEW_INSTALL";
3028 - (NSString *) name {
3029 return name_.empty() ? id_ : name_;
3032 - (UIImage *) icon {
3033 NSString *section = [self simpleSection];
3036 if (parsed_ != NULL)
3037 if (NSString *href = parsed_->icon_)
3038 if ([href hasPrefix:@"file:///"])
3039 icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
3040 if (icon == nil) if (section != nil)
3041 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]];
3042 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
3043 if ([dicon hasPrefix:@"file:///"])
3044 icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
3046 icon = [UIImage imageNamed:@"unknown.png"];
3050 - (NSString *) homepage {
3051 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
3054 - (NSString *) depiction {
3055 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
3058 - (MIMEAddress *) author {
3059 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
3062 - (NSString *) support {
3063 return parsed_ != NULL && !parsed_->support_.empty() ? parsed_->support_ : [[self source] supportForPackage:id_];
3066 - (NSArray *) files {
3067 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
3068 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
3071 fin.open([path UTF8String]);
3076 while (std::getline(fin, line))
3077 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
3082 - (NSString *) state {
3083 @synchronized (database_) {
3084 if ([database_ era] != era_ || file_.end())
3087 switch (iterator_->CurrentState) {
3088 case pkgCache::State::NotInstalled:
3089 return @"NotInstalled";
3090 case pkgCache::State::UnPacked:
3092 case pkgCache::State::HalfConfigured:
3093 return @"HalfConfigured";
3094 case pkgCache::State::HalfInstalled:
3095 return @"HalfInstalled";
3096 case pkgCache::State::ConfigFiles:
3097 return @"ConfigFiles";
3098 case pkgCache::State::Installed:
3099 return @"Installed";
3100 case pkgCache::State::TriggersAwaited:
3101 return @"TriggersAwaited";
3102 case pkgCache::State::TriggersPending:
3103 return @"TriggersPending";
3106 return (NSString *) [NSNull null];
3109 - (NSString *) selection {
3110 @synchronized (database_) {
3111 if ([database_ era] != era_ || file_.end())
3114 switch (iterator_->SelectedState) {
3115 case pkgCache::State::Unknown:
3117 case pkgCache::State::Install:
3119 case pkgCache::State::Hold:
3121 case pkgCache::State::DeInstall:
3122 return @"DeInstall";
3123 case pkgCache::State::Purge:
3127 return (NSString *) [NSNull null];
3130 - (NSArray *) warnings {
3131 @synchronized (database_) {
3132 if ([database_ era] != era_ || file_.end())
3135 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
3136 const char *name(iterator_.Name());
3138 size_t length(strlen(name));
3139 if (length < 2) invalid:
3140 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
3141 else for (size_t i(0); i != length; ++i)
3143 /* XXX: technically this is not allowed */
3144 (name[i] < 'A' || name[i] > 'Z') &&
3145 (name[i] < 'a' || name[i] > 'z') &&
3146 (name[i] < '0' || name[i] > '9') &&
3147 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
3150 if (strcmp(name, "cydia") != 0) {
3153 bool _private = false;
3155 bool dbstash = false;
3156 bool dsstore = false;
3158 bool repository = [[self section] isEqualToString:@"Repositories"];
3160 if (NSArray *files = [self files])
3161 for (NSString *file in files)
3162 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
3164 else if (!user && [file isEqualToString:@"/User"])
3166 else if (!_private && [file isEqualToString:@"/private"])
3168 else if (!stash && [file isEqualToString:@"/var/stash"])
3170 else if (!dbstash && [file isEqualToString:@"/var/db/stash"])
3172 else if (!dsstore && [file hasSuffix:@"/.DS_Store"])
3175 /* XXX: this is not sensitive enough. only some folders are valid. */
3176 if (cydia && !repository)
3177 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
3179 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
3181 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
3183 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
3185 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/db/stash"]];
3187 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @".DS_Store"]];
3190 return [warnings count] == 0 ? nil : warnings;
3193 - (NSArray *) applications {
3194 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
3196 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
3198 static RegEx application_r("/Applications/(.*)\\.app/Info.plist");
3199 if (NSArray *files = [self files])
3200 for (NSString *file in files)
3201 if (application_r(file)) {
3202 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
3205 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
3206 if (id == nil || [id isEqualToString:me])
3209 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
3211 display = application_r[1];
3213 NSString *bundle([file stringByDeletingLastPathComponent]);
3214 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
3215 // XXX: maybe this should check if this is really a string, not just for length
3216 if (icon == nil || ![icon respondsToSelector:@selector(length)] || [icon length] == 0)
3218 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
3220 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
3221 [applications addObject:application];
3223 [application addObject:id];
3224 [application addObject:display];
3225 [application addObject:url];
3228 return [applications count] == 0 ? nil : applications;
3231 - (Source *) source {
3232 if (source_ == nil) {
3233 @synchronized (database_) {
3234 if ([database_ era] != era_ || file_.end())
3235 source_ = (Source *) [NSNull null];
3237 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
3241 return source_ == (Source *) [NSNull null] ? nil : source_;
3244 - (time_t) upgraded {
3248 - (uint32_t) recent {
3249 return std::numeric_limits<uint32_t>::max() - upgraded_;
3256 - (BOOL) matches:(NSArray *)query {
3257 if (query == nil || [query count] == 0)
3266 string = [self name];
3267 length = [string length];
3270 for (NSString *term in query) {
3271 range = [string rangeOfString:term options:MatchCompareOptions_];
3272 if (range.location != NSNotFound)
3273 rank_ -= 6 * 1000000 / length;
3278 length = [string length];
3281 for (NSString *term in query) {
3282 range = [string rangeOfString:term options:MatchCompareOptions_];
3283 if (range.location != NSNotFound)
3284 rank_ -= 6 * 1000000 / length;
3288 string = [self shortDescription];
3289 length = [string length];
3290 NSUInteger stop(std::min<NSUInteger>(length, 200));
3293 for (NSString *term in query) {
3294 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
3295 if (range.location != NSNotFound)
3296 rank_ -= 2 * 100000;
3302 - (NSArray *) tags {
3306 - (BOOL) hasTag:(NSString *)tag {
3307 return tags_ == nil ? NO : [tags_ containsObject:tag];
3310 - (NSString *) primaryPurpose {
3311 for (NSString *tag in (NSArray *) tags_)
3312 if ([tag hasPrefix:@"purpose::"])
3313 return [tag substringFromIndex:9];
3317 - (NSArray *) purposes {
3318 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
3319 for (NSString *tag in (NSArray *) tags_)
3320 if ([tag hasPrefix:@"purpose::"])
3321 [purposes addObject:[tag substringFromIndex:9]];
3322 return [purposes count] == 0 ? nil : purposes;
3325 - (bool) isCommercial {
3326 return [self hasTag:@"cydia::commercial"];
3329 - (void) setIndex:(size_t)index {
3330 if (metadata_->index_ != index)
3331 metadata_->index_ = index;
3334 - (CYString &) cyname {
3335 return !transform_.empty() ? transform_ : !name_.empty() ? name_ : id_;
3338 - (uint32_t) compareBySection:(NSArray *)sections {
3339 NSString *section([self section]);
3340 for (size_t i(0), e([sections count]); i != e; ++i) {
3341 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3345 return _not(uint32_t);
3349 @synchronized (database_) {
3350 if ([database_ era] != era_ || file_.end())
3353 pkgProblemResolver *resolver = [database_ resolver];
3354 resolver->Clear(iterator_);
3356 pkgCacheFile &cache([database_ cache]);
3357 cache->SetReInstall(iterator_, false);
3358 cache->MarkKeep(iterator_, false);
3362 @synchronized (database_) {
3363 if ([database_ era] != era_ || file_.end())
3366 pkgProblemResolver *resolver = [database_ resolver];
3367 resolver->Clear(iterator_);
3368 resolver->Protect(iterator_);
3370 pkgCacheFile &cache([database_ cache]);
3371 cache->SetCandidateVersion(version_);
3372 cache->SetReInstall(iterator_, false);
3373 cache->MarkInstall(iterator_, false);
3375 pkgDepCache::StateCache &state((*cache)[iterator_]);
3376 if (!state.Install())
3377 cache->SetReInstall(iterator_, true);
3381 @synchronized (database_) {
3382 if ([database_ era] != era_ || file_.end())
3385 pkgProblemResolver *resolver = [database_ resolver];
3386 resolver->Clear(iterator_);
3387 resolver->Remove(iterator_);
3388 resolver->Protect(iterator_);
3390 pkgCacheFile &cache([database_ cache]);
3391 cache->SetReInstall(iterator_, false);
3392 cache->MarkDelete(iterator_, true);
3397 /* Section Class {{{ */
3398 @interface Section : NSObject {
3402 _H<NSString> localized_;
3405 - (NSComparisonResult) compareByLocalized:(Section *)section;
3406 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3407 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3408 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3410 - (NSString *) name;
3411 - (void) setName:(NSString *)name;
3417 - (void) addToCount;
3419 - (void) setCount:(size_t)count;
3420 - (NSString *) localized;
3424 @implementation Section
3426 - (NSComparisonResult) compareByLocalized:(Section *)section {
3427 NSString *lhs(localized_);
3428 NSString *rhs([section localized]);
3430 /*if ([lhs length] != 0 && [rhs length] != 0) {
3431 unichar lhc = [lhs characterAtIndex:0];
3432 unichar rhc = [rhs characterAtIndex:0];
3434 if (isalpha(lhc) && !isalpha(rhc))
3435 return NSOrderedAscending;
3436 else if (!isalpha(lhc) && isalpha(rhc))
3437 return NSOrderedDescending;
3440 return [lhs compare:rhs options:LaxCompareOptions_];
3443 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3444 if ((self = [self initWithName:name localize:NO]) != nil) {
3445 if (localized != nil)
3446 localized_ = localized;
3450 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3451 return [self initWithName:name row:0 localize:localize];
3454 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3455 if ((self = [super init]) != nil) {
3459 localized_ = LocalizeSection(name_);
3463 - (NSString *) name {
3467 - (void) setName:(NSString *)name {
3483 - (void) addToCount {
3487 - (void) setCount:(size_t)count {
3491 - (NSString *) localized {
3498 class CydiaLogCleaner :
3499 public pkgArchiveCleaner
3502 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3507 /* Database Implementation {{{ */
3508 @implementation Database
3510 + (Database *) sharedInstance {
3511 static _H<Database> instance;
3512 if (instance == nil)
3513 instance = [[[Database alloc] init] autorelease];
3521 - (void) releasePackages {
3522 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3523 CFArrayRemoveAllValues(packages_);
3527 // XXX: actually implement this thing
3529 [self releasePackages];
3530 NSRecycleZone(zone_);
3534 - (void) _readCydia:(NSNumber *)fd {
3535 boost::fdistream is([fd intValue]);
3538 static RegEx finish_r("finish:([^:]*)");
3540 while (std::getline(is, line)) {
3541 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3543 const char *data(line.c_str());
3544 size_t size = line.size();
3545 lprintf("C:%s\n", data);
3547 if (finish_r(data, size)) {
3548 NSString *finish = finish_r[1];
3549 int index = [Finishes_ indexOfObject:finish];
3550 if (index != INT_MAX && index > Finish_)
3560 - (void) _readStatus:(NSNumber *)fd {
3561 boost::fdistream is([fd intValue]);
3564 static RegEx conffile_r("status: [^ ]* : conffile-prompt : (.*?) *");
3565 static RegEx pmstatus_r("([^:]*):([^:]*):([^:]*):(.*)");
3567 while (std::getline(is, line)) {
3568 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3570 const char *data(line.c_str());
3571 size_t size(line.size());
3572 lprintf("S:%s\n", data);
3574 if (conffile_r(data, size)) {
3575 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3576 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3577 } else if (strncmp(data, "status: ", 8) == 0) {
3578 // status: <package>: {unpacked,half-configured,installed}
3579 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3580 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3581 } else if (strncmp(data, "processing: ", 12) == 0) {
3582 // processing: configure: config-test
3583 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3584 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3585 } else if (pmstatus_r(data, size)) {
3586 std::string type([pmstatus_r[1] UTF8String]);
3588 NSString *package = pmstatus_r[2];
3589 if ([package isEqualToString:@"dpkg-exec"])
3592 float percent([pmstatus_r[3] floatValue]);
3593 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3595 NSString *string = pmstatus_r[4];
3597 if (type == "pmerror") {
3598 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3599 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3600 } else if (type == "pmstatus") {
3601 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3602 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3603 } else if (type == "pmconffile")
3604 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3606 lprintf("E:unknown pmstatus\n");
3608 lprintf("E:unknown status\n");
3616 - (void) _readOutput:(NSNumber *)fd {
3617 boost::fdistream is([fd intValue]);
3620 while (std::getline(is, line)) {
3621 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3623 lprintf("O:%s\n", line.c_str());
3625 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3626 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3638 - (Package *) packageWithName:(NSString *)name {
3641 @synchronized (self) {
3642 if (static_cast<pkgDepCache *>(cache_) == NULL)
3644 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]
3649 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:NULL database:self];
3653 if ((self = [super init]) != nil) {
3660 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3662 size_t capacity(MetaFile_->active_);
3668 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3669 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3673 _assert(pipe(fds) != -1);
3676 _config->Set("APT::Keep-Fds::", cydiafd_);
3677 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3680 detachNewThreadSelector:@selector(_readCydia:)
3682 withObject:[NSNumber numberWithInt:fds[0]]
3685 _assert(pipe(fds) != -1);
3689 detachNewThreadSelector:@selector(_readStatus:)
3691 withObject:[NSNumber numberWithInt:fds[0]]
3694 _assert(pipe(fds) != -1);
3695 _assert(dup2(fds[0], 0) != -1);
3696 _assert(close(fds[0]) != -1);
3698 input_ = fdopen(fds[1], "a");
3700 _assert(pipe(fds) != -1);
3701 _assert(dup2(fds[1], 1) != -1);
3702 _assert(close(fds[1]) != -1);
3705 detachNewThreadSelector:@selector(_readOutput:)
3707 withObject:[NSNumber numberWithInt:fds[0]]
3712 - (pkgCacheFile &) cache {
3716 - (pkgDepCache::Policy *) policy {
3720 - (pkgRecords *) records {
3724 - (pkgProblemResolver *) resolver {
3728 - (pkgAcquire &) fetcher {
3732 - (pkgSourceList &) list {
3736 - (NSArray *) packages {
3737 return (NSArray *) packages_;
3740 - (NSArray *) sources {
3744 - (Source *) sourceWithKey:(NSString *)key {
3745 for (Source *source in [self sources]) {
3746 if ([[source key] isEqualToString:key])
3751 - (bool) popErrorWithTitle:(NSString *)title {
3754 while (!_error->empty()) {
3756 bool warning(!_error->PopMessage(error));
3761 size_t size(error.size());
3762 if (size == 0 || error[size - 1] != '\n')
3764 error.resize(size - 1);
3767 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3769 static RegEx no_pubkey("GPG error:.* NO_PUBKEY .*");
3770 if (warning && no_pubkey(error.c_str()))
3773 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3779 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3780 return [self popErrorWithTitle:title] || !success;
3783 - (bool) popErrorWithTitle:(NSString *)title forReadList:(pkgSourceList &)list {
3784 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3792 if (access("/etc/apt/sources.list", F_OK) == 0)
3793 error |= [self popErrorWithTitle:title forOperation:list.ReadAppend("/etc/apt/sources.list")];
3795 std::string base("/etc/apt/sources.list.d");
3796 if (DIR *sources = opendir(base.c_str())) {
3797 while (dirent *source = readdir(sources))
3798 if (source->d_name[0] != '.' && source->d_namlen > 5 && strcmp(source->d_name + source->d_namlen - 5, ".list") == 0 && strcmp(source->d_name, "cydia.list") != 0)
3799 error |= [self popErrorWithTitle:title forOperation:list.ReadAppend((base + "/" + source->d_name).c_str())];
3803 error |= [self popErrorWithTitle:title forOperation:list.ReadAppend(SOURCES_LIST)];
3808 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3809 @synchronized (self) {
3812 [self releasePackages];
3815 [sourceList_ removeAllObjects];
3836 new (&pool_) CYPool();
3838 NSRecycleZone(zone_);
3839 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3841 int chk(creat("/tmp/cydia.chk", 0644));
3845 if (invocation != nil)
3846 [invocation invoke];
3848 NSString *title(UCLocalize("DATABASE"));
3850 list_ = new pkgSourceList();
3851 _profile(reloadDataWithInvocation$ReadMainList)
3852 if ([self popErrorWithTitle:title forReadList:*list_])
3856 _profile(reloadDataWithInvocation$Source$initWithMetaIndex)
3857 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3858 Source *object([[[Source alloc] initWithMetaIndex:*source forDatabase:self inPool:&pool_] autorelease]);
3859 [sourceList_ addObject:object];
3864 OpProgress progress;
3867 delock_ = GetStatusDate();
3868 _profile(reloadDataWithInvocation$pkgCacheFile)
3869 opened = cache_.Open(progress, false);
3872 // XXX: this block should probably be merged with popError: in some way
3873 while (!_error->empty()) {
3875 bool warning(!_error->PopMessage(error));
3877 lprintf("cache_.Open():[%s]\n", error.c_str());
3879 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3883 else if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3884 repair = @selector(configure);
3885 //else if (error == "The package lists or status file could not be parsed or opened.")
3886 // repair = @selector(update);
3887 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3888 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3889 // else if (error == "Malformed Status line")
3890 // else if (error == "The list of sources could not be read.")
3892 if (repair != NULL) {
3894 [delegate_ repairWithSelector:repair];
3900 } else if ([self popErrorWithTitle:title forOperation:true])
3904 unlink("/tmp/cydia.chk");
3906 now_ = [[NSDate date] timeIntervalSince1970];
3908 policy_ = new pkgDepCache::Policy();
3909 records_ = new pkgRecords(cache_);
3910 resolver_ = new pkgProblemResolver(cache_);
3911 fetcher_ = new pkgAcquire(&status_);
3914 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3915 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3919 _profile(reloadDataWithInvocation$pkgApplyStatus)
3920 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3924 if (cache_->BrokenCount() != 0) {
3925 _profile(pkgApplyStatus$pkgFixBroken)
3926 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3930 if (cache_->BrokenCount() != 0) {
3931 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3935 _profile(pkgApplyStatus$pkgMinimizeUpgrade)
3936 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3941 for (Source *object in (id) sourceList_) {
3942 metaIndex *source([object metaIndex]);
3943 std::vector<pkgIndexFile *> *indices = source->GetIndexFiles();
3944 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3945 // XXX: this could be more intelligent
3946 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3947 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3949 sourceMap_[cached->ID] = object;
3954 /*std::vector<Package *> packages;
3955 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3958 _profile(reloadDataWithInvocation$packageWithIterator)
3959 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3960 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:&pool_ database:self])
3961 //packages.push_back(package);
3962 CFArrayAppendValue(packages_, CFRetain(package));
3966 /*if (packages.empty())
3967 packages_ = [[NSArray alloc] init];
3969 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3972 _profile(reloadDataWithInvocation$radix$8)
3973 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(8)];
3976 _profile(reloadDataWithInvocation$radix$4)
3977 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3980 _profile(reloadDataWithInvocation$radix$0)
3981 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3984 _profile(reloadDataWithInvocation$insertion)
3985 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3988 /*_profile(reloadDataWithInvocation$CFQSortArray)
3989 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);
3992 /*_profile(reloadDataWithInvocation$stdsort)
3993 std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3996 /*_profile(reloadDataWithInvocation$CFArraySortValues)
3997 CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
4000 /*_profile(reloadDataWithInvocation$sortUsingFunction)
4001 [packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
4005 size_t count(CFArrayGetCount(packages_));
4006 MetaFile_->active_ = count;
4007 for (size_t index(0); index != count; ++index)
4008 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
4013 @synchronized (self) {
4015 resolver_ = new pkgProblemResolver(cache_);
4017 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
4018 if (!cache_[iterator].Keep())
4019 cache_->MarkKeep(iterator, false);
4020 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
4021 cache_->SetReInstall(iterator, false);
4024 - (void) configure {
4025 NSString *dpkg = [NSString stringWithFormat:@"/usr/libexec/cydo --configure -a --status-fd %u", statusfd_];
4027 system([dpkg UTF8String]);
4032 @synchronized (self) {
4033 // XXX: I don't remember this condition
4038 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
4040 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
4042 if ([self popErrorWithTitle:title])
4046 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
4048 CydiaLogCleaner cleaner;
4049 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
4056 fetcher_->Shutdown();
4058 pkgRecords records(cache_);
4060 lock_ = new FileFd();
4061 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
4063 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
4065 if ([self popErrorWithTitle:title])
4069 if ([self popErrorWithTitle:title forReadList:list])
4072 manager_ = (_system->CreatePM(cache_));
4073 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
4080 bool substrate(RestartSubstrate_);
4081 RestartSubstrate_ = false;
4083 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
4085 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
4087 if ([self popErrorWithTitle:title forReadList:list])
4089 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
4090 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
4093 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4095 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
4097 [self popErrorWithTitle:title];
4101 bool failed = false;
4102 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
4103 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
4105 if ((*item)->Status == pkgAcquire::Item::StatIdle)
4108 std::string uri = (*item)->DescURI();
4109 std::string error = (*item)->ErrorText;
4111 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
4114 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError]);
4115 [delegate_ addProgressEventOnMainThread:event forTask:title];
4118 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4126 RestartSubstrate_ = true;
4128 if (![delock_ isEqual:GetStatusDate()]) {
4129 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("DPKG_LOCKED") ofType:kCydiaProgressEventTypeError] forTask:title];
4135 pkgPackageManager::OrderResult result(manager_->DoInstall(statusfd_));
4137 NSString *oextended(@"/var/lib/apt/extended_states");
4138 NSString *nextended(Cache("extended_states"));
4141 if (stat([nextended UTF8String], &info) != -1 && (info.st_mode & S_IFMT) == S_IFREG)
4142 system([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /bin/cp --remove-destination %@ %@", ShellEscape(nextended), ShellEscape(oextended)] UTF8String]);
4144 unlink([nextended UTF8String]);
4145 symlink([oextended UTF8String], [nextended UTF8String]);
4147 if ([self popErrorWithTitle:title])
4150 if (result == pkgPackageManager::Failed) {
4155 if (result != pkgPackageManager::Completed) {
4160 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
4162 if ([self popErrorWithTitle:title forReadList:list])
4164 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
4165 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
4168 if (![before isEqualToArray:after])
4173 return ![delock_ isEqual:GetStatusDate()];
4177 NSString *title(UCLocalize("UPGRADE"));
4178 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
4184 [self updateWithStatus:status_];
4187 - (void) updateWithStatus:(CancelStatus &)status {
4188 NSString *title(UCLocalize("REFRESHING_DATA"));
4191 if ([self popErrorWithTitle:title forReadList:list])
4195 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
4196 if ([self popErrorWithTitle:title])
4199 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4201 bool success(ListUpdate(status, list, PulseInterval_));
4202 if (status.WasCancelled())
4205 [self popErrorWithTitle:title forOperation:success];
4207 [[NSDictionary dictionaryWithObjectsAndKeys:
4208 [NSDate date], @"LastUpdate",
4209 nil] writeToFile:@ CacheState_ atomically:YES];
4212 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4215 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
4216 delegate_ = delegate;
4219 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
4220 progress_ = delegate;
4221 status_.setDelegate(delegate);
4224 - (NSObject<ProgressDelegate> *) progressDelegate {
4228 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
4229 SourceMap::const_iterator i(sourceMap_.find(file->ID));
4230 return i == sourceMap_.end() ? nil : i->second;
4233 - (void) setFetch:(bool)fetch forURI:(const char *)uri {
4234 for (Source *source in (id) sourceList_)
4235 [source setFetch:fetch forURI:uri];
4238 - (void) resetFetch {
4239 for (Source *source in (id) sourceList_)
4240 [source resetFetch];
4243 - (NSString *) mappedSectionForPointer:(const char *)section {
4244 _H<NSString> *mapped;
4246 _profile(Database$mappedSectionForPointer$Cache)
4247 mapped = §ions_[section];
4250 if (*mapped == NULL) {
4251 size_t length(strlen(section));
4252 char spaced[length + 1];
4254 _profile(Database$mappedSectionForPointer$Replace)
4255 for (size_t index(0); index != length; ++index)
4256 spaced[index] = section[index] == '_' ? ' ' : section[index];
4257 spaced[length] = '\0';
4262 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
4263 string = [NSString stringWithUTF8String:spaced];
4266 _profile(Database$mappedSectionForPointer$Map)
4267 string = [SectionMap_ objectForKey:string] ?: string;
4277 static _H<NSMutableSet> Diversions_;
4279 @interface Diversion : NSObject {
4282 _H<NSString> format_;
4287 @implementation Diversion
4289 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
4290 if ((self = [super init]) != nil) {
4291 pattern_ = [from UTF8String];
4297 - (NSString *) divert:(NSString *)url {
4298 return !pattern_(url) ? nil : pattern_->*format_;
4301 + (NSURL *) divertURL:(NSURL *)url {
4303 NSString *href([url absoluteString]);
4305 for (Diversion *diversion in (id) Diversions_)
4306 if (NSString *diverted = [diversion divert:href]) {
4308 NSLog(@"div: %@", diverted);
4310 url = [NSURL URLWithString:diverted];
4317 - (NSString *) key {
4321 - (NSUInteger) hash {
4325 - (BOOL) isEqual:(Diversion *)object {
4326 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
4331 @interface CydiaObject : NSObject {
4332 _H<CyteWebViewController> indirect_;
4333 _transient id delegate_;
4336 - (id) initWithDelegate:(IndirectDelegate *)indirect;
4342 @interface CydiaWebViewController : CyteWebViewController {
4343 _H<CydiaObject> cydia_;
4346 + (void) addDiversion:(Diversion *)diversion;
4347 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request;
4348 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia;
4349 - (void) setDelegate:(id)delegate;
4353 /* Web Scripting {{{ */
4354 @implementation CydiaObject
4356 - (id) initWithDelegate:(IndirectDelegate *)indirect {
4357 if ((self = [super init]) != nil) {
4358 indirect_ = (CyteWebViewController *) indirect;
4362 - (void) setDelegate:(id)delegate {
4363 delegate_ = delegate;
4366 + (NSArray *) _attributeKeys {
4367 return [NSArray arrayWithObjects:
4372 @"coreFoundationVersionNumber",
4388 - (NSArray *) attributeKeys {
4389 return [[self class] _attributeKeys];
4392 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4393 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4396 - (NSString *) version {
4400 - (unsigned) bittage {
4402 #elif defined(__arm64__)
4404 #elif defined(__arm__)
4411 - (NSString *) build {
4415 - (NSString *) coreFoundationVersionNumber {
4416 return [NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber];
4419 - (NSString *) device {
4420 return UniqueIdentifier();
4423 - (NSString *) firmware {
4424 return [[UIDevice currentDevice] systemVersion];
4427 - (NSString *) hostname {
4428 return [[UIDevice currentDevice] name];
4431 - (NSString *) idiom {
4432 return (id) Idiom_ ?: [NSNull null];
4435 - (NSArray *) cells {
4436 auto *$_CTServerConnectionCreate(reinterpret_cast<id (*)(void *, void *, void *)>(dlsym(RTLD_DEFAULT, "_CTServerConnectionCreate")));
4437 if ($_CTServerConnectionCreate == NULL)
4440 struct CTResult { int flag; int error; };
4441 auto *$_CTServerConnectionCellMonitorCopyCellInfo(reinterpret_cast<CTResult (*)(CFTypeRef, void *, CFArrayRef *)>(dlsym(RTLD_DEFAULT, "_CTServerConnectionCellMonitorCopyCellInfo")));
4442 if ($_CTServerConnectionCellMonitorCopyCellInfo == NULL)
4445 _H<const void> connection($_CTServerConnectionCreate(NULL, NULL, NULL), true);
4446 if (connection == nil)
4450 CFArrayRef cells(NULL);
4451 auto result($_CTServerConnectionCellMonitorCopyCellInfo(connection, &count, &cells));
4452 if (result.flag != 0)
4455 return [(NSArray *) cells autorelease];
4458 - (NSString *) mcc {
4459 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode")))
4460 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault) autorelease];
4464 - (NSString *) mnc {
4465 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberNetworkCode")))
4466 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault) autorelease];
4470 - (NSString *) operator {
4471 if (CFStringRef (*$CTRegistrationCopyOperatorName)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTRegistrationCopyOperatorName")))
4472 return [(NSString *) (*$CTRegistrationCopyOperatorName)(kCFAllocatorDefault) autorelease];
4476 - (NSString *) bbsnum {
4477 return (id) BBSNum_ ?: [NSNull null];
4480 - (NSString *) ecid {
4481 return (id) ChipID_ ?: [NSNull null];
4484 - (NSString *) serial {
4485 return SerialNumber_;
4488 - (NSString *) role {
4489 return (id) [NSNull null];
4492 - (NSString *) model {
4493 return [NSString stringWithUTF8String:Machine_];
4496 + (NSString *) webScriptNameForSelector:(SEL)selector {
4498 else if (selector == @selector(addBridgedHost:))
4499 return @"addBridgedHost";
4500 else if (selector == @selector(addInsecureHost:))
4501 return @"addInsecureHost";
4502 else if (selector == @selector(addInternalRedirect::))
4503 return @"addInternalRedirect";
4504 else if (selector == @selector(addPipelinedHost:scheme:))
4505 return @"addPipelinedHost";
4506 else if (selector == @selector(addSource:::))
4507 return @"addSource";
4508 else if (selector == @selector(addTrivialSource:))
4509 return @"addTrivialSource";
4510 else if (selector == @selector(close))
4512 else if (selector == @selector(du:))
4514 else if (selector == @selector(stringWithFormat:arguments:))
4516 else if (selector == @selector(getAllSources))
4517 return @"getAllSources";
4518 else if (selector == @selector(getApplicationInfo:value:))
4519 return @"getApplicationInfoValue";
4520 else if (selector == @selector(getDisplayIdentifiers))
4521 return @"getDisplayIdentifiers";
4522 else if (selector == @selector(getLocalizedNameForDisplayIdentifier:))
4523 return @"getLocalizedNameForDisplayIdentifier";
4524 else if (selector == @selector(getKernelNumber:))
4525 return @"getKernelNumber";
4526 else if (selector == @selector(getKernelString:))
4527 return @"getKernelString";
4528 else if (selector == @selector(getInstalledPackages))
4529 return @"getInstalledPackages";
4530 else if (selector == @selector(getIORegistryEntry::))
4531 return @"getIORegistryEntry";
4532 else if (selector == @selector(getLocaleIdentifier))
4533 return @"getLocaleIdentifier";
4534 else if (selector == @selector(getPreferredLanguages))
4535 return @"getPreferredLanguages";
4536 else if (selector == @selector(getPackageById:))
4537 return @"getPackageById";
4538 else if (selector == @selector(getMetadataKeys))
4539 return @"getMetadataKeys";
4540 else if (selector == @selector(getMetadataValue:))
4541 return @"getMetadataValue";
4542 else if (selector == @selector(getSessionValue:))
4543 return @"getSessionValue";
4544 else if (selector == @selector(installPackages:))
4545 return @"installPackages";
4546 else if (selector == @selector(isReachable:))
4547 return @"isReachable";
4548 else if (selector == @selector(localizedStringForKey:value:table:))
4550 else if (selector == @selector(popViewController:))
4551 return @"popViewController";
4552 else if (selector == @selector(refreshSources))
4553 return @"refreshSources";
4554 else if (selector == @selector(registerFrame:))
4555 return @"registerFrame";
4556 else if (selector == @selector(removeButton))
4557 return @"removeButton";
4558 else if (selector == @selector(saveConfig))
4559 return @"saveConfig";
4560 else if (selector == @selector(setMetadataValue::))
4561 return @"setMetadataValue";
4562 else if (selector == @selector(setSessionValue::))
4563 return @"setSessionValue";
4564 else if (selector == @selector(substitutePackageNames:))
4565 return @"substitutePackageNames";
4566 else if (selector == @selector(scrollToBottom:))
4567 return @"scrollToBottom";
4568 else if (selector == @selector(setAllowsNavigationAction:))
4569 return @"setAllowsNavigationAction";
4570 else if (selector == @selector(setBadgeValue:))
4571 return @"setBadgeValue";
4572 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4573 return @"setButtonImage";
4574 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4575 return @"setButtonTitle";
4576 else if (selector == @selector(setHidesBackButton:))
4577 return @"setHidesBackButton";
4578 else if (selector == @selector(setHidesNavigationBar:))
4579 return @"setHidesNavigationBar";
4580 else if (selector == @selector(setNavigationBarStyle:))
4581 return @"setNavigationBarStyle";
4582 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4583 return @"setNavigationBarTintColor";
4584 else if (selector == @selector(setPasteboardString:))
4585 return @"setPasteboardString";
4586 else if (selector == @selector(setPasteboardURL:))
4587 return @"setPasteboardURL";
4588 else if (selector == @selector(setScrollAlwaysBounceVertical:))
4589 return @"setScrollAlwaysBounceVertical";
4590 else if (selector == @selector(setScrollIndicatorStyle:))
4591 return @"setScrollIndicatorStyle";
4592 else if (selector == @selector(setToken:))
4594 else if (selector == @selector(setViewportWidth:))
4595 return @"setViewportWidth";
4596 else if (selector == @selector(statfs:))
4598 else if (selector == @selector(supports:))
4600 else if (selector == @selector(unload))
4606 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4607 return [self webScriptNameForSelector:selector] == nil;
4610 - (BOOL) supports:(NSString *)feature {
4611 return [feature isEqualToString:@"window.open"];
4615 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4618 - (void) setScrollAlwaysBounceVertical:(NSNumber *)value {
4619 [indirect_ performSelectorOnMainThread:@selector(setScrollAlwaysBounceVerticalNumber:) withObject:value waitUntilDone:NO];
4622 - (void) setScrollIndicatorStyle:(NSString *)style {
4623 [indirect_ performSelectorOnMainThread:@selector(setScrollIndicatorStyleWithName:) withObject:style waitUntilDone:NO];
4626 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4627 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4630 - (NSDictionary *) getApplicationInfo:(NSString *)display value:(NSString *)key {
4632 if (SBBundlePathForDisplayIdentifier(SBSSpringBoardServerPort(), [display UTF8String], path) != 0)
4633 return (id) [NSNull null];
4634 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:[[NSString stringWithUTF8String:path] stringByAppendingString:@"/Info.plist"]]);
4636 return (id) [NSNull null];
4637 return [info objectForKey:key];
4640 - (NSArray *) getDisplayIdentifiers {
4641 return SBSCopyApplicationDisplayIdentifiers(false, false);
4644 - (NSString *) getLocalizedNameForDisplayIdentifier:(NSString *)identifier {
4645 return [SBSCopyLocalizedApplicationNameForDisplayIdentifier(identifier) autorelease] ?: (id) [NSNull null];
4648 - (NSNumber *) getKernelNumber:(NSString *)name {
4649 const char *string([name UTF8String]);
4652 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4653 return (id) [NSNull null];
4655 if (size != sizeof(int))
4656 return (id) [NSNull null];
4659 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4660 return (id) [NSNull null];
4662 return [NSNumber numberWithInt:value];
4665 - (NSString *) getKernelString:(NSString *)name {
4666 const char *string([name UTF8String]);
4669 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4670 return (id) [NSNull null];
4672 char value[size + 1];
4673 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4674 return (id) [NSNull null];
4676 // XXX: just in case you request something ludicrous
4679 return [NSString stringWithCString:value];
4682 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4683 NSObject *value(CYIOGetValue([path UTF8String], entry));
4686 if ([value isKindOfClass:[NSData class]])
4687 value = CYHex((NSData *) value);
4692 - (NSArray *) getMetadataKeys {
4693 @synchronized (Values_) {
4694 return [Values_ allKeys];
4697 - (void) registerFrame:(DOMHTMLIFrameElement *)iframe {
4698 WebFrame *frame([iframe contentFrame]);
4699 [indirect_ registerFrame:frame];
4702 - (id) getMetadataValue:(NSString *)key {
4703 @synchronized (Values_) {
4704 return [Values_ objectForKey:key];
4707 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4708 @synchronized (Values_) {
4709 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4710 [Values_ removeObjectForKey:key];
4712 [Values_ setObject:value forKey:key];
4715 - (id) getSessionValue:(NSString *)key {
4716 @synchronized (SessionData_) {
4717 return [SessionData_ objectForKey:key];
4720 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4721 @synchronized (SessionData_) {
4722 if (value == (id) [WebUndefined undefined])
4723 [SessionData_ removeObjectForKey:key];
4725 [SessionData_ setObject:value forKey:key];
4728 - (void) addBridgedHost:(NSString *)host {
4729 @synchronized (HostConfig_) {
4730 [BridgedHosts_ addObject:host];
4733 - (void) addInsecureHost:(NSString *)host {
4734 @synchronized (HostConfig_) {
4735 [InsecureHosts_ addObject:host];
4738 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4739 @synchronized (HostConfig_) {
4740 if (scheme != (id) [WebUndefined undefined])
4741 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4743 [PipelinedHosts_ addObject:host];
4746 - (void) popViewController:(NSNumber *)value {
4747 if (value == (id) [WebUndefined undefined])
4748 value = [NSNumber numberWithBool:YES];
4749 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4752 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4753 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4755 for (NSString *section in sections)
4756 [array addObject:section];
4758 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4761 distribution, @"Distribution",
4763 nil] waitUntilDone:NO];
4766 - (BOOL) addTrivialSource:(NSString *)href {
4767 href = VerifySource(href);
4770 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4774 - (void) refreshSources {
4775 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4778 - (void) saveConfig {
4779 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4782 - (NSArray *) getAllSources {
4783 return [[Database sharedInstance] sources];
4786 - (NSArray *) getInstalledPackages {
4787 Database *database([Database sharedInstance]);
4788 @synchronized (database) {
4789 NSArray *packages([database packages]);
4790 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4791 for (Package *package in packages)
4792 if (![package uninstalled])
4793 [installed addObject:package];
4797 - (Package *) getPackageById:(NSString *)id {
4798 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4802 return (Package *) [NSNull null];
4805 - (NSString *) getLocaleIdentifier {
4806 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4809 - (NSArray *) getPreferredLanguages {
4813 - (NSArray *) statfs:(NSString *)path {
4816 if (path == nil || statfs([path UTF8String], &stat) == -1)
4819 return [NSArray arrayWithObjects:
4820 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4821 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4822 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4826 - (NSNumber *) du:(NSString *)path {
4827 NSNumber *value(nil);
4829 FILE *du(popen([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /usr/libexec/cydia/du -ks %@", ShellEscape(path)] UTF8String], "r"));
4832 while (fgets(line, sizeof(line), du) != NULL) {
4833 size_t length(strlen(line));
4834 while (length != 0 && line[length - 1] == '\n')
4835 line[--length] = '\0';
4836 if (char *tab = strchr(line, '\t')) {
4838 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4848 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4851 - (NSNumber *) isReachable:(NSString *)name {
4852 return [NSNumber numberWithBool:IsReachable([name UTF8String])];
4855 - (void) installPackages:(NSArray *)packages {
4856 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4859 - (NSString *) substitutePackageNames:(NSString *)message {
4860 NSMutableArray *words([[[message componentsSeparatedByString:@" "] mutableCopy] autorelease]);
4861 for (size_t i(0), e([words count]); i != e; ++i) {
4862 NSString *word([words objectAtIndex:i]);
4863 if (Package *package = [[Database sharedInstance] packageWithName:word])
4864 [words replaceObjectAtIndex:i withObject:[package name]];
4867 return [words componentsJoinedByString:@" "];
4870 - (void) removeButton {
4871 [indirect_ removeButton];
4874 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4875 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4878 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4879 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4882 - (void) setBadgeValue:(id)value {
4883 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4886 - (void) setAllowsNavigationAction:(NSString *)value {
4887 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4890 - (void) setHidesBackButton:(NSString *)value {
4891 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4894 - (void) setHidesNavigationBar:(NSString *)value {
4895 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4898 - (void) setNavigationBarStyle:(NSString *)value {
4899 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4902 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4903 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4904 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4905 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4908 - (void) setPasteboardString:(NSString *)value {
4909 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4912 - (void) setPasteboardURL:(NSString *)value {
4913 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4916 - (void) setToken:(NSString *)token {
4917 // XXX: the website expects this :/
4920 - (void) scrollToBottom:(NSNumber *)animated {
4921 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4924 - (void) setViewportWidth:(float)width {
4925 [indirect_ setViewportWidthOnMainThread:width];
4928 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4929 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4930 unsigned count([arguments count]);
4932 for (unsigned i(0); i != count; ++i)
4933 values[i] = [arguments objectAtIndex:i];
4934 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4937 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4938 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4940 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4942 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4948 @interface NSURL (CydiaSecure)
4951 @implementation NSURL (CydiaSecure)
4953 - (bool) isCydiaSecure {
4954 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4957 @synchronized (HostConfig_) {
4958 if ([InsecureHosts_ containsObject:[self host]])
4967 /* Cydia Browser Controller {{{ */
4968 @implementation CydiaWebViewController
4970 - (NSURL *) navigationURL {
4971 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4974 + (void) _initialize {
4975 [super _initialize];
4977 Diversions_ = [NSMutableSet setWithCapacity:0];
4980 + (void) addDiversion:(Diversion *)diversion {
4981 [Diversions_ addObject:diversion];
4984 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4985 [super webView:view didClearWindowObject:window forFrame:frame];
4986 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
4989 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia {
4990 WebDataSource *source([frame dataSource]);
4991 NSURLResponse *response([source response]);
4992 NSURL *url([response URL]);
4993 NSString *scheme([[url scheme] lowercaseString]);
4995 bool bridged(false);
4997 @synchronized (HostConfig_) {
4998 if ([scheme isEqualToString:@"file"])
5000 else if ([scheme isEqualToString:@"https"])
5001 if ([BridgedHosts_ containsObject:[url host]])
5006 [window setValue:cydia forKey:@"cydia"];
5009 - (void) _setupMail:(MFMailComposeViewController *)controller {
5010 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
5012 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
5013 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
5016 - (NSURL *) URLWithURL:(NSURL *)url {
5017 return [Diversion divertURL:url];
5020 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
5021 return [CydiaWebViewController requestWithHeaders:[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
5024 - (NSURLRequest *) webThreadWebView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
5025 return [CydiaWebViewController requestWithHeaders:[super webThreadWebView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
5028 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request {
5029 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
5031 NSURL *url([copy URL]);
5032 NSString *href([url absoluteString]);
5033 NSString *host([url host]);
5035 if ([href hasPrefix:@"https://cydia.saurik.com/TSS/"]) {
5036 if (NSString *agent = [copy valueForHTTPHeaderField:@"X-User-Agent"]) {
5037 [copy setValue:agent forHTTPHeaderField:@"User-Agent"];
5038 [copy setValue:nil forHTTPHeaderField:@"X-User-Agent"];
5041 [copy setValue:nil forHTTPHeaderField:@"Referer"];
5042 [copy setValue:nil forHTTPHeaderField:@"Origin"];
5044 [copy setURL:[NSURL URLWithString:[@"http://gs.apple.com/TSS/" stringByAppendingString:[href substringFromIndex:29]]]];
5048 if ([copy valueForHTTPHeaderField:@"X-Cydia-Cf"] == nil)
5049 [copy setValue:[NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber] forHTTPHeaderField:@"X-Cydia-Cf"];
5050 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
5051 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
5053 bool bridged; @synchronized (HostConfig_) {
5054 bridged = [BridgedHosts_ containsObject:host];
5057 if ([url isCydiaSecure] && bridged && UniqueID_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Id"] == nil)
5058 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
5063 - (void) setDelegate:(id)delegate {
5064 [super setDelegate:delegate];
5065 [cydia_ setDelegate:delegate];
5068 - (NSString *) applicationNameForUserAgent {
5073 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
5074 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
5080 @interface AppCacheController : CydiaWebViewController {
5085 @implementation AppCacheController
5087 - (void) didReceiveMemoryWarning {
5088 // XXX: this doesn't work
5091 - (bool) retainsNetworkActivityIndicator {
5099 @interface NSObject (CydiaScript)
5100 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
5103 @implementation NSObject (CydiaScript)
5105 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5111 @implementation NSArray (CydiaScript)
5113 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5114 WebScriptObject *object([context evaluateWebScript:@"[]"]);
5115 for (size_t i(0), e([self count]); i != e; ++i)
5116 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
5122 @implementation NSDictionary (CydiaScript)
5124 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5125 WebScriptObject *object([context evaluateWebScript:@"({})"]);
5127 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
5134 /* Confirmation Controller {{{ */
5135 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
5136 if (!iterator.end())
5137 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
5138 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
5140 pkgCache::PkgIterator package(dep.TargetPkg());
5143 if (strcmp(package.Name(), "mobilesubstrate") == 0)
5150 @protocol ConfirmationControllerDelegate
5151 - (void) cancelAndClear:(bool)clear;
5152 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
5156 @interface ConfirmationController : CydiaWebViewController {
5157 _transient Database *database_;
5159 _H<UIAlertView> essential_;
5161 _H<NSDictionary> changes_;
5162 _H<NSMutableArray> issues_;
5163 _H<NSDictionary> sizes_;
5168 - (id) initWithDatabase:(Database *)database;
5172 @implementation ConfirmationController
5176 RestartSubstrate_ = true;
5177 [delegate_ confirmWithNavigationController:[self navigationController]];
5180 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
5181 NSString *context([alert context]);
5183 if ([context isEqualToString:@"remove"]) {
5184 if (button == [alert cancelButtonIndex])
5186 else if (button == [alert firstOtherButtonIndex]) {
5187 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
5190 [alert dismissWithClickedButtonIndex:-1 animated:YES];
5191 } else if ([context isEqualToString:@"unable"]) {
5192 [self dismissModalViewControllerAnimated:YES];
5193 [alert dismissWithClickedButtonIndex:-1 animated:YES];
5195 [super alertView:alert clickedButtonAtIndex:button];
5199 - (void) _doContinue {
5200 [delegate_ cancelAndClear:NO];
5201 [self dismissModalViewControllerAnimated:YES];
5204 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
5205 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
5209 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5210 [super webView:view didClearWindowObject:window forFrame:frame];
5212 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
5213 (id) changes_, @"changes",
5214 (id) issues_, @"issues",
5215 (id) sizes_, @"sizes",
5217 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
5220 - (id) initWithDatabase:(Database *)database {
5221 if ((self = [super init]) != nil) {
5222 database_ = database;
5224 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
5225 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
5226 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
5227 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
5228 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
5232 pkgCacheFile &cache([database_ cache]);
5233 NSArray *packages([database_ packages]);
5234 pkgDepCache::Policy *policy([database_ policy]);
5236 issues_ = [NSMutableArray arrayWithCapacity:4];
5238 for (Package *package in packages) {
5239 pkgCache::PkgIterator iterator([package iterator]);
5240 NSString *name([package id]);
5242 if ([package broken]) {
5243 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
5245 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5247 reasons, @"reasons",
5250 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
5254 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
5255 pkgCache::DepIterator start;
5256 pkgCache::DepIterator end;
5257 dep.GlobOr(start, end); // ++dep
5259 if (!cache->IsImportantDep(end))
5261 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
5264 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
5266 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5267 [NSString stringWithUTF8String:start.DepType()], @"relationship",
5268 clauses, @"clauses",
5272 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
5274 pkgCache::PkgIterator target(start.TargetPkg());
5275 if (target->ProvidesList != 0)
5276 reason = @"missing";
5278 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
5280 reason = @"installed";
5281 installed = [NSString stringWithUTF8String:ver.VerStr()];
5282 } else if (!cache[target].CandidateVerIter(cache).end())
5283 reason = @"uninstalled";
5284 else if (target->ProvidesList == 0)
5285 reason = @"uninstallable";
5287 reason = @"virtual";
5290 NSDictionary *version(start.TargetVer() == 0 ? (NSDictionary *) [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
5291 [NSString stringWithUTF8String:start.CompType()], @"operator",
5292 [NSString stringWithUTF8String:start.TargetVer()], @"value",
5295 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5296 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
5297 version, @"version",
5299 installed, @"installed",
5302 // yes, seriously. (wtf?)
5310 pkgDepCache::StateCache &state(cache[iterator]);
5312 static RegEx special_r("(firmware|gsc\\..*|cy\\+.*)");
5314 if (state.NewInstall())
5315 [installs addObject:name];
5316 // XXX: else if (state.Install())
5317 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
5318 [reinstalls addObject:name];
5319 // XXX: move before previous if
5320 else if (state.Upgrade())
5321 [upgrades addObject:name];
5322 else if (state.Downgrade())
5323 [downgrades addObject:name];
5324 else if (!state.Delete())
5325 // XXX: _assert(state.Keep());
5327 else if (special_r(name))
5328 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5329 [NSNull null], @"package",
5330 [NSArray arrayWithObjects:
5331 [NSDictionary dictionaryWithObjectsAndKeys:
5332 @"Conflicts", @"relationship",
5333 [NSArray arrayWithObjects:
5334 [NSDictionary dictionaryWithObjectsAndKeys:
5336 [NSNull null], @"version",
5337 @"installed", @"reason",
5344 if ([package essential])
5346 [removes addObject:name];
5349 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
5350 substrate_ |= DepSubstrate(iterator.CurrentVer());
5355 else if (Advanced_) {
5356 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
5358 essential_ = [[[UIAlertView alloc]
5359 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
5360 message:UCLocalize("REMOVING_ESSENTIALS_EX")
5362 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
5364 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
5368 [essential_ setContext:@"remove"];
5369 [essential_ setNumberOfRows:2];
5371 essential_ = [[[UIAlertView alloc]
5372 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
5373 message:UCLocalize("UNABLE_TO_COMPLY_EX")
5375 cancelButtonTitle:UCLocalize("OKAY")
5376 otherButtonTitles:nil
5379 [essential_ setContext:@"unable"];
5382 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5383 installs, @"installs",
5384 reinstalls, @"reinstalls",
5385 upgrades, @"upgrades",
5386 downgrades, @"downgrades",
5387 removes, @"removes",
5390 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5391 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
5392 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
5395 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
5399 - (UIBarButtonItem *) leftButton {
5400 return [[[UIBarButtonItem alloc]
5401 initWithTitle:UCLocalize("CANCEL")
5402 style:UIBarButtonItemStylePlain
5404 action:@selector(cancelButtonClicked)
5409 - (void) applyRightButton {
5410 if ([issues_ count] == 0 && ![self isLoading])
5411 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
5412 initWithTitle:UCLocalize("CONFIRM")
5413 style:UIBarButtonItemStyleDone
5415 action:@selector(confirmButtonClicked)
5418 [[self navigationItem] setRightBarButtonItem:nil];
5422 - (void) cancelButtonClicked {
5423 [delegate_ cancelAndClear:YES];
5424 [self dismissModalViewControllerAnimated:YES];
5428 - (void) confirmButtonClicked {
5429 if (essential_ != nil)
5439 /* Progress Data {{{ */
5440 @interface CydiaProgressData : NSObject {
5441 _transient id delegate_;
5450 _H<NSMutableArray> events_;
5451 _H<NSString> title_;
5453 _H<NSString> status_;
5454 _H<NSString> finish_;
5459 @implementation CydiaProgressData
5461 + (NSArray *) _attributeKeys {
5462 return [NSArray arrayWithObjects:
5474 - (NSArray *) attributeKeys {
5475 return [[self class] _attributeKeys];
5478 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5479 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5483 if ((self = [super init]) != nil) {
5484 events_ = [NSMutableArray arrayWithCapacity:32];
5492 - (void) setDelegate:(id)delegate {
5493 delegate_ = delegate;
5496 - (void) setPercent:(float)value {
5500 - (NSNumber *) percent {
5501 return [NSNumber numberWithFloat:percent_];
5504 - (void) setCurrent:(float)value {
5508 - (NSNumber *) current {
5509 return [NSNumber numberWithFloat:current_];
5512 - (void) setTotal:(float)value {
5516 - (NSNumber *) total {
5517 return [NSNumber numberWithFloat:total_];
5520 - (void) setSpeed:(float)value {
5524 - (NSNumber *) speed {
5525 return [NSNumber numberWithFloat:speed_];
5528 - (NSArray *) events {
5532 - (void) removeAllEvents {
5533 [events_ removeAllObjects];
5536 - (void) addEvent:(CydiaProgressEvent *)event {
5537 [events_ addObject:event];
5540 - (void) setTitle:(NSString *)text {
5544 - (NSString *) title {
5548 - (void) setFinish:(NSString *)text {
5552 - (NSString *) finish {
5553 return (id) finish_ ?: [NSNull null];
5556 - (void) setRunning:(bool)running {
5560 - (NSNumber *) running {
5561 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5566 /* Progress Controller {{{ */
5567 @interface ProgressController : CydiaWebViewController <
5570 _transient Database *database_;
5571 _H<CydiaProgressData, 1> progress_;
5575 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5577 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5579 - (void) setTitle:(NSString *)title;
5580 - (void) setCancellable:(bool)cancellable;
5584 @implementation ProgressController
5587 [database_ setProgressDelegate:nil];
5591 - (UIBarButtonItem *) leftButton {
5592 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5593 initWithTitle:UCLocalize("CANCEL")
5594 style:UIBarButtonItemStylePlain
5596 action:@selector(cancel)
5597 ] autorelease] : nil;
5600 - (void) updateCancel {
5601 [super applyLeftButton];
5604 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5605 if ((self = [super init]) != nil) {
5606 database_ = database;
5607 delegate_ = delegate;
5609 [database_ setProgressDelegate:self];
5611 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5612 [progress_ setDelegate:self];
5614 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5616 [scroller_ setBackgroundColor:[UIColor blackColor]];
5618 [[self navigationItem] setHidesBackButton:YES];
5620 [self updateCancel];
5624 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5625 [super webView:view didClearWindowObject:window forFrame:frame];
5626 [window setValue:progress_ forKey:@"cydiaProgress"];
5629 - (void) updateProgress {
5630 [self dispatchEvent:@"CydiaProgressUpdate"];
5633 - (void) viewWillAppear:(BOOL)animated {
5634 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5635 [super viewWillAppear:animated];
5639 UpdateExternalStatus(0);
5642 [delegate_ saveState];
5646 [delegate_ returnToCydia];
5650 [delegate_ terminateWithSuccess];
5651 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5652 [delegate_ suspendWithAnimation:YES];
5654 [delegate_ suspend];*/
5666 UIProgressHUD *hud([delegate_ addProgressHUD]);
5667 [hud setText:UCLocalize("LOADING")];
5668 [delegate_ performSelector:@selector(reloadSpringBoard) withObject:nil afterDelay:0.5];
5674 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5675 SBReboot(SBSSpringBoardServerPort());
5677 reboot2(RB_AUTOBOOT);
5684 - (void) setTitle:(NSString *)title {
5685 [progress_ setTitle:title];
5686 [self updateProgress];
5689 - (UIBarButtonItem *) rightButton {
5690 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5691 initWithTitle:UCLocalize("CLOSE")
5692 style:UIBarButtonItemStylePlain
5694 action:@selector(close)
5698 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5699 UpdateExternalStatus(1);
5701 [progress_ setRunning:true];
5702 [self setTitle:title];
5703 // implicit updateProgress
5705 SHA1SumValue notifyconf; {
5707 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5710 MMap mmap(file, MMap::ReadOnly);
5712 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5713 notifyconf = sha1.Result();
5717 SHA1SumValue springlist; {
5719 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5722 MMap mmap(file, MMap::ReadOnly);
5724 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5725 springlist = sha1.Result();
5729 if (invocation != nil) {
5730 [invocation yieldToSelector:@selector(invoke)];
5731 [self setTitle:@"COMPLETE"];
5736 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5739 MMap mmap(file, MMap::ReadOnly);
5741 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5742 if (!(notifyconf == sha1.Result()))
5749 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5752 MMap mmap(file, MMap::ReadOnly);
5754 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5755 if (!(springlist == sha1.Result()))
5761 if (RestartSubstrate_)
5765 RestartSubstrate_ = false;
5768 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5769 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5770 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5771 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5772 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5775 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5777 [progress_ setRunning:false];
5778 [self updateProgress];
5780 [self applyRightButton];
5783 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5784 [progress_ addEvent:event];
5785 [self updateProgress];
5788 - (bool) isProgressCancelled {
5789 return cancel_ == 2;
5794 [self updateCancel];
5797 - (void) setCancellable:(bool)cancellable {
5798 unsigned cancel(cancel_);
5802 else if (cancel_ == 0)
5805 if (cancel != cancel_)
5806 [self updateCancel];
5809 - (void) setProgressCancellable:(NSNumber *)cancellable {
5810 [self setCancellable:[cancellable boolValue]];
5813 - (void) setProgressPercent:(NSNumber *)percent {
5814 [progress_ setPercent:[percent floatValue]];
5815 [self updateProgress];
5818 - (void) setProgressStatus:(NSDictionary *)status {
5819 if (status == nil) {
5820 [progress_ setCurrent:0];
5821 [progress_ setTotal:0];
5822 [progress_ setSpeed:0];
5824 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5826 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5827 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5828 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5831 [self updateProgress];
5837 /* Package Cell {{{ */
5838 @interface PackageCell : CyteTableViewCell <
5839 CyteTableViewCellDelegate
5843 _H<NSString> description_;
5845 _H<NSString> source_;
5847 _H<UIImage> placard_;
5851 - (PackageCell *) init;
5852 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5854 - (void) drawContentRect:(CGRect)rect;
5858 @implementation PackageCell
5860 - (PackageCell *) init {
5861 CGRect frame(CGRectMake(0, 0, 320, 74));
5862 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5863 UIView *content([self contentView]);
5864 CGRect bounds([content bounds]);
5866 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5867 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5868 [content addSubview:content_];
5870 [content_ setDelegate:self];
5871 [content_ setOpaque:YES];
5875 - (NSString *) accessibilityLabel {
5879 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5880 summarized_ = summary;
5890 [content_ setBackgroundColor:[UIColor whiteColor]];
5894 Source *source = [package source];
5896 icon_ = [package icon];
5898 if (NSString *name = [package name])
5899 name_ = [NSString stringWithString:name];
5901 if (NSString *description = [package shortDescription])
5902 description_ = [NSString stringWithString:description];
5904 commercial_ = [package isCommercial];
5906 NSString *label = nil;
5907 bool trusted = false;
5909 if (source != nil) {
5910 label = [source label];
5911 trusted = [source trusted];
5912 } else if ([[package id] isEqualToString:@"firmware"])
5913 label = UCLocalize("APPLE");
5915 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5917 NSString *from(label);
5919 NSString *section = [package simpleSection];
5920 if (section != nil && ![section isEqualToString:label]) {
5921 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5922 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5925 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5927 if (NSString *purpose = [package primaryPurpose])
5928 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5933 if (NSString *mode = [package mode]) {
5934 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5935 color = RemovingColor_;
5936 placard = @"removing";
5938 color = InstallingColor_;
5939 placard = @"installing";
5942 color = [UIColor whiteColor];
5944 if ([package installed] != nil)
5945 placard = @"installed";
5950 [content_ setBackgroundColor:color];
5953 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5956 [self setNeedsDisplay];
5957 [content_ setNeedsDisplay];
5960 - (void) drawSummaryContentRect:(CGRect)rect {
5961 bool highlighted(highlighted_);
5962 float width([self bounds].size.width);
5966 rect.size = [(UIImage *) icon_ size];
5968 while (rect.size.width > 16 || rect.size.height > 16) {
5969 rect.size.width /= 2;
5970 rect.size.height /= 2;
5973 rect.origin.x = 19 - rect.size.width / 2;
5974 rect.origin.y = 19 - rect.size.height / 2;
5976 [icon_ drawInRect:Retina(rect)];
5979 if (badge_ != nil) {
5981 rect.size = [(UIImage *) badge_ size];
5983 rect.size.width /= 4;
5984 rect.size.height /= 4;
5986 rect.origin.x = 25 - rect.size.width / 2;
5987 rect.origin.y = 25 - rect.size.height / 2;
5989 [badge_ drawInRect:Retina(rect)];
5992 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5996 UISetColor(commercial_ ? Purple_ : Black_);
5997 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
5999 if (placard_ != nil)
6000 [placard_ drawAtPoint:CGPointMake(width - 52, 11)];
6003 - (void) drawNormalContentRect:(CGRect)rect {
6004 bool highlighted(highlighted_);
6005 float width([self bounds].size.width);
6009 rect.size = [(UIImage *) icon_ size];
6011 while (rect.size.width > 32 || rect.size.height > 32) {
6012 rect.size.width /= 2;
6013 rect.size.height /= 2;
6016 rect.origin.x = 25 - rect.size.width / 2;
6017 rect.origin.y = 25 - rect.size.height / 2;
6019 [icon_ drawInRect:Retina(rect)];
6022 if (badge_ != nil) {
6024 rect.size = [(UIImage *) badge_ size];
6026 rect.size.width /= 2;
6027 rect.size.height /= 2;
6029 rect.origin.x = 36 - rect.size.width / 2;
6030 rect.origin.y = 36 - rect.size.height / 2;
6032 [badge_ drawInRect:Retina(rect)];
6035 if (highlighted && kCFCoreFoundationVersionNumber < 800)
6039 UISetColor(commercial_ ? Purple_ : Black_);
6040 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
6041 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
6044 UISetColor(commercial_ ? Purplish_ : Gray_);
6045 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:NSLineBreakByTruncatingTail];
6047 if (placard_ != nil)
6048 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
6051 - (void) drawContentRect:(CGRect)rect {
6053 [self drawSummaryContentRect:rect];
6055 [self drawNormalContentRect:rect];
6060 /* Section Cell {{{ */
6061 @interface SectionCell : CyteTableViewCell <
6062 CyteTableViewCellDelegate
6064 _H<NSString> basic_;
6065 _H<NSString> section_;
6067 _H<NSString> count_;
6069 _H<UISwitch> switch_;
6073 - (void) setSection:(Section *)section editing:(BOOL)editing;
6077 @implementation SectionCell
6079 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
6080 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
6081 icon_ = [UIImage imageNamed:@"folder.png"];
6082 // XXX: this initial frame is wrong, but is fixed later
6083 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
6084 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
6086 UIView *content([self contentView]);
6087 CGRect bounds([content bounds]);
6089 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
6090 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6091 [content addSubview:content_];
6092 [content_ setBackgroundColor:[UIColor whiteColor]];
6094 [content_ setDelegate:self];
6098 - (void) onSwitch:(id)sender {
6099 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
6100 if (metadata == nil) {
6101 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
6102 [Sections_ setObject:metadata forKey:basic_];
6105 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
6108 - (void) setSection:(Section *)section editing:(BOOL)editing {
6109 if (editing != editing_) {
6111 [switch_ removeFromSuperview];
6113 [self addSubview:switch_];
6122 if (section == nil) {
6123 name_ = UCLocalize("ALL_PACKAGES");
6126 basic_ = [section name];
6127 section_ = [section localized];
6129 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
6130 count_ = [NSString stringWithFormat:@"%zd", [section count]];
6133 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
6136 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
6137 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
6139 [content_ setNeedsDisplay];
6142 - (void) setFrame:(CGRect)frame {
6143 [super setFrame:frame];
6145 CGRect rect([switch_ frame]);
6146 [switch_ setFrame:CGRectMake(frame.size.width - rect.size.width - 9, 9, rect.size.width, rect.size.height)];
6149 - (NSString *) accessibilityLabel {
6153 - (void) drawContentRect:(CGRect)rect {
6154 bool highlighted(highlighted_ && !editing_);
6156 [icon_ drawInRect:CGRectMake(7, 7, 32, 32)];
6158 if (highlighted && kCFCoreFoundationVersionNumber < 800)
6161 float width(rect.size.width);
6163 width -= 9 + [switch_ frame].size.width;
6167 [name_ drawAtPoint:CGPointMake(48, 12) forWidth:(width - 58) withFont:Font18_ lineBreakMode:NSLineBreakByTruncatingTail];
6169 CGSize size = [count_ sizeWithFont:Font14_];
6171 UISetColor(Folder_);
6173 [count_ drawAtPoint:CGPointMake(Retina(10 + (30 - size.width) / 2), 18) withFont:Font12Bold_];
6179 /* File Table {{{ */
6180 @interface FileTable : CyteViewController <
6181 UITableViewDataSource,
6184 _transient Database *database_;
6185 _H<Package> package_;
6187 _H<NSMutableArray> files_;
6188 _H<UITableView, 2> list_;
6191 - (id) initWithDatabase:(Database *)database;
6192 - (void) setPackage:(Package *)package;
6196 @implementation FileTable
6198 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6199 return files_ == nil ? 0 : [files_ count];
6202 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6206 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6207 static NSString *reuseIdentifier = @"Cell";
6209 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6211 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6212 [cell setFont:[UIFont systemFontOfSize:16]];
6214 [cell setText:[files_ objectAtIndex:indexPath.row]];
6215 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
6220 - (NSURL *) navigationURL {
6221 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
6225 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
6226 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6227 [list_ setRowHeight:24.0f];
6228 [(UITableView *) list_ setDataSource:self];
6229 [list_ setDelegate:self];
6230 [self setView:list_];
6233 - (void) viewDidLoad {
6234 [super viewDidLoad];
6236 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
6239 - (void) releaseSubviews {
6245 [super releaseSubviews];
6248 - (id) initWithDatabase:(Database *)database {
6249 if ((self = [super init]) != nil) {
6250 database_ = database;
6254 - (void) setPackage:(Package *)package {
6258 files_ = [NSMutableArray arrayWithCapacity:32];
6260 if (package != nil) {
6262 name_ = [package id];
6264 if (NSArray *files = [package files])
6265 [files_ addObjectsFromArray:files];
6267 if ([files_ count] != 0) {
6268 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
6269 [files_ removeObjectAtIndex:0];
6270 [files_ sortUsingSelector:@selector(compareByPath:)];
6272 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
6273 [stack addObject:@"/"];
6275 for (int i(0), e([files_ count]); i != e; ++i) {
6276 NSString *file = [files_ objectAtIndex:i];
6277 while (![file hasPrefix:[stack lastObject]])
6278 [stack removeLastObject];
6279 NSString *directory = [stack lastObject];
6280 [stack addObject:[file stringByAppendingString:@"/"]];
6281 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
6282 int(([stack count] - 2) * 3), "",
6283 [file substringFromIndex:[directory length]]
6292 - (void) reloadData {
6295 [self setPackage:[database_ packageWithName:name_]];
6300 /* Package Controller {{{ */
6301 @interface CYPackageController : CydiaWebViewController <
6302 UIActionSheetDelegate
6304 _transient Database *database_;
6305 _H<Package> package_;
6308 std::vector<std::pair<_H<NSString>, _H<NSString>>> buttons_;
6309 _H<UIActionSheet> sheet_;
6310 _H<UIBarButtonItem> button_;
6311 _H<NSArray> versions_;
6314 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer;
6318 @implementation CYPackageController
6320 - (NSURL *) navigationURL {
6321 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
6324 - (void) _clickButtonWithPackage:(Package *)package {
6325 [delegate_ installPackage:package];
6328 - (void) _clickButtonWithName:(NSString *)name {
6329 if ([name isEqualToString:@"CLEAR"])
6330 return [delegate_ clearPackage:package_];
6331 else if ([name isEqualToString:@"REMOVE"])
6332 return [delegate_ removePackage:package_];
6333 else if ([name isEqualToString:@"DOWNGRADE"]) {
6334 sheet_ = [[[UIActionSheet alloc]
6337 cancelButtonTitle:nil
6338 destructiveButtonTitle:nil
6339 otherButtonTitles:nil
6342 for (Package *version in (id) versions_)
6343 [sheet_ addButtonWithTitle:[version latest]];
6344 [sheet_ setContext:@"version"];
6346 [delegate_ showActionSheet:sheet_ fromItem:[[self navigationItem] rightBarButtonItem]];
6350 else if ([name isEqualToString:@"INSTALL"]);
6351 else if ([name isEqualToString:@"REINSTALL"]);
6352 else if ([name isEqualToString:@"UPGRADE"]);
6353 else _assert(false);
6355 [delegate_ installPackage:package_];
6358 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
6359 NSString *context([sheet context]);
6360 if (sheet_ == sheet)
6363 if ([context isEqualToString:@"modify"]) {
6364 if (button != [sheet cancelButtonIndex]) {
6366 [self performSelector:@selector(_clickButtonWithName:) withObject:buttons_[button].first afterDelay:0];
6368 [self _clickButtonWithName:buttons_[button].first];
6371 [sheet dismissWithClickedButtonIndex:button animated:YES];
6372 } else if ([context isEqualToString:@"version"]) {
6373 if (button != [sheet cancelButtonIndex]) {
6374 Package *version([versions_ objectAtIndex:button]);
6376 [self performSelector:@selector(_clickButtonWithPackage:) withObject:version afterDelay:0];
6378 [self _clickButtonWithPackage:version];
6381 [sheet dismissWithClickedButtonIndex:button animated:YES];
6385 - (bool) _allowJavaScriptPanel {
6390 - (void) _customButtonClicked {
6391 size_t count(buttons_.size());
6396 [self _clickButtonWithName:buttons_[0].first];
6398 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
6399 for (const auto &button : buttons_)
6400 [buttons addObject:button.second];
6402 sheet_ = [[[UIActionSheet alloc]
6405 cancelButtonTitle:nil
6406 destructiveButtonTitle:nil
6407 otherButtonTitles:nil
6410 for (NSString *button in buttons)
6411 [sheet_ addButtonWithTitle:button];
6412 [sheet_ setContext:@"modify"];
6414 [delegate_ showActionSheet:sheet_ fromItem:[[self navigationItem] rightBarButtonItem]];
6418 - (void) reloadButtonClicked {
6419 if (commercial_ && function_ == nil && [package_ uninstalled])
6421 [self customButtonClicked];
6424 - (void) applyLoadingTitle {
6425 // Don't show "Loading" as the title. Ever.
6428 - (UIBarButtonItem *) rightButton {
6433 - (void) setPageColor:(UIColor *)color {
6434 return [super setPageColor:nil];
6437 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer {
6438 if ((self = [super init]) != nil) {
6439 database_ = database;
6440 name_ = name == nil ? @"" : [NSString stringWithString:name];
6441 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]] withReferrer:referrer];
6445 - (void) reloadData {
6448 [sheet_ dismissWithClickedButtonIndex:[sheet_ cancelButtonIndex] animated:YES];
6451 package_ = [database_ packageWithName:name_];
6452 versions_ = [package_ downgrades];
6456 if (package_ != nil) {
6457 [(Package *) package_ parse];
6459 commercial_ = [package_ isCommercial];
6461 if ([package_ mode] != nil)
6462 buttons_.push_back(std::make_pair(@"CLEAR", UCLocalize("CLEAR")));
6463 if ([package_ source] == nil);
6464 else if ([package_ upgradableAndEssential:NO])
6465 buttons_.push_back(std::make_pair(@"UPGRADE", UCLocalize("UPGRADE")));
6466 else if ([package_ uninstalled])
6467 buttons_.push_back(std::make_pair(@"INSTALL", UCLocalize("INSTALL")));
6469 buttons_.push_back(std::make_pair(@"REINSTALL", UCLocalize("REINSTALL")));
6470 if (![package_ uninstalled])
6471 buttons_.push_back(std::make_pair(@"REMOVE", UCLocalize("REMOVE")));
6472 if ([versions_ count] != 0)
6473 buttons_.push_back(std::make_pair(@"DOWNGRADE", UCLocalize("DOWNGRADE")));
6477 switch (buttons_.size()) {
6478 case 0: title = nil; break;
6479 case 1: title = buttons_[0].second; break;
6480 default: title = UCLocalize("MODIFY"); break;
6483 button_ = [[[UIBarButtonItem alloc]
6485 style:UIBarButtonItemStylePlain
6487 action:@selector(customButtonClicked)
6491 - (bool) isLoading {
6492 return commercial_ ? [super isLoading] : false;
6498 /* Package List Controller {{{ */
6499 @interface PackageListController : CyteViewController <
6500 UITableViewDataSource,
6503 _transient Database *database_;
6505 _H<NSArray> packages_;
6506 _H<NSArray> sections_;
6507 _H<UITableView, 2> list_;
6509 _H<NSArray> thumbs_;
6510 std::vector<NSInteger> offset_;
6512 _H<NSString> title_;
6513 unsigned reloading_;
6516 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6517 - (void) setDelegate:(id)delegate;
6518 - (void) resetCursor;
6521 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages;
6525 @implementation PackageListController
6527 - (NSURL *) referrerURL {
6528 return [self navigationURL];
6531 - (bool) isSummarized {
6535 - (bool) showsSections {
6539 - (void) deselectWithAnimation:(BOOL)animated {
6540 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6543 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6544 CGRect base = [[self view] bounds];
6545 base.size.height -= bounds.size.height;
6546 base.origin = [list_ frame].origin;
6548 [UIView beginAnimations:nil context:NULL];
6549 [UIView setAnimationBeginsFromCurrentState:YES];
6550 [UIView setAnimationCurve:curve];
6551 [UIView setAnimationDuration:duration];
6552 [list_ setFrame:base];
6553 [UIView commitAnimations];
6556 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6557 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6560 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6561 [self resizeForKeyboardBounds:bounds duration:0];
6564 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6565 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6566 *curve = UIViewAnimationCurveEaseInOut;
6568 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6570 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6573 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6576 - (void) keyboardWillShow:(NSNotification *)notification {
6579 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6580 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6582 NSTimeInterval duration;
6583 UIViewAnimationCurve curve;
6584 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6586 CGRect kbframe = CGRectMake(Retina(center.x - bounds.size.width / 2), Retina(center.y - bounds.size.height / 2), bounds.size.width, bounds.size.height);
6587 UIViewController *base = self;
6588 while ([base parentOrPresentingViewController] != nil)
6589 base = [base parentOrPresentingViewController];
6590 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6591 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6593 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6594 intersection.size.height += CYStatusBarHeight();
6596 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6599 - (void) keyboardWillHide:(NSNotification *)notification {
6600 NSTimeInterval duration;
6601 UIViewAnimationCurve curve;
6602 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6604 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6607 - (void) viewWillAppear:(BOOL)animated {
6608 [super viewWillAppear:animated];
6610 [self resizeForKeyboardBounds:CGRectZero];
6611 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6612 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6615 - (void) viewWillDisappear:(BOOL)animated {
6616 [super viewWillDisappear:animated];
6618 [self resizeForKeyboardBounds:CGRectZero];
6619 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6620 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6623 - (void) viewDidAppear:(BOOL)animated {
6624 [super viewDidAppear:animated];
6625 [self deselectWithAnimation:animated];
6628 - (void) didSelectPackage:(Package *)package {
6629 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[[self referrerURL] absoluteString]] autorelease]);
6630 [view setDelegate:delegate_];
6631 [[self navigationController] pushViewController:view animated:YES];
6634 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6635 NSInteger count([sections_ count]);
6636 return count == 0 ? 1 : count;
6639 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6640 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6642 return [[sections_ objectAtIndex:section] name];
6645 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6646 if ([sections_ count] == 0)
6648 return [[sections_ objectAtIndex:section] count];
6651 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6652 @synchronized (database_) {
6653 if ([database_ era] != era_)
6656 Section *section([sections_ objectAtIndex:[path section]]);
6657 NSInteger row([path row]);
6658 Package *package([packages_ objectAtIndex:([section row] + row)]);
6659 return [[package retain] autorelease];
6662 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6663 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6665 cell = [[[PackageCell alloc] init] autorelease];
6667 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6668 [cell setPackage:package asSummary:[self isSummarized]];
6672 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6673 Package *package([self packageAtIndexPath:path]);
6674 package = [database_ packageWithName:[package id]];
6675 [self didSelectPackage:package];
6678 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6682 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6683 return offset_[index];
6686 - (void) updateHeight {
6687 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6690 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6691 if ((self = [super init]) != nil) {
6692 database_ = database;
6693 title_ = [title copy];
6694 [[self navigationItem] setTitle:title_];
6699 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
6700 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
6701 [self setView:view];
6703 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6704 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6705 [view addSubview:list_];
6707 // XXX: is 20 the most optimal number here?
6708 [list_ setSectionIndexMinimumDisplayRowCount:20];
6710 [(UITableView *) list_ setDataSource:self];
6711 [list_ setDelegate:self];
6713 [self updateHeight];
6716 - (void) releaseSubviews {
6725 [super releaseSubviews];
6728 - (void) setDelegate:(id)delegate {
6729 delegate_ = delegate;
6732 - (bool) shouldYield {
6736 - (bool) shouldBlock {
6740 - (NSMutableArray *) _reloadPackages {
6741 @synchronized (database_) {
6742 era_ = [database_ era];
6743 NSArray *packages([database_ packages]);
6745 return [NSMutableArray arrayWithArray:packages];
6748 - (void) _reloadData {
6749 if (reloading_ != 0) {
6754 NSMutableArray *packages;
6757 if ([self shouldYield]) {
6761 if (![self shouldBlock])
6764 hud = [delegate_ addProgressHUD];
6765 [hud setText:UCLocalize("LOADING")];
6769 packages = [self yieldToSelector:@selector(_reloadPackages)];
6772 [delegate_ removeProgressHUD:hud];
6773 } while (reloading_ == 2);
6775 packages = [self _reloadPackages];
6778 @synchronized (database_) {
6779 if (era_ != [database_ era])
6786 packages_ = packages;
6788 if ([self showsSections])
6789 sections_ = [self sectionsForPackages:packages];
6791 Section *section([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6792 [section setCount:[packages_ count]];
6793 sections_ = [NSArray arrayWithObject:section];
6796 [self updateHeight];
6798 _profile(PackageTable$reloadData$List)
6799 [(UITableView *) list_ setDataSource:self];
6807 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
6808 Section *prefix([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6809 size_t end([packages count]);
6811 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
6812 Section *section(prefix);
6814 thumbs_ = CollationThumbs_;
6815 offset_ = CollationOffset_;
6818 size_t offsets([CollationStarts_ count]);
6820 NSString *start([CollationStarts_ objectAtIndex:offset]);
6821 size_t length([start length]);
6823 for (size_t index(0); index != end; ++index) {
6825 Package *package([packages objectAtIndex:index]);
6826 NSString *name(PackageName(package, @selector(cyname)));
6828 //while ([start compare:name options:NSNumericSearch range:NSMakeRange(0, length) locale:CollationLocale_] != NSOrderedDescending) {
6829 while (StringNameCompare(start, name, length) != kCFCompareGreaterThan) {
6830 NSString *title([CollationTitles_ objectAtIndex:offset]);
6831 section = [[[Section alloc] initWithName:title row:index localize:NO] autorelease];
6832 [sections addObject:section];
6834 start = ++offset == offsets ? nil : [CollationStarts_ objectAtIndex:offset];
6837 length = [start length];
6841 [section addToCount];
6844 for (; offset != offsets; ++offset) {
6845 NSString *title([CollationTitles_ objectAtIndex:offset]);
6846 Section *section([[[Section alloc] initWithName:title row:end localize:NO] autorelease]);
6847 [sections addObject:section];
6850 if ([prefix count] != 0) {
6851 Section *suffix([sections lastObject]);
6852 [prefix setName:[suffix name]];
6853 [suffix setName:nil];
6854 [sections insertObject:prefix atIndex:(offsets - 1)];
6860 - (void) reloadData {
6863 if ([self shouldYield])
6864 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6869 - (void) resetCursor {
6870 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6873 - (void) clearData {
6874 [self updateHeight];
6876 [list_ setDataSource:nil];
6884 /* Filtered Package List Controller {{{ */
6885 typedef Function<bool, Package *> PackageFilter;
6886 typedef Function<void, NSMutableArray *> PackageSorter;
6887 @interface FilteredPackageListController : PackageListController {
6888 PackageFilter filter_;
6889 PackageSorter sorter_;
6892 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter;
6894 - (void) setFilter:(PackageFilter)filter;
6895 - (void) setSorter:(PackageSorter)sorter;
6899 @implementation FilteredPackageListController
6901 - (void) setFilter:(PackageFilter)filter {
6902 @synchronized (self) {
6906 - (void) setSorter:(PackageSorter)sorter {
6907 @synchronized (self) {
6911 - (NSMutableArray *) _reloadPackages {
6912 @synchronized (database_) {
6913 era_ = [database_ era];
6915 NSArray *packages([database_ packages]);
6916 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6918 PackageFilter filter;
6919 PackageSorter sorter;
6921 @synchronized (self) {
6926 _profile(PackageTable$reloadData$Filter)
6927 for (Package *package in packages)
6928 if (filter(package))
6929 [filtered addObject:package];
6937 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter {
6938 if ((self = [super initWithDatabase:database title:title]) != nil) {
6939 [self setFilter:filter];
6946 /* Home Controller {{{ */
6947 @interface HomeController : CydiaWebViewController {
6948 CFRunLoopRef runloop_;
6949 SCNetworkReachabilityRef reachability_;
6954 @implementation HomeController
6956 static void HomeControllerReachabilityCallback(SCNetworkReachabilityRef reachability, SCNetworkReachabilityFlags flags, void *info) {
6957 [(HomeController *) info dispatchEvent:@"CydiaReachabilityCallback"];
6961 if ((self = [super init]) != nil) {
6962 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6965 reachability_ = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "cydia.saurik.com");
6966 if (reachability_ != NULL) {
6967 SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
6968 SCNetworkReachabilitySetCallback(reachability_, HomeControllerReachabilityCallback, &context);
6970 CFRunLoopRef runloop(CFRunLoopGetCurrent());
6971 if (SCNetworkReachabilityScheduleWithRunLoop(reachability_, runloop, kCFRunLoopDefaultMode))
6978 if (reachability_ != NULL && runloop_ != NULL)
6979 SCNetworkReachabilityUnscheduleFromRunLoop(reachability_, runloop_, kCFRunLoopDefaultMode);
6983 - (NSURL *) navigationURL {
6984 return [NSURL URLWithString:@"cydia://home"];
6987 - (void) aboutButtonClicked {
6988 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6990 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6991 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6992 [alert setCancelButtonIndex:0];
6995 @"Copyright \u00a9 2008-2015\n"
6998 "Jay Freeman (saurik)\n"
6999 "saurik@saurik.com\n"
7000 "http://www.saurik.com/"
7006 - (UIBarButtonItem *) leftButton {
7007 return [[[UIBarButtonItem alloc]
7008 initWithTitle:UCLocalize("ABOUT")
7009 style:UIBarButtonItemStylePlain
7011 action:@selector(aboutButtonClicked)
7018 /* Cydia Navigation Controller Interface {{{ */
7019 @interface UINavigationController (Cydia)
7021 - (NSArray *) navigationURLCollection;
7022 - (void) unloadData;
7027 /* Cydia Tab Bar Controller {{{ */
7028 @interface CydiaTabBarController : CyteTabBarController <
7029 UITabBarControllerDelegate,
7032 _transient Database *database_;
7034 _H<UIActivityIndicatorView> indicator_;
7037 // XXX: ok, "updatedelegate_"?...
7038 _transient NSObject<CydiaDelegate> *updatedelegate_;
7041 - (NSArray *) navigationURLCollection;
7042 - (void) beginUpdate;
7047 @implementation CydiaTabBarController
7049 - (NSArray *) navigationURLCollection {
7050 NSMutableArray *items([NSMutableArray array]);
7052 // XXX: Should this deal with transient view controllers?
7053 for (id navigation in [self viewControllers]) {
7054 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
7056 [items addObject:stack];
7062 - (id) initWithDatabase:(Database *)database {
7063 if ((self = [super init]) != nil) {
7064 database_ = database;
7065 [self setDelegate:self];
7067 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteTiny] autorelease];
7068 [indicator_ setOrigin:CGPointMake(kCFCoreFoundationVersionNumber >= 800 ? 2 : 4, 2)];
7070 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7074 - (void) beginUpdate {
7078 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
7079 UITabBarItem *item([controller tabBarItem]);
7081 [item setBadgeValue:@""];
7082 UIView *badge(MSHookIvar<UIView *>([item view], "_badge"));
7084 [indicator_ startAnimating];
7085 [badge addSubview:indicator_];
7087 [updatedelegate_ retainNetworkActivityIndicator];
7091 detachNewThreadSelector:@selector(performUpdate)
7097 - (void) performUpdate {
7098 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
7100 SourceStatus status(self, database_);
7101 [database_ updateWithStatus:status];
7104 performSelectorOnMainThread:@selector(completeUpdate)
7112 - (void) stopUpdateWithSelector:(SEL)selector {
7114 [updatedelegate_ releaseNetworkActivityIndicator];
7116 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
7117 [[controller tabBarItem] setBadgeValue:nil];
7119 [indicator_ removeFromSuperview];
7120 [indicator_ stopAnimating];
7122 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
7125 - (void) completeUpdate {
7128 [self stopUpdateWithSelector:@selector(reloadData)];
7131 - (void) cancelUpdate {
7132 [self stopUpdateWithSelector:@selector(updateDataAndLoad)];
7135 - (void) cancelPressed {
7136 [self cancelUpdate];
7143 - (bool) isSourceCancelled {
7147 - (void) startSourceFetch:(NSString *)uri {
7150 - (void) stopSourceFetch:(NSString *)uri {
7153 - (void) setUpdateDelegate:(id)delegate {
7154 updatedelegate_ = delegate;
7160 /* Cydia Navigation Controller Implementation {{{ */
7161 @implementation UINavigationController (Cydia)
7163 - (NSArray *) navigationURLCollection {
7164 NSMutableArray *stack([NSMutableArray array]);
7166 for (CyteViewController *controller in [self viewControllers]) {
7167 NSString *url = [[controller navigationURL] absoluteString];
7169 [stack addObject:url];
7175 - (void) reloadData {
7178 UIViewController *visible([self visibleViewController]);
7180 [visible reloadData];
7182 // on the iPad, this view controller is ALSO visible. :(
7184 if (UIViewController *modal = [self modalViewController])
7185 if ([modal modalPresentationStyle] == UIModalPresentationFormSheet)
7186 if (UIViewController *top = [self topViewController])
7191 - (void) unloadData {
7192 for (CyteViewController *page in [self viewControllers])
7201 /* Cydia:// Protocol {{{ */
7202 @interface CydiaURLProtocol : NSURLProtocol {
7207 @implementation CydiaURLProtocol
7209 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7210 NSURL *url([request URL]);
7214 NSString *scheme([[url scheme] lowercaseString]);
7215 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7217 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7223 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7227 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7228 id<NSURLProtocolClient> client([self client]);
7230 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7232 NSData *data(UIImagePNGRepresentation(icon));
7234 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7235 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7236 [client URLProtocol:self didLoadData:data];
7237 [client URLProtocolDidFinishLoading:self];
7241 - (void) startLoading {
7242 id<NSURLProtocolClient> client([self client]);
7243 NSURLRequest *request([self request]);
7245 NSURL *url([request URL]);
7246 NSString *href([url absoluteString]);
7247 NSString *scheme([[url scheme] lowercaseString]);
7251 if ([scheme isEqualToString:@"cydia"])
7252 path = [href substringFromIndex:8];
7253 else if ([scheme isEqualToString:@"about"])
7254 path = [href substringFromIndex:12];
7255 else _assert(false);
7257 NSRange slash([path rangeOfString:@"/"]);
7260 if (slash.location == NSNotFound) {
7264 command = [path substringToIndex:slash.location];
7265 path = [path substringFromIndex:(slash.location + 1)];
7268 Database *database([Database sharedInstance]);
7271 else if ([command isEqualToString:@"application-icon"]) {
7274 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7278 if (icon == nil && $SBSCopyIconImagePNGDataForDisplayIdentifier != NULL) {
7279 NSData *data([$SBSCopyIconImagePNGDataForDisplayIdentifier(path) autorelease]);
7280 icon = [UIImage imageWithData:data];
7284 if (NSString *file = SBSCopyIconImagePathForDisplayIdentifier(path))
7285 icon = [UIImage imageAtPath:file];
7288 icon = [UIImage imageNamed:@"unknown.png"];
7290 [self _returnPNGWithImage:icon forRequest:request];
7291 } else if ([command isEqualToString:@"package-icon"]) {
7294 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7295 Package *package([database packageWithName:path]);
7299 UIImage *icon([package icon]);
7300 [self _returnPNGWithImage:icon forRequest:request];
7301 } else if ([command isEqualToString:@"uikit-image"]) {
7304 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7305 UIImage *icon(_UIImageWithName(path));
7306 [self _returnPNGWithImage:icon forRequest:request];
7307 } else if ([command isEqualToString:@"section-icon"]) {
7310 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7311 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7313 icon = [UIImage imageNamed:@"unknown.png"];
7314 [self _returnPNGWithImage:icon forRequest:request];
7316 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7320 - (void) stopLoading {
7326 /* Section Controller {{{ */
7327 @interface SectionController : FilteredPackageListController {
7329 _H<NSString> section_;
7332 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section;
7336 @implementation SectionController
7338 - (NSURL *) referrerURL {
7339 NSString *name(section_);
7340 name = name ?: @"*";
7341 NSString *key(key_);
7343 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sections/%@/%@", UI_, [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7346 - (NSURL *) navigationURL {
7347 NSString *name(section_);
7348 name = name ?: @"*";
7349 NSString *key(key_);
7351 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@/%@", [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7354 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section {
7357 title = UCLocalize("ALL_PACKAGES");
7358 else if (![section isEqual:@""])
7359 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(section) value:nil table:@"Sections"];
7361 title = UCLocalize("NO_SECTION");
7363 if ((self = [super initWithDatabase:database title:title]) != nil) {
7364 key_ = [source key];
7369 - (void) reloadData {
7370 Source *source([database_ sourceWithKey:key_]);
7371 _H<NSString> name(section_);
7373 [self setFilter:[=](Package *package) {
7374 NSString *section([package section]);
7378 section == nil && [name length] == 0 ||
7379 [name isEqualToString:section]
7382 [package source] == source
7383 ) && [package visible];
7391 /* Sections Controller {{{ */
7392 @interface SectionsController : CyteViewController <
7393 UITableViewDataSource,
7396 _transient Database *database_;
7398 _H<NSMutableArray> sections_;
7399 _H<NSMutableArray> filtered_;
7400 _H<UITableView, 2> list_;
7403 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7404 - (void) editButtonClicked;
7408 @implementation SectionsController
7410 - (NSURL *) navigationURL {
7411 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
7414 - (Source *) source {
7417 return [database_ sourceWithKey:key_];
7420 - (void) updateNavigationItem {
7421 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7422 if ([sections_ count] == 0) {
7423 [[self navigationItem] setRightBarButtonItem:nil];
7425 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7426 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7428 action:@selector(editButtonClicked)
7429 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7433 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7434 [super setEditing:editing animated:animated];
7439 [delegate_ updateData];
7441 [self updateNavigationItem];
7444 - (void) viewDidAppear:(BOOL)animated {
7445 [super viewDidAppear:animated];
7446 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7449 - (void) viewWillDisappear:(BOOL)animated {
7450 [super viewWillDisappear:animated];
7451 [self setEditing:NO];
7454 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7455 Section *section = nil;
7456 int index = [indexPath row];
7457 if (![self isEditing]) {
7460 section = [filtered_ objectAtIndex:index];
7462 section = [sections_ objectAtIndex:index];
7467 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7468 if ([self isEditing])
7469 return [sections_ count];
7471 return [filtered_ count] + 1;
7474 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7478 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7479 static NSString *reuseIdentifier = @"SectionCell";
7481 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7483 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7485 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7490 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7491 if ([self isEditing])
7494 Section *section = [self sectionAtIndexPath:indexPath];
7496 SectionController *controller = [[[SectionController alloc]
7497 initWithDatabase:database_
7498 source:[self source]
7499 section:[section name]
7501 [controller setDelegate:delegate_];
7503 [[self navigationController] pushViewController:controller animated:YES];
7507 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
7508 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7509 [list_ setRowHeight:46];
7510 [(UITableView *) list_ setDataSource:self];
7511 [list_ setDelegate:self];
7512 [self setView:list_];
7515 - (void) viewDidLoad {
7516 [super viewDidLoad];
7518 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7521 - (void) releaseSubviews {
7527 [super releaseSubviews];
7530 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7531 if ((self = [super init]) != nil) {
7532 database_ = database;
7533 key_ = [source key];
7537 - (void) reloadData {
7540 NSArray *packages = [database_ packages];
7542 sections_ = [NSMutableArray arrayWithCapacity:16];
7543 filtered_ = [NSMutableArray arrayWithCapacity:16];
7545 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7547 Source *source([self source]);
7550 for (Package *package in packages) {
7551 if (source != nil && [package source] != source)
7554 NSString *name([package section]);
7555 NSString *key(name == nil ? @"" : name);
7559 _profile(SectionsView$reloadData$Section)
7560 section = [sections objectForKey:key];
7561 if (section == nil) {
7562 _profile(SectionsView$reloadData$Section$Allocate)
7563 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7564 [sections setObject:section forKey:key];
7569 [section addToCount];
7571 _profile(SectionsView$reloadData$Filter)
7572 if (![package visible])
7580 [sections_ addObjectsFromArray:[sections allValues]];
7582 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7584 for (Section *section in (id) sections_) {
7585 size_t count([section row]);
7589 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7590 [section setCount:count];
7591 [filtered_ addObject:section];
7594 [self updateNavigationItem];
7599 - (void) editButtonClicked {
7600 [self setEditing:![self isEditing] animated:YES];
7606 /* Changes Controller {{{ */
7607 @interface ChangesController : FilteredPackageListController {
7611 - (id) initWithDatabase:(Database *)database;
7615 @implementation ChangesController
7617 - (NSURL *) referrerURL {
7618 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/changes/", UI_]];
7621 - (NSURL *) navigationURL {
7622 return [NSURL URLWithString:@"cydia://changes"];
7625 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7626 @synchronized (database_) {
7627 if ([database_ era] != era_)
7630 NSUInteger sectionIndex([path section]);
7631 if (sectionIndex >= [sections_ count])
7633 Section *section([sections_ objectAtIndex:sectionIndex]);
7634 NSInteger row([path row]);
7635 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7638 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7639 NSString *context([alert context]);
7641 if ([context isEqualToString:@"norefresh"])
7642 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7645 - (void) setLeftBarButtonItem {
7646 if ([delegate_ updating])
7647 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7648 initWithTitle:UCLocalize("CANCEL")
7649 style:UIBarButtonItemStyleDone
7651 action:@selector(cancelButtonClicked)
7652 ] autorelease] animated:YES];
7654 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7655 initWithTitle:UCLocalize("REFRESH")
7656 style:UIBarButtonItemStylePlain
7658 action:@selector(refreshButtonClicked)
7659 ] autorelease] animated:YES];
7662 - (void) refreshButtonClicked {
7663 if ([delegate_ requestUpdate])
7664 [self setLeftBarButtonItem];
7667 - (void) cancelButtonClicked {
7668 [delegate_ cancelUpdate];
7671 - (void) upgradeButtonClicked {
7672 [delegate_ distUpgrade];
7673 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7676 - (bool) shouldYield {
7680 - (bool) shouldBlock {
7684 - (void) useFilter {
7685 @synchronized (self) {
7686 [self setFilter:[](Package *package) {
7687 return [package upgradableAndEssential:YES] || [package visible];
7690 [self setSorter:[](NSMutableArray *packages) {
7691 [packages radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7695 - (id) initWithDatabase:(Database *)database {
7696 if ((self = [super initWithDatabase:database title:UCLocalize("CHANGES")]) != nil) {
7701 - (void) viewDidLoad {
7702 [super viewDidLoad];
7703 [self setLeftBarButtonItem];
7706 - (void) viewWillAppear:(BOOL)animated {
7707 [super viewWillAppear:animated];
7708 [self setLeftBarButtonItem];
7711 - (void) reloadData {
7712 [self setLeftBarButtonItem];
7716 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
7717 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
7719 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7720 Section *ignored = nil;
7721 Section *section = nil;
7725 bool unseens = false;
7727 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7729 for (size_t offset = 0, count = [packages count]; offset != count; ++offset) {
7730 Package *package = [packages objectAtIndex:offset];
7732 BOOL uae = [package upgradableAndEssential:YES];
7736 time_t seen([package seen]);
7738 if (section == nil || last != seen) {
7742 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7745 _profile(ChangesController$reloadData$Allocate)
7746 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7747 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7748 [sections addObject:section];
7752 [section addToCount];
7753 } else if ([package ignored]) {
7754 if (ignored == nil) {
7755 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7757 [ignored addToCount];
7760 [upgradable addToCount];
7765 CFRelease(formatter);
7768 Section *last = [sections lastObject];
7769 size_t count = [last count];
7770 [packages removeObjectsInRange:NSMakeRange([packages count] - count, count)];
7771 [sections removeLastObject];
7774 if ([ignored count] != 0)
7775 [sections insertObject:ignored atIndex:0];
7777 [sections insertObject:upgradable atIndex:0];
7781 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7782 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7783 style:UIBarButtonItemStylePlain
7785 action:@selector(upgradeButtonClicked)
7786 ] autorelease]) animated:YES];
7793 /* Search Controller {{{ */
7794 @interface SearchController : FilteredPackageListController <
7797 _H<UISearchBar, 1> search_;
7802 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7803 - (void) reloadData;
7807 @implementation SearchController
7809 - (NSURL *) referrerURL {
7810 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/search?q=%@", UI_, [([search_ text] ?: @"") stringByAddingPercentEscapesIncludingReserved]]];
7813 - (NSURL *) navigationURL {
7814 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7815 return [NSURL URLWithString:@"cydia://search"];
7817 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [[search_ text] stringByAddingPercentEscapesIncludingReserved]]];
7820 - (NSArray *) termsForQuery:(NSString *)query {
7821 NSMutableArray *terms([NSMutableArray arrayWithCapacity:2]);
7822 for (NSString *component in [query componentsSeparatedByString:@" "])
7823 if ([component length] != 0)
7824 [terms addObject:component];
7829 - (void) useSearch {
7830 _H<NSArray> query([self termsForQuery:[search_ text]]);
7833 @synchronized (self) {
7834 [self setFilter:[=](Package *package) {
7835 if (![package unfiltered])
7837 if (![package matches:query])
7842 [self setSorter:[](NSMutableArray *packages) {
7843 [packages radixSortUsingSelector:@selector(rank)];
7851 - (void) usePrefix:(NSString *)prefix {
7852 _H<NSString> query(prefix);
7855 @synchronized (self) {
7856 [self setFilter:[=](Package *package) {
7857 if ([query length] == 0)
7859 if (![package unfiltered])
7861 if ([[package name] compare:query options:MatchCompareOptions_ range:NSMakeRange(0, [query length])] != NSOrderedSame)
7866 [self setSorter:nullptr];
7872 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7874 [self usePrefix:[search_ text]];
7877 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7878 [search_ resignFirstResponder];
7882 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7883 [search_ setText:@""];
7884 [self searchBarButtonClicked:searchBar];
7887 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7888 [self searchBarButtonClicked:searchBar];
7891 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7892 [self usePrefix:text];
7895 - (bool) shouldYield {
7899 - (bool) shouldBlock {
7903 - (bool) isSummarized {
7907 - (bool) showsSections {
7911 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7912 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH")])) {
7913 search_ = [[[UISearchBar alloc] init] autorelease];
7914 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7915 [search_ setDelegate:self];
7917 UITextField *textField;
7918 if ([search_ respondsToSelector:@selector(searchField)])
7919 textField = [search_ searchField];
7921 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7923 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7924 [textField setEnablesReturnKeyAutomatically:NO];
7925 [[self navigationItem] setTitleView:textField];
7928 [search_ setText:query];
7933 - (void) viewDidAppear:(BOOL)animated {
7934 [super viewDidAppear:animated];
7936 if (!searchloaded_) {
7937 searchloaded_ = YES;
7938 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7939 [search_ layoutSubviews];
7942 if ([self isSummarized])
7943 [search_ becomeFirstResponder];
7946 - (void) reloadData {
7951 - (void) didSelectPackage:(Package *)package {
7952 [search_ resignFirstResponder];
7953 [super didSelectPackage:package];
7958 /* Package Settings Controller {{{ */
7959 @interface PackageSettingsController : CyteViewController <
7960 UITableViewDataSource,
7963 _transient Database *database_;
7965 _H<Package> package_;
7966 _H<UITableView, 2> table_;
7967 _H<UISwitch> subscribedSwitch_;
7968 _H<UISwitch> ignoredSwitch_;
7969 _H<UITableViewCell> subscribedCell_;
7970 _H<UITableViewCell> ignoredCell_;
7973 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7977 @implementation PackageSettingsController
7979 - (NSURL *) navigationURL {
7980 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
7983 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7984 if (package_ == nil)
7987 if ([package_ installed] == nil)
7993 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7994 if (package_ == nil)
7997 // both sections contain just one item right now.
8001 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8005 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8007 return UCLocalize("SHOW_ALL_CHANGES_EX");
8009 return UCLocalize("IGNORE_UPGRADES_EX");
8012 - (void) onSubscribed:(id)control {
8013 bool value([control isOn]);
8014 if (package_ == nil)
8016 if ([package_ setSubscribed:value])
8017 [delegate_ updateData];
8020 - (void) _updateIgnored {
8021 const char *package([name_ UTF8String]);
8022 bool on([ignoredSwitch_ isOn]);
8024 FILE *dpkg(popen("/usr/libexec/cydia/cydo --set-selections", "w"));
8025 fwrite(package, strlen(package), 1, dpkg);
8028 fwrite(" hold\n", 6, 1, dpkg);
8030 fwrite(" install\n", 9, 1, dpkg);
8035 - (void) onIgnored:(id)control {
8036 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
8037 [invocation setTarget:self];
8038 [invocation setSelector:@selector(_updateIgnored)];
8040 [delegate_ reloadDataWithInvocation:invocation];
8043 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8044 if (package_ == nil)
8047 switch ([indexPath section]) {
8048 case 0: return subscribedCell_;
8049 case 1: return ignoredCell_;
8058 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8059 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8060 [self setView:view];
8062 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
8063 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8064 [(UITableView *) table_ setDataSource:self];
8065 [table_ setDelegate:self];
8066 [view addSubview:table_];
8068 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
8069 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
8070 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
8072 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
8073 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
8074 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
8076 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
8077 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
8078 [subscribedCell_ setAccessoryView:subscribedSwitch_];
8079 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
8081 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
8082 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
8083 [ignoredCell_ setAccessoryView:ignoredSwitch_];
8084 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
8087 - (void) viewDidLoad {
8088 [super viewDidLoad];
8090 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
8093 - (void) releaseSubviews {
8095 subscribedCell_ = nil;
8097 ignoredSwitch_ = nil;
8098 subscribedSwitch_ = nil;
8100 [super releaseSubviews];
8103 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
8104 if ((self = [super init]) != nil) {
8105 database_ = database;
8110 - (void) reloadData {
8113 package_ = [database_ packageWithName:name_];
8115 if (package_ != nil) {
8116 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
8117 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
8118 } // XXX: what now, G?
8120 [table_ reloadData];
8126 /* Installed Controller {{{ */
8127 @interface InstalledController : FilteredPackageListController {
8131 - (id) initWithDatabase:(Database *)database;
8132 - (void) queueStatusDidChange;
8136 @implementation InstalledController
8138 - (NSURL *) referrerURL {
8139 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/installed/", UI_]];
8142 - (NSURL *) navigationURL {
8143 return [NSURL URLWithString:@"cydia://installed"];
8146 - (void) useRecent {
8149 @synchronized (self) {
8150 [self setFilter:[](Package *package) {
8151 return ![package uninstalled] && package->role_ < 7;
8154 [self setSorter:[](NSMutableArray *packages) {
8155 [packages radixSortUsingSelector:@selector(recent)];
8159 - (void) useFilter:(UISegmentedControl *)segmented {
8160 NSInteger selected([segmented selectedSegmentIndex]);
8162 return [self useRecent];
8163 bool simple(selected == 0);
8166 @synchronized (self) {
8167 [self setFilter:[=](Package *package) {
8168 return ![package uninstalled] && package->role_ <= (simple ? 1 : 3);
8171 [self setSorter:nullptr];
8174 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
8176 return [super sectionsForPackages:packages];
8178 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterLongStyle, kCFDateFormatterNoStyle));
8180 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
8181 Section *section(nil);
8184 for (size_t offset(0), count([packages count]); offset != count; ++offset) {
8185 Package *package([packages objectAtIndex:offset]);
8187 time_t upgraded([package upgraded]);
8188 if (upgraded < 1168364520)
8191 upgraded -= upgraded % (60 * 60 * 24);
8193 if (section == nil || upgraded != last) {
8198 continue; // XXX: name = UCLocalize("...");
8200 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:upgraded]);
8204 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
8205 [sections addObject:section];
8208 [section addToCount];
8211 CFRelease(formatter);
8215 - (id) initWithDatabase:(Database *)database {
8216 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED")]) != nil) {
8217 UISegmentedControl *segmented([[[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:UCLocalize("USER"), UCLocalize("EXPERT"), UCLocalize("RECENT"), nil]] autorelease]);
8218 [segmented setSelectedSegmentIndex:0];
8219 [segmented setSegmentedControlStyle:UISegmentedControlStyleBar];
8220 [[self navigationItem] setTitleView:segmented];
8222 [segmented addTarget:self action:@selector(modeChanged:) forEvents:UIControlEventValueChanged];
8223 [self useFilter:segmented];
8225 [self queueStatusDidChange];
8230 - (void) queueButtonClicked {
8235 - (void) queueStatusDidChange {
8238 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8239 initWithTitle:UCLocalize("QUEUE")
8240 style:UIBarButtonItemStyleDone
8242 action:@selector(queueButtonClicked)
8245 [[self navigationItem] setRightBarButtonItem:nil];
8250 - (void) modeChanged:(UISegmentedControl *)segmented {
8251 [self useFilter:segmented];
8258 /* Source Cell {{{ */
8259 @interface SourceCell : CyteTableViewCell <
8260 CyteTableViewCellDelegate,
8263 _H<Source, 1> source_;
8266 _H<NSString> origin_;
8267 _H<NSString> label_;
8268 _H<UIActivityIndicatorView> indicator_;
8271 - (void) setSource:(Source *)source;
8272 - (void) setFetch:(NSNumber *)fetch;
8276 @implementation SourceCell
8278 - (void) _setImage:(NSArray *)data {
8279 if ([url_ isEqual:[data objectAtIndex:0]]) {
8280 icon_ = [data objectAtIndex:1];
8281 [content_ setNeedsDisplay];
8285 - (void) _setSource:(NSURL *) url {
8286 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8288 if (NSData *data = [NSURLConnection
8289 sendSynchronousRequest:[NSURLRequest
8291 cachePolicy:NSURLRequestUseProtocolCachePolicy
8295 returningResponse:NULL
8298 if (UIImage *image = [UIImage imageWithData:data])
8299 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
8304 - (void) setSource:(Source *)source {
8306 [source_ setDelegate:self];
8308 [self setFetch:[NSNumber numberWithBool:[source_ fetch]]];
8310 icon_ = [UIImage imageNamed:@"unknown.png"];
8312 origin_ = [source name];
8313 label_ = [source rooturi];
8315 [content_ setNeedsDisplay];
8317 url_ = [source iconURL];
8318 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
8321 - (void) setAllSource {
8323 [indicator_ stopAnimating];
8325 icon_ = [UIImage imageNamed:@"folder.png"];
8326 origin_ = UCLocalize("ALL_SOURCES");
8327 label_ = UCLocalize("ALL_SOURCES_EX");
8328 [content_ setNeedsDisplay];
8331 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8332 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8333 UIView *content([self contentView]);
8334 CGRect bounds([content bounds]);
8336 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8337 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8338 [content_ setBackgroundColor:[UIColor whiteColor]];
8339 [content addSubview:content_];
8341 [content_ setDelegate:self];
8342 [content_ setOpaque:YES];
8344 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGraySmall] autorelease];
8345 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin];// | UIViewAutoresizingFlexibleBottomMargin];
8346 [content addSubview:indicator_];
8348 [[content_ layer] setContentsGravity:kCAGravityTopLeft];
8352 - (void) layoutSubviews {
8353 [super layoutSubviews];
8355 UIView *content([self contentView]);
8356 CGRect bounds([content bounds]);
8358 CGRect frame([indicator_ frame]);
8359 frame.origin.x = bounds.size.width - frame.size.width;
8360 frame.origin.y = Retina((bounds.size.height - frame.size.height) / 2);
8362 if (kCFCoreFoundationVersionNumber < 800)
8363 frame.origin.x -= 8;
8364 [indicator_ setFrame:frame];
8367 - (NSString *) accessibilityLabel {
8371 - (void) drawContentRect:(CGRect)rect {
8372 bool highlighted(highlighted_);
8373 float width(rect.size.width);
8377 rect.size = [(UIImage *) icon_ size];
8379 while (rect.size.width > 32 || rect.size.height > 32) {
8380 rect.size.width /= 2;
8381 rect.size.height /= 2;
8384 rect.origin.x = 26 - rect.size.width / 2;
8385 rect.origin.y = 26 - rect.size.height / 2;
8387 [icon_ drawInRect:Retina(rect)];
8390 if (highlighted && kCFCoreFoundationVersionNumber < 800)
8395 [origin_ drawAtPoint:CGPointMake(52, 8) forWidth:(width - 49) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
8399 [label_ drawAtPoint:CGPointMake(52, 29) forWidth:(width - 49) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
8402 - (void) setFetch:(NSNumber *)fetch {
8403 if ([fetch boolValue])
8404 [indicator_ startAnimating];
8406 [indicator_ stopAnimating];
8411 /* Sources Controller {{{ */
8412 @interface SourcesController : CyteViewController <
8413 UITableViewDataSource,
8416 _transient Database *database_;
8419 _H<UITableView, 2> list_;
8420 _H<NSMutableArray> sources_;
8424 _H<UIProgressHUD> hud_;
8427 NSURLConnection *trivial_bz2_;
8428 NSURLConnection *trivial_gz_;
8433 - (id) initWithDatabase:(Database *)database;
8434 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated;
8438 @implementation SourcesController
8440 - (void) _releaseConnection:(NSURLConnection *)connection {
8441 if (connection != nil) {
8442 [connection cancel];
8443 //[connection setDelegate:nil];
8444 [connection release];
8449 [self _releaseConnection:trivial_gz_];
8450 [self _releaseConnection:trivial_bz2_];
8455 - (NSURL *) navigationURL {
8456 return [NSURL URLWithString:@"cydia://sources"];
8459 - (void) viewDidAppear:(BOOL)animated {
8460 [super viewDidAppear:animated];
8461 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8464 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8468 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8470 return UCLocalize("INDIVIDUAL_SOURCES");
8474 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8477 case 1: return [sources_ count];
8482 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8483 @synchronized (database_) {
8484 if ([database_ era] != era_)
8486 if ([indexPath section] != 1)
8488 NSUInteger index([indexPath row]);
8489 if (index >= [sources_ count])
8491 return [sources_ objectAtIndex:index];
8494 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8495 static NSString *cellIdentifier = @"SourceCell";
8497 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8498 if (cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8499 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8501 Source *source([self sourceAtIndexPath:indexPath]);
8503 [cell setAllSource];
8505 [cell setSource:source];
8510 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8511 SectionsController *controller([[[SectionsController alloc]
8512 initWithDatabase:database_
8513 source:[self sourceAtIndexPath:indexPath]
8516 [controller setDelegate:delegate_];
8517 [[self navigationController] pushViewController:controller animated:YES];
8520 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8521 if ([indexPath section] != 1)
8523 Source *source = [self sourceAtIndexPath:indexPath];
8524 return [source record] != nil;
8527 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8528 _assert([indexPath section] == 1);
8529 if (editingStyle == UITableViewCellEditingStyleDelete) {
8530 Source *source = [self sourceAtIndexPath:indexPath];
8531 if (source == nil) return;
8533 [Sources_ removeObjectForKey:[source key]];
8535 [delegate_ _saveConfig];
8536 [delegate_ reloadDataWithInvocation:nil];
8540 - (void) tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath {
8541 [self updateButtonsForEditingStatusAnimated:YES];
8545 [delegate_ addTrivialSource:href_];
8548 [delegate_ syncData];
8551 - (NSString *) getWarning {
8552 NSString *href(href_);
8553 NSRange colon([href rangeOfString:@"://"]);
8554 if (colon.location != NSNotFound)
8555 href = [href substringFromIndex:(colon.location + 3)];
8556 href = [href stringByAddingPercentEscapes];
8557 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8559 NSURL *url([NSURL URLWithString:href]);
8561 NSStringEncoding encoding;
8562 NSError *error(nil);
8564 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8565 return [warning length] == 0 ? nil : warning;
8569 - (void) _endConnection:(NSURLConnection *)connection {
8570 // XXX: the memory management in this method is horribly awkward
8572 NSURLConnection **field = NULL;
8573 if (connection == trivial_bz2_)
8574 field = &trivial_bz2_;
8575 else if (connection == trivial_gz_)
8576 field = &trivial_gz_;
8577 _assert(field != NULL);
8578 [connection release];
8582 trivial_bz2_ == nil &&
8585 NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil);
8587 [delegate_ releaseNetworkActivityIndicator];
8589 [delegate_ removeProgressHUD:hud_];
8593 if (warning != nil) {
8594 UIAlertView *alert = [[[UIAlertView alloc]
8595 initWithTitle:UCLocalize("SOURCE_WARNING")
8598 cancelButtonTitle:UCLocalize("CANCEL")
8600 UCLocalize("ADD_ANYWAY"),
8604 [alert setContext:@"warning"];
8605 [alert setNumberOfRows:1];
8608 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
8614 } else if (error_ != nil) {
8615 UIAlertView *alert = [[[UIAlertView alloc]
8616 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8617 message:[error_ localizedDescription]
8619 cancelButtonTitle:UCLocalize("OK")
8620 otherButtonTitles:nil
8623 [alert setContext:@"urlerror"];
8628 UIAlertView *alert = [[[UIAlertView alloc]
8629 initWithTitle:UCLocalize("NOT_REPOSITORY")
8630 message:UCLocalize("NOT_REPOSITORY_EX")
8632 cancelButtonTitle:UCLocalize("OK")
8633 otherButtonTitles:nil
8636 [alert setContext:@"trivial"];
8646 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8647 switch ([response statusCode]) {
8653 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8654 lprintf("connection:\"%s\" didFailWithError:\"%s\"\n", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8656 [self _endConnection:connection];
8659 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8660 [self _endConnection:connection];
8663 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8664 NSURL *url([NSURL URLWithString:href]);
8666 NSMutableURLRequest *request = [NSMutableURLRequest
8668 cachePolicy:NSURLRequestUseProtocolCachePolicy
8672 [request setHTTPMethod:method];
8674 if (Machine_ != NULL)
8675 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8677 if (UniqueID_ != nil)
8678 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8680 if ([url isCydiaSecure]) {
8681 if (UniqueID_ != nil)
8682 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
8685 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8688 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8689 NSString *context([alert context]);
8691 if ([context isEqualToString:@"source"]) {
8694 NSString *href = [[alert textField] text];
8695 href = VerifySource(href);
8700 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8701 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8705 // XXX: this is stupid
8706 hud_ = [delegate_ addProgressHUD];
8707 [hud_ setText:UCLocalize("VERIFYING_URL")];
8708 [delegate_ retainNetworkActivityIndicator];
8717 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8718 } else if ([context isEqualToString:@"trivial"])
8719 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8720 else if ([context isEqualToString:@"urlerror"])
8721 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8722 else if ([context isEqualToString:@"warning"]) {
8725 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
8734 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8738 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated {
8739 BOOL editing([list_ isEditing]);
8742 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8743 initWithTitle:UCLocalize("ADD")
8744 style:UIBarButtonItemStylePlain
8746 action:@selector(addButtonClicked)
8747 ] autorelease] animated:animated];
8748 else if ([delegate_ updating])
8749 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8750 initWithTitle:UCLocalize("CANCEL")
8751 style:UIBarButtonItemStyleDone
8753 action:@selector(cancelButtonClicked)
8754 ] autorelease] animated:animated];
8756 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8757 initWithTitle:UCLocalize("REFRESH")
8758 style:UIBarButtonItemStylePlain
8760 action:@selector(refreshButtonClicked)
8761 ] autorelease] animated:animated];
8763 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8764 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8765 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8767 action:@selector(editButtonClicked)
8768 ] autorelease] animated:animated];
8772 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease];
8773 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8774 [list_ setRowHeight:53];
8775 [(UITableView *) list_ setDataSource:self];
8776 [list_ setDelegate:self];
8777 [self setView:list_];
8780 - (void) viewDidLoad {
8781 [super viewDidLoad];
8783 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8784 [self updateButtonsForEditingStatusAnimated:NO];
8787 - (void) viewWillAppear:(BOOL)animated {
8788 [super viewWillAppear:animated];
8790 [list_ setEditing:NO];
8791 [self updateButtonsForEditingStatusAnimated:NO];
8794 - (void) releaseSubviews {
8799 [super releaseSubviews];
8802 - (id) initWithDatabase:(Database *)database {
8803 if ((self = [super init]) != nil) {
8804 database_ = database;
8808 - (void) reloadData {
8810 [self updateButtonsForEditingStatusAnimated:YES];
8812 @synchronized (database_) {
8813 era_ = [database_ era];
8815 sources_ = [NSMutableArray arrayWithCapacity:16];
8816 [sources_ addObjectsFromArray:[database_ sources]];
8818 [sources_ sortUsingSelector:@selector(compareByName:)];
8821 int count([sources_ count]);
8823 for (int i = 0; i != count; i++) {
8824 if ([[sources_ objectAtIndex:i] record] == nil)
8832 - (void) showAddSourcePrompt {
8833 UIAlertView *alert = [[[UIAlertView alloc]
8834 initWithTitle:UCLocalize("ENTER_APT_URL")
8837 cancelButtonTitle:UCLocalize("CANCEL")
8839 UCLocalize("ADD_SOURCE"),
8843 [alert setContext:@"source"];
8845 [alert setNumberOfRows:1];
8846 [alert addTextFieldWithValue:@"http://" label:@""];
8848 UITextInputTraits *traits = [[alert textField] textInputTraits];
8849 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8850 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8851 [traits setKeyboardType:UIKeyboardTypeURL];
8852 // XXX: UIReturnKeyDone
8853 [traits setReturnKeyType:UIReturnKeyNext];
8858 - (void) addButtonClicked {
8859 [self showAddSourcePrompt];
8862 - (void) refreshButtonClicked {
8863 if ([delegate_ requestUpdate])
8864 [self updateButtonsForEditingStatusAnimated:YES];
8867 - (void) cancelButtonClicked {
8868 [delegate_ cancelUpdate];
8871 - (void) editButtonClicked {
8872 [list_ setEditing:![list_ isEditing] animated:YES];
8873 [self updateButtonsForEditingStatusAnimated:YES];
8879 /* Stash Controller {{{ */
8880 @interface StashController : CyteViewController {
8881 _H<UIActivityIndicatorView> spinner_;
8882 _H<UILabel> status_;
8883 _H<UILabel> caption_;
8888 @implementation StashController
8891 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8892 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8893 [self setView:view];
8895 [view setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8897 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8898 CGRect spinrect = [spinner_ frame];
8899 spinrect.origin.x = Retina([[self view] frame].size.width / 2 - spinrect.size.width / 2);
8900 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8901 [spinner_ setFrame:spinrect];
8902 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8903 [view addSubview:spinner_];
8904 [spinner_ startAnimating];
8907 captrect.size.width = [[self view] frame].size.width;
8908 captrect.size.height = 40.0f;
8909 captrect.origin.x = 0;
8910 captrect.origin.y = Retina([[self view] frame].size.height / 2 - captrect.size.height * 2);
8911 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8912 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8913 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8914 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8915 [caption_ setTextColor:[UIColor whiteColor]];
8916 [caption_ setBackgroundColor:[UIColor clearColor]];
8917 [caption_ setShadowColor:[UIColor blackColor]];
8918 [caption_ setTextAlignment:NSTextAlignmentCenter];
8919 [view addSubview:caption_];
8922 statusrect.size.width = [[self view] frame].size.width;
8923 statusrect.size.height = 30.0f;
8924 statusrect.origin.x = 0;
8925 statusrect.origin.y = Retina([[self view] frame].size.height / 2 - statusrect.size.height);
8926 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8927 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8928 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8929 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8930 [status_ setTextColor:[UIColor whiteColor]];
8931 [status_ setBackgroundColor:[UIColor clearColor]];
8932 [status_ setShadowColor:[UIColor blackColor]];
8933 [status_ setTextAlignment:NSTextAlignmentCenter];
8934 [view addSubview:status_];
8937 - (void) releaseSubviews {
8942 [super releaseSubviews];
8948 @interface CYURLCache : SDURLCache {
8953 @implementation CYURLCache
8955 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8958 else if ([event isEqualToString:@"no-cache"])
8960 else if ([event isEqualToString:@"store"])
8962 else if ([event isEqualToString:@"invalid"])
8964 else if ([event isEqualToString:@"memory"])
8966 else if ([event isEqualToString:@"disk"])
8968 else if ([event isEqualToString:@"miss"])
8971 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8975 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
8976 if (NSURLResponse *response = [cached response])
8977 if (NSString *mime = [response MIMEType])
8978 if ([mime isEqualToString:@"text/cache-manifest"]) {
8979 NSURL *url([response URL]);
8982 NSLog(@"###: %@", [url absoluteString]);
8985 @synchronized (HostConfig_) {
8986 [CachedURLs_ addObject:url];
8990 [super storeCachedResponse:cached forRequest:request];
8993 - (void) createDiskCachePath {
8994 [super createDiskCachePath];
8999 @interface Cydia : UIApplication <
9000 ConfirmationControllerDelegate,
9004 _H<UIWindow> window_;
9005 _H<CydiaTabBarController> tabbar_;
9006 _H<CyteTabBarController> emulated_;
9007 _H<AppCacheController> appcache_;
9009 _H<NSMutableArray> essential_;
9010 _H<NSMutableArray> broken_;
9012 Database *database_;
9014 _H<NSURL> starturl_;
9019 _H<StashController> stash_;
9028 @implementation Cydia
9030 - (void) lockSuspend {
9031 if (locked_++ == 0) {
9032 if ($SBSSetInterceptsMenuButtonForever != NULL)
9033 (*$SBSSetInterceptsMenuButtonForever)(true);
9035 [self setIdleTimerDisabled:YES];
9039 - (void) unlockSuspend {
9040 if (--locked_ == 0) {
9041 [self setIdleTimerDisabled:NO];
9043 if ($SBSSetInterceptsMenuButtonForever != NULL)
9044 (*$SBSSetInterceptsMenuButtonForever)(false);
9048 - (void) beginUpdate {
9049 [tabbar_ beginUpdate];
9052 - (void) cancelUpdate {
9053 [tabbar_ cancelUpdate];
9056 - (bool) requestUpdate {
9057 if (IsReachable("cydia.saurik.com")) {
9061 UIAlertView *alert = [[[UIAlertView alloc]
9062 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("REFRESH")]
9063 message:@"Host Unreachable" // XXX: Localize
9065 cancelButtonTitle:UCLocalize("OK")
9066 otherButtonTitles:nil
9069 [alert setContext:@"norefresh"];
9077 return [tabbar_ updating];
9081 if ([broken_ count] != 0) {
9082 int count = [broken_ count];
9084 UIAlertView *alert = [[[UIAlertView alloc]
9085 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
9086 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
9088 cancelButtonTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("FORCIBLY_CLEAR"), UCLocalize("UNSAFE")]
9090 UCLocalize("TEMPORARY_IGNORE"),
9094 [alert setContext:@"fixhalf"];
9095 [alert setNumberOfRows:2];
9097 } else if (!Ignored_ && [essential_ count] != 0) {
9098 int count = [essential_ count];
9100 UIAlertView *alert = [[[UIAlertView alloc]
9101 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
9102 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
9104 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
9106 UCLocalize("UPGRADE_ESSENTIAL"),
9107 UCLocalize("COMPLETE_UPGRADE"),
9111 [alert setContext:@"upgrade"];
9116 - (void) returnToCydia {
9120 - (void) reloadSpringBoard {
9121 if (kCFCoreFoundationVersionNumber >= 700) // XXX: iOS 6.x
9122 system("/bin/launchctl stop com.apple.backboardd");
9124 system("/bin/launchctl stop com.apple.SpringBoard");
9126 system("/usr/bin/killall backboardd SpringBoard");
9129 - (void) _saveConfig {
9130 SaveConfig(database_);
9133 // Navigation controller for the queuing badge.
9134 - (UINavigationController *) queueNavigationController {
9135 NSArray *controllers = [tabbar_ viewControllers];
9136 return [controllers objectAtIndex:3];
9139 - (void) unloadData {
9140 [tabbar_ unloadData];
9143 - (void) _updateData {
9147 UINavigationController *navigation = [self queueNavigationController];
9149 id queuedelegate = nil;
9150 if ([[navigation viewControllers] count] > 0)
9151 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9153 [queuedelegate queueStatusDidChange];
9154 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9157 - (void) _refreshIfPossible {
9158 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9160 NSDate *update([[NSDictionary dictionaryWithContentsOfFile:@ CacheState_] objectForKey:@"LastUpdate"]);
9162 bool recently = false;
9163 if (update != nil) {
9164 NSTimeInterval interval([update timeIntervalSinceNow]);
9165 if (interval > -(15*60))
9169 // Don't automatic refresh if:
9170 // - We already refreshed recently.
9171 // - We already auto-refreshed this launch.
9172 // - Auto-refresh is disabled.
9173 // - Cydia's server is not reachable
9174 if (recently || loaded_ || ManualRefresh || !IsReachable("cydia.saurik.com")) {
9175 // If we are cancelling, we need to make sure it knows it's already loaded.
9178 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9180 // We are going to load, so remember that.
9183 [tabbar_ performSelectorOnMainThread:@selector(beginUpdate) withObject:nil waitUntilDone:NO];
9189 - (void) refreshIfPossible {
9190 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
9193 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9194 _profile(reloadDataWithInvocation)
9195 @synchronized (self) {
9196 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9198 [hud setText:UCLocalize("RELOADING_DATA")];
9200 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9204 [essential_ removeAllObjects];
9205 [broken_ removeAllObjects];
9207 _profile(reloadDataWithInvocation$Essential)
9208 NSArray *packages([database_ packages]);
9209 for (Package *package in packages) {
9211 [broken_ addObject:package];
9212 if ([package upgradableAndEssential:YES] && ![package ignored]) {
9213 if ([package essential] && [package installed] != nil)
9214 [essential_ addObject:package];
9220 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9223 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9224 [changesItem setBadgeValue:badge];
9225 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9226 [self setApplicationIconBadgeNumber:changes];
9229 [changesItem setBadgeValue:nil];
9230 [changesItem setAnimatedBadge:NO];
9231 [self setApplicationIconBadgeNumber:0];
9238 [self removeProgressHUD:hud];
9245 - (void) updateData {
9249 - (void) updateDataAndLoad {
9251 if ([database_ progressDelegate] == nil)
9257 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9260 - (void) disemulate {
9261 if (emulated_ == nil)
9264 if ([window_ respondsToSelector:@selector(setRootViewController:)])
9265 [window_ setRootViewController:tabbar_];
9267 [window_ addSubview:[tabbar_ view]];
9268 [[emulated_ view] removeFromSuperview];
9272 [window_ setUserInteractionEnabled:YES];
9275 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9276 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9278 UIViewController *parent;
9279 if (emulated_ == nil)
9289 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9290 [parent presentModalViewController:navigation animated:YES];
9293 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9294 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9296 if (navigation != nil)
9297 [navigation pushViewController:progress animated:YES];
9299 [self presentModalViewController:progress force:YES];
9301 [progress invoke:invocation withTitle:title];
9305 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9306 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9309 - (void) repairWithInvocation:(NSInvocation *)invocation {
9311 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9315 - (void) repairWithSelector:(SEL)selector {
9316 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9319 - (void) reloadData {
9320 [self reloadDataWithInvocation:nil];
9321 if ([database_ progressDelegate] == nil)
9327 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9330 - (void) addSource:(NSDictionary *) source {
9331 CydiaAddSource(source);
9334 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9335 CydiaAddSource(href, distribution, sections);
9338 // XXX: this method should not return anything
9339 - (BOOL) addTrivialSource:(NSString *)href {
9340 CydiaAddSource(href, @"./");
9345 pkgProblemResolver *resolver = [database_ resolver];
9347 resolver->InstallProtect();
9348 if (!resolver->Resolve(true))
9353 // XXX: this is a really crappy way of doing this.
9354 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9355 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9356 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9357 if ([tabbar_ updating])
9358 [tabbar_ cancelUpdate];
9360 if (![database_ prepare])
9363 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9364 [page setDelegate:self];
9365 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9368 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9369 [tabbar_ presentModalViewController:confirm_ animated:YES];
9375 @synchronized (self) {
9380 - (void) clearPackage:(Package *)package {
9381 @synchronized (self) {
9388 - (void) installPackages:(NSArray *)packages {
9389 @synchronized (self) {
9390 for (Package *package in packages)
9397 - (void) installPackage:(Package *)package {
9398 @synchronized (self) {
9405 - (void) removePackage:(Package *)package {
9406 @synchronized (self) {
9413 - (void) distUpgrade {
9414 @synchronized (self) {
9415 if (![database_ upgrade])
9423 system("/usr/bin/uicache");
9428 UIProgressHUD *hud([self addProgressHUD]);
9429 [hud setText:UCLocalize("LOADING")];
9430 [self yieldToSelector:@selector(_uicache)];
9431 [self removeProgressHUD:hud];
9435 [database_ perform];
9436 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9437 [self performSelectorOnMainThread:@selector(uicache) withObject:nil waitUntilDone:YES];
9440 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9443 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9444 [self unlockSuspend];
9447 - (void) retainNetworkActivityIndicator {
9448 if (activity_++ == 0)
9449 [self setNetworkActivityIndicatorVisible:YES];
9452 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9456 - (void) releaseNetworkActivityIndicator {
9457 if (--activity_ == 0)
9458 [self setNetworkActivityIndicatorVisible:NO];
9461 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9466 - (void) cancelAndClear:(bool)clear {
9467 @synchronized (self) {
9479 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9480 NSString *context([alert context]);
9482 if ([context isEqualToString:@"conffile"]) {
9483 FILE *input = [database_ input];
9484 if (button == [alert cancelButtonIndex])
9485 fprintf(input, "N\n");
9486 else if (button == [alert firstOtherButtonIndex])
9487 fprintf(input, "Y\n");
9490 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9491 } else if ([context isEqualToString:@"fixhalf"]) {
9492 if (button == [alert cancelButtonIndex]) {
9493 @synchronized (self) {
9494 for (Package *broken in (id) broken_) {
9496 NSString *id(ShellEscape([broken id]));
9497 system([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /bin/rm -f"
9498 " /var/lib/dpkg/info/%@.prerm"
9499 " /var/lib/dpkg/info/%@.postrm"
9500 " /var/lib/dpkg/info/%@.preinst"
9501 " /var/lib/dpkg/info/%@.postinst"
9502 " /var/lib/dpkg/info/%@.extrainst_"
9503 "", id, id, id, id, id] UTF8String]);
9509 } else if (button == [alert firstOtherButtonIndex]) {
9510 [broken_ removeAllObjects];
9514 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9515 } else if ([context isEqualToString:@"upgrade"]) {
9516 if (button == [alert firstOtherButtonIndex]) {
9517 @synchronized (self) {
9518 for (Package *essential in (id) essential_)
9519 [essential install];
9524 } else if (button == [alert firstOtherButtonIndex] + 1) {
9526 } else if (button == [alert cancelButtonIndex]) {
9530 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9534 - (void) system:(NSString *)command {
9535 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9538 system([command UTF8String]);
9544 - (void) applicationWillSuspend {
9546 [super applicationWillSuspend];
9549 - (BOOL) isSafeToSuspend {
9552 NSLog(@"isSafeToSuspend: locked_ != 0");
9557 if ([tabbar_ modalViewController] != nil)
9560 // Use external process status API internally.
9561 // This is probably a really bad idea.
9562 // XXX: what is the point of this? does this solve anything at all?
9563 uint64_t status = 0;
9565 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9566 notify_get_state(notify_token, &status);
9567 notify_cancel(notify_token);
9572 NSLog(@"isSafeToSuspend: status != 0");
9578 NSLog(@"isSafeToSuspend: -> true");
9583 - (void) suspendReturningToLastApp:(BOOL)returning {
9584 if ([self isSafeToSuspend])
9585 [super suspendReturningToLastApp:returning];
9589 if ([self isSafeToSuspend])
9593 - (void) applicationSuspend {
9594 if ([self isSafeToSuspend])
9595 [super applicationSuspend];
9598 - (void) applicationSuspend:(__GSEvent *)event {
9599 if ([self isSafeToSuspend])
9600 [super applicationSuspend:event];
9603 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9604 if ([self isSafeToSuspend])
9605 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9608 - (void) _setSuspended:(BOOL)value {
9609 if ([self isSafeToSuspend])
9610 [super _setSuspended:value];
9613 - (UIProgressHUD *) addProgressHUD {
9614 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9615 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9617 [window_ setUserInteractionEnabled:NO];
9619 UIViewController *target(tabbar_);
9620 if (UIViewController *modal = [target modalViewController])
9623 [hud showInView:[target view]];
9629 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9630 [self unlockSuspend];
9632 [hud removeFromSuperview];
9633 [window_ setUserInteractionEnabled:YES];
9636 - (CyteViewController *) pageForPackage:(NSString *)name withReferrer:(NSString *)referrer {
9637 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name withReferrer:referrer] autorelease];
9640 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external withReferrer:(NSString *)referrer {
9641 NSString *scheme([[url scheme] lowercaseString]);
9642 if ([[url absoluteString] length] <= [scheme length] + 3)
9644 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9645 NSArray *components([path componentsSeparatedByString:@"/"]);
9647 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"]) {
9648 CyteViewController *controller([self pageForPackage:[components objectAtIndex:1] withReferrer:referrer]);
9649 if (controller != nil)
9650 [controller setDelegate:self];
9654 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9657 NSString *base([components objectAtIndex:0]);
9659 CyteViewController *controller = nil;
9661 if ([base isEqualToString:@"url"]) {
9662 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9663 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9664 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9665 } else if (!external && [components count] == 1) {
9666 if ([base isEqualToString:@"sources"]) {
9667 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9670 if ([base isEqualToString:@"home"]) {
9671 controller = [[[HomeController alloc] init] autorelease];
9674 if ([base isEqualToString:@"sections"]) {
9675 controller = [[[SectionsController alloc] initWithDatabase:database_ source:nil] autorelease];
9678 if ([base isEqualToString:@"search"]) {
9679 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9682 if ([base isEqualToString:@"changes"]) {
9683 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9686 if ([base isEqualToString:@"installed"]) {
9687 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9689 } else if ([components count] == 2) {
9690 NSString *argument = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9692 if ([base isEqualToString:@"package"]) {
9693 controller = [self pageForPackage:argument withReferrer:referrer];
9696 if (!external && [base isEqualToString:@"search"]) {
9697 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9700 if (!external && [base isEqualToString:@"sections"]) {
9701 if ([argument isEqualToString:@"all"] || [argument isEqualToString:@"*"])
9703 controller = [[[SectionController alloc] initWithDatabase:database_ source:nil section:argument] autorelease];
9706 if ([base isEqualToString:@"sources"]) {
9707 if ([argument isEqualToString:@"add"]) {
9708 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9709 [(SourcesController *)controller showAddSourcePrompt];
9711 Source *source([database_ sourceWithKey:argument]);
9712 controller = [[[SectionsController alloc] initWithDatabase:database_ source:source] autorelease];
9716 if (!external && [base isEqualToString:@"launch"]) {
9717 [self launchApplicationWithIdentifier:argument suspended:NO];
9720 } else if (!external && [components count] == 3) {
9721 NSString *arg1 = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9722 NSString *arg2 = [[components objectAtIndex:2] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9724 if ([base isEqualToString:@"package"]) {
9725 if ([arg2 isEqualToString:@"settings"]) {
9726 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9727 } else if ([arg2 isEqualToString:@"files"]) {
9728 if (Package *package = [database_ packageWithName:arg1]) {
9729 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9730 [(FileTable *)controller setPackage:package];
9735 if ([base isEqualToString:@"sections"]) {
9736 Source *source([arg1 isEqualToString:@"*"] ? nil : [database_ sourceWithKey:arg1]);
9737 NSString *section([arg2 isEqualToString:@"*"] ? nil : arg2);
9738 controller = [[[SectionController alloc] initWithDatabase:database_ source:source section:section] autorelease];
9742 [controller setDelegate:self];
9746 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9747 CyteViewController *page([self pageForURL:url forExternal:external withReferrer:nil]);
9750 [tabbar_ setUnselectedViewController:page];
9755 - (void) applicationOpenURL:(NSURL *)url {
9756 [super applicationOpenURL:url];
9761 [self openCydiaURL:url forExternal:YES];
9764 - (void) applicationWillResignActive:(UIApplication *)application {
9765 // Stop refreshing if you get a phone call or lock the device.
9766 if ([tabbar_ updating])
9767 [tabbar_ cancelUpdate];
9769 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9770 [super applicationWillResignActive:application];
9773 - (void) saveState {
9774 [[NSDictionary dictionaryWithObjectsAndKeys:
9775 @"InterfaceState", [tabbar_ navigationURLCollection],
9776 @"LastClosed", [NSDate date],
9777 @"InterfaceIndex", [NSNumber numberWithInt:[tabbar_ selectedIndex]],
9778 nil] writeToFile:@ SavedState_ atomically:YES];
9783 - (void) applicationWillTerminate:(UIApplication *)application {
9787 - (void) applicationDidEnterBackground:(UIApplication *)application {
9788 if (kCFCoreFoundationVersionNumber < 1000 && [self isSafeToSuspend])
9789 return [self terminateWithSuccess];
9790 Backgrounded_ = [NSDate date];
9794 - (void) applicationWillEnterForeground:(UIApplication *)application {
9795 if (Backgrounded_ == nil)
9798 NSTimeInterval interval([Backgrounded_ timeIntervalSinceNow]);
9800 if (interval <= -(30*60)) {
9801 [tabbar_ setSelectedIndex:0];
9802 [[[tabbar_ viewControllers] objectAtIndex:0] popToRootViewControllerAnimated:NO];
9805 if (interval <= -(15*60)) {
9806 if (IsReachable("cydia.saurik.com")) {
9807 [tabbar_ beginUpdate];
9808 [appcache_ reloadURLWithCache:YES];
9812 if ([database_ delocked])
9816 - (void) setConfigurationData:(NSString *)data {
9817 static RegEx conffile_r("'(.*)' '(.*)' ([01]) ([01])");
9819 if (!conffile_r(data)) {
9820 lprintf("E:invalid conffile\n");
9824 NSString *ofile = conffile_r[1];
9825 //NSString *nfile = conffile_r[2];
9827 UIAlertView *alert = [[[UIAlertView alloc]
9828 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9829 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9831 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9833 UCLocalize("ACCEPT_NEW_COPY"),
9834 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9838 [alert setContext:@"conffile"];
9839 [alert setNumberOfRows:2];
9843 - (void) addStashController {
9845 stash_ = [[[StashController alloc] init] autorelease];
9846 [window_ addSubview:[stash_ view]];
9849 - (void) removeStashController {
9850 [[stash_ view] removeFromSuperview];
9852 [self unlockSuspend];
9856 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9857 UpdateExternalStatus(1);
9858 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/cydo /usr/libexec/cydia/free.sh"];
9859 UpdateExternalStatus(0);
9861 [self removeStashController];
9862 [self reloadSpringBoard];
9865 - (void) setupViewControllers {
9866 tabbar_ = [[[CydiaTabBarController alloc] initWithDatabase:database_] autorelease];
9868 NSMutableArray *items;
9869 if (kCFCoreFoundationVersionNumber < 800) {
9870 items = [NSMutableArray arrayWithObjects:
9871 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage imageNamed:@"home.png"] tag:0] autorelease],
9872 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage imageNamed:@"install.png"] tag:0] autorelease],
9873 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage imageNamed:@"changes.png"] tag:0] autorelease],
9874 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage imageNamed:@"manage.png"] tag:0] autorelease],
9875 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage imageNamed:@"search.png"] tag:0] autorelease],
9878 items = [NSMutableArray arrayWithObjects:
9879 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage imageNamed:@"home7.png"] selectedImage:[UIImage imageNamed:@"home7s.png"]] autorelease],
9880 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage imageNamed:@"install7.png"] selectedImage:[UIImage imageNamed:@"install7s.png"]] autorelease],
9881 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage imageNamed:@"changes7.png"] selectedImage:[UIImage imageNamed:@"changes7s.png"]] autorelease],
9882 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage imageNamed:@"manage7.png"] selectedImage:[UIImage imageNamed:@"manage7s.png"]] autorelease],
9883 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage imageNamed:@"search7.png"] selectedImage:[UIImage imageNamed:@"search7s.png"]] autorelease],
9887 NSMutableArray *controllers([NSMutableArray array]);
9888 for (UITabBarItem *item in items) {
9889 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9890 [controller setTabBarItem:item];
9891 [controllers addObject:controller];
9893 [tabbar_ setViewControllers:controllers];
9895 [tabbar_ setUpdateDelegate:self];
9898 - (void) _sendMemoryWarningNotification {
9899 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: maybe 4_0?
9900 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationMemoryWarningNotification" object:[UIApplication sharedApplication]];
9902 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
9905 - (void) _sendMemoryWarningNotifications {
9907 [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO];
9913 - (void) applicationDidReceiveMemoryWarning:(UIApplication *)application {
9915 [[NSURLCache sharedURLCache] removeAllCachedResponses];
9918 - (void) applicationDidFinishLaunching:(id)unused {
9919 //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil];
9922 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9923 [self setApplicationSupportsShakeToEdit:NO];
9925 @synchronized (HostConfig_) {
9926 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9929 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9930 initWithMemoryCapacity:524288
9931 diskCapacity:10485760
9932 diskPath:Cache("SDURLCache")
9935 [CydiaWebViewController _initialize];
9937 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9939 // this would disallow http{,s} URLs from accessing this data
9940 //[WebView registerURLSchemeAsLocal:@"cydia"];
9942 Font12_ = [UIFont systemFontOfSize:12];
9943 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9944 Font14_ = [UIFont systemFontOfSize:14];
9945 Font18_ = [UIFont systemFontOfSize:18];
9946 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9947 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9949 essential_ = [NSMutableArray arrayWithCapacity:4];
9950 broken_ = [NSMutableArray arrayWithCapacity:4];
9952 // XXX: I really need this thing... like, seriously... I'm sorry
9953 appcache_ = [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] autorelease];
9954 [appcache_ reloadData];
9956 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9957 [window_ orderFront:self];
9958 [window_ makeKey:self];
9959 [window_ setHidden:NO];
9961 if (access("/.cydia_no_stash", F_OK) == 0);
9965 [self addStashController];
9966 // XXX: this would be much cleaner as a yieldToSelector:
9967 // that way the removeStashController could happen right here inline
9968 // we also could no longer require the useless stash_ field anymore
9969 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9974 int error(stat("/", &root));
9975 _assert(error != -1);
9977 #define Stash_(path) do { \
9978 struct stat folder; \
9979 int error(lstat((path), &folder)); \
9980 if (error != -1 && ( \
9981 folder.st_dev == root.st_dev && \
9982 S_ISDIR(folder.st_mode) \
9983 ) || error == -1 && ( \
9984 errno == ENOENT || \
9989 Stash_("/Applications");
9990 Stash_("/Library/Ringtones");
9991 Stash_("/Library/Wallpaper");
9992 //Stash_("/usr/bin");
9993 Stash_("/usr/include");
9994 Stash_("/usr/share");
9995 //Stash_("/var/lib");
9999 database_ = [Database sharedInstance];
10000 [database_ setDelegate:self];
10002 [window_ setUserInteractionEnabled:NO];
10003 [self setupViewControllers];
10005 CydiaLoadingViewController *loading([[[CydiaLoadingViewController alloc] init] autorelease]);
10006 UINavigationController *navigation([[[UINavigationController alloc] init] autorelease]);
10007 [navigation setViewControllers:[NSArray arrayWithObject:loading]];
10009 emulated_ = [[[CyteTabBarController alloc] init] autorelease];
10010 [emulated_ setViewControllers:[NSArray arrayWithObject:navigation]];
10011 [emulated_ setSelectedIndex:0];
10013 if ([emulated_ respondsToSelector:@selector(concealTabBarSelection)])
10014 [emulated_ concealTabBarSelection];
10016 if ([window_ respondsToSelector:@selector(setRootViewController:)])
10017 [window_ setRootViewController:emulated_];
10019 [window_ addSubview:[emulated_ view]];
10021 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
10025 - (NSArray *) defaultStartPages {
10026 NSMutableArray *standard = [NSMutableArray array];
10027 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
10028 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
10029 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
10030 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
10031 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
10035 - (void) loadData {
10037 if ([emulated_ modalViewController] != nil)
10038 [emulated_ dismissModalViewControllerAnimated:YES];
10039 [window_ setUserInteractionEnabled:NO];
10041 [self reloadDataWithInvocation:nil];
10042 [self refreshIfPossible];
10045 NSDictionary *state([NSDictionary dictionaryWithContentsOfFile:@ SavedState_]);
10047 int savedIndex = [[state objectForKey:@"InterfaceIndex"] intValue];
10048 NSArray *saved = [[[state objectForKey:@"InterfaceState"] mutableCopy] autorelease];
10049 int standardIndex = 0;
10050 NSArray *standard = [self defaultStartPages];
10057 NSDate *closed = [state objectForKey:@"LastClosed"];
10058 if (valid && closed != nil) {
10059 NSTimeInterval interval([closed timeIntervalSinceNow]);
10060 if (interval <= -(30*60))
10064 if (valid && [saved count] != [standard count])
10068 for (unsigned int i = 0; i < [standard count]; i++) {
10069 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
10070 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
10071 // but it's good enough for now.
10072 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
10079 NSArray *items = nil;
10081 [tabbar_ setSelectedIndex:savedIndex];
10084 [tabbar_ setSelectedIndex:standardIndex];
10088 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
10089 NSArray *stack = [items objectAtIndex:tab];
10090 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
10091 NSMutableArray *current = [NSMutableArray array];
10093 for (unsigned int nav = 0; nav < [stack count]; nav++) {
10094 NSString *addr = [stack objectAtIndex:nav];
10095 NSURL *url = [NSURL URLWithString:addr];
10096 CyteViewController *page = [self pageForURL:url forExternal:NO withReferrer:nil];
10098 [current addObject:page];
10101 [navigation setViewControllers:current];
10104 // (Try to) show the startup URL.
10105 if (starturl_ != nil) {
10106 [self openCydiaURL:starturl_ forExternal:YES];
10111 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
10113 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
10114 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
10117 if (item != nil && IsWildcat_) {
10118 [sheet showFromBarButtonItem:item animated:YES];
10120 [sheet showInView:window_];
10124 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
10125 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
10126 [progress setTitle:task];
10127 [progress addProgressEvent:event];
10130 - (void) addProgressEventForTask:(NSArray *)data {
10131 CydiaProgressEvent *event([data objectAtIndex:0]);
10132 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
10133 [self addProgressEvent:event forTask:task];
10136 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
10137 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
10143 id Alloc_(id self, SEL selector) {
10144 id object = alloc_(self, selector);
10145 lprintf("[%s]A-%p\n", self->isa->name, object);
10150 id Dealloc_(id self, SEL selector) {
10151 id object = dealloc_(self, selector);
10152 lprintf("[%s]D-%p\n", self->isa->name, object);
10156 Class $NSURLConnection;
10158 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
10159 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
10161 NSURL *url([copy URL]);
10163 NSString *host([url host]);
10164 NSString *scheme([[url scheme] lowercaseString]);
10166 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
10168 @synchronized (HostConfig_) {
10169 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
10170 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
10171 [copy setHTTPShouldUsePipelining:YES];
10173 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
10174 if ([control isEqualToString:@"max-age=0"])
10175 if ([CachedURLs_ containsObject:url]) {
10177 NSLog(@"~~~: %@", url);
10180 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
10182 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
10183 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
10184 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
10188 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
10194 static CGSize $WAKWindow$screenSize(WAKWindow *self, SEL _cmd) {
10195 CGSize size([[UIScreen mainScreen] bounds].size);
10196 /*if ([$WAKWindow respondsToSelector:@selector(hasLandscapeOrientation)])
10197 if ([$WAKWindow hasLandscapeOrientation])
10198 std::swap(size.width, size.height);*/
10202 Class $NSUserDefaults;
10204 MSHook(id, NSUserDefaults$objectForKey$, NSUserDefaults *self, SEL _cmd, NSString *key) {
10205 if ([key respondsToSelector:@selector(isEqualToString:)] && [key isEqualToString:@"WebKitLocalStorageDatabasePathPreferenceKey"])
10206 return Cache("LocalStorage");
10207 return _NSUserDefaults$objectForKey$(self, _cmd, key);
10210 static NSMutableDictionary *AutoreleaseDeepMutableCopyOfDictionary(CFTypeRef type) {
10213 if (CFGetTypeID(type) != CFDictionaryGetTypeID())
10215 CFTypeRef copy(CFPropertyListCreateDeepCopy(kCFAllocatorDefault, type, kCFPropertyListMutableContainers));
10217 return [(NSMutableDictionary *) copy autorelease];
10220 int main_store(int, char *argv[]);
10222 int main(int argc, char *argv[]) {
10224 const char *argv0(argv[0]);
10225 if (const char *slash = strrchr(argv0, '/'))
10228 else if (!strcmp(argv0, "store"))
10229 return main_store(argc, argv);
10232 int fd(open("/tmp/cydia.log", O_WRONLY | O_APPEND | O_CREAT, 0644));
10236 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10240 UpdateExternalStatus(0);
10242 UIScreen *screen([UIScreen mainScreen]);
10243 if ([screen respondsToSelector:@selector(scale)])
10244 ScreenScale_ = [screen scale];
10248 UIDevice *device([UIDevice currentDevice]);
10249 if ([device respondsToSelector:@selector(userInterfaceIdiom)]) {
10250 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10251 if (idiom == UIUserInterfaceIdiomPad)
10255 Idiom_ = IsWildcat_ ? @"ipad" : @"iphone";
10257 RegEx pattern("([0-9]+\\.[0-9]+).*");
10259 if (pattern([device systemVersion]))
10260 Firmware_ = pattern[1];
10261 if (pattern(Cydia_))
10262 Major_ = pattern[1];
10264 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
10266 HostConfig_ = [[[NSObject alloc] init] autorelease];
10267 @synchronized (HostConfig_) {
10268 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10269 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
10270 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
10271 CachedURLs_ = [NSMutableSet setWithCapacity:32];
10274 NSString *ui(@"ui/ios");
10276 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
10277 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"/%@", Major_]];
10278 UI_ = CydiaURL(ui);
10280 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10282 /* Library Hacks {{{ */
10283 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10285 $WAKWindow = objc_getClass("WAKWindow");
10286 if ($WAKWindow != NULL)
10287 if (Method method = class_getInstanceMethod($WAKWindow, @selector(screenSize)))
10288 method_setImplementation(method, (IMP) &$WAKWindow$screenSize);
10290 $NSURLConnection = objc_getClass("NSURLConnection");
10291 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10292 if (NSURLConnection$init$ != NULL) {
10293 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10294 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10297 $NSUserDefaults = objc_getClass("NSUserDefaults");
10298 Method NSUserDefaults$objectForKey$(class_getInstanceMethod($NSUserDefaults, @selector(objectForKey:)));
10299 if (NSUserDefaults$objectForKey$ != NULL) {
10300 _NSUserDefaults$objectForKey$ = reinterpret_cast<id (*)(NSUserDefaults *, SEL, NSString *)>(method_getImplementation(NSUserDefaults$objectForKey$));
10301 method_setImplementation(NSUserDefaults$objectForKey$, reinterpret_cast<IMP>(&$NSUserDefaults$objectForKey$));
10304 /* Set Locale {{{ */
10305 Locale_ = CFLocaleCopyCurrent();
10306 Languages_ = [NSLocale preferredLanguages];
10308 std::string languages;
10309 const char *translation(NULL);
10311 // XXX: this isn't really a language, but this is compatible with older Cydia builds
10312 if (Locale_ != NULL)
10313 if (const char *language = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String]) {
10314 RegEx pattern("([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?");
10315 if (pattern(language)) {
10316 translation = strdup([pattern->*@"%1$@%2$@" UTF8String]);
10317 languages += translation;
10322 if (Languages_ != nil)
10323 for (NSString *language : Languages_) {
10324 languages += [language UTF8String];
10329 NSLog(@"Setting Language: [%s] %s", translation, languages.c_str());
10331 /* Index Collation {{{ */
10332 if (Class $UILocalizedIndexedCollation = objc_getClass("UILocalizedIndexedCollation")) { @try {
10333 NSBundle *bundle([NSBundle bundleForClass:$UILocalizedIndexedCollation]);
10334 NSString *path([bundle pathForResource:@"UITableViewLocalizedSectionIndex" ofType:@"plist"]);
10335 //path = @"/System/Library/Frameworks/UIKit.framework/.lproj/UITableViewLocalizedSectionIndex.plist";
10336 NSDictionary *dictionary([NSDictionary dictionaryWithContentsOfFile:path]);
10337 _H<UILocalizedIndexedCollation> collation([[[$UILocalizedIndexedCollation alloc] initWithDictionary:dictionary] autorelease]);
10339 CollationLocale_ = MSHookIvar<NSLocale *>(collation, "_locale");
10341 if (kCFCoreFoundationVersionNumber >= 800 && [[CollationLocale_ localeIdentifier] isEqualToString:@"zh@collation=stroke"]) {
10342 CollationThumbs_ = [NSArray arrayWithObjects:@"1",@"•",@"4",@"•",@"7",@"•",@"10",@"•",@"13",@"•",@"16",@"•",@"19",@"A",@"•",@"E",@"•",@"I",@"•",@"M",@"•",@"R",@"•",@"V",@"•",@"Z",@"#",nil];
10343 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})
10344 CollationOffset_.push_back(offset);
10345 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];
10346 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];
10349 CollationThumbs_ = [collation sectionIndexTitles];
10350 for (size_t index(0), end([CollationThumbs_ count]); index != end; ++index)
10351 CollationOffset_.push_back([collation sectionForSectionIndexTitleAtIndex:index]);
10353 CollationTitles_ = [collation sectionTitles];
10354 CollationStarts_ = MSHookIvar<NSArray *>(collation, "_sectionStartStrings");
10356 NSString *&transform(MSHookIvar<NSString *>(collation, "_transform"));
10357 if (&transform != NULL && transform != nil) {
10358 /*if ([collation respondsToSelector:@selector(transformedCollationStringForString:)])
10359 CollationModify_ = [=](NSString *value) { return [collation transformedCollationStringForString:value]; };*/
10360 const UChar *uid(reinterpret_cast<const UChar *>([transform cStringUsingEncoding:NSUnicodeStringEncoding]));
10361 UErrorCode code(U_ZERO_ERROR);
10362 CollationTransl_ = utrans_openU(uid, -1, UTRANS_FORWARD, NULL, 0, NULL, &code);
10363 if (!U_SUCCESS(code))
10364 NSLog(@"%s", u_errorName(code));
10368 } @catch (NSException *e) {
10372 CollationLocale_ = [[[NSLocale alloc] initWithLocaleIdentifier:@"en@collation=dictionary"] autorelease];
10374 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];
10375 for (NSInteger offset(0); offset != 28; ++offset)
10376 CollationOffset_.push_back(offset);
10378 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];
10379 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];
10382 /* Parse Arguments {{{ */
10383 bool substrate(false);
10389 for (int argi(1); argi != argc; ++argi)
10390 if (strcmp(argv[argi], "--") == 0) {
10392 argv[argi] = argv[0];
10398 for (int argi(1); argi != arge; ++argi)
10399 if (strcmp(args[argi], "--substrate") == 0)
10402 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10406 App_ = [[NSBundle mainBundle] bundlePath];
10409 Cache_ = [[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia", @"/var/mobile"] retain];
10410 mkdir([Cache_ UTF8String], 0755);
10412 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10413 alloc_ = alloc->method_imp;
10414 alloc->method_imp = (IMP) &Alloc_;*/
10416 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10417 dealloc_ = dealloc->method_imp;
10418 dealloc->method_imp = (IMP) &Dealloc_;*/
10420 void *gestalt(dlopen("/usr/lib/libMobileGestalt.dylib", RTLD_GLOBAL | RTLD_LAZY));
10421 $MGCopyAnswer = reinterpret_cast<CFStringRef (*)(CFStringRef)>(dlsym(gestalt, "MGCopyAnswer"));
10423 /* System Information {{{ */
10427 size = sizeof(maxproc);
10428 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10429 perror("sysctlbyname(\"kern.maxproc\", ?)");
10430 else if (maxproc < 64) {
10432 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10433 perror("sysctlbyname(\"kern.maxproc\", #)");
10436 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10437 char *osversion = new char[size];
10438 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10439 perror("sysctlbyname(\"kern.osversion\", ?)");
10441 System_ = [NSString stringWithUTF8String:osversion];
10443 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10444 char *machine = new char[size];
10445 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10446 perror("sysctlbyname(\"hw.machine\", ?)");
10448 Machine_ = machine;
10450 int64_t usermem(0);
10451 size = sizeof(usermem);
10452 if (sysctlbyname("hw.usermem", &usermem, &size, NULL, 0) == -1)
10455 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10456 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10457 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10459 UniqueID_ = UniqueIdentifier(device);
10461 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10462 Product_ = [info objectForKey:@"SafariProductVersion"];
10463 Safari_ = [info objectForKey:@"CFBundleVersion"];
10466 NSString *agent([NSString stringWithFormat:@"Cydia/%@ CyF/%.2f", Cydia_, kCFCoreFoundationVersionNumber]);
10468 if (RegEx match = RegEx("([0-9]+(\\.[0-9]+)+).*", Safari_))
10469 agent = [NSString stringWithFormat:@"Safari/%@ %@", match[1], agent];
10470 if (RegEx match = RegEx("([0-9]+[A-Z][0-9]+[a-z]?).*", System_))
10471 agent = [NSString stringWithFormat:@"Mobile/%@ %@", match[1], agent];
10472 if (RegEx match = RegEx("([0-9]+(\\.[0-9]+)+).*", Product_))
10473 agent = [NSString stringWithFormat:@"Version/%@ %@", match[1], agent];
10475 UserAgent_ = agent;
10477 /* Load Database {{{ */
10478 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10481 mkdir("/var/mobile/Library/Cydia", 0755);
10482 MetaFile_.Open("/var/mobile/Library/Cydia/metadata.cb0");
10485 Values_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaValues"), CFSTR("com.saurik.Cydia")));
10486 Sections_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaSections"), CFSTR("com.saurik.Cydia")));
10487 Sources_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaSources"), CFSTR("com.saurik.Cydia")));
10488 Version_ = [(NSNumber *) CFPreferencesCopyAppValue(CFSTR("CydiaVersion"), CFSTR("com.saurik.Cydia")) autorelease];
10491 NSDictionary *metadata([[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease]);
10493 if (Values_ == nil)
10494 Values_ = [metadata objectForKey:@"Values"];
10495 if (Values_ == nil)
10496 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10498 if (Sections_ == nil)
10499 Sections_ = [metadata objectForKey:@"Sections"];
10500 if (Sections_ == nil)
10501 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10503 if (Sources_ == nil)
10504 Sources_ = [metadata objectForKey:@"Sources"];
10505 if (Sources_ == nil)
10506 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10508 // XXX: this wrong, but in a way that doesn't matter :/
10509 if (Version_ == nil)
10510 Version_ = [metadata objectForKey:@"Version"];
10511 if (Version_ == nil)
10512 Version_ = [NSNumber numberWithUnsignedInt:0];
10514 if (NSDictionary *packages = [metadata objectForKey:@"Packages"]) {
10516 CFDictionaryApplyFunction((CFDictionaryRef) packages, &PackageImport, &fail);
10519 NSLog(@"unable to import package preferences... from 2010? oh well :/");
10522 if ([Version_ unsignedIntValue] == 0) {
10523 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10524 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10525 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10526 CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./");
10528 Version_ = [NSNumber numberWithUnsignedInt:1];
10530 if (NSMutableDictionary *cache = [NSMutableDictionary dictionaryWithContentsOfFile:@ CacheState_]) {
10531 [cache removeObjectForKey:@"LastUpdate"];
10532 [cache writeToFile:@ CacheState_ atomically:YES];
10536 _H<NSMutableArray> broken([NSMutableArray array]);
10537 for (NSString *key in (id) Sources_)
10538 if ([key rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"# "]].location != NSNotFound || ![([[Sources_ objectForKey:key] objectForKey:@"URI"] ?: @"/") hasSuffix:@"/"])
10539 [broken addObject:key];
10540 if ([broken count] != 0)
10541 for (NSString *key in (id) broken)
10542 [Sources_ removeObjectForKey:key];
10546 system("/usr/libexec/cydia/cydo /bin/rm -f /var/lib/cydia/metadata.plist");
10549 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10551 if (kCFCoreFoundationVersionNumber > 1000)
10552 system("/usr/libexec/cydia/cydo /usr/libexec/cydia/setnsfpn /var/lib");
10554 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10556 if (access("/User", F_OK) != 0 || version != 6) {
10558 system("/usr/libexec/cydia/cydo /usr/libexec/cydia/firmware.sh");
10562 if (access("/tmp/cydia.chk", F_OK) == 0) {
10563 if (unlink([Cache("pkgcache.bin") UTF8String]) == -1)
10564 _assert(errno == ENOENT);
10565 if (unlink([Cache("srcpkgcache.bin") UTF8String]) == -1)
10566 _assert(errno == ENOENT);
10569 system("/usr/libexec/cydia/cydo /bin/ln -sf /var/mobile/Library/Caches/com.saurik.Cydia/sources.list /etc/apt/sources.list.d/cydia.list");
10571 /* APT Initialization {{{ */
10572 _assert(pkgInitConfig(*_config));
10573 _assert(pkgInitSystem(*_config, _system));
10575 _config->Set("Acquire::AllowInsecureRepositories", true);
10576 _config->Set("Acquire::Check-Valid-Until", false);
10577 _config->Set("Dir::Bin::Methods::store", "/Applications/Cydia.app/store");
10579 _config->Set("pkgCacheGen::ForceEssential", "");
10581 if (translation != NULL)
10582 _config->Set("APT::Acquire::Translation", translation);
10583 _config->Set("Acquire::Languages", languages);
10585 // XXX: this timeout might be important :(
10586 //_config->Set("Acquire::http::Timeout", 15);
10588 _config->Set("Acquire::http::MaxParallel", usermem >= 384 * 1024 * 1024 ? 16 : 3);
10590 mkdir([Cache("archives") UTF8String], 0755);
10591 mkdir([Cache("archives/partial") UTF8String], 0755);
10592 _config->Set("Dir::Cache", [Cache_ UTF8String]);
10594 symlink("/var/lib/apt/extended_states", [Cache("extended_states") UTF8String]);
10595 _config->Set("Dir::State", [Cache_ UTF8String]);
10597 mkdir([Cache("lists") UTF8String], 0755);
10598 mkdir([Cache("lists/partial") UTF8String], 0755);
10599 mkdir([Cache("periodic") UTF8String], 0755);
10600 _config->Set("Dir::State::Lists", [Cache("lists") UTF8String]);
10602 std::string logs("/var/mobile/Library/Logs/Cydia");
10603 mkdir(logs.c_str(), 0755);
10604 _config->Set("Dir::Log", logs);
10606 _config->Set("Dir::Bin::dpkg", "/usr/libexec/cydia/cydo");
10608 /* Color Choices {{{ */
10609 space_ = CGColorSpaceCreateDeviceRGB();
10611 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10612 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10613 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10614 Folder_.Set(space_, 0x8e/255.f, 0x8e/255.f, 0x93/255.f, 1.0);
10615 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10616 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10617 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10618 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10619 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10620 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10622 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10623 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10625 /* UIKit Configuration {{{ */
10626 // XXX: I have a feeling this was important
10627 //UIKeyboardDisableAutomaticAppearance();
10630 $SBSSetInterceptsMenuButtonForever = reinterpret_cast<void (*)(bool)>(dlsym(RTLD_DEFAULT, "SBSSetInterceptsMenuButtonForever"));
10631 $SBSCopyIconImagePNGDataForDisplayIdentifier = reinterpret_cast<NSData *(*)(NSString *)>(dlsym(RTLD_DEFAULT, "SBSCopyIconImagePNGDataForDisplayIdentifier"));
10633 const char *symbol(kCFCoreFoundationVersionNumber >= 800 ? "MGGetBoolAnswer" : "GSSystemHasCapability");
10634 BOOL (*GSSystemHasCapability)(CFStringRef) = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, symbol));
10635 bool fast = GSSystemHasCapability != NULL && GSSystemHasCapability(CFSTR("armv7"));
10637 PulseInterval_ = fast ? 50000 : 500000;
10639 Colon_ = UCLocalize("COLON_DELIMITED");
10640 Elision_ = UCLocalize("ELISION");
10641 Error_ = UCLocalize("ERROR");
10642 Warning_ = UCLocalize("WARNING");
10645 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10647 CGColorSpaceRelease(space_);
10648 CFRelease(Locale_);