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;
1138 - (bool) hasPackages;
1140 - (void) _readCydia:(NSNumber *)fd;
1141 - (void) _readStatus:(NSNumber *)fd;
1142 - (void) _readOutput:(NSNumber *)fd;
1146 - (Package *) packageWithName:(NSString *)name;
1148 - (pkgCacheFile &) cache;
1149 - (pkgDepCache::Policy *) policy;
1150 - (pkgRecords *) records;
1151 - (pkgProblemResolver *) resolver;
1152 - (pkgAcquire &) fetcher;
1153 - (pkgSourceList &) list;
1154 - (NSArray *) packages;
1155 - (NSArray *) sources;
1156 - (Source *) sourceWithKey:(NSString *)key;
1157 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1165 - (void) updateWithStatus:(CancelStatus &)status;
1167 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1169 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1170 - (NSObject<ProgressDelegate> *) progressDelegate;
1172 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1173 - (void) setFetch:(bool)fetch forURI:(const char *)uri;
1174 - (void) resetFetch;
1176 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1180 /* SourceStatus {{{ */
1181 class SourceStatus :
1185 _transient NSObject<FetchDelegate> *delegate_;
1186 _transient Database *database_;
1187 std::set<std::string> fetches_;
1190 SourceStatus(NSObject<FetchDelegate> *delegate, Database *database) :
1191 delegate_(delegate),
1196 void Set(bool fetch, const std::string &uri) {
1198 if (!fetches_.insert(uri).second)
1201 if (fetches_.erase(uri) == 0)
1205 //printf("Set(%s, %s)\n", fetch ? "true" : "false", uri.c_str());
1206 [database_ setFetch:fetch forURI:uri.c_str()];
1209 _finline void Set(bool fetch, pkgAcquire::Item *item) {
1210 /*unsigned long ID(fetch ? 1 : 0);
1214 Set(fetch, item->DescURI());
1217 void Log(const char *tag, pkgAcquire::Item *item) {
1218 //printf("%s(%s) S:%u Q:%u\n", tag, item->DescURI().c_str(), item->Status, item->QueueCounter);
1221 virtual void Fetch(pkgAcquire::ItemDesc &desc) {
1222 Log("Fetch", desc.Owner);
1223 Set(true, desc.Owner);
1226 virtual void Done(pkgAcquire::ItemDesc &desc) {
1227 Log("Done", desc.Owner);
1228 Set(false, desc.Owner);
1231 virtual void Fail(pkgAcquire::ItemDesc &desc) {
1232 Log("Fail", desc.Owner);
1233 Set(false, desc.Owner);
1236 virtual bool Pulse_(pkgAcquire *Owner) {
1237 std::set<std::string> fetches;
1238 for (pkgAcquire::ItemCIterator item(Owner->ItemsBegin()); item != Owner->ItemsEnd(); ++item) {
1240 if ((*item)->QueueCounter == 0)
1242 else switch ((*item)->Status) {
1243 case pkgAcquire::Item::StatFetching:
1244 fetches.insert((*item)->DescURI());
1253 Log(fetch ? "Pulse<true>" : "Pulse<false>", *item);
1257 std::vector<std::string> stops;
1258 std::set_difference(fetches_.begin(), fetches_.end(), fetches.begin(), fetches.end(), std::back_insert_iterator<std::vector<std::string>>(stops));
1259 for (std::vector<std::string>::const_iterator stop(stops.begin()); stop != stops.end(); ++stop) {
1260 //printf("Stop(%s)\n", stop->c_str());
1264 return ![delegate_ isSourceCancelled];
1267 virtual void Stop() {
1268 pkgAcquireStatus::Stop();
1269 [database_ resetFetch];
1273 /* ProgressEvent Implementation {{{ */
1274 @implementation CydiaProgressEvent
1276 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1277 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1280 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1281 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1282 [event setPackage:package];
1286 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItemDesc:(pkgAcquire::ItemDesc &)desc {
1287 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1289 NSString *description([NSString stringWithUTF8String:desc.Description.c_str()]);
1290 NSArray *fields([description componentsSeparatedByString:@" "]);
1291 [event setItem:fields];
1293 if ([fields count] > 3) {
1294 [event setPackage:[fields objectAtIndex:2]];
1295 [event setVersion:[fields objectAtIndex:3]];
1298 [event setURL:[NSString stringWithUTF8String:desc.URI.c_str()]];
1303 + (NSArray *) _attributeKeys {
1304 return [NSArray arrayWithObjects:
1314 - (NSArray *) attributeKeys {
1315 return [[self class] _attributeKeys];
1318 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1319 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1322 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1323 if ((self = [super init]) != nil) {
1329 - (NSString *) message {
1333 - (NSString *) type {
1337 - (NSArray *) item {
1338 return (id) item_ ?: [NSNull null];
1341 - (void) setItem:(NSArray *)item {
1345 - (NSString *) package {
1346 return (id) package_ ?: [NSNull null];
1349 - (void) setPackage:(NSString *)package {
1353 - (NSString *) url {
1354 return (id) url_ ?: [NSNull null];
1357 - (void) setURL:(NSString *)url {
1361 - (void) setVersion:(NSString *)version {
1365 - (NSString *) version {
1366 return (id) version_ ?: [NSNull null];
1369 - (NSString *) compound:(NSString *)value {
1371 NSString *mode(nil); {
1372 NSString *type([self type]);
1373 if ([type isEqualToString:kCydiaProgressEventTypeError])
1374 mode = UCLocalize("ERROR");
1375 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1376 mode = UCLocalize("WARNING");
1380 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1386 - (NSString *) compoundMessage {
1387 return [self compound:[self message]];
1390 - (NSString *) compoundTitle {
1393 if (package_ == nil)
1395 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1396 title = [package name];
1400 return [self compound:title];
1406 // Cytore Definitions {{{
1407 struct PackageValue :
1410 Cytore::Offset<PackageValue> next_;
1412 uint32_t index_ : 23;
1413 uint32_t subscribed_ : 1;
1430 Cytore::Offset<PackageValue> packages_[1 << 16];
1433 static Cytore::File<MetaValue> MetaFile_;
1435 // Cytore Helper Functions {{{
1436 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1437 SplitHash nhash = { hashlittle(name, length) };
1439 PackageValue *metadata;
1441 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1442 for (;; offset = &metadata->next_) { if (offset->IsNull()) {
1443 *offset = MetaFile_.New<PackageValue>(length + 1);
1444 metadata = &MetaFile_.Get(*offset);
1446 if (metadata == NULL) {
1450 metadata = new PackageValue();
1451 memset(metadata, 0, sizeof(*metadata));
1454 memcpy(metadata->name_, name, length);
1455 metadata->name_[length] = '\0';
1456 metadata->nhash_ = nhash.u16[1];
1458 metadata = &MetaFile_.Get(*offset);
1459 if (metadata->nhash_ != nhash.u16[1])
1461 if (strncmp(metadata->name_, name, length) != 0)
1463 if (metadata->name_[length] != '\0')
1470 static void PackageImport(const void *key, const void *value, void *context) {
1471 bool &fail(*reinterpret_cast<bool *>(context));
1474 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1475 NSLog(@"failed to import package %@", key);
1479 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1480 NSDictionary *package((NSDictionary *) value);
1482 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1483 if ([subscribed boolValue] && !metadata->subscribed_)
1484 metadata->subscribed_ = true;
1486 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1487 time_t time([date timeIntervalSince1970]);
1488 if (metadata->first_ > time || metadata->first_ == 0)
1489 metadata->first_ = time;
1492 NSDate *date([package objectForKey:@"LastSeen"]);
1493 NSString *version([package objectForKey:@"LastVersion"]);
1495 if (date != nil && version != nil) {
1496 time_t time([date timeIntervalSince1970]);
1497 if (metadata->last_ < time || metadata->last_ == 0)
1498 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1499 size_t length(strlen(buffer));
1500 uint16_t vhash(hashlittle(buffer, length));
1502 size_t capped(std::min<size_t>(8, length));
1503 char *latest(buffer + length - capped);
1505 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1506 metadata->vhash_ = vhash;
1508 metadata->last_ = time;
1514 static NSDate *GetStatusDate() {
1515 return [[[NSFileManager defaultManager] attributesOfItemAtPath:@"/var/lib/dpkg/status" error:NULL] fileModificationDate];
1518 static void SaveConfig(NSObject *lock) {
1519 @synchronized (lock) {
1525 CFPreferencesSetMultiple((CFDictionaryRef) [NSDictionary dictionaryWithObjectsAndKeys:
1526 Values_, @"CydiaValues",
1527 Sections_, @"CydiaSections",
1528 (id) Sources_, @"CydiaSources",
1529 Version_, @"CydiaVersion",
1530 nil], NULL, CFSTR("com.saurik.Cydia"), kCFPreferencesCurrentUser, kCFPreferencesCurrentHost);
1532 if (!CFPreferencesAppSynchronize(CFSTR("com.saurik.Cydia")))
1533 NSLog(@"CFPreferencesAppSynchronize(com.saurik.Cydia) == false");
1535 CydiaWriteSources();
1538 /* Source Class {{{ */
1539 @interface Source : NSObject {
1541 Database *database_;
1544 CYString depiction_;
1545 CYString description_;
1551 CYString distribution_;
1557 _H<NSString> authority_;
1559 CYString defaultIcon_;
1561 _H<NSMutableDictionary> record_;
1564 std::set<std::string> fetches_;
1565 std::set<std::string> files_;
1566 _transient NSObject<SourceDelegate> *delegate_;
1569 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(CYPool *)pool;
1571 - (NSComparisonResult) compareByName:(Source *)source;
1573 - (NSString *) depictionForPackage:(NSString *)package;
1574 - (NSString *) supportForPackage:(NSString *)package;
1576 - (metaIndex *) metaIndex;
1577 - (NSDictionary *) record;
1580 - (NSString *) rooturi;
1581 - (NSString *) distribution;
1582 - (NSString *) type;
1585 - (NSString *) host;
1587 - (NSString *) name;
1588 - (NSString *) shortDescription;
1589 - (NSString *) label;
1590 - (NSString *) origin;
1591 - (NSString *) version;
1593 - (NSString *) defaultIcon;
1594 - (NSURL *) iconURL;
1596 - (void) setFetch:(bool)fetch forURI:(const char *)uri;
1597 - (void) resetFetch;
1601 @implementation Source
1603 + (NSString *) webScriptNameForSelector:(SEL)selector {
1605 else if (selector == @selector(addSection:))
1606 return @"addSection";
1607 else if (selector == @selector(getField:))
1609 else if (selector == @selector(removeSection:))
1610 return @"removeSection";
1611 else if (selector == @selector(remove))
1617 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1618 return [self webScriptNameForSelector:selector] == nil;
1621 + (NSArray *) _attributeKeys {
1622 return [NSArray arrayWithObjects:
1633 @"shortDescription",
1640 - (NSArray *) attributeKeys {
1641 return [[self class] _attributeKeys];
1644 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1645 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1648 - (metaIndex *) metaIndex {
1652 - (void) setMetaIndex:(metaIndex *)index inPool:(CYPool *)pool {
1653 trusted_ = index->IsTrusted();
1655 uri_.set(pool, index->GetURI());
1656 distribution_.set(pool, index->GetDist());
1657 type_.set(pool, index->GetType());
1659 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1660 if (dindex != NULL) {
1661 std::string file(dindex->MetaIndexURI(""));
1662 base_.set(pool, file);
1665 _profile(Source$setMetaIndex$GetIndexes)
1666 dindex->GetIndexes(&acquire, true);
1668 _profile(Source$setMetaIndex$DescURI)
1669 for (pkgAcquire::ItemIterator item(acquire.ItemsBegin()); item != acquire.ItemsEnd(); item++) {
1670 std::string file((*item)->DescURI());
1671 files_.insert(file);
1672 if (file.length() < sizeof("Packages.bz2") || file.substr(file.length() - sizeof("Packages.bz2")) != "/Packages.bz2")
1674 file = file.substr(0, file.length() - 4);
1675 files_.insert(file);
1676 files_.insert(file + ".gz");
1677 files_.insert(file + "Index");
1682 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1685 pkgTagFile tags(&fd);
1687 pkgTagSection section;
1694 {"default-icon", &defaultIcon_},
1695 {"depiction", &depiction_},
1696 {"description", &description_},
1698 {"origin", &origin_},
1699 {"support", &support_},
1700 {"version", &version_},
1703 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1704 const char *start, *end;
1706 if (section.Find(names[i].name_, start, end)) {
1707 CYString &value(*names[i].value_);
1708 value.set(pool, start, end - start);
1714 record_ = [Sources_ objectForKey:[self key]];
1716 NSURL *url([NSURL URLWithString:uri_]);
1720 host_ = [host_ lowercaseString];
1725 authority_ = [url path];
1728 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(CYPool *)pool {
1729 if ((self = [super init]) != nil) {
1730 era_ = [database era];
1731 database_ = database;
1734 _profile(Source$initWithMetaIndex$setMetaIndex)
1735 [self setMetaIndex:index inPool:pool];
1740 - (NSString *) getField:(NSString *)name {
1741 @synchronized (database_) {
1742 if ([database_ era] != era_ || index_ == NULL)
1745 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index_));
1750 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly)) {
1755 pkgTagFile tags(&fd);
1757 pkgTagSection section;
1760 const char *start, *end;
1761 if (!section.Find([name UTF8String], start, end))
1762 return (NSString *) [NSNull null];
1764 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
1767 - (NSComparisonResult) compareByName:(Source *)source {
1768 NSString *lhs = [self name];
1769 NSString *rhs = [source name];
1771 if ([lhs length] != 0 && [rhs length] != 0) {
1772 unichar lhc = [lhs characterAtIndex:0];
1773 unichar rhc = [rhs characterAtIndex:0];
1775 if (isalpha(lhc) && !isalpha(rhc))
1776 return NSOrderedAscending;
1777 else if (!isalpha(lhc) && isalpha(rhc))
1778 return NSOrderedDescending;
1781 return [lhs compare:rhs options:LaxCompareOptions_];
1784 - (NSString *) depictionForPackage:(NSString *)package {
1785 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1788 - (NSString *) supportForPackage:(NSString *)package {
1789 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1792 - (NSArray *) sections {
1793 return record_ == nil ? (id) [NSNull null] : [record_ objectForKey:@"Sections"] ?: [NSArray array];
1796 - (void) _addSection:(NSString *)section {
1799 else if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) {
1800 if (![sections containsObject:section])
1801 [sections addObject:section];
1803 [record_ setObject:[NSMutableArray arrayWithObject:section] forKey:@"Sections"];
1806 - (bool) addSection:(NSString *)section {
1810 [self performSelectorOnMainThread:@selector(_addSection:) withObject:section waitUntilDone:NO];
1814 - (void) _removeSection:(NSString *)section {
1818 if (NSMutableArray *sections = [record_ objectForKey:@"Sections"])
1819 if ([sections containsObject:section])
1820 [sections removeObject:section];
1823 - (bool) removeSection:(NSString *)section {
1827 [self performSelectorOnMainThread:@selector(_removeSection:) withObject:section waitUntilDone:NO];
1832 [Sources_ removeObjectForKey:[self key]];
1836 bool value(record_ != nil);
1837 [self performSelectorOnMainThread:@selector(_remove) withObject:nil waitUntilDone:NO];
1841 - (NSDictionary *) record {
1849 - (NSString *) rooturi {
1853 - (NSString *) distribution {
1854 return distribution_;
1857 - (NSString *) type {
1861 - (NSString *) baseuri {
1862 return base_.empty() ? nil : (id) base_;
1865 - (NSString *) iconuri {
1866 if (NSString *base = [self baseuri])
1867 return [base stringByAppendingString:@"CydiaIcon.png"];
1872 - (NSURL *) iconURL {
1873 if (NSString *uri = [self iconuri])
1874 return [NSURL URLWithString:uri];
1878 - (NSString *) key {
1879 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1882 - (NSString *) host {
1886 - (NSString *) name {
1887 return origin_.empty() ? (id) authority_ : origin_;
1890 - (NSString *) shortDescription {
1891 return description_;
1894 - (NSString *) label {
1895 return label_.empty() ? (id) authority_ : label_;
1898 - (NSString *) origin {
1902 - (NSString *) version {
1906 - (NSString *) defaultIcon {
1907 return defaultIcon_;
1910 - (void) setDelegate:(NSObject<SourceDelegate> *)delegate {
1911 delegate_ = delegate;
1915 return !fetches_.empty();
1918 - (void) setFetch:(bool)fetch forURI:(const char *)uri {
1920 if (fetches_.erase(uri) == 0)
1922 } else if (files_.find(uri) == files_.end())
1924 else if (!fetches_.insert(uri).second)
1927 [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:[self fetch]] waitUntilDone:NO];
1930 - (void) resetFetch {
1932 [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:NO];
1937 /* CydiaOperation Class {{{ */
1938 @interface CydiaOperation : NSObject {
1939 _H<NSString> operator_;
1940 _H<NSString> value_;
1943 - (NSString *) operator;
1944 - (NSString *) value;
1948 @implementation CydiaOperation
1950 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1951 if ((self = [super init]) != nil) {
1952 operator_ = [NSString stringWithUTF8String:_operator];
1953 value_ = [NSString stringWithUTF8String:value];
1957 + (NSArray *) _attributeKeys {
1958 return [NSArray arrayWithObjects:
1964 - (NSArray *) attributeKeys {
1965 return [[self class] _attributeKeys];
1968 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1969 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1972 - (NSString *) operator {
1976 - (NSString *) value {
1982 /* CydiaClause Class {{{ */
1983 @interface CydiaClause : NSObject {
1984 _H<NSString> package_;
1985 _H<CydiaOperation> version_;
1988 - (NSString *) package;
1989 - (CydiaOperation *) version;
1993 @implementation CydiaClause
1995 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1996 if ((self = [super init]) != nil) {
1997 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1999 if (const char *version = dep.TargetVer())
2000 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
2002 version_ = (id) [NSNull null];
2006 + (NSArray *) _attributeKeys {
2007 return [NSArray arrayWithObjects:
2013 - (NSArray *) attributeKeys {
2014 return [[self class] _attributeKeys];
2017 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2018 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2021 - (NSString *) package {
2025 - (CydiaOperation *) version {
2031 /* CydiaRelation Class {{{ */
2032 @interface CydiaRelation : NSObject {
2033 _H<NSString> relationship_;
2034 _H<NSMutableArray> clauses_;
2037 - (NSString *) relationship;
2038 - (NSArray *) clauses;
2042 @implementation CydiaRelation
2044 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
2045 if ((self = [super init]) != nil) {
2046 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
2047 clauses_ = [NSMutableArray arrayWithCapacity:8];
2049 pkgCache::DepIterator start;
2050 pkgCache::DepIterator end;
2051 dep.GlobOr(start, end); // ++dep
2054 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
2056 // yes, seriously. (wtf?)
2064 + (NSArray *) _attributeKeys {
2065 return [NSArray arrayWithObjects:
2071 - (NSArray *) attributeKeys {
2072 return [[self class] _attributeKeys];
2075 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2076 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2079 - (NSString *) relationship {
2080 return relationship_;
2083 - (NSArray *) clauses {
2087 - (void) addClause:(CydiaClause *)clause {
2088 [clauses_ addObject:clause];
2093 /* Package Class {{{ */
2094 struct ParsedPackage {
2098 CYString architecture_;
2101 CYString depiction_;
2108 @interface Package : NSObject {
2110 @public uint32_t role_ : 3;
2111 uint32_t essential_ : 1;
2112 uint32_t obsolete_ : 1;
2113 uint32_t ignored_ : 1;
2114 uint32_t pooled_ : 1;
2120 _transient Database *database_;
2122 pkgCache::VerIterator version_;
2123 pkgCache::PkgIterator iterator_;
2124 pkgCache::VerFileIterator file_;
2128 CYString transform_;
2131 CYString installed_;
2134 const char *section_;
2135 _transient NSString *section$_;
2139 PackageValue *metadata_;
2140 ParsedPackage *parsed_;
2142 _H<NSMutableArray> tags_;
2145 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database;
2146 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database;
2148 - (pkgCache::PkgIterator) iterator;
2151 - (NSString *) section;
2152 - (NSString *) simpleSection;
2154 - (NSString *) longSection;
2155 - (NSString *) shortSection;
2159 - (MIMEAddress *) maintainer;
2161 - (NSString *) longDescription;
2162 - (NSString *) shortDescription;
2165 - (PackageValue *) metadata;
2168 - (bool) subscribed;
2169 - (bool) setSubscribed:(bool)subscribed;
2173 - (NSString *) latest;
2174 - (NSString *) installed;
2175 - (BOOL) uninstalled;
2177 - (BOOL) upgradableAndEssential:(BOOL)essential;
2180 - (BOOL) unfiltered;
2184 - (BOOL) halfConfigured;
2185 - (BOOL) halfInstalled;
2187 - (NSString *) mode;
2190 - (NSString *) name;
2192 - (NSString *) homepage;
2193 - (NSString *) depiction;
2194 - (MIMEAddress *) author;
2196 - (NSString *) support;
2198 - (NSArray *) files;
2199 - (NSArray *) warnings;
2200 - (NSArray *) applications;
2202 - (Source *) source;
2205 - (BOOL) matches:(NSArray *)query;
2207 - (BOOL) hasTag:(NSString *)tag;
2208 - (NSString *) primaryPurpose;
2209 - (NSArray *) purposes;
2210 - (bool) isCommercial;
2212 - (void) setIndex:(size_t)index;
2214 - (CYString &) cyname;
2216 - (uint32_t) compareBySection:(NSArray *)sections;
2223 uint32_t PackageChangesRadix(Package *self, void *) {
2228 uint32_t timestamp : 30;
2229 uint32_t ignored : 1;
2230 uint32_t upgradable : 1;
2234 bool upgradable([self upgradableAndEssential:YES]);
2235 value.bits.upgradable = upgradable ? 1 : 0;
2238 value.bits.timestamp = 0;
2239 value.bits.ignored = [self ignored] ? 0 : 1;
2240 value.bits.upgradable = 1;
2242 value.bits.timestamp = [self seen] >> 2;
2243 value.bits.ignored = 0;
2244 value.bits.upgradable = 0;
2247 return _not(uint32_t) - value.key;
2250 CYString &(*PackageName)(Package *self, SEL sel);
2252 uint32_t PackagePrefixRadix(Package *self, void *context) {
2253 size_t offset(reinterpret_cast<size_t>(context));
2254 CYString &name(PackageName(self, @selector(cyname)));
2256 size_t size(name.size());
2259 char *text(name.data());
2262 if (!isdigit(text[0]))
2266 while (size != digits && isdigit(text[digits]))
2274 if (offset == 0 && zeros != 0) {
2275 memset(data, '0', zeros);
2276 memcpy(data + zeros, text, 4 - zeros);
2278 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2279 if (size <= offset - zeros)
2282 text += offset - zeros;
2283 size -= offset - zeros;
2286 memcpy(data, text, 4);
2288 memcpy(data, text, size);
2289 memset(data + size, 0, 4 - size);
2292 for (size_t i(0); i != 4; ++i)
2293 if (isalpha(data[i]))
2301 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2303 /* XXX: ntohl may be more honest */
2304 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2307 CFComparisonResult StringNameCompare(CFStringRef lhn, CFStringRef rhn, size_t length) {
2308 _profile(PackageNameCompare)
2310 return rhn == NULL ? kCFCompareEqualTo : kCFCompareLessThan;
2311 else if (rhn == NULL)
2312 return kCFCompareGreaterThan;
2314 CFIndex length(CFStringGetLength(lhn));
2316 _profile(PackageNameCompare$NumbersLast)
2317 if (length != 0 && CFStringGetLength(rhn) != 0) {
2318 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2319 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2320 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2321 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2322 return lha ? kCFCompareLessThan : kCFCompareGreaterThan;
2326 _profile(PackageNameCompare$Compare)
2327 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, (CFLocaleRef) (id) CollationLocale_);
2332 _finline CFComparisonResult StringNameCompare(NSString *lhn, NSString*rhn, size_t length) {
2333 return StringNameCompare((CFStringRef) lhn, (CFStringRef) rhn, length);
2336 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2337 CYString &lhn(PackageName(lhs, @selector(cyname)));
2338 NSString *rhn(PackageName(rhs, @selector(cyname)));
2339 return StringNameCompare(lhn, rhn, lhn.size());
2342 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *arg) {
2343 return PackageNameCompare(*lhs, *rhs, arg);
2346 struct PackageNameOrdering :
2347 std::binary_function<Package *, Package *, bool>
2349 _finline bool operator ()(Package *lhs, Package *rhs) const {
2350 return PackageNameCompare(lhs, rhs, NULL) == kCFCompareLessThan;
2354 @implementation Package
2356 - (NSString *) description {
2357 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2363 if (parsed_ != NULL)
2368 + (NSString *) webScriptNameForSelector:(SEL)selector {
2370 else if (selector == @selector(clear))
2372 else if (selector == @selector(getField:))
2374 else if (selector == @selector(getRecord))
2375 return @"getRecord";
2376 else if (selector == @selector(hasTag:))
2378 else if (selector == @selector(install))
2380 else if (selector == @selector(remove))
2386 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2387 return [self webScriptNameForSelector:selector] == nil;
2390 + (NSArray *) _attributeKeys {
2391 return [NSArray arrayWithObjects:
2412 @"shortDescription",
2425 - (NSArray *) attributeKeys {
2426 return [[self class] _attributeKeys];
2429 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2430 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2433 - (NSArray *) relations {
2434 @synchronized (database_) {
2435 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2436 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2437 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2441 - (NSString *) architecture {
2443 @synchronized (database_) {
2444 return parsed_->architecture_.empty() ? [NSNull null] : (id) parsed_->architecture_;
2447 - (NSString *) getField:(NSString *)name {
2448 @synchronized (database_) {
2449 if ([database_ era] != era_ || file_.end())
2452 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2454 const char *start, *end;
2455 if (!parser.Find([name UTF8String], start, end))
2456 return (NSString *) [NSNull null];
2458 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2461 - (NSString *) getRecord {
2462 @synchronized (database_) {
2463 if ([database_ era] != era_ || file_.end())
2466 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2468 const char *start, *end;
2469 parser.GetRec(start, end);
2471 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2475 if (parsed_ != NULL)
2477 @synchronized (database_) {
2478 if ([database_ era] != era_ || file_.end())
2481 ParsedPackage *parsed(new ParsedPackage);
2484 _profile(Package$parse)
2485 pkgRecords::Parser *parser;
2487 _profile(Package$parse$Lookup)
2488 parser = &[database_ records]->Lookup(file_);
2494 _profile(Package$parse$Find)
2499 {"architecture", &parsed->architecture_},
2500 {"icon", &parsed->icon_},
2501 {"depiction", &parsed->depiction_},
2502 {"homepage", &parsed->homepage_},
2503 {"website", &website},
2505 {"support", &parsed->support_},
2506 {"author", &parsed->author_},
2507 {"md5sum", &parsed->md5sum_},
2510 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2511 const char *start, *end;
2513 if (parser->Find(names[i].name_, start, end)) {
2514 CYString &value(*names[i].value_);
2515 _profile(Package$parse$Value)
2516 value.set(pool_, start, end - start);
2522 _profile(Package$parse$Tagline)
2523 parsed->tagline_.set(pool_, parser->ShortDesc());
2526 _profile(Package$parse$Retain)
2527 if (parsed->homepage_.empty())
2528 parsed->homepage_ = website;
2529 if (parsed->homepage_ == parsed->depiction_)
2530 parsed->homepage_.clear();
2531 if (parsed->support_.empty())
2532 parsed->support_ = bugs;
2537 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database {
2538 if ((self = [super init]) != nil) {
2539 _profile(Package$initWithVersion)
2541 pool_ = new CYPool();
2547 database_ = database;
2548 era_ = [database era];
2552 pkgCache::PkgIterator iterator(version_.ParentPkg());
2553 iterator_ = iterator;
2555 _profile(Package$initWithVersion$Version)
2556 file_ = version_.FileList();
2559 _profile(Package$initWithVersion$Cache)
2560 name_.set(NULL, version_.Display());
2562 latest_.set(NULL, StripVersion_(version_.VerStr()));
2564 pkgCache::VerIterator current(iterator.CurrentVer());
2566 installed_.set(NULL, StripVersion_(current.VerStr()));
2569 _profile(Package$initWithVersion$Transliterate) do {
2570 if (CollationTransl_ == NULL)
2575 _profile(Package$initWithVersion$Transliterate$utf8)
2576 const uint8_t *data(reinterpret_cast<const uint8_t *>(name_.data()));
2577 for (size_t i(0), e(name_.size()); i != e; ++i)
2578 if (data[i] >= 0x80)
2583 UErrorCode code(U_ZERO_ERROR);
2586 _profile(Package$initWithVersion$Transliterate$u_strFromUTF8WithSub)
2587 CollationString_.resize(name_.size());
2588 u_strFromUTF8WithSub(&CollationString_[0], CollationString_.size(), &length, name_.data(), name_.size(), 0xfffd, NULL, &code);
2589 if (!U_SUCCESS(code))
2591 CollationString_.resize(length);
2594 _profile(Package$initWithVersion$Transliterate$utrans_trans)
2595 length = CollationString_.size();
2596 utrans_trans(CollationTransl_, reinterpret_cast<UReplaceable *>(&CollationString_), &CollationUCalls_, 0, &length, &code);
2597 if (!U_SUCCESS(code))
2599 _assert(CollationString_.size() == length);
2602 _profile(Package$initWithVersion$Transliterate$u_strToUTF8WithSub$preflight)
2603 u_strToUTF8WithSub(NULL, 0, &length, CollationString_.data(), CollationString_.size(), 0xfffd, NULL, &code);
2604 if (code == U_BUFFER_OVERFLOW_ERROR)
2605 code = U_ZERO_ERROR;
2606 else if (!U_SUCCESS(code))
2611 _profile(Package$initWithVersion$Transliterate$apr_palloc)
2612 transform = pool_->malloc<char>(length);
2614 _profile(Package$initWithVersion$Transliterate$u_strToUTF8WithSub$transform)
2615 u_strToUTF8WithSub(transform, length, NULL, CollationString_.data(), CollationString_.size(), 0xfffd, NULL, &code);
2616 if (!U_SUCCESS(code))
2620 transform_.set(NULL, transform, length);
2621 } while (false); _end
2623 _profile(Package$initWithVersion$Tags)
2625 pkgCache::TagIterator tag(version_.TagList());
2627 pkgCache::TagIterator tag(iterator.TagList());
2630 tags_ = [NSMutableArray arrayWithCapacity:8];
2632 goto tag; for (; !tag.end(); ++tag) tag: {
2633 const char *name(tag.Name());
2634 NSString *string((NSString *) CYStringCreate(name));
2638 [tags_ addObject:[string autorelease]];
2640 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2641 if (strcmp(name + 6, "enduser") == 0)
2643 else if (strcmp(name + 6, "hacker") == 0)
2645 else if (strcmp(name + 6, "developer") == 0)
2647 else if (strcmp(name + 6, "cydia") == 0)
2653 if (strncmp(name, "cydia::", 7) == 0) {
2654 if (strcmp(name + 7, "essential") == 0)
2656 else if (strcmp(name + 7, "obsolete") == 0)
2663 _profile(Package$initWithVersion$Metadata)
2664 const char *mixed(iterator.Name());
2665 size_t size(strlen(mixed));
2666 static const size_t prefix(sizeof("/var/lib/dpkg/info/") - 1);
2667 char lower[prefix + size + 5 + 1];
2669 for (size_t i(0); i != size; ++i)
2670 lower[prefix + i] = mixed[i] | 0x20;
2672 if (!installed_.empty()) {
2673 memcpy(lower, "/var/lib/dpkg/info/", prefix);
2674 memcpy(lower + prefix + size, ".list", 6);
2676 if (stat(lower, &info) != -1)
2677 upgraded_ = info.st_birthtime;
2680 PackageValue *metadata(PackageFind(lower + prefix, size));
2681 metadata_ = metadata;
2683 id_.set(NULL, metadata->name_, size);
2685 const char *latest(version_.VerStr());
2686 size_t length(strlen(latest));
2688 uint16_t vhash(hashlittle(latest, length));
2690 size_t capped(std::min<size_t>(8, length));
2691 latest = latest + length - capped;
2693 if (metadata->first_ == 0)
2694 metadata->first_ = now_;
2696 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2697 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2698 metadata->vhash_ = vhash;
2699 metadata->last_ = now_;
2700 } else if (metadata->last_ == 0)
2701 metadata->last_ = metadata->first_;
2704 _profile(Package$initWithVersion$Section)
2705 section_ = version_.Section();
2708 _profile(Package$initWithVersion$Flags)
2709 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2710 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2715 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database {
2716 pkgCache::VerIterator version;
2718 _profile(Package$packageWithIterator$GetCandidateVer)
2719 version = [database policy]->GetCandidateVer(iterator);
2727 _profile(Package$packageWithIterator$Allocate)
2728 package = [Package allocWithZone:zone];
2731 _profile(Package$packageWithIterator$Initialize)
2733 initWithVersion:version
2740 _profile(Package$packageWithIterator$Autorelease)
2741 package = [package autorelease];
2747 - (pkgCache::PkgIterator) iterator {
2751 - (NSArray *) downgrades {
2752 NSMutableArray *versions([NSMutableArray arrayWithCapacity:4]);
2754 for (auto version(iterator_.VersionList()); !version.end(); ++version) {
2755 if (version == version_)
2757 Package *package([[[Package allocWithZone:NULL] initWithVersion:version withZone:NULL inPool:NULL database:database_] autorelease]);
2758 if ([package source] == nil)
2760 [versions addObject:package];
2766 - (NSString *) section {
2767 if (section$_ == nil) {
2768 if (section_ == NULL)
2771 _profile(Package$section$mappedSectionForPointer)
2772 section$_ = [database_ mappedSectionForPointer:section_];
2777 - (NSString *) simpleSection {
2778 if (NSString *section = [self section])
2779 return Simplify(section);
2784 - (NSString *) longSection {
2785 if (NSString *section = [self section])
2786 return LocalizeSection(section);
2791 - (NSString *) shortSection {
2792 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2795 - (NSString *) uri {
2798 pkgIndexFile *index;
2799 pkgCache::PkgFileIterator file(file_.File());
2800 if (![database_ list].FindIndex(file, index))
2802 return [NSString stringWithUTF8String:iterator_->Path];
2803 //return [NSString stringWithUTF8String:file.Site()];
2804 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2808 - (MIMEAddress *) maintainer {
2809 @synchronized (database_) {
2810 if ([database_ era] != era_ || file_.end())
2813 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2814 const std::string &maintainer(parser->Maintainer());
2815 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2818 - (NSString *) md5sum {
2819 return parsed_ == NULL ? nil : (id) parsed_->md5sum_;
2823 @synchronized (database_) {
2824 if ([database_ era] != era_ || version_.end())
2827 return version_->InstalledSize;
2830 - (NSString *) longDescription {
2831 @synchronized (database_) {
2832 if ([database_ era] != era_ || file_.end())
2835 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2836 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2838 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2839 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2840 if ([lines count] < 2)
2843 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2844 for (size_t i(1), e([lines count]); i != e; ++i) {
2845 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2846 [trimmed addObject:trim];
2849 return [trimmed componentsJoinedByString:@"\n"];
2852 - (NSString *) shortDescription {
2853 if (parsed_ != NULL)
2854 return static_cast<NSString *>(parsed_->tagline_);
2856 @synchronized (database_) {
2857 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2858 std::string value(parser.ShortDesc());
2861 if (value.size() > 200)
2863 return [(id) CYStringCreate(value) autorelease];
2867 _profile(Package$index)
2868 CFStringRef name((CFStringRef) [self name]);
2869 if (CFStringGetLength(name) == 0)
2871 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2872 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2874 return toupper(character);
2878 - (PackageValue *) metadata {
2883 PackageValue *metadata([self metadata]);
2884 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2887 - (bool) subscribed {
2888 return [self metadata]->subscribed_;
2891 - (bool) setSubscribed:(bool)subscribed {
2892 PackageValue *metadata([self metadata]);
2893 if (metadata->subscribed_ == subscribed)
2895 metadata->subscribed_ = subscribed;
2903 - (NSString *) latest {
2907 - (NSString *) installed {
2911 - (BOOL) uninstalled {
2912 return installed_.empty();
2915 - (BOOL) upgradableAndEssential:(BOOL)essential {
2916 _profile(Package$upgradableAndEssential)
2917 pkgCache::VerIterator current(iterator_.CurrentVer());
2919 return essential && essential_;
2921 return version_ != current;
2925 - (BOOL) essential {
2930 return [database_ cache][iterator_].InstBroken();
2933 - (BOOL) unfiltered {
2934 _profile(Package$unfiltered$obsolete)
2935 if (_unlikely(obsolete_))
2939 _profile(Package$unfiltered$role)
2940 if (_unlikely(role_ > 3))
2948 if (![self unfiltered])
2953 _profile(Package$visible$section)
2954 section = [self section];
2957 _profile(Package$visible$isSectionVisible)
2958 if (!isSectionVisible(section))
2966 unsigned char current(iterator_->CurrentState);
2967 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2970 - (BOOL) halfConfigured {
2971 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2974 - (BOOL) halfInstalled {
2975 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2979 @synchronized (database_) {
2980 if ([database_ era] != era_ || iterator_.end())
2983 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2984 return state.Mode != pkgDepCache::ModeKeep;
2987 - (NSString *) mode {
2988 @synchronized (database_) {
2989 if ([database_ era] != era_ || iterator_.end())
2992 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2994 switch (state.Mode) {
2995 case pkgDepCache::ModeDelete:
2996 if ((state.iFlags & pkgDepCache::Purge) != 0)
3000 case pkgDepCache::ModeKeep:
3001 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
3002 return @"REINSTALL";
3003 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
3007 case pkgDepCache::ModeInstall:
3008 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
3009 return @"REINSTALL";
3010 else*/ switch (state.Status) {
3012 return @"DOWNGRADE";
3018 return @"NEW_INSTALL";
3029 - (NSString *) name {
3030 return name_.empty() ? id_ : name_;
3033 - (UIImage *) icon {
3034 NSString *section = [self simpleSection];
3037 if (parsed_ != NULL)
3038 if (NSString *href = parsed_->icon_)
3039 if ([href hasPrefix:@"file:///"])
3040 icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
3041 if (icon == nil) if (section != nil)
3042 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]];
3043 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
3044 if ([dicon hasPrefix:@"file:///"])
3045 icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
3047 icon = [UIImage imageNamed:@"unknown.png"];
3051 - (NSString *) homepage {
3052 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
3055 - (NSString *) depiction {
3056 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
3059 - (MIMEAddress *) author {
3060 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
3063 - (NSString *) support {
3064 return parsed_ != NULL && !parsed_->support_.empty() ? parsed_->support_ : [[self source] supportForPackage:id_];
3067 - (NSArray *) files {
3068 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
3069 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
3072 fin.open([path UTF8String]);
3077 while (std::getline(fin, line))
3078 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
3083 - (NSString *) state {
3084 @synchronized (database_) {
3085 if ([database_ era] != era_ || file_.end())
3088 switch (iterator_->CurrentState) {
3089 case pkgCache::State::NotInstalled:
3090 return @"NotInstalled";
3091 case pkgCache::State::UnPacked:
3093 case pkgCache::State::HalfConfigured:
3094 return @"HalfConfigured";
3095 case pkgCache::State::HalfInstalled:
3096 return @"HalfInstalled";
3097 case pkgCache::State::ConfigFiles:
3098 return @"ConfigFiles";
3099 case pkgCache::State::Installed:
3100 return @"Installed";
3101 case pkgCache::State::TriggersAwaited:
3102 return @"TriggersAwaited";
3103 case pkgCache::State::TriggersPending:
3104 return @"TriggersPending";
3107 return (NSString *) [NSNull null];
3110 - (NSString *) selection {
3111 @synchronized (database_) {
3112 if ([database_ era] != era_ || file_.end())
3115 switch (iterator_->SelectedState) {
3116 case pkgCache::State::Unknown:
3118 case pkgCache::State::Install:
3120 case pkgCache::State::Hold:
3122 case pkgCache::State::DeInstall:
3123 return @"DeInstall";
3124 case pkgCache::State::Purge:
3128 return (NSString *) [NSNull null];
3131 - (NSArray *) warnings {
3132 @synchronized (database_) {
3133 if ([database_ era] != era_ || file_.end())
3136 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
3137 const char *name(iterator_.Name());
3139 size_t length(strlen(name));
3140 if (length < 2) invalid:
3141 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
3142 else for (size_t i(0); i != length; ++i)
3144 /* XXX: technically this is not allowed */
3145 (name[i] < 'A' || name[i] > 'Z') &&
3146 (name[i] < 'a' || name[i] > 'z') &&
3147 (name[i] < '0' || name[i] > '9') &&
3148 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
3151 if (strcmp(name, "cydia") != 0) {
3154 bool _private = false;
3156 bool dbstash = false;
3157 bool dsstore = false;
3159 bool repository = [[self section] isEqualToString:@"Repositories"];
3161 if (NSArray *files = [self files])
3162 for (NSString *file in files)
3163 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
3165 else if (!user && [file isEqualToString:@"/User"])
3167 else if (!_private && [file isEqualToString:@"/private"])
3169 else if (!stash && [file isEqualToString:@"/var/stash"])
3171 else if (!dbstash && [file isEqualToString:@"/var/db/stash"])
3173 else if (!dsstore && [file hasSuffix:@"/.DS_Store"])
3176 /* XXX: this is not sensitive enough. only some folders are valid. */
3177 if (cydia && !repository)
3178 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
3180 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
3182 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
3184 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
3186 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/db/stash"]];
3188 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @".DS_Store"]];
3191 return [warnings count] == 0 ? nil : warnings;
3194 - (NSArray *) applications {
3195 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
3197 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
3199 static RegEx application_r("/Applications/(.*)\\.app/Info.plist");
3200 if (NSArray *files = [self files])
3201 for (NSString *file in files)
3202 if (application_r(file)) {
3203 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
3206 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
3207 if (id == nil || [id isEqualToString:me])
3210 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
3212 display = application_r[1];
3214 NSString *bundle([file stringByDeletingLastPathComponent]);
3215 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
3216 // XXX: maybe this should check if this is really a string, not just for length
3217 if (icon == nil || ![icon respondsToSelector:@selector(length)] || [icon length] == 0)
3219 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
3221 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
3222 [applications addObject:application];
3224 [application addObject:id];
3225 [application addObject:display];
3226 [application addObject:url];
3229 return [applications count] == 0 ? nil : applications;
3232 - (Source *) source {
3233 if (source_ == nil) {
3234 @synchronized (database_) {
3235 if ([database_ era] != era_ || file_.end())
3236 source_ = (Source *) [NSNull null];
3238 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
3242 return source_ == (Source *) [NSNull null] ? nil : source_;
3245 - (time_t) upgraded {
3249 - (uint32_t) recent {
3250 return std::numeric_limits<uint32_t>::max() - upgraded_;
3257 - (BOOL) matches:(NSArray *)query {
3258 if (query == nil || [query count] == 0)
3267 string = [self name];
3268 length = [string length];
3271 for (NSString *term in query) {
3272 range = [string rangeOfString:term options:MatchCompareOptions_];
3273 if (range.location != NSNotFound)
3274 rank_ -= 6 * 1000000 / length;
3279 length = [string length];
3282 for (NSString *term in query) {
3283 range = [string rangeOfString:term options:MatchCompareOptions_];
3284 if (range.location != NSNotFound)
3285 rank_ -= 6 * 1000000 / length;
3289 string = [self shortDescription];
3290 length = [string length];
3291 NSUInteger stop(std::min<NSUInteger>(length, 200));
3294 for (NSString *term in query) {
3295 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
3296 if (range.location != NSNotFound)
3297 rank_ -= 2 * 100000;
3303 - (NSArray *) tags {
3307 - (BOOL) hasTag:(NSString *)tag {
3308 return tags_ == nil ? NO : [tags_ containsObject:tag];
3311 - (NSString *) primaryPurpose {
3312 for (NSString *tag in (NSArray *) tags_)
3313 if ([tag hasPrefix:@"purpose::"])
3314 return [tag substringFromIndex:9];
3318 - (NSArray *) purposes {
3319 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
3320 for (NSString *tag in (NSArray *) tags_)
3321 if ([tag hasPrefix:@"purpose::"])
3322 [purposes addObject:[tag substringFromIndex:9]];
3323 return [purposes count] == 0 ? nil : purposes;
3326 - (bool) isCommercial {
3327 return [self hasTag:@"cydia::commercial"];
3330 - (void) setIndex:(size_t)index {
3331 if (metadata_->index_ != index)
3332 metadata_->index_ = index;
3335 - (CYString &) cyname {
3336 return !transform_.empty() ? transform_ : !name_.empty() ? name_ : id_;
3339 - (uint32_t) compareBySection:(NSArray *)sections {
3340 NSString *section([self section]);
3341 for (size_t i(0), e([sections count]); i != e; ++i) {
3342 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3346 return _not(uint32_t);
3350 @synchronized (database_) {
3351 if ([database_ era] != era_ || file_.end())
3354 pkgProblemResolver *resolver = [database_ resolver];
3355 resolver->Clear(iterator_);
3357 pkgCacheFile &cache([database_ cache]);
3358 cache->SetReInstall(iterator_, false);
3359 cache->MarkKeep(iterator_, false);
3363 @synchronized (database_) {
3364 if ([database_ era] != era_ || file_.end())
3367 pkgProblemResolver *resolver = [database_ resolver];
3368 resolver->Clear(iterator_);
3369 resolver->Protect(iterator_);
3371 pkgCacheFile &cache([database_ cache]);
3372 cache->SetCandidateVersion(version_);
3373 cache->SetReInstall(iterator_, false);
3374 cache->MarkInstall(iterator_, false);
3376 pkgDepCache::StateCache &state((*cache)[iterator_]);
3377 if (!state.Install())
3378 cache->SetReInstall(iterator_, true);
3382 @synchronized (database_) {
3383 if ([database_ era] != era_ || file_.end())
3386 pkgProblemResolver *resolver = [database_ resolver];
3387 resolver->Clear(iterator_);
3388 resolver->Remove(iterator_);
3389 resolver->Protect(iterator_);
3391 pkgCacheFile &cache([database_ cache]);
3392 cache->SetReInstall(iterator_, false);
3393 cache->MarkDelete(iterator_, true);
3398 /* Section Class {{{ */
3399 @interface Section : NSObject {
3403 _H<NSString> localized_;
3406 - (NSComparisonResult) compareByLocalized:(Section *)section;
3407 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3408 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3409 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3411 - (NSString *) name;
3412 - (void) setName:(NSString *)name;
3418 - (void) addToCount;
3420 - (void) setCount:(size_t)count;
3421 - (NSString *) localized;
3425 @implementation Section
3427 - (NSComparisonResult) compareByLocalized:(Section *)section {
3428 NSString *lhs(localized_);
3429 NSString *rhs([section localized]);
3431 /*if ([lhs length] != 0 && [rhs length] != 0) {
3432 unichar lhc = [lhs characterAtIndex:0];
3433 unichar rhc = [rhs characterAtIndex:0];
3435 if (isalpha(lhc) && !isalpha(rhc))
3436 return NSOrderedAscending;
3437 else if (!isalpha(lhc) && isalpha(rhc))
3438 return NSOrderedDescending;
3441 return [lhs compare:rhs options:LaxCompareOptions_];
3444 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3445 if ((self = [self initWithName:name localize:NO]) != nil) {
3446 if (localized != nil)
3447 localized_ = localized;
3451 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3452 return [self initWithName:name row:0 localize:localize];
3455 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3456 if ((self = [super init]) != nil) {
3460 localized_ = LocalizeSection(name_);
3464 - (NSString *) name {
3468 - (void) setName:(NSString *)name {
3484 - (void) addToCount {
3488 - (void) setCount:(size_t)count {
3492 - (NSString *) localized {
3499 class CydiaLogCleaner :
3500 public pkgArchiveCleaner
3503 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3508 /* Database Implementation {{{ */
3509 @implementation Database
3511 + (Database *) sharedInstance {
3512 static _H<Database> instance;
3513 if (instance == nil)
3514 instance = [[[Database alloc] init] autorelease];
3522 - (void) releasePackages {
3523 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3524 CFArrayRemoveAllValues(packages_);
3527 - (bool) hasPackages {
3528 return CFArrayGetCount(packages_) != 0;
3532 // XXX: actually implement this thing
3534 [self releasePackages];
3535 NSRecycleZone(zone_);
3539 - (void) _readCydia:(NSNumber *)fd {
3540 boost::fdistream is([fd intValue]);
3543 static RegEx finish_r("finish:([^:]*)");
3545 while (std::getline(is, line)) {
3546 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3548 const char *data(line.c_str());
3549 size_t size = line.size();
3550 lprintf("C:%s\n", data);
3552 if (finish_r(data, size)) {
3553 NSString *finish = finish_r[1];
3554 int index = [Finishes_ indexOfObject:finish];
3555 if (index != INT_MAX && index > Finish_)
3565 - (void) _readStatus:(NSNumber *)fd {
3566 boost::fdistream is([fd intValue]);
3569 static RegEx conffile_r("status: [^ ]* : conffile-prompt : (.*?) *");
3570 static RegEx pmstatus_r("([^:]*):([^:]*):([^:]*):(.*)");
3572 while (std::getline(is, line)) {
3573 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3575 const char *data(line.c_str());
3576 size_t size(line.size());
3577 lprintf("S:%s\n", data);
3579 if (conffile_r(data, size)) {
3580 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3581 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3582 } else if (strncmp(data, "status: ", 8) == 0) {
3583 // status: <package>: {unpacked,half-configured,installed}
3584 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3585 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3586 } else if (strncmp(data, "processing: ", 12) == 0) {
3587 // processing: configure: config-test
3588 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3589 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3590 } else if (pmstatus_r(data, size)) {
3591 std::string type([pmstatus_r[1] UTF8String]);
3593 NSString *package = pmstatus_r[2];
3594 if ([package isEqualToString:@"dpkg-exec"])
3597 float percent([pmstatus_r[3] floatValue]);
3598 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3600 NSString *string = pmstatus_r[4];
3602 if (type == "pmerror") {
3603 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3604 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3605 } else if (type == "pmstatus") {
3606 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3607 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3608 } else if (type == "pmconffile")
3609 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3611 lprintf("E:unknown pmstatus\n");
3613 lprintf("E:unknown status\n");
3621 - (void) _readOutput:(NSNumber *)fd {
3622 boost::fdistream is([fd intValue]);
3625 while (std::getline(is, line)) {
3626 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3628 lprintf("O:%s\n", line.c_str());
3630 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3631 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3643 - (Package *) packageWithName:(NSString *)name {
3646 @synchronized (self) {
3647 if (static_cast<pkgDepCache *>(cache_) == NULL)
3649 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]
3654 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:NULL database:self];
3658 if ((self = [super init]) != nil) {
3665 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3667 size_t capacity(MetaFile_->active_);
3673 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3674 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3678 _assert(pipe(fds) != -1);
3681 _config->Set("APT::Keep-Fds::", cydiafd_);
3682 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3685 detachNewThreadSelector:@selector(_readCydia:)
3687 withObject:[NSNumber numberWithInt:fds[0]]
3690 _assert(pipe(fds) != -1);
3694 detachNewThreadSelector:@selector(_readStatus:)
3696 withObject:[NSNumber numberWithInt:fds[0]]
3699 _assert(pipe(fds) != -1);
3700 _assert(dup2(fds[0], 0) != -1);
3701 _assert(close(fds[0]) != -1);
3703 input_ = fdopen(fds[1], "a");
3705 _assert(pipe(fds) != -1);
3706 _assert(dup2(fds[1], 1) != -1);
3707 _assert(close(fds[1]) != -1);
3710 detachNewThreadSelector:@selector(_readOutput:)
3712 withObject:[NSNumber numberWithInt:fds[0]]
3717 - (pkgCacheFile &) cache {
3721 - (pkgDepCache::Policy *) policy {
3725 - (pkgRecords *) records {
3729 - (pkgProblemResolver *) resolver {
3733 - (pkgAcquire &) fetcher {
3737 - (pkgSourceList &) list {
3741 - (NSArray *) packages {
3742 return (NSArray *) packages_;
3745 - (NSArray *) sources {
3749 - (Source *) sourceWithKey:(NSString *)key {
3750 for (Source *source in [self sources]) {
3751 if ([[source key] isEqualToString:key])
3756 - (bool) popErrorWithTitle:(NSString *)title {
3759 while (!_error->empty()) {
3761 bool warning(!_error->PopMessage(error));
3766 size_t size(error.size());
3767 if (size == 0 || error[size - 1] != '\n')
3769 error.resize(size - 1);
3772 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3774 static RegEx no_pubkey("GPG error:.* NO_PUBKEY .*");
3775 if (warning && no_pubkey(error.c_str()))
3778 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3784 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3785 return [self popErrorWithTitle:title] || !success;
3788 - (bool) popErrorWithTitle:(NSString *)title forReadList:(pkgSourceList &)list {
3789 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3797 if (access("/etc/apt/sources.list", F_OK) == 0)
3798 error |= [self popErrorWithTitle:title forOperation:list.ReadAppend("/etc/apt/sources.list")];
3800 std::string base("/etc/apt/sources.list.d");
3801 if (DIR *sources = opendir(base.c_str())) {
3802 while (dirent *source = readdir(sources))
3803 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)
3804 error |= [self popErrorWithTitle:title forOperation:list.ReadAppend((base + "/" + source->d_name).c_str())];
3808 error |= [self popErrorWithTitle:title forOperation:list.ReadAppend(SOURCES_LIST)];
3813 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3814 @synchronized (self) {
3817 [self releasePackages];
3820 [sourceList_ removeAllObjects];
3841 new (&pool_) CYPool();
3843 NSRecycleZone(zone_);
3844 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3846 int chk(creat("/tmp/cydia.chk", 0644));
3850 if (invocation != nil)
3851 [invocation invoke];
3853 NSString *title(UCLocalize("DATABASE"));
3855 list_ = new pkgSourceList();
3856 _profile(reloadDataWithInvocation$ReadMainList)
3857 if ([self popErrorWithTitle:title forReadList:*list_])
3861 _profile(reloadDataWithInvocation$Source$initWithMetaIndex)
3862 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3863 Source *object([[[Source alloc] initWithMetaIndex:*source forDatabase:self inPool:&pool_] autorelease]);
3864 [sourceList_ addObject:object];
3869 OpProgress progress;
3872 delock_ = GetStatusDate();
3873 _profile(reloadDataWithInvocation$pkgCacheFile)
3874 opened = cache_.Open(progress, false);
3877 // XXX: this block should probably be merged with popError: in some way
3878 while (!_error->empty()) {
3880 bool warning(!_error->PopMessage(error));
3882 lprintf("cache_.Open():[%s]\n", error.c_str());
3884 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3888 else if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3889 repair = @selector(configure);
3890 //else if (error == "The package lists or status file could not be parsed or opened.")
3891 // repair = @selector(update);
3892 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3893 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3894 // else if (error == "Malformed Status line")
3895 // else if (error == "The list of sources could not be read.")
3897 if (repair != NULL) {
3899 [delegate_ repairWithSelector:repair];
3905 } else if ([self popErrorWithTitle:title forOperation:true])
3909 unlink("/tmp/cydia.chk");
3911 now_ = [[NSDate date] timeIntervalSince1970];
3913 policy_ = new pkgDepCache::Policy();
3914 records_ = new pkgRecords(cache_);
3915 resolver_ = new pkgProblemResolver(cache_);
3916 fetcher_ = new pkgAcquire(&status_);
3919 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3920 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3924 _profile(reloadDataWithInvocation$pkgApplyStatus)
3925 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3929 if (cache_->BrokenCount() != 0) {
3930 _profile(pkgApplyStatus$pkgFixBroken)
3931 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3935 if (cache_->BrokenCount() != 0) {
3936 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3940 _profile(pkgApplyStatus$pkgMinimizeUpgrade)
3941 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3946 for (Source *object in (id) sourceList_) {
3947 metaIndex *source([object metaIndex]);
3948 std::vector<pkgIndexFile *> *indices = source->GetIndexFiles();
3949 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3950 // XXX: this could be more intelligent
3951 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3952 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3954 sourceMap_[cached->ID] = object;
3959 /*std::vector<Package *> packages;
3960 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3963 _profile(reloadDataWithInvocation$packageWithIterator)
3964 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3965 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:&pool_ database:self])
3966 //packages.push_back(package);
3967 CFArrayAppendValue(packages_, CFRetain(package));
3971 /*if (packages.empty())
3972 packages_ = [[NSArray alloc] init];
3974 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3977 _profile(reloadDataWithInvocation$radix$8)
3978 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(8)];
3981 _profile(reloadDataWithInvocation$radix$4)
3982 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3985 _profile(reloadDataWithInvocation$radix$0)
3986 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3989 _profile(reloadDataWithInvocation$insertion)
3990 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3993 /*_profile(reloadDataWithInvocation$CFQSortArray)
3994 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);
3997 /*_profile(reloadDataWithInvocation$stdsort)
3998 std::sort(packages.begin(), packages.end(), PackageNameOrdering());
4001 /*_profile(reloadDataWithInvocation$CFArraySortValues)
4002 CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
4005 /*_profile(reloadDataWithInvocation$sortUsingFunction)
4006 [packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
4010 size_t count(CFArrayGetCount(packages_));
4011 MetaFile_->active_ = count;
4012 for (size_t index(0); index != count; ++index)
4013 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
4018 @synchronized (self) {
4020 resolver_ = new pkgProblemResolver(cache_);
4022 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
4023 if (!cache_[iterator].Keep())
4024 cache_->MarkKeep(iterator, false);
4025 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
4026 cache_->SetReInstall(iterator, false);
4029 - (void) configure {
4030 NSString *dpkg = [NSString stringWithFormat:@"/usr/libexec/cydo --configure -a --status-fd %u", statusfd_];
4032 system([dpkg UTF8String]);
4037 @synchronized (self) {
4038 // XXX: I don't remember this condition
4043 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
4045 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
4047 if ([self popErrorWithTitle:title])
4051 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
4053 CydiaLogCleaner cleaner;
4054 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
4061 fetcher_->Shutdown();
4063 pkgRecords records(cache_);
4065 lock_ = new FileFd();
4066 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
4068 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
4070 if ([self popErrorWithTitle:title])
4074 if ([self popErrorWithTitle:title forReadList:list])
4077 manager_ = (_system->CreatePM(cache_));
4078 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
4085 bool substrate(RestartSubstrate_);
4086 RestartSubstrate_ = false;
4088 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
4090 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
4092 if ([self popErrorWithTitle:title forReadList:list])
4094 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
4095 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
4098 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4100 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
4102 [self popErrorWithTitle:title];
4106 bool failed = false;
4107 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
4108 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
4110 if ((*item)->Status == pkgAcquire::Item::StatIdle)
4113 std::string uri = (*item)->DescURI();
4114 std::string error = (*item)->ErrorText;
4116 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
4119 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError]);
4120 [delegate_ addProgressEventOnMainThread:event forTask:title];
4123 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4131 RestartSubstrate_ = true;
4133 if (![delock_ isEqual:GetStatusDate()]) {
4134 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("DPKG_LOCKED") ofType:kCydiaProgressEventTypeError] forTask:title];
4140 pkgPackageManager::OrderResult result(manager_->DoInstall(statusfd_));
4142 NSString *oextended(@"/var/lib/apt/extended_states");
4143 NSString *nextended(Cache("extended_states"));
4146 if (stat([nextended UTF8String], &info) != -1 && (info.st_mode & S_IFMT) == S_IFREG)
4147 system([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /bin/cp --remove-destination %@ %@", ShellEscape(nextended), ShellEscape(oextended)] UTF8String]);
4149 unlink([nextended UTF8String]);
4150 symlink([oextended UTF8String], [nextended UTF8String]);
4152 if ([self popErrorWithTitle:title])
4155 if (result == pkgPackageManager::Failed) {
4160 if (result != pkgPackageManager::Completed) {
4165 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
4167 if ([self popErrorWithTitle:title forReadList:list])
4169 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
4170 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
4173 if (![before isEqualToArray:after])
4178 return ![delock_ isEqual:GetStatusDate()];
4182 NSString *title(UCLocalize("UPGRADE"));
4183 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
4189 [self updateWithStatus:status_];
4192 - (void) updateWithStatus:(CancelStatus &)status {
4193 NSString *title(UCLocalize("REFRESHING_DATA"));
4196 if ([self popErrorWithTitle:title forReadList:list])
4200 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
4201 if ([self popErrorWithTitle:title])
4204 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4206 bool success(ListUpdate(status, list, PulseInterval_));
4207 if (status.WasCancelled())
4210 [self popErrorWithTitle:title forOperation:success];
4212 [[NSDictionary dictionaryWithObjectsAndKeys:
4213 [NSDate date], @"LastUpdate",
4214 nil] writeToFile:@ CacheState_ atomically:YES];
4217 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4220 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
4221 delegate_ = delegate;
4224 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
4225 progress_ = delegate;
4226 status_.setDelegate(delegate);
4229 - (NSObject<ProgressDelegate> *) progressDelegate {
4233 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
4234 SourceMap::const_iterator i(sourceMap_.find(file->ID));
4235 return i == sourceMap_.end() ? nil : i->second;
4238 - (void) setFetch:(bool)fetch forURI:(const char *)uri {
4239 for (Source *source in (id) sourceList_)
4240 [source setFetch:fetch forURI:uri];
4243 - (void) resetFetch {
4244 for (Source *source in (id) sourceList_)
4245 [source resetFetch];
4248 - (NSString *) mappedSectionForPointer:(const char *)section {
4249 _H<NSString> *mapped;
4251 _profile(Database$mappedSectionForPointer$Cache)
4252 mapped = §ions_[section];
4255 if (*mapped == NULL) {
4256 size_t length(strlen(section));
4257 char spaced[length + 1];
4259 _profile(Database$mappedSectionForPointer$Replace)
4260 for (size_t index(0); index != length; ++index)
4261 spaced[index] = section[index] == '_' ? ' ' : section[index];
4262 spaced[length] = '\0';
4267 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
4268 string = [NSString stringWithUTF8String:spaced];
4271 _profile(Database$mappedSectionForPointer$Map)
4272 string = [SectionMap_ objectForKey:string] ?: string;
4282 static _H<NSMutableSet> Diversions_;
4284 @interface Diversion : NSObject {
4287 _H<NSString> format_;
4292 @implementation Diversion
4294 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
4295 if ((self = [super init]) != nil) {
4296 pattern_ = [from UTF8String];
4302 - (NSString *) divert:(NSString *)url {
4303 return !pattern_(url) ? nil : pattern_->*format_;
4306 + (NSURL *) divertURL:(NSURL *)url {
4308 NSString *href([url absoluteString]);
4310 for (Diversion *diversion in (id) Diversions_)
4311 if (NSString *diverted = [diversion divert:href]) {
4313 NSLog(@"div: %@", diverted);
4315 url = [NSURL URLWithString:diverted];
4322 - (NSString *) key {
4326 - (NSUInteger) hash {
4330 - (BOOL) isEqual:(Diversion *)object {
4331 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
4336 @interface CydiaObject : NSObject {
4337 _H<CyteWebViewController> indirect_;
4338 _transient id delegate_;
4341 - (id) initWithDelegate:(IndirectDelegate *)indirect;
4347 @interface CydiaWebViewController : CyteWebViewController {
4348 _H<CydiaObject> cydia_;
4351 + (void) addDiversion:(Diversion *)diversion;
4352 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request;
4353 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia;
4354 - (void) setDelegate:(id)delegate;
4358 /* Web Scripting {{{ */
4359 @implementation CydiaObject
4361 - (id) initWithDelegate:(IndirectDelegate *)indirect {
4362 if ((self = [super init]) != nil) {
4363 indirect_ = (CyteWebViewController *) indirect;
4367 - (void) setDelegate:(id)delegate {
4368 delegate_ = delegate;
4371 + (NSArray *) _attributeKeys {
4372 return [NSArray arrayWithObjects:
4377 @"coreFoundationVersionNumber",
4393 - (NSArray *) attributeKeys {
4394 return [[self class] _attributeKeys];
4397 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4398 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4401 - (NSString *) version {
4405 - (unsigned) bittage {
4407 #elif defined(__arm64__)
4409 #elif defined(__arm__)
4416 - (NSString *) build {
4420 - (NSString *) coreFoundationVersionNumber {
4421 return [NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber];
4424 - (NSString *) device {
4425 return UniqueIdentifier();
4428 - (NSString *) firmware {
4429 return [[UIDevice currentDevice] systemVersion];
4432 - (NSString *) hostname {
4433 return [[UIDevice currentDevice] name];
4436 - (NSString *) idiom {
4437 return (id) Idiom_ ?: [NSNull null];
4440 - (NSArray *) cells {
4441 auto *$_CTServerConnectionCreate(reinterpret_cast<id (*)(void *, void *, void *)>(dlsym(RTLD_DEFAULT, "_CTServerConnectionCreate")));
4442 if ($_CTServerConnectionCreate == NULL)
4445 struct CTResult { int flag; int error; };
4446 auto *$_CTServerConnectionCellMonitorCopyCellInfo(reinterpret_cast<CTResult (*)(CFTypeRef, void *, CFArrayRef *)>(dlsym(RTLD_DEFAULT, "_CTServerConnectionCellMonitorCopyCellInfo")));
4447 if ($_CTServerConnectionCellMonitorCopyCellInfo == NULL)
4450 _H<const void> connection($_CTServerConnectionCreate(NULL, NULL, NULL), true);
4451 if (connection == nil)
4455 CFArrayRef cells(NULL);
4456 auto result($_CTServerConnectionCellMonitorCopyCellInfo(connection, &count, &cells));
4457 if (result.flag != 0)
4460 return [(NSArray *) cells autorelease];
4463 - (NSString *) mcc {
4464 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode")))
4465 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault) autorelease];
4469 - (NSString *) mnc {
4470 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberNetworkCode")))
4471 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault) autorelease];
4475 - (NSString *) operator {
4476 if (CFStringRef (*$CTRegistrationCopyOperatorName)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTRegistrationCopyOperatorName")))
4477 return [(NSString *) (*$CTRegistrationCopyOperatorName)(kCFAllocatorDefault) autorelease];
4481 - (NSString *) bbsnum {
4482 return (id) BBSNum_ ?: [NSNull null];
4485 - (NSString *) ecid {
4486 return (id) ChipID_ ?: [NSNull null];
4489 - (NSString *) serial {
4490 return SerialNumber_;
4493 - (NSString *) role {
4494 return (id) [NSNull null];
4497 - (NSString *) model {
4498 return [NSString stringWithUTF8String:Machine_];
4501 + (NSString *) webScriptNameForSelector:(SEL)selector {
4503 else if (selector == @selector(addBridgedHost:))
4504 return @"addBridgedHost";
4505 else if (selector == @selector(addInsecureHost:))
4506 return @"addInsecureHost";
4507 else if (selector == @selector(addInternalRedirect::))
4508 return @"addInternalRedirect";
4509 else if (selector == @selector(addPipelinedHost:scheme:))
4510 return @"addPipelinedHost";
4511 else if (selector == @selector(addSource:::))
4512 return @"addSource";
4513 else if (selector == @selector(addTrivialSource:))
4514 return @"addTrivialSource";
4515 else if (selector == @selector(close))
4517 else if (selector == @selector(du:))
4519 else if (selector == @selector(stringWithFormat:arguments:))
4521 else if (selector == @selector(getAllSources))
4522 return @"getAllSources";
4523 else if (selector == @selector(getApplicationInfo:value:))
4524 return @"getApplicationInfoValue";
4525 else if (selector == @selector(getDisplayIdentifiers))
4526 return @"getDisplayIdentifiers";
4527 else if (selector == @selector(getLocalizedNameForDisplayIdentifier:))
4528 return @"getLocalizedNameForDisplayIdentifier";
4529 else if (selector == @selector(getKernelNumber:))
4530 return @"getKernelNumber";
4531 else if (selector == @selector(getKernelString:))
4532 return @"getKernelString";
4533 else if (selector == @selector(getInstalledPackages))
4534 return @"getInstalledPackages";
4535 else if (selector == @selector(getIORegistryEntry::))
4536 return @"getIORegistryEntry";
4537 else if (selector == @selector(getLocaleIdentifier))
4538 return @"getLocaleIdentifier";
4539 else if (selector == @selector(getPreferredLanguages))
4540 return @"getPreferredLanguages";
4541 else if (selector == @selector(getPackageById:))
4542 return @"getPackageById";
4543 else if (selector == @selector(getMetadataKeys))
4544 return @"getMetadataKeys";
4545 else if (selector == @selector(getMetadataValue:))
4546 return @"getMetadataValue";
4547 else if (selector == @selector(getSessionValue:))
4548 return @"getSessionValue";
4549 else if (selector == @selector(installPackages:))
4550 return @"installPackages";
4551 else if (selector == @selector(isReachable:))
4552 return @"isReachable";
4553 else if (selector == @selector(localizedStringForKey:value:table:))
4555 else if (selector == @selector(popViewController:))
4556 return @"popViewController";
4557 else if (selector == @selector(refreshSources))
4558 return @"refreshSources";
4559 else if (selector == @selector(registerFrame:))
4560 return @"registerFrame";
4561 else if (selector == @selector(removeButton))
4562 return @"removeButton";
4563 else if (selector == @selector(saveConfig))
4564 return @"saveConfig";
4565 else if (selector == @selector(setMetadataValue::))
4566 return @"setMetadataValue";
4567 else if (selector == @selector(setSessionValue::))
4568 return @"setSessionValue";
4569 else if (selector == @selector(substitutePackageNames:))
4570 return @"substitutePackageNames";
4571 else if (selector == @selector(scrollToBottom:))
4572 return @"scrollToBottom";
4573 else if (selector == @selector(setAllowsNavigationAction:))
4574 return @"setAllowsNavigationAction";
4575 else if (selector == @selector(setBadgeValue:))
4576 return @"setBadgeValue";
4577 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4578 return @"setButtonImage";
4579 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4580 return @"setButtonTitle";
4581 else if (selector == @selector(setHidesBackButton:))
4582 return @"setHidesBackButton";
4583 else if (selector == @selector(setHidesNavigationBar:))
4584 return @"setHidesNavigationBar";
4585 else if (selector == @selector(setNavigationBarStyle:))
4586 return @"setNavigationBarStyle";
4587 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4588 return @"setNavigationBarTintColor";
4589 else if (selector == @selector(setPasteboardString:))
4590 return @"setPasteboardString";
4591 else if (selector == @selector(setPasteboardURL:))
4592 return @"setPasteboardURL";
4593 else if (selector == @selector(setScrollAlwaysBounceVertical:))
4594 return @"setScrollAlwaysBounceVertical";
4595 else if (selector == @selector(setScrollIndicatorStyle:))
4596 return @"setScrollIndicatorStyle";
4597 else if (selector == @selector(setToken:))
4599 else if (selector == @selector(setViewportWidth:))
4600 return @"setViewportWidth";
4601 else if (selector == @selector(statfs:))
4603 else if (selector == @selector(supports:))
4605 else if (selector == @selector(unload))
4611 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4612 return [self webScriptNameForSelector:selector] == nil;
4615 - (BOOL) supports:(NSString *)feature {
4616 return [feature isEqualToString:@"window.open"];
4620 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4623 - (void) setScrollAlwaysBounceVertical:(NSNumber *)value {
4624 [indirect_ performSelectorOnMainThread:@selector(setScrollAlwaysBounceVerticalNumber:) withObject:value waitUntilDone:NO];
4627 - (void) setScrollIndicatorStyle:(NSString *)style {
4628 [indirect_ performSelectorOnMainThread:@selector(setScrollIndicatorStyleWithName:) withObject:style waitUntilDone:NO];
4631 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4632 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4635 - (NSDictionary *) getApplicationInfo:(NSString *)display value:(NSString *)key {
4637 if (SBBundlePathForDisplayIdentifier(SBSSpringBoardServerPort(), [display UTF8String], path) != 0)
4638 return (id) [NSNull null];
4639 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:[[NSString stringWithUTF8String:path] stringByAppendingString:@"/Info.plist"]]);
4641 return (id) [NSNull null];
4642 return [info objectForKey:key];
4645 - (NSArray *) getDisplayIdentifiers {
4646 return SBSCopyApplicationDisplayIdentifiers(false, false);
4649 - (NSString *) getLocalizedNameForDisplayIdentifier:(NSString *)identifier {
4650 return [SBSCopyLocalizedApplicationNameForDisplayIdentifier(identifier) autorelease] ?: (id) [NSNull null];
4653 - (NSNumber *) getKernelNumber:(NSString *)name {
4654 const char *string([name UTF8String]);
4657 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4658 return (id) [NSNull null];
4660 if (size != sizeof(int))
4661 return (id) [NSNull null];
4664 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4665 return (id) [NSNull null];
4667 return [NSNumber numberWithInt:value];
4670 - (NSString *) getKernelString:(NSString *)name {
4671 const char *string([name UTF8String]);
4674 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4675 return (id) [NSNull null];
4677 char value[size + 1];
4678 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4679 return (id) [NSNull null];
4681 // XXX: just in case you request something ludicrous
4684 return [NSString stringWithCString:value];
4687 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4688 NSObject *value(CYIOGetValue([path UTF8String], entry));
4691 if ([value isKindOfClass:[NSData class]])
4692 value = CYHex((NSData *) value);
4697 - (NSArray *) getMetadataKeys {
4698 @synchronized (Values_) {
4699 return [Values_ allKeys];
4702 - (void) registerFrame:(DOMHTMLIFrameElement *)iframe {
4703 WebFrame *frame([iframe contentFrame]);
4704 [indirect_ registerFrame:frame];
4707 - (id) getMetadataValue:(NSString *)key {
4708 @synchronized (Values_) {
4709 return [Values_ objectForKey:key];
4712 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4713 @synchronized (Values_) {
4714 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4715 [Values_ removeObjectForKey:key];
4717 [Values_ setObject:value forKey:key];
4720 - (id) getSessionValue:(NSString *)key {
4721 @synchronized (SessionData_) {
4722 return [SessionData_ objectForKey:key];
4725 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4726 @synchronized (SessionData_) {
4727 if (value == (id) [WebUndefined undefined])
4728 [SessionData_ removeObjectForKey:key];
4730 [SessionData_ setObject:value forKey:key];
4733 - (void) addBridgedHost:(NSString *)host {
4734 @synchronized (HostConfig_) {
4735 [BridgedHosts_ addObject:host];
4738 - (void) addInsecureHost:(NSString *)host {
4739 @synchronized (HostConfig_) {
4740 [InsecureHosts_ addObject:host];
4743 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4744 @synchronized (HostConfig_) {
4745 if (scheme != (id) [WebUndefined undefined])
4746 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4748 [PipelinedHosts_ addObject:host];
4751 - (void) popViewController:(NSNumber *)value {
4752 if (value == (id) [WebUndefined undefined])
4753 value = [NSNumber numberWithBool:YES];
4754 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4757 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4758 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4760 for (NSString *section in sections)
4761 [array addObject:section];
4763 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4766 distribution, @"Distribution",
4768 nil] waitUntilDone:NO];
4771 - (BOOL) addTrivialSource:(NSString *)href {
4772 href = VerifySource(href);
4775 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4779 - (void) refreshSources {
4780 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4783 - (void) saveConfig {
4784 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4787 - (NSArray *) getAllSources {
4788 return [[Database sharedInstance] sources];
4791 - (NSArray *) getInstalledPackages {
4792 Database *database([Database sharedInstance]);
4793 @synchronized (database) {
4794 NSArray *packages([database packages]);
4795 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4796 for (Package *package in packages)
4797 if (![package uninstalled])
4798 [installed addObject:package];
4802 - (Package *) getPackageById:(NSString *)id {
4803 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4807 return (Package *) [NSNull null];
4810 - (NSString *) getLocaleIdentifier {
4811 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4814 - (NSArray *) getPreferredLanguages {
4818 - (NSArray *) statfs:(NSString *)path {
4821 if (path == nil || statfs([path UTF8String], &stat) == -1)
4824 return [NSArray arrayWithObjects:
4825 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4826 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4827 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4831 - (NSNumber *) du:(NSString *)path {
4832 NSNumber *value(nil);
4834 FILE *du(popen([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /usr/libexec/cydia/du -ks %@", ShellEscape(path)] UTF8String], "r"));
4837 while (fgets(line, sizeof(line), du) != NULL) {
4838 size_t length(strlen(line));
4839 while (length != 0 && line[length - 1] == '\n')
4840 line[--length] = '\0';
4841 if (char *tab = strchr(line, '\t')) {
4843 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4853 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4856 - (NSNumber *) isReachable:(NSString *)name {
4857 return [NSNumber numberWithBool:IsReachable([name UTF8String])];
4860 - (void) installPackages:(NSArray *)packages {
4861 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4864 - (NSString *) substitutePackageNames:(NSString *)message {
4865 auto database([Database sharedInstance]);
4867 // XXX: this check is less racy than you'd expect, but this entire concept is a little awkward
4868 if (![database hasPackages])
4871 NSMutableArray *words([[[message componentsSeparatedByString:@" "] mutableCopy] autorelease]);
4872 for (size_t i(0), e([words count]); i != e; ++i) {
4873 NSString *word([words objectAtIndex:i]);
4874 if (Package *package = [database packageWithName:word])
4875 [words replaceObjectAtIndex:i withObject:[package name]];
4878 return [words componentsJoinedByString:@" "];
4881 - (void) removeButton {
4882 [indirect_ removeButton];
4885 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4886 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4889 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4890 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4893 - (void) setBadgeValue:(id)value {
4894 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4897 - (void) setAllowsNavigationAction:(NSString *)value {
4898 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4901 - (void) setHidesBackButton:(NSString *)value {
4902 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4905 - (void) setHidesNavigationBar:(NSString *)value {
4906 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4909 - (void) setNavigationBarStyle:(NSString *)value {
4910 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4913 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4914 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4915 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4916 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4919 - (void) setPasteboardString:(NSString *)value {
4920 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4923 - (void) setPasteboardURL:(NSString *)value {
4924 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4927 - (void) setToken:(NSString *)token {
4928 // XXX: the website expects this :/
4931 - (void) scrollToBottom:(NSNumber *)animated {
4932 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4935 - (void) setViewportWidth:(float)width {
4936 [indirect_ setViewportWidthOnMainThread:width];
4939 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4940 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4941 unsigned count([arguments count]);
4943 for (unsigned i(0); i != count; ++i)
4944 values[i] = [arguments objectAtIndex:i];
4945 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4948 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4949 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4951 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4953 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4959 @interface NSURL (CydiaSecure)
4962 @implementation NSURL (CydiaSecure)
4964 - (bool) isCydiaSecure {
4965 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4968 @synchronized (HostConfig_) {
4969 if ([InsecureHosts_ containsObject:[self host]])
4978 /* Cydia Browser Controller {{{ */
4979 @implementation CydiaWebViewController
4981 - (NSURL *) navigationURL {
4982 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4985 + (void) _initialize {
4986 [super _initialize];
4988 Diversions_ = [NSMutableSet setWithCapacity:0];
4991 + (void) addDiversion:(Diversion *)diversion {
4992 [Diversions_ addObject:diversion];
4995 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4996 [super webView:view didClearWindowObject:window forFrame:frame];
4997 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
5000 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia {
5001 WebDataSource *source([frame dataSource]);
5002 NSURLResponse *response([source response]);
5003 NSURL *url([response URL]);
5004 NSString *scheme([[url scheme] lowercaseString]);
5006 bool bridged(false);
5008 @synchronized (HostConfig_) {
5009 if ([scheme isEqualToString:@"file"])
5011 else if ([scheme isEqualToString:@"https"])
5012 if ([BridgedHosts_ containsObject:[url host]])
5017 [window setValue:cydia forKey:@"cydia"];
5020 - (void) _setupMail:(MFMailComposeViewController *)controller {
5021 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
5023 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
5024 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
5027 - (NSURL *) URLWithURL:(NSURL *)url {
5028 return [Diversion divertURL:url];
5031 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
5032 return [CydiaWebViewController requestWithHeaders:[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
5035 - (NSURLRequest *) webThreadWebView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
5036 return [CydiaWebViewController requestWithHeaders:[super webThreadWebView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
5039 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request {
5040 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
5042 NSURL *url([copy URL]);
5043 NSString *href([url absoluteString]);
5044 NSString *host([url host]);
5046 if ([href hasPrefix:@"https://cydia.saurik.com/TSS/"]) {
5047 if (NSString *agent = [copy valueForHTTPHeaderField:@"X-User-Agent"]) {
5048 [copy setValue:agent forHTTPHeaderField:@"User-Agent"];
5049 [copy setValue:nil forHTTPHeaderField:@"X-User-Agent"];
5052 [copy setValue:nil forHTTPHeaderField:@"Referer"];
5053 [copy setValue:nil forHTTPHeaderField:@"Origin"];
5055 [copy setURL:[NSURL URLWithString:[@"http://gs.apple.com/TSS/" stringByAppendingString:[href substringFromIndex:29]]]];
5059 if ([copy valueForHTTPHeaderField:@"X-Cydia-Cf"] == nil)
5060 [copy setValue:[NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber] forHTTPHeaderField:@"X-Cydia-Cf"];
5061 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
5062 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
5064 bool bridged; @synchronized (HostConfig_) {
5065 bridged = [BridgedHosts_ containsObject:host];
5068 if ([url isCydiaSecure] && bridged && UniqueID_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Id"] == nil)
5069 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
5074 - (void) setDelegate:(id)delegate {
5075 [super setDelegate:delegate];
5076 [cydia_ setDelegate:delegate];
5079 - (NSString *) applicationNameForUserAgent {
5084 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
5085 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
5091 @interface AppCacheController : CydiaWebViewController {
5096 @implementation AppCacheController
5098 - (void) didReceiveMemoryWarning {
5099 // XXX: this doesn't work
5102 - (bool) retainsNetworkActivityIndicator {
5110 @interface NSObject (CydiaScript)
5111 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
5114 @implementation NSObject (CydiaScript)
5116 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5122 @implementation NSArray (CydiaScript)
5124 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5125 WebScriptObject *object([context evaluateWebScript:@"[]"]);
5126 for (size_t i(0), e([self count]); i != e; ++i)
5127 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
5133 @implementation NSDictionary (CydiaScript)
5135 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5136 WebScriptObject *object([context evaluateWebScript:@"({})"]);
5138 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
5145 /* Confirmation Controller {{{ */
5146 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
5147 if (!iterator.end())
5148 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
5149 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
5151 pkgCache::PkgIterator package(dep.TargetPkg());
5154 if (strcmp(package.Name(), "mobilesubstrate") == 0)
5161 @protocol ConfirmationControllerDelegate
5162 - (void) cancelAndClear:(bool)clear;
5163 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
5167 @interface ConfirmationController : CydiaWebViewController {
5168 _transient Database *database_;
5170 _H<UIAlertView> essential_;
5172 _H<NSDictionary> changes_;
5173 _H<NSMutableArray> issues_;
5174 _H<NSDictionary> sizes_;
5179 - (id) initWithDatabase:(Database *)database;
5183 @implementation ConfirmationController
5187 RestartSubstrate_ = true;
5188 [delegate_ confirmWithNavigationController:[self navigationController]];
5191 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
5192 NSString *context([alert context]);
5194 if ([context isEqualToString:@"remove"]) {
5195 if (button == [alert cancelButtonIndex])
5197 else if (button == [alert firstOtherButtonIndex]) {
5198 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
5201 [alert dismissWithClickedButtonIndex:-1 animated:YES];
5202 } else if ([context isEqualToString:@"unable"]) {
5203 [self dismissModalViewControllerAnimated:YES];
5204 [alert dismissWithClickedButtonIndex:-1 animated:YES];
5206 [super alertView:alert clickedButtonAtIndex:button];
5210 - (void) _doContinue {
5211 [delegate_ cancelAndClear:NO];
5212 [self dismissModalViewControllerAnimated:YES];
5215 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
5216 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
5220 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5221 [super webView:view didClearWindowObject:window forFrame:frame];
5223 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
5224 (id) changes_, @"changes",
5225 (id) issues_, @"issues",
5226 (id) sizes_, @"sizes",
5228 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
5231 - (id) initWithDatabase:(Database *)database {
5232 if ((self = [super init]) != nil) {
5233 database_ = database;
5235 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
5236 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
5237 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
5238 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
5239 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
5243 pkgCacheFile &cache([database_ cache]);
5244 NSArray *packages([database_ packages]);
5245 pkgDepCache::Policy *policy([database_ policy]);
5247 issues_ = [NSMutableArray arrayWithCapacity:4];
5249 for (Package *package in packages) {
5250 pkgCache::PkgIterator iterator([package iterator]);
5251 NSString *name([package id]);
5253 if ([package broken]) {
5254 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
5256 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5258 reasons, @"reasons",
5261 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
5265 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
5266 pkgCache::DepIterator start;
5267 pkgCache::DepIterator end;
5268 dep.GlobOr(start, end); // ++dep
5270 if (!cache->IsImportantDep(end))
5272 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
5275 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
5277 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5278 [NSString stringWithUTF8String:start.DepType()], @"relationship",
5279 clauses, @"clauses",
5283 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
5285 pkgCache::PkgIterator target(start.TargetPkg());
5286 if (target->ProvidesList != 0)
5287 reason = @"missing";
5289 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
5291 reason = @"installed";
5292 installed = [NSString stringWithUTF8String:ver.VerStr()];
5293 } else if (!cache[target].CandidateVerIter(cache).end())
5294 reason = @"uninstalled";
5295 else if (target->ProvidesList == 0)
5296 reason = @"uninstallable";
5298 reason = @"virtual";
5301 NSDictionary *version(start.TargetVer() == 0 ? (NSDictionary *) [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
5302 [NSString stringWithUTF8String:start.CompType()], @"operator",
5303 [NSString stringWithUTF8String:start.TargetVer()], @"value",
5306 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5307 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
5308 version, @"version",
5310 installed, @"installed",
5313 // yes, seriously. (wtf?)
5321 pkgDepCache::StateCache &state(cache[iterator]);
5323 static RegEx special_r("(firmware|gsc\\..*|cy\\+.*)");
5325 if (state.NewInstall())
5326 [installs addObject:name];
5327 // XXX: else if (state.Install())
5328 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
5329 [reinstalls addObject:name];
5330 // XXX: move before previous if
5331 else if (state.Upgrade())
5332 [upgrades addObject:name];
5333 else if (state.Downgrade())
5334 [downgrades addObject:name];
5335 else if (!state.Delete())
5336 // XXX: _assert(state.Keep());
5338 else if (special_r(name))
5339 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5340 [NSNull null], @"package",
5341 [NSArray arrayWithObjects:
5342 [NSDictionary dictionaryWithObjectsAndKeys:
5343 @"Conflicts", @"relationship",
5344 [NSArray arrayWithObjects:
5345 [NSDictionary dictionaryWithObjectsAndKeys:
5347 [NSNull null], @"version",
5348 @"installed", @"reason",
5355 if ([package essential])
5357 [removes addObject:name];
5360 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
5361 substrate_ |= DepSubstrate(iterator.CurrentVer());
5366 else if (Advanced_) {
5367 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
5369 essential_ = [[[UIAlertView alloc]
5370 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
5371 message:UCLocalize("REMOVING_ESSENTIALS_EX")
5373 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
5375 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
5379 [essential_ setContext:@"remove"];
5380 [essential_ setNumberOfRows:2];
5382 essential_ = [[[UIAlertView alloc]
5383 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
5384 message:UCLocalize("UNABLE_TO_COMPLY_EX")
5386 cancelButtonTitle:UCLocalize("OKAY")
5387 otherButtonTitles:nil
5390 [essential_ setContext:@"unable"];
5393 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5394 installs, @"installs",
5395 reinstalls, @"reinstalls",
5396 upgrades, @"upgrades",
5397 downgrades, @"downgrades",
5398 removes, @"removes",
5401 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5402 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
5403 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
5406 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
5410 - (UIBarButtonItem *) leftButton {
5411 return [[[UIBarButtonItem alloc]
5412 initWithTitle:UCLocalize("CANCEL")
5413 style:UIBarButtonItemStylePlain
5415 action:@selector(cancelButtonClicked)
5420 - (void) applyRightButton {
5421 if ([issues_ count] == 0 && ![self isLoading])
5422 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
5423 initWithTitle:UCLocalize("CONFIRM")
5424 style:UIBarButtonItemStyleDone
5426 action:@selector(confirmButtonClicked)
5429 [[self navigationItem] setRightBarButtonItem:nil];
5433 - (void) cancelButtonClicked {
5434 [delegate_ cancelAndClear:YES];
5435 [self dismissModalViewControllerAnimated:YES];
5439 - (void) confirmButtonClicked {
5440 if (essential_ != nil)
5450 /* Progress Data {{{ */
5451 @interface CydiaProgressData : NSObject {
5452 _transient id delegate_;
5461 _H<NSMutableArray> events_;
5462 _H<NSString> title_;
5464 _H<NSString> status_;
5465 _H<NSString> finish_;
5470 @implementation CydiaProgressData
5472 + (NSArray *) _attributeKeys {
5473 return [NSArray arrayWithObjects:
5485 - (NSArray *) attributeKeys {
5486 return [[self class] _attributeKeys];
5489 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5490 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5494 if ((self = [super init]) != nil) {
5495 events_ = [NSMutableArray arrayWithCapacity:32];
5503 - (void) setDelegate:(id)delegate {
5504 delegate_ = delegate;
5507 - (void) setPercent:(float)value {
5511 - (NSNumber *) percent {
5512 return [NSNumber numberWithFloat:percent_];
5515 - (void) setCurrent:(float)value {
5519 - (NSNumber *) current {
5520 return [NSNumber numberWithFloat:current_];
5523 - (void) setTotal:(float)value {
5527 - (NSNumber *) total {
5528 return [NSNumber numberWithFloat:total_];
5531 - (void) setSpeed:(float)value {
5535 - (NSNumber *) speed {
5536 return [NSNumber numberWithFloat:speed_];
5539 - (NSArray *) events {
5543 - (void) removeAllEvents {
5544 [events_ removeAllObjects];
5547 - (void) addEvent:(CydiaProgressEvent *)event {
5548 [events_ addObject:event];
5551 - (void) setTitle:(NSString *)text {
5555 - (NSString *) title {
5559 - (void) setFinish:(NSString *)text {
5563 - (NSString *) finish {
5564 return (id) finish_ ?: [NSNull null];
5567 - (void) setRunning:(bool)running {
5571 - (NSNumber *) running {
5572 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5577 /* Progress Controller {{{ */
5578 @interface ProgressController : CydiaWebViewController <
5581 _transient Database *database_;
5582 _H<CydiaProgressData, 1> progress_;
5586 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5588 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5590 - (void) setTitle:(NSString *)title;
5591 - (void) setCancellable:(bool)cancellable;
5595 @implementation ProgressController
5598 [database_ setProgressDelegate:nil];
5602 - (UIBarButtonItem *) leftButton {
5603 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5604 initWithTitle:UCLocalize("CANCEL")
5605 style:UIBarButtonItemStylePlain
5607 action:@selector(cancel)
5608 ] autorelease] : nil;
5611 - (void) updateCancel {
5612 [super applyLeftButton];
5615 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5616 if ((self = [super init]) != nil) {
5617 database_ = database;
5618 delegate_ = delegate;
5620 [database_ setProgressDelegate:self];
5622 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5623 [progress_ setDelegate:self];
5625 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5627 [scroller_ setBackgroundColor:[UIColor blackColor]];
5629 [[self navigationItem] setHidesBackButton:YES];
5631 [self updateCancel];
5635 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5636 [super webView:view didClearWindowObject:window forFrame:frame];
5637 [window setValue:progress_ forKey:@"cydiaProgress"];
5640 - (void) updateProgress {
5641 [self dispatchEvent:@"CydiaProgressUpdate"];
5644 - (void) viewWillAppear:(BOOL)animated {
5645 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5646 [super viewWillAppear:animated];
5650 UpdateExternalStatus(0);
5653 [delegate_ saveState];
5657 [delegate_ returnToCydia];
5661 [delegate_ terminateWithSuccess];
5662 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5663 [delegate_ suspendWithAnimation:YES];
5665 [delegate_ suspend];*/
5677 UIProgressHUD *hud([delegate_ addProgressHUD]);
5678 [hud setText:UCLocalize("LOADING")];
5679 [delegate_ performSelector:@selector(reloadSpringBoard) withObject:nil afterDelay:0.5];
5685 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5686 SBReboot(SBSSpringBoardServerPort());
5688 reboot2(RB_AUTOBOOT);
5695 - (void) setTitle:(NSString *)title {
5696 [progress_ setTitle:title];
5697 [self updateProgress];
5700 - (UIBarButtonItem *) rightButton {
5701 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5702 initWithTitle:UCLocalize("CLOSE")
5703 style:UIBarButtonItemStylePlain
5705 action:@selector(close)
5709 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5710 UpdateExternalStatus(1);
5712 [progress_ setRunning:true];
5713 [self setTitle:title];
5714 // implicit updateProgress
5716 SHA1SumValue notifyconf; {
5718 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5721 MMap mmap(file, MMap::ReadOnly);
5723 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5724 notifyconf = sha1.Result();
5728 SHA1SumValue springlist; {
5730 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5733 MMap mmap(file, MMap::ReadOnly);
5735 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5736 springlist = sha1.Result();
5740 if (invocation != nil) {
5741 [invocation yieldToSelector:@selector(invoke)];
5742 [self setTitle:@"COMPLETE"];
5747 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5750 MMap mmap(file, MMap::ReadOnly);
5752 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5753 if (!(notifyconf == sha1.Result()))
5760 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5763 MMap mmap(file, MMap::ReadOnly);
5765 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5766 if (!(springlist == sha1.Result()))
5772 if (RestartSubstrate_)
5776 RestartSubstrate_ = false;
5779 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5780 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5781 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5782 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5783 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5786 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5788 [progress_ setRunning:false];
5789 [self updateProgress];
5791 [self applyRightButton];
5794 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5795 [progress_ addEvent:event];
5796 [self updateProgress];
5799 - (bool) isProgressCancelled {
5800 return cancel_ == 2;
5805 [self updateCancel];
5808 - (void) setCancellable:(bool)cancellable {
5809 unsigned cancel(cancel_);
5813 else if (cancel_ == 0)
5816 if (cancel != cancel_)
5817 [self updateCancel];
5820 - (void) setProgressCancellable:(NSNumber *)cancellable {
5821 [self setCancellable:[cancellable boolValue]];
5824 - (void) setProgressPercent:(NSNumber *)percent {
5825 [progress_ setPercent:[percent floatValue]];
5826 [self updateProgress];
5829 - (void) setProgressStatus:(NSDictionary *)status {
5830 if (status == nil) {
5831 [progress_ setCurrent:0];
5832 [progress_ setTotal:0];
5833 [progress_ setSpeed:0];
5835 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5837 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5838 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5839 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5842 [self updateProgress];
5848 /* Package Cell {{{ */
5849 @interface PackageCell : CyteTableViewCell <
5850 CyteTableViewCellDelegate
5854 _H<NSString> description_;
5856 _H<NSString> source_;
5858 _H<UIImage> placard_;
5862 - (PackageCell *) init;
5863 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5865 - (void) drawContentRect:(CGRect)rect;
5869 @implementation PackageCell
5871 - (PackageCell *) init {
5872 CGRect frame(CGRectMake(0, 0, 320, 74));
5873 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5874 UIView *content([self contentView]);
5875 CGRect bounds([content bounds]);
5877 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5878 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5879 [content addSubview:content_];
5881 [content_ setDelegate:self];
5882 [content_ setOpaque:YES];
5886 - (NSString *) accessibilityLabel {
5890 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5891 summarized_ = summary;
5901 [content_ setBackgroundColor:[UIColor whiteColor]];
5905 Source *source = [package source];
5907 icon_ = [package icon];
5909 if (NSString *name = [package name])
5910 name_ = [NSString stringWithString:name];
5912 if (NSString *description = [package shortDescription])
5913 description_ = [NSString stringWithString:description];
5915 commercial_ = [package isCommercial];
5917 NSString *label = nil;
5918 bool trusted = false;
5920 if (source != nil) {
5921 label = [source label];
5922 trusted = [source trusted];
5923 } else if ([[package id] isEqualToString:@"firmware"])
5924 label = UCLocalize("APPLE");
5926 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5928 NSString *from(label);
5930 NSString *section = [package simpleSection];
5931 if (section != nil && ![section isEqualToString:label]) {
5932 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5933 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5936 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5938 if (NSString *purpose = [package primaryPurpose])
5939 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5944 if (NSString *mode = [package mode]) {
5945 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5946 color = RemovingColor_;
5947 placard = @"removing";
5949 color = InstallingColor_;
5950 placard = @"installing";
5953 color = [UIColor whiteColor];
5955 if ([package installed] != nil)
5956 placard = @"installed";
5961 [content_ setBackgroundColor:color];
5964 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5967 [self setNeedsDisplay];
5968 [content_ setNeedsDisplay];
5971 - (void) drawSummaryContentRect:(CGRect)rect {
5972 bool highlighted(highlighted_);
5973 float width([self bounds].size.width);
5977 rect.size = [(UIImage *) icon_ size];
5979 while (rect.size.width > 16 || rect.size.height > 16) {
5980 rect.size.width /= 2;
5981 rect.size.height /= 2;
5984 rect.origin.x = 19 - rect.size.width / 2;
5985 rect.origin.y = 19 - rect.size.height / 2;
5987 [icon_ drawInRect:Retina(rect)];
5990 if (badge_ != nil) {
5992 rect.size = [(UIImage *) badge_ size];
5994 rect.size.width /= 4;
5995 rect.size.height /= 4;
5997 rect.origin.x = 25 - rect.size.width / 2;
5998 rect.origin.y = 25 - rect.size.height / 2;
6000 [badge_ drawInRect:Retina(rect)];
6003 if (highlighted && kCFCoreFoundationVersionNumber < 800)
6007 UISetColor(commercial_ ? Purple_ : Black_);
6008 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
6010 if (placard_ != nil)
6011 [placard_ drawAtPoint:CGPointMake(width - 52, 11)];
6014 - (void) drawNormalContentRect:(CGRect)rect {
6015 bool highlighted(highlighted_);
6016 float width([self bounds].size.width);
6020 rect.size = [(UIImage *) icon_ size];
6022 while (rect.size.width > 32 || rect.size.height > 32) {
6023 rect.size.width /= 2;
6024 rect.size.height /= 2;
6027 rect.origin.x = 25 - rect.size.width / 2;
6028 rect.origin.y = 25 - rect.size.height / 2;
6030 [icon_ drawInRect:Retina(rect)];
6033 if (badge_ != nil) {
6035 rect.size = [(UIImage *) badge_ size];
6037 rect.size.width /= 2;
6038 rect.size.height /= 2;
6040 rect.origin.x = 36 - rect.size.width / 2;
6041 rect.origin.y = 36 - rect.size.height / 2;
6043 [badge_ drawInRect:Retina(rect)];
6046 if (highlighted && kCFCoreFoundationVersionNumber < 800)
6050 UISetColor(commercial_ ? Purple_ : Black_);
6051 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
6052 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
6055 UISetColor(commercial_ ? Purplish_ : Gray_);
6056 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:NSLineBreakByTruncatingTail];
6058 if (placard_ != nil)
6059 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
6062 - (void) drawContentRect:(CGRect)rect {
6064 [self drawSummaryContentRect:rect];
6066 [self drawNormalContentRect:rect];
6071 /* Section Cell {{{ */
6072 @interface SectionCell : CyteTableViewCell <
6073 CyteTableViewCellDelegate
6075 _H<NSString> basic_;
6076 _H<NSString> section_;
6078 _H<NSString> count_;
6080 _H<UISwitch> switch_;
6084 - (void) setSection:(Section *)section editing:(BOOL)editing;
6088 @implementation SectionCell
6090 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
6091 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
6092 icon_ = [UIImage imageNamed:@"folder.png"];
6093 // XXX: this initial frame is wrong, but is fixed later
6094 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
6095 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
6097 UIView *content([self contentView]);
6098 CGRect bounds([content bounds]);
6100 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
6101 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6102 [content addSubview:content_];
6103 [content_ setBackgroundColor:[UIColor whiteColor]];
6105 [content_ setDelegate:self];
6109 - (void) onSwitch:(id)sender {
6110 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
6111 if (metadata == nil) {
6112 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
6113 [Sections_ setObject:metadata forKey:basic_];
6116 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
6119 - (void) setSection:(Section *)section editing:(BOOL)editing {
6120 if (editing != editing_) {
6122 [switch_ removeFromSuperview];
6124 [self addSubview:switch_];
6133 if (section == nil) {
6134 name_ = UCLocalize("ALL_PACKAGES");
6137 basic_ = [section name];
6138 section_ = [section localized];
6140 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
6141 count_ = [NSString stringWithFormat:@"%zd", [section count]];
6144 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
6147 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
6148 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
6150 [content_ setNeedsDisplay];
6153 - (void) setFrame:(CGRect)frame {
6154 [super setFrame:frame];
6156 CGRect rect([switch_ frame]);
6157 [switch_ setFrame:CGRectMake(frame.size.width - rect.size.width - 9, 9, rect.size.width, rect.size.height)];
6160 - (NSString *) accessibilityLabel {
6164 - (void) drawContentRect:(CGRect)rect {
6165 bool highlighted(highlighted_ && !editing_);
6167 [icon_ drawInRect:CGRectMake(7, 7, 32, 32)];
6169 if (highlighted && kCFCoreFoundationVersionNumber < 800)
6172 float width(rect.size.width);
6174 width -= 9 + [switch_ frame].size.width;
6178 [name_ drawAtPoint:CGPointMake(48, 12) forWidth:(width - 58) withFont:Font18_ lineBreakMode:NSLineBreakByTruncatingTail];
6180 CGSize size = [count_ sizeWithFont:Font14_];
6182 UISetColor(Folder_);
6184 [count_ drawAtPoint:CGPointMake(Retina(10 + (30 - size.width) / 2), 18) withFont:Font12Bold_];
6190 /* File Table {{{ */
6191 @interface FileTable : CyteViewController <
6192 UITableViewDataSource,
6195 _transient Database *database_;
6196 _H<Package> package_;
6198 _H<NSMutableArray> files_;
6199 _H<UITableView, 2> list_;
6202 - (id) initWithDatabase:(Database *)database;
6203 - (void) setPackage:(Package *)package;
6207 @implementation FileTable
6209 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6210 return files_ == nil ? 0 : [files_ count];
6213 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6217 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6218 static NSString *reuseIdentifier = @"Cell";
6220 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6222 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6223 [cell setFont:[UIFont systemFontOfSize:16]];
6225 [cell setText:[files_ objectAtIndex:indexPath.row]];
6226 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
6231 - (NSURL *) navigationURL {
6232 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
6236 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
6237 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6238 [list_ setRowHeight:24.0f];
6239 [(UITableView *) list_ setDataSource:self];
6240 [list_ setDelegate:self];
6241 [self setView:list_];
6244 - (void) viewDidLoad {
6245 [super viewDidLoad];
6247 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
6250 - (void) releaseSubviews {
6256 [super releaseSubviews];
6259 - (id) initWithDatabase:(Database *)database {
6260 if ((self = [super init]) != nil) {
6261 database_ = database;
6265 - (void) setPackage:(Package *)package {
6269 files_ = [NSMutableArray arrayWithCapacity:32];
6271 if (package != nil) {
6273 name_ = [package id];
6275 if (NSArray *files = [package files])
6276 [files_ addObjectsFromArray:files];
6278 if ([files_ count] != 0) {
6279 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
6280 [files_ removeObjectAtIndex:0];
6281 [files_ sortUsingSelector:@selector(compareByPath:)];
6283 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
6284 [stack addObject:@"/"];
6286 for (int i(0), e([files_ count]); i != e; ++i) {
6287 NSString *file = [files_ objectAtIndex:i];
6288 while (![file hasPrefix:[stack lastObject]])
6289 [stack removeLastObject];
6290 NSString *directory = [stack lastObject];
6291 [stack addObject:[file stringByAppendingString:@"/"]];
6292 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
6293 int(([stack count] - 2) * 3), "",
6294 [file substringFromIndex:[directory length]]
6303 - (void) reloadData {
6306 [self setPackage:[database_ packageWithName:name_]];
6311 /* Package Controller {{{ */
6312 @interface CYPackageController : CydiaWebViewController <
6313 UIActionSheetDelegate
6315 _transient Database *database_;
6316 _H<Package> package_;
6319 std::vector<std::pair<_H<NSString>, _H<NSString>>> buttons_;
6320 _H<UIActionSheet> sheet_;
6321 _H<UIBarButtonItem> button_;
6322 _H<NSArray> versions_;
6325 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer;
6329 @implementation CYPackageController
6331 - (NSURL *) navigationURL {
6332 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
6335 - (void) _clickButtonWithPackage:(Package *)package {
6336 [delegate_ installPackage:package];
6339 - (void) _clickButtonWithName:(NSString *)name {
6340 if ([name isEqualToString:@"CLEAR"])
6341 return [delegate_ clearPackage:package_];
6342 else if ([name isEqualToString:@"REMOVE"])
6343 return [delegate_ removePackage:package_];
6344 else if ([name isEqualToString:@"DOWNGRADE"]) {
6345 sheet_ = [[[UIActionSheet alloc]
6348 cancelButtonTitle:nil
6349 destructiveButtonTitle:nil
6350 otherButtonTitles:nil
6353 for (Package *version in (id) versions_)
6354 [sheet_ addButtonWithTitle:[version latest]];
6355 [sheet_ setContext:@"version"];
6357 [delegate_ showActionSheet:sheet_ fromItem:[[self navigationItem] rightBarButtonItem]];
6361 else if ([name isEqualToString:@"INSTALL"]);
6362 else if ([name isEqualToString:@"REINSTALL"]);
6363 else if ([name isEqualToString:@"UPGRADE"]);
6364 else _assert(false);
6366 [delegate_ installPackage:package_];
6369 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
6370 NSString *context([sheet context]);
6371 if (sheet_ == sheet)
6374 if ([context isEqualToString:@"modify"]) {
6375 if (button != [sheet cancelButtonIndex]) {
6377 [self performSelector:@selector(_clickButtonWithName:) withObject:buttons_[button].first afterDelay:0];
6379 [self _clickButtonWithName:buttons_[button].first];
6382 [sheet dismissWithClickedButtonIndex:button animated:YES];
6383 } else if ([context isEqualToString:@"version"]) {
6384 if (button != [sheet cancelButtonIndex]) {
6385 Package *version([versions_ objectAtIndex:button]);
6387 [self performSelector:@selector(_clickButtonWithPackage:) withObject:version afterDelay:0];
6389 [self _clickButtonWithPackage:version];
6392 [sheet dismissWithClickedButtonIndex:button animated:YES];
6396 - (bool) _allowJavaScriptPanel {
6401 - (void) _customButtonClicked {
6402 size_t count(buttons_.size());
6407 [self _clickButtonWithName:buttons_[0].first];
6409 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
6410 for (const auto &button : buttons_)
6411 [buttons addObject:button.second];
6413 sheet_ = [[[UIActionSheet alloc]
6416 cancelButtonTitle:nil
6417 destructiveButtonTitle:nil
6418 otherButtonTitles:nil
6421 for (NSString *button in buttons)
6422 [sheet_ addButtonWithTitle:button];
6423 [sheet_ setContext:@"modify"];
6425 [delegate_ showActionSheet:sheet_ fromItem:[[self navigationItem] rightBarButtonItem]];
6429 - (void) reloadButtonClicked {
6430 if (commercial_ && function_ == nil && [package_ uninstalled])
6432 [self customButtonClicked];
6435 - (void) applyLoadingTitle {
6436 // Don't show "Loading" as the title. Ever.
6439 - (UIBarButtonItem *) rightButton {
6444 - (void) setPageColor:(UIColor *)color {
6445 return [super setPageColor:nil];
6448 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer {
6449 if ((self = [super init]) != nil) {
6450 database_ = database;
6451 name_ = name == nil ? @"" : [NSString stringWithString:name];
6452 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]] withReferrer:referrer];
6456 - (void) reloadData {
6459 [sheet_ dismissWithClickedButtonIndex:[sheet_ cancelButtonIndex] animated:YES];
6462 package_ = [database_ packageWithName:name_];
6463 versions_ = [package_ downgrades];
6467 if (package_ != nil) {
6468 [(Package *) package_ parse];
6470 commercial_ = [package_ isCommercial];
6472 if ([package_ mode] != nil)
6473 buttons_.push_back(std::make_pair(@"CLEAR", UCLocalize("CLEAR")));
6474 if ([package_ source] == nil);
6475 else if ([package_ upgradableAndEssential:NO])
6476 buttons_.push_back(std::make_pair(@"UPGRADE", UCLocalize("UPGRADE")));
6477 else if ([package_ uninstalled])
6478 buttons_.push_back(std::make_pair(@"INSTALL", UCLocalize("INSTALL")));
6480 buttons_.push_back(std::make_pair(@"REINSTALL", UCLocalize("REINSTALL")));
6481 if (![package_ uninstalled])
6482 buttons_.push_back(std::make_pair(@"REMOVE", UCLocalize("REMOVE")));
6483 if ([versions_ count] != 0)
6484 buttons_.push_back(std::make_pair(@"DOWNGRADE", UCLocalize("DOWNGRADE")));
6488 switch (buttons_.size()) {
6489 case 0: title = nil; break;
6490 case 1: title = buttons_[0].second; break;
6491 default: title = UCLocalize("MODIFY"); break;
6494 button_ = [[[UIBarButtonItem alloc]
6496 style:UIBarButtonItemStylePlain
6498 action:@selector(customButtonClicked)
6502 - (bool) isLoading {
6503 return commercial_ ? [super isLoading] : false;
6509 /* Package List Controller {{{ */
6510 @interface PackageListController : CyteViewController <
6511 UITableViewDataSource,
6514 _transient Database *database_;
6516 _H<NSArray> packages_;
6517 _H<NSArray> sections_;
6518 _H<UITableView, 2> list_;
6520 _H<NSArray> thumbs_;
6521 std::vector<NSInteger> offset_;
6523 _H<NSString> title_;
6524 unsigned reloading_;
6527 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6528 - (void) setDelegate:(id)delegate;
6529 - (void) resetCursor;
6532 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages;
6536 @implementation PackageListController
6538 - (NSURL *) referrerURL {
6539 return [self navigationURL];
6542 - (bool) isSummarized {
6546 - (bool) showsSections {
6550 - (void) deselectWithAnimation:(BOOL)animated {
6551 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6554 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6555 CGRect base = [[self view] bounds];
6556 base.size.height -= bounds.size.height;
6557 base.origin = [list_ frame].origin;
6559 [UIView beginAnimations:nil context:NULL];
6560 [UIView setAnimationBeginsFromCurrentState:YES];
6561 [UIView setAnimationCurve:curve];
6562 [UIView setAnimationDuration:duration];
6563 [list_ setFrame:base];
6564 [UIView commitAnimations];
6567 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6568 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6571 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6572 [self resizeForKeyboardBounds:bounds duration:0];
6575 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6576 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6577 *curve = UIViewAnimationCurveEaseInOut;
6579 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6581 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6584 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6587 - (void) keyboardWillShow:(NSNotification *)notification {
6590 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6591 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6593 NSTimeInterval duration;
6594 UIViewAnimationCurve curve;
6595 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6597 CGRect kbframe = CGRectMake(Retina(center.x - bounds.size.width / 2), Retina(center.y - bounds.size.height / 2), bounds.size.width, bounds.size.height);
6598 UIViewController *base = self;
6599 while ([base parentOrPresentingViewController] != nil)
6600 base = [base parentOrPresentingViewController];
6601 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6602 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6604 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6605 intersection.size.height += CYStatusBarHeight();
6607 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6610 - (void) keyboardWillHide:(NSNotification *)notification {
6611 NSTimeInterval duration;
6612 UIViewAnimationCurve curve;
6613 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6615 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6618 - (void) viewWillAppear:(BOOL)animated {
6619 [super viewWillAppear:animated];
6621 [self resizeForKeyboardBounds:CGRectZero];
6622 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6623 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6626 - (void) viewWillDisappear:(BOOL)animated {
6627 [super viewWillDisappear:animated];
6629 [self resizeForKeyboardBounds:CGRectZero];
6630 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6631 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6634 - (void) viewDidAppear:(BOOL)animated {
6635 [super viewDidAppear:animated];
6636 [self deselectWithAnimation:animated];
6639 - (void) didSelectPackage:(Package *)package {
6640 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[[self referrerURL] absoluteString]] autorelease]);
6641 [view setDelegate:delegate_];
6642 [[self navigationController] pushViewController:view animated:YES];
6645 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6646 NSInteger count([sections_ count]);
6647 return count == 0 ? 1 : count;
6650 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6651 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6653 return [[sections_ objectAtIndex:section] name];
6656 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6657 if ([sections_ count] == 0)
6659 return [[sections_ objectAtIndex:section] count];
6662 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6663 @synchronized (database_) {
6664 if ([database_ era] != era_)
6667 Section *section([sections_ objectAtIndex:[path section]]);
6668 NSInteger row([path row]);
6669 Package *package([packages_ objectAtIndex:([section row] + row)]);
6670 return [[package retain] autorelease];
6673 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6674 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6676 cell = [[[PackageCell alloc] init] autorelease];
6678 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6679 [cell setPackage:package asSummary:[self isSummarized]];
6683 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6684 Package *package([self packageAtIndexPath:path]);
6685 package = [database_ packageWithName:[package id]];
6686 [self didSelectPackage:package];
6689 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6693 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6694 return offset_[index];
6697 - (void) updateHeight {
6698 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6701 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6702 if ((self = [super init]) != nil) {
6703 database_ = database;
6704 title_ = [title copy];
6705 [[self navigationItem] setTitle:title_];
6710 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
6711 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
6712 [self setView:view];
6714 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6715 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6716 [view addSubview:list_];
6718 // XXX: is 20 the most optimal number here?
6719 [list_ setSectionIndexMinimumDisplayRowCount:20];
6721 [(UITableView *) list_ setDataSource:self];
6722 [list_ setDelegate:self];
6724 [self updateHeight];
6727 - (void) releaseSubviews {
6736 [super releaseSubviews];
6739 - (void) setDelegate:(id)delegate {
6740 delegate_ = delegate;
6743 - (bool) shouldYield {
6747 - (bool) shouldBlock {
6751 - (NSMutableArray *) _reloadPackages {
6752 @synchronized (database_) {
6753 era_ = [database_ era];
6754 NSArray *packages([database_ packages]);
6756 return [NSMutableArray arrayWithArray:packages];
6759 - (void) _reloadData {
6760 if (reloading_ != 0) {
6765 NSMutableArray *packages;
6768 if ([self shouldYield]) {
6772 if (![self shouldBlock])
6775 hud = [delegate_ addProgressHUD];
6776 [hud setText:UCLocalize("LOADING")];
6780 packages = [self yieldToSelector:@selector(_reloadPackages)];
6783 [delegate_ removeProgressHUD:hud];
6784 } while (reloading_ == 2);
6786 packages = [self _reloadPackages];
6789 @synchronized (database_) {
6790 if (era_ != [database_ era])
6797 packages_ = packages;
6799 if ([self showsSections])
6800 sections_ = [self sectionsForPackages:packages];
6802 Section *section([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6803 [section setCount:[packages_ count]];
6804 sections_ = [NSArray arrayWithObject:section];
6807 [self updateHeight];
6809 _profile(PackageTable$reloadData$List)
6810 [(UITableView *) list_ setDataSource:self];
6818 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
6819 Section *prefix([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6820 size_t end([packages count]);
6822 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
6823 Section *section(prefix);
6825 thumbs_ = CollationThumbs_;
6826 offset_ = CollationOffset_;
6829 size_t offsets([CollationStarts_ count]);
6831 NSString *start([CollationStarts_ objectAtIndex:offset]);
6832 size_t length([start length]);
6834 for (size_t index(0); index != end; ++index) {
6836 Package *package([packages objectAtIndex:index]);
6837 NSString *name(PackageName(package, @selector(cyname)));
6839 //while ([start compare:name options:NSNumericSearch range:NSMakeRange(0, length) locale:CollationLocale_] != NSOrderedDescending) {
6840 while (StringNameCompare(start, name, length) != kCFCompareGreaterThan) {
6841 NSString *title([CollationTitles_ objectAtIndex:offset]);
6842 section = [[[Section alloc] initWithName:title row:index localize:NO] autorelease];
6843 [sections addObject:section];
6845 start = ++offset == offsets ? nil : [CollationStarts_ objectAtIndex:offset];
6848 length = [start length];
6852 [section addToCount];
6855 for (; offset != offsets; ++offset) {
6856 NSString *title([CollationTitles_ objectAtIndex:offset]);
6857 Section *section([[[Section alloc] initWithName:title row:end localize:NO] autorelease]);
6858 [sections addObject:section];
6861 if ([prefix count] != 0) {
6862 Section *suffix([sections lastObject]);
6863 [prefix setName:[suffix name]];
6864 [suffix setName:nil];
6865 [sections insertObject:prefix atIndex:(offsets - 1)];
6871 - (void) reloadData {
6874 if ([self shouldYield])
6875 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6880 - (void) resetCursor {
6881 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6884 - (void) clearData {
6885 [self updateHeight];
6887 [list_ setDataSource:nil];
6895 /* Filtered Package List Controller {{{ */
6896 typedef Function<bool, Package *> PackageFilter;
6897 typedef Function<void, NSMutableArray *> PackageSorter;
6898 @interface FilteredPackageListController : PackageListController {
6899 PackageFilter filter_;
6900 PackageSorter sorter_;
6903 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter;
6905 - (void) setFilter:(PackageFilter)filter;
6906 - (void) setSorter:(PackageSorter)sorter;
6910 @implementation FilteredPackageListController
6912 - (void) setFilter:(PackageFilter)filter {
6913 @synchronized (self) {
6917 - (void) setSorter:(PackageSorter)sorter {
6918 @synchronized (self) {
6922 - (NSMutableArray *) _reloadPackages {
6923 @synchronized (database_) {
6924 era_ = [database_ era];
6926 NSArray *packages([database_ packages]);
6927 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6929 PackageFilter filter;
6930 PackageSorter sorter;
6932 @synchronized (self) {
6937 _profile(PackageTable$reloadData$Filter)
6938 for (Package *package in packages)
6939 if (filter(package))
6940 [filtered addObject:package];
6948 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter {
6949 if ((self = [super initWithDatabase:database title:title]) != nil) {
6950 [self setFilter:filter];
6957 /* Home Controller {{{ */
6958 @interface HomeController : CydiaWebViewController {
6959 CFRunLoopRef runloop_;
6960 SCNetworkReachabilityRef reachability_;
6965 @implementation HomeController
6967 static void HomeControllerReachabilityCallback(SCNetworkReachabilityRef reachability, SCNetworkReachabilityFlags flags, void *info) {
6968 [(HomeController *) info dispatchEvent:@"CydiaReachabilityCallback"];
6972 if ((self = [super init]) != nil) {
6973 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6976 reachability_ = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "cydia.saurik.com");
6977 if (reachability_ != NULL) {
6978 SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
6979 SCNetworkReachabilitySetCallback(reachability_, HomeControllerReachabilityCallback, &context);
6981 CFRunLoopRef runloop(CFRunLoopGetCurrent());
6982 if (SCNetworkReachabilityScheduleWithRunLoop(reachability_, runloop, kCFRunLoopDefaultMode))
6989 if (reachability_ != NULL && runloop_ != NULL)
6990 SCNetworkReachabilityUnscheduleFromRunLoop(reachability_, runloop_, kCFRunLoopDefaultMode);
6994 - (NSURL *) navigationURL {
6995 return [NSURL URLWithString:@"cydia://home"];
6998 - (void) aboutButtonClicked {
6999 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
7001 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
7002 [alert addButtonWithTitle:UCLocalize("CLOSE")];
7003 [alert setCancelButtonIndex:0];
7006 @"Copyright \u00a9 2008-2015\n"
7009 "Jay Freeman (saurik)\n"
7010 "saurik@saurik.com\n"
7011 "http://www.saurik.com/"
7017 - (UIBarButtonItem *) leftButton {
7018 return [[[UIBarButtonItem alloc]
7019 initWithTitle:UCLocalize("ABOUT")
7020 style:UIBarButtonItemStylePlain
7022 action:@selector(aboutButtonClicked)
7029 /* Cydia Navigation Controller Interface {{{ */
7030 @interface UINavigationController (Cydia)
7032 - (NSArray *) navigationURLCollection;
7033 - (void) unloadData;
7038 /* Cydia Tab Bar Controller {{{ */
7039 @interface CydiaTabBarController : CyteTabBarController <
7040 UITabBarControllerDelegate,
7043 _transient Database *database_;
7045 _H<UIActivityIndicatorView> indicator_;
7048 // XXX: ok, "updatedelegate_"?...
7049 _transient NSObject<CydiaDelegate> *updatedelegate_;
7052 - (NSArray *) navigationURLCollection;
7053 - (void) beginUpdate;
7058 @implementation CydiaTabBarController
7060 - (NSArray *) navigationURLCollection {
7061 NSMutableArray *items([NSMutableArray array]);
7063 // XXX: Should this deal with transient view controllers?
7064 for (id navigation in [self viewControllers]) {
7065 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
7067 [items addObject:stack];
7073 - (id) initWithDatabase:(Database *)database {
7074 if ((self = [super init]) != nil) {
7075 database_ = database;
7076 [self setDelegate:self];
7078 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteTiny] autorelease];
7079 [indicator_ setOrigin:CGPointMake(kCFCoreFoundationVersionNumber >= 800 ? 2 : 4, 2)];
7081 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7085 - (void) beginUpdate {
7089 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
7090 UITabBarItem *item([controller tabBarItem]);
7092 [item setBadgeValue:@""];
7093 UIView *badge(MSHookIvar<UIView *>([item view], "_badge"));
7095 [indicator_ startAnimating];
7096 [badge addSubview:indicator_];
7098 [updatedelegate_ retainNetworkActivityIndicator];
7102 detachNewThreadSelector:@selector(performUpdate)
7108 - (void) performUpdate {
7109 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
7111 SourceStatus status(self, database_);
7112 [database_ updateWithStatus:status];
7115 performSelectorOnMainThread:@selector(completeUpdate)
7123 - (void) stopUpdateWithSelector:(SEL)selector {
7125 [updatedelegate_ releaseNetworkActivityIndicator];
7127 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
7128 [[controller tabBarItem] setBadgeValue:nil];
7130 [indicator_ removeFromSuperview];
7131 [indicator_ stopAnimating];
7133 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
7136 - (void) completeUpdate {
7139 [self stopUpdateWithSelector:@selector(reloadData)];
7142 - (void) cancelUpdate {
7143 [self stopUpdateWithSelector:@selector(updateDataAndLoad)];
7146 - (void) cancelPressed {
7147 [self cancelUpdate];
7154 - (bool) isSourceCancelled {
7158 - (void) startSourceFetch:(NSString *)uri {
7161 - (void) stopSourceFetch:(NSString *)uri {
7164 - (void) setUpdateDelegate:(id)delegate {
7165 updatedelegate_ = delegate;
7171 /* Cydia Navigation Controller Implementation {{{ */
7172 @implementation UINavigationController (Cydia)
7174 - (NSArray *) navigationURLCollection {
7175 NSMutableArray *stack([NSMutableArray array]);
7177 for (CyteViewController *controller in [self viewControllers]) {
7178 NSString *url = [[controller navigationURL] absoluteString];
7180 [stack addObject:url];
7186 - (void) reloadData {
7189 UIViewController *visible([self visibleViewController]);
7191 [visible reloadData];
7193 // on the iPad, this view controller is ALSO visible. :(
7195 if (UIViewController *modal = [self modalViewController])
7196 if ([modal modalPresentationStyle] == UIModalPresentationFormSheet)
7197 if (UIViewController *top = [self topViewController])
7202 - (void) unloadData {
7203 for (CyteViewController *page in [self viewControllers])
7212 /* Cydia:// Protocol {{{ */
7213 @interface CydiaURLProtocol : NSURLProtocol {
7218 @implementation CydiaURLProtocol
7220 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7221 NSURL *url([request URL]);
7225 NSString *scheme([[url scheme] lowercaseString]);
7226 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7228 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7234 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7238 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7239 id<NSURLProtocolClient> client([self client]);
7241 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7243 NSData *data(UIImagePNGRepresentation(icon));
7245 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7246 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7247 [client URLProtocol:self didLoadData:data];
7248 [client URLProtocolDidFinishLoading:self];
7252 - (void) startLoading {
7253 id<NSURLProtocolClient> client([self client]);
7254 NSURLRequest *request([self request]);
7256 NSURL *url([request URL]);
7257 NSString *href([url absoluteString]);
7258 NSString *scheme([[url scheme] lowercaseString]);
7262 if ([scheme isEqualToString:@"cydia"])
7263 path = [href substringFromIndex:8];
7264 else if ([scheme isEqualToString:@"about"])
7265 path = [href substringFromIndex:12];
7266 else _assert(false);
7268 NSRange slash([path rangeOfString:@"/"]);
7271 if (slash.location == NSNotFound) {
7275 command = [path substringToIndex:slash.location];
7276 path = [path substringFromIndex:(slash.location + 1)];
7279 Database *database([Database sharedInstance]);
7282 else if ([command isEqualToString:@"application-icon"]) {
7285 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7289 if (icon == nil && $SBSCopyIconImagePNGDataForDisplayIdentifier != NULL) {
7290 NSData *data([$SBSCopyIconImagePNGDataForDisplayIdentifier(path) autorelease]);
7291 icon = [UIImage imageWithData:data];
7295 if (NSString *file = SBSCopyIconImagePathForDisplayIdentifier(path))
7296 icon = [UIImage imageAtPath:file];
7299 icon = [UIImage imageNamed:@"unknown.png"];
7301 [self _returnPNGWithImage:icon forRequest:request];
7302 } else if ([command isEqualToString:@"package-icon"]) {
7305 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7306 Package *package([database packageWithName:path]);
7310 UIImage *icon([package icon]);
7311 [self _returnPNGWithImage:icon forRequest:request];
7312 } else if ([command isEqualToString:@"uikit-image"]) {
7315 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7316 UIImage *icon(_UIImageWithName(path));
7317 [self _returnPNGWithImage:icon forRequest:request];
7318 } else if ([command isEqualToString:@"section-icon"]) {
7321 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7322 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7324 icon = [UIImage imageNamed:@"unknown.png"];
7325 [self _returnPNGWithImage:icon forRequest:request];
7327 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7331 - (void) stopLoading {
7337 /* Section Controller {{{ */
7338 @interface SectionController : FilteredPackageListController {
7340 _H<NSString> section_;
7343 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section;
7347 @implementation SectionController
7349 - (NSURL *) referrerURL {
7350 NSString *name(section_);
7351 name = name ?: @"*";
7352 NSString *key(key_);
7354 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sections/%@/%@", UI_, [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7357 - (NSURL *) navigationURL {
7358 NSString *name(section_);
7359 name = name ?: @"*";
7360 NSString *key(key_);
7362 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@/%@", [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7365 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section {
7368 title = UCLocalize("ALL_PACKAGES");
7369 else if (![section isEqual:@""])
7370 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(section) value:nil table:@"Sections"];
7372 title = UCLocalize("NO_SECTION");
7374 if ((self = [super initWithDatabase:database title:title]) != nil) {
7375 key_ = [source key];
7380 - (void) reloadData {
7381 Source *source([database_ sourceWithKey:key_]);
7382 _H<NSString> name(section_);
7384 [self setFilter:[=](Package *package) {
7385 NSString *section([package section]);
7389 section == nil && [name length] == 0 ||
7390 [name isEqualToString:section]
7393 [package source] == source
7394 ) && [package visible];
7402 /* Sections Controller {{{ */
7403 @interface SectionsController : CyteViewController <
7404 UITableViewDataSource,
7407 _transient Database *database_;
7409 _H<NSMutableArray> sections_;
7410 _H<NSMutableArray> filtered_;
7411 _H<UITableView, 2> list_;
7414 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7415 - (void) editButtonClicked;
7419 @implementation SectionsController
7421 - (NSURL *) navigationURL {
7422 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
7425 - (Source *) source {
7428 return [database_ sourceWithKey:key_];
7431 - (void) updateNavigationItem {
7432 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7433 if ([sections_ count] == 0) {
7434 [[self navigationItem] setRightBarButtonItem:nil];
7436 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7437 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7439 action:@selector(editButtonClicked)
7440 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7444 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7445 [super setEditing:editing animated:animated];
7450 [delegate_ updateData];
7452 [self updateNavigationItem];
7455 - (void) viewDidAppear:(BOOL)animated {
7456 [super viewDidAppear:animated];
7457 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7460 - (void) viewWillDisappear:(BOOL)animated {
7461 [super viewWillDisappear:animated];
7462 [self setEditing:NO];
7465 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7466 Section *section = nil;
7467 int index = [indexPath row];
7468 if (![self isEditing]) {
7471 section = [filtered_ objectAtIndex:index];
7473 section = [sections_ objectAtIndex:index];
7478 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7479 if ([self isEditing])
7480 return [sections_ count];
7482 return [filtered_ count] + 1;
7485 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7489 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7490 static NSString *reuseIdentifier = @"SectionCell";
7492 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7494 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7496 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7501 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7502 if ([self isEditing])
7505 Section *section = [self sectionAtIndexPath:indexPath];
7507 SectionController *controller = [[[SectionController alloc]
7508 initWithDatabase:database_
7509 source:[self source]
7510 section:[section name]
7512 [controller setDelegate:delegate_];
7514 [[self navigationController] pushViewController:controller animated:YES];
7518 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
7519 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7520 [list_ setRowHeight:46];
7521 [(UITableView *) list_ setDataSource:self];
7522 [list_ setDelegate:self];
7523 [self setView:list_];
7526 - (void) viewDidLoad {
7527 [super viewDidLoad];
7529 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7532 - (void) releaseSubviews {
7538 [super releaseSubviews];
7541 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7542 if ((self = [super init]) != nil) {
7543 database_ = database;
7544 key_ = [source key];
7548 - (void) reloadData {
7551 NSArray *packages = [database_ packages];
7553 sections_ = [NSMutableArray arrayWithCapacity:16];
7554 filtered_ = [NSMutableArray arrayWithCapacity:16];
7556 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7558 Source *source([self source]);
7561 for (Package *package in packages) {
7562 if (source != nil && [package source] != source)
7565 NSString *name([package section]);
7566 NSString *key(name == nil ? @"" : name);
7570 _profile(SectionsView$reloadData$Section)
7571 section = [sections objectForKey:key];
7572 if (section == nil) {
7573 _profile(SectionsView$reloadData$Section$Allocate)
7574 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7575 [sections setObject:section forKey:key];
7580 [section addToCount];
7582 _profile(SectionsView$reloadData$Filter)
7583 if (![package visible])
7591 [sections_ addObjectsFromArray:[sections allValues]];
7593 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7595 for (Section *section in (id) sections_) {
7596 size_t count([section row]);
7600 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7601 [section setCount:count];
7602 [filtered_ addObject:section];
7605 [self updateNavigationItem];
7610 - (void) editButtonClicked {
7611 [self setEditing:![self isEditing] animated:YES];
7617 /* Changes Controller {{{ */
7618 @interface ChangesController : FilteredPackageListController {
7622 - (id) initWithDatabase:(Database *)database;
7626 @implementation ChangesController
7628 - (NSURL *) referrerURL {
7629 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/changes/", UI_]];
7632 - (NSURL *) navigationURL {
7633 return [NSURL URLWithString:@"cydia://changes"];
7636 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7637 @synchronized (database_) {
7638 if ([database_ era] != era_)
7641 NSUInteger sectionIndex([path section]);
7642 if (sectionIndex >= [sections_ count])
7644 Section *section([sections_ objectAtIndex:sectionIndex]);
7645 NSInteger row([path row]);
7646 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7649 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7650 NSString *context([alert context]);
7652 if ([context isEqualToString:@"norefresh"])
7653 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7656 - (void) setLeftBarButtonItem {
7657 if ([delegate_ updating])
7658 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7659 initWithTitle:UCLocalize("CANCEL")
7660 style:UIBarButtonItemStyleDone
7662 action:@selector(cancelButtonClicked)
7663 ] autorelease] animated:YES];
7665 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7666 initWithTitle:UCLocalize("REFRESH")
7667 style:UIBarButtonItemStylePlain
7669 action:@selector(refreshButtonClicked)
7670 ] autorelease] animated:YES];
7673 - (void) refreshButtonClicked {
7674 if ([delegate_ requestUpdate])
7675 [self setLeftBarButtonItem];
7678 - (void) cancelButtonClicked {
7679 [delegate_ cancelUpdate];
7682 - (void) upgradeButtonClicked {
7683 [delegate_ distUpgrade];
7684 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7687 - (bool) shouldYield {
7691 - (bool) shouldBlock {
7695 - (void) useFilter {
7696 @synchronized (self) {
7697 [self setFilter:[](Package *package) {
7698 return [package upgradableAndEssential:YES] || [package visible];
7701 [self setSorter:[](NSMutableArray *packages) {
7702 [packages radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7706 - (id) initWithDatabase:(Database *)database {
7707 if ((self = [super initWithDatabase:database title:UCLocalize("CHANGES")]) != nil) {
7712 - (void) viewDidLoad {
7713 [super viewDidLoad];
7714 [self setLeftBarButtonItem];
7717 - (void) viewWillAppear:(BOOL)animated {
7718 [super viewWillAppear:animated];
7719 [self setLeftBarButtonItem];
7722 - (void) reloadData {
7723 [self setLeftBarButtonItem];
7727 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
7728 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
7730 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7731 Section *ignored = nil;
7732 Section *section = nil;
7736 bool unseens = false;
7738 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7740 for (size_t offset = 0, count = [packages count]; offset != count; ++offset) {
7741 Package *package = [packages objectAtIndex:offset];
7743 BOOL uae = [package upgradableAndEssential:YES];
7747 time_t seen([package seen]);
7749 if (section == nil || last != seen) {
7753 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7756 _profile(ChangesController$reloadData$Allocate)
7757 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7758 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7759 [sections addObject:section];
7763 [section addToCount];
7764 } else if ([package ignored]) {
7765 if (ignored == nil) {
7766 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7768 [ignored addToCount];
7771 [upgradable addToCount];
7776 CFRelease(formatter);
7779 Section *last = [sections lastObject];
7780 size_t count = [last count];
7781 [packages removeObjectsInRange:NSMakeRange([packages count] - count, count)];
7782 [sections removeLastObject];
7785 if ([ignored count] != 0)
7786 [sections insertObject:ignored atIndex:0];
7788 [sections insertObject:upgradable atIndex:0];
7792 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7793 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7794 style:UIBarButtonItemStylePlain
7796 action:@selector(upgradeButtonClicked)
7797 ] autorelease]) animated:YES];
7804 /* Search Controller {{{ */
7805 @interface SearchController : FilteredPackageListController <
7808 _H<UISearchBar, 1> search_;
7813 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7814 - (void) reloadData;
7818 @implementation SearchController
7820 - (NSURL *) referrerURL {
7821 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/search?q=%@", UI_, [([search_ text] ?: @"") stringByAddingPercentEscapesIncludingReserved]]];
7824 - (NSURL *) navigationURL {
7825 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7826 return [NSURL URLWithString:@"cydia://search"];
7828 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [[search_ text] stringByAddingPercentEscapesIncludingReserved]]];
7831 - (NSArray *) termsForQuery:(NSString *)query {
7832 NSMutableArray *terms([NSMutableArray arrayWithCapacity:2]);
7833 for (NSString *component in [query componentsSeparatedByString:@" "])
7834 if ([component length] != 0)
7835 [terms addObject:component];
7840 - (void) useSearch {
7841 _H<NSArray> query([self termsForQuery:[search_ text]]);
7844 @synchronized (self) {
7845 [self setFilter:[=](Package *package) {
7846 if (![package unfiltered])
7848 if (![package matches:query])
7853 [self setSorter:[](NSMutableArray *packages) {
7854 [packages radixSortUsingSelector:@selector(rank)];
7862 - (void) usePrefix:(NSString *)prefix {
7863 _H<NSString> query(prefix);
7866 @synchronized (self) {
7867 [self setFilter:[=](Package *package) {
7868 if ([query length] == 0)
7870 if (![package unfiltered])
7872 if ([[package name] compare:query options:MatchCompareOptions_ range:NSMakeRange(0, [query length])] != NSOrderedSame)
7877 [self setSorter:nullptr];
7883 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7885 [self usePrefix:[search_ text]];
7888 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7889 [search_ resignFirstResponder];
7893 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7894 [search_ setText:@""];
7895 [self searchBarButtonClicked:searchBar];
7898 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7899 [self searchBarButtonClicked:searchBar];
7902 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7903 [self usePrefix:text];
7906 - (bool) shouldYield {
7910 - (bool) shouldBlock {
7914 - (bool) isSummarized {
7918 - (bool) showsSections {
7922 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7923 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH")])) {
7924 search_ = [[[UISearchBar alloc] init] autorelease];
7925 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7926 [search_ setDelegate:self];
7928 UITextField *textField;
7929 if ([search_ respondsToSelector:@selector(searchField)])
7930 textField = [search_ searchField];
7932 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7934 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7935 [textField setEnablesReturnKeyAutomatically:NO];
7936 [[self navigationItem] setTitleView:textField];
7939 [search_ setText:query];
7944 - (void) viewDidAppear:(BOOL)animated {
7945 [super viewDidAppear:animated];
7947 if (!searchloaded_) {
7948 searchloaded_ = YES;
7949 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7950 [search_ layoutSubviews];
7953 if ([self isSummarized])
7954 [search_ becomeFirstResponder];
7957 - (void) reloadData {
7962 - (void) didSelectPackage:(Package *)package {
7963 [search_ resignFirstResponder];
7964 [super didSelectPackage:package];
7969 /* Package Settings Controller {{{ */
7970 @interface PackageSettingsController : CyteViewController <
7971 UITableViewDataSource,
7974 _transient Database *database_;
7976 _H<Package> package_;
7977 _H<UITableView, 2> table_;
7978 _H<UISwitch> subscribedSwitch_;
7979 _H<UISwitch> ignoredSwitch_;
7980 _H<UITableViewCell> subscribedCell_;
7981 _H<UITableViewCell> ignoredCell_;
7984 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7988 @implementation PackageSettingsController
7990 - (NSURL *) navigationURL {
7991 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
7994 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7995 if (package_ == nil)
7998 if ([package_ installed] == nil)
8004 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8005 if (package_ == nil)
8008 // both sections contain just one item right now.
8012 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8016 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8018 return UCLocalize("SHOW_ALL_CHANGES_EX");
8020 return UCLocalize("IGNORE_UPGRADES_EX");
8023 - (void) onSubscribed:(id)control {
8024 bool value([control isOn]);
8025 if (package_ == nil)
8027 if ([package_ setSubscribed:value])
8028 [delegate_ updateData];
8031 - (void) _updateIgnored {
8032 const char *package([name_ UTF8String]);
8033 bool on([ignoredSwitch_ isOn]);
8035 FILE *dpkg(popen("/usr/libexec/cydia/cydo --set-selections", "w"));
8036 fwrite(package, strlen(package), 1, dpkg);
8039 fwrite(" hold\n", 6, 1, dpkg);
8041 fwrite(" install\n", 9, 1, dpkg);
8046 - (void) onIgnored:(id)control {
8047 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
8048 [invocation setTarget:self];
8049 [invocation setSelector:@selector(_updateIgnored)];
8051 [delegate_ reloadDataWithInvocation:invocation];
8054 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8055 if (package_ == nil)
8058 switch ([indexPath section]) {
8059 case 0: return subscribedCell_;
8060 case 1: return ignoredCell_;
8069 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8070 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8071 [self setView:view];
8073 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
8074 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8075 [(UITableView *) table_ setDataSource:self];
8076 [table_ setDelegate:self];
8077 [view addSubview:table_];
8079 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
8080 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
8081 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
8083 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
8084 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
8085 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
8087 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
8088 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
8089 [subscribedCell_ setAccessoryView:subscribedSwitch_];
8090 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
8092 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
8093 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
8094 [ignoredCell_ setAccessoryView:ignoredSwitch_];
8095 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
8098 - (void) viewDidLoad {
8099 [super viewDidLoad];
8101 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
8104 - (void) releaseSubviews {
8106 subscribedCell_ = nil;
8108 ignoredSwitch_ = nil;
8109 subscribedSwitch_ = nil;
8111 [super releaseSubviews];
8114 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
8115 if ((self = [super init]) != nil) {
8116 database_ = database;
8121 - (void) reloadData {
8124 package_ = [database_ packageWithName:name_];
8126 if (package_ != nil) {
8127 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
8128 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
8129 } // XXX: what now, G?
8131 [table_ reloadData];
8137 /* Installed Controller {{{ */
8138 @interface InstalledController : FilteredPackageListController {
8142 - (id) initWithDatabase:(Database *)database;
8143 - (void) queueStatusDidChange;
8147 @implementation InstalledController
8149 - (NSURL *) referrerURL {
8150 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/installed/", UI_]];
8153 - (NSURL *) navigationURL {
8154 return [NSURL URLWithString:@"cydia://installed"];
8157 - (void) useRecent {
8160 @synchronized (self) {
8161 [self setFilter:[](Package *package) {
8162 return ![package uninstalled] && package->role_ < 7;
8165 [self setSorter:[](NSMutableArray *packages) {
8166 [packages radixSortUsingSelector:@selector(recent)];
8170 - (void) useFilter:(UISegmentedControl *)segmented {
8171 NSInteger selected([segmented selectedSegmentIndex]);
8173 return [self useRecent];
8174 bool simple(selected == 0);
8177 @synchronized (self) {
8178 [self setFilter:[=](Package *package) {
8179 return ![package uninstalled] && package->role_ <= (simple ? 1 : 3);
8182 [self setSorter:nullptr];
8185 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
8187 return [super sectionsForPackages:packages];
8189 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterLongStyle, kCFDateFormatterNoStyle));
8191 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
8192 Section *section(nil);
8195 for (size_t offset(0), count([packages count]); offset != count; ++offset) {
8196 Package *package([packages objectAtIndex:offset]);
8198 time_t upgraded([package upgraded]);
8199 if (upgraded < 1168364520)
8202 upgraded -= upgraded % (60 * 60 * 24);
8204 if (section == nil || upgraded != last) {
8209 continue; // XXX: name = UCLocalize("...");
8211 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:upgraded]);
8215 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
8216 [sections addObject:section];
8219 [section addToCount];
8222 CFRelease(formatter);
8226 - (id) initWithDatabase:(Database *)database {
8227 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED")]) != nil) {
8228 UISegmentedControl *segmented([[[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:UCLocalize("USER"), UCLocalize("EXPERT"), UCLocalize("RECENT"), nil]] autorelease]);
8229 [segmented setSelectedSegmentIndex:0];
8230 [segmented setSegmentedControlStyle:UISegmentedControlStyleBar];
8231 [[self navigationItem] setTitleView:segmented];
8233 [segmented addTarget:self action:@selector(modeChanged:) forEvents:UIControlEventValueChanged];
8234 [self useFilter:segmented];
8236 [self queueStatusDidChange];
8241 - (void) queueButtonClicked {
8246 - (void) queueStatusDidChange {
8249 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8250 initWithTitle:UCLocalize("QUEUE")
8251 style:UIBarButtonItemStyleDone
8253 action:@selector(queueButtonClicked)
8256 [[self navigationItem] setRightBarButtonItem:nil];
8261 - (void) modeChanged:(UISegmentedControl *)segmented {
8262 [self useFilter:segmented];
8269 /* Source Cell {{{ */
8270 @interface SourceCell : CyteTableViewCell <
8271 CyteTableViewCellDelegate,
8274 _H<Source, 1> source_;
8277 _H<NSString> origin_;
8278 _H<NSString> label_;
8279 _H<UIActivityIndicatorView> indicator_;
8282 - (void) setSource:(Source *)source;
8283 - (void) setFetch:(NSNumber *)fetch;
8287 @implementation SourceCell
8289 - (void) _setImage:(NSArray *)data {
8290 if ([url_ isEqual:[data objectAtIndex:0]]) {
8291 icon_ = [data objectAtIndex:1];
8292 [content_ setNeedsDisplay];
8296 - (void) _setSource:(NSURL *) url {
8297 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8299 if (NSData *data = [NSURLConnection
8300 sendSynchronousRequest:[NSURLRequest
8302 cachePolicy:NSURLRequestUseProtocolCachePolicy
8306 returningResponse:NULL
8309 if (UIImage *image = [UIImage imageWithData:data])
8310 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
8315 - (void) setSource:(Source *)source {
8317 [source_ setDelegate:self];
8319 [self setFetch:[NSNumber numberWithBool:[source_ fetch]]];
8321 icon_ = [UIImage imageNamed:@"unknown.png"];
8323 origin_ = [source name];
8324 label_ = [source rooturi];
8326 [content_ setNeedsDisplay];
8328 url_ = [source iconURL];
8329 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
8332 - (void) setAllSource {
8334 [indicator_ stopAnimating];
8336 icon_ = [UIImage imageNamed:@"folder.png"];
8337 origin_ = UCLocalize("ALL_SOURCES");
8338 label_ = UCLocalize("ALL_SOURCES_EX");
8339 [content_ setNeedsDisplay];
8342 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8343 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8344 UIView *content([self contentView]);
8345 CGRect bounds([content bounds]);
8347 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8348 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8349 [content_ setBackgroundColor:[UIColor whiteColor]];
8350 [content addSubview:content_];
8352 [content_ setDelegate:self];
8353 [content_ setOpaque:YES];
8355 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGraySmall] autorelease];
8356 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin];// | UIViewAutoresizingFlexibleBottomMargin];
8357 [content addSubview:indicator_];
8359 [[content_ layer] setContentsGravity:kCAGravityTopLeft];
8363 - (void) layoutSubviews {
8364 [super layoutSubviews];
8366 UIView *content([self contentView]);
8367 CGRect bounds([content bounds]);
8369 CGRect frame([indicator_ frame]);
8370 frame.origin.x = bounds.size.width - frame.size.width;
8371 frame.origin.y = Retina((bounds.size.height - frame.size.height) / 2);
8373 if (kCFCoreFoundationVersionNumber < 800)
8374 frame.origin.x -= 8;
8375 [indicator_ setFrame:frame];
8378 - (NSString *) accessibilityLabel {
8382 - (void) drawContentRect:(CGRect)rect {
8383 bool highlighted(highlighted_);
8384 float width(rect.size.width);
8388 rect.size = [(UIImage *) icon_ size];
8390 while (rect.size.width > 32 || rect.size.height > 32) {
8391 rect.size.width /= 2;
8392 rect.size.height /= 2;
8395 rect.origin.x = 26 - rect.size.width / 2;
8396 rect.origin.y = 26 - rect.size.height / 2;
8398 [icon_ drawInRect:Retina(rect)];
8401 if (highlighted && kCFCoreFoundationVersionNumber < 800)
8406 [origin_ drawAtPoint:CGPointMake(52, 8) forWidth:(width - 49) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
8410 [label_ drawAtPoint:CGPointMake(52, 29) forWidth:(width - 49) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
8413 - (void) setFetch:(NSNumber *)fetch {
8414 if ([fetch boolValue])
8415 [indicator_ startAnimating];
8417 [indicator_ stopAnimating];
8422 /* Sources Controller {{{ */
8423 @interface SourcesController : CyteViewController <
8424 UITableViewDataSource,
8427 _transient Database *database_;
8430 _H<UITableView, 2> list_;
8431 _H<NSMutableArray> sources_;
8435 _H<UIProgressHUD> hud_;
8438 NSURLConnection *trivial_bz2_;
8439 NSURLConnection *trivial_gz_;
8444 - (id) initWithDatabase:(Database *)database;
8445 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated;
8449 @implementation SourcesController
8451 - (void) _releaseConnection:(NSURLConnection *)connection {
8452 if (connection != nil) {
8453 [connection cancel];
8454 //[connection setDelegate:nil];
8455 [connection release];
8460 [self _releaseConnection:trivial_gz_];
8461 [self _releaseConnection:trivial_bz2_];
8466 - (NSURL *) navigationURL {
8467 return [NSURL URLWithString:@"cydia://sources"];
8470 - (void) viewDidAppear:(BOOL)animated {
8471 [super viewDidAppear:animated];
8472 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8475 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8479 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8481 return UCLocalize("INDIVIDUAL_SOURCES");
8485 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8488 case 1: return [sources_ count];
8493 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8494 @synchronized (database_) {
8495 if ([database_ era] != era_)
8497 if ([indexPath section] != 1)
8499 NSUInteger index([indexPath row]);
8500 if (index >= [sources_ count])
8502 return [sources_ objectAtIndex:index];
8505 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8506 static NSString *cellIdentifier = @"SourceCell";
8508 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8509 if (cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8510 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8512 Source *source([self sourceAtIndexPath:indexPath]);
8514 [cell setAllSource];
8516 [cell setSource:source];
8521 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8522 SectionsController *controller([[[SectionsController alloc]
8523 initWithDatabase:database_
8524 source:[self sourceAtIndexPath:indexPath]
8527 [controller setDelegate:delegate_];
8528 [[self navigationController] pushViewController:controller animated:YES];
8531 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8532 if ([indexPath section] != 1)
8534 Source *source = [self sourceAtIndexPath:indexPath];
8535 return [source record] != nil;
8538 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8539 _assert([indexPath section] == 1);
8540 if (editingStyle == UITableViewCellEditingStyleDelete) {
8541 Source *source = [self sourceAtIndexPath:indexPath];
8542 if (source == nil) return;
8544 [Sources_ removeObjectForKey:[source key]];
8546 [delegate_ syncData];
8550 - (void) tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath {
8551 [self updateButtonsForEditingStatusAnimated:YES];
8555 [delegate_ addTrivialSource:href_];
8558 [delegate_ syncData];
8561 - (NSString *) getWarning {
8562 NSString *href(href_);
8563 NSRange colon([href rangeOfString:@"://"]);
8564 if (colon.location != NSNotFound)
8565 href = [href substringFromIndex:(colon.location + 3)];
8566 href = [href stringByAddingPercentEscapes];
8567 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8569 NSURL *url([NSURL URLWithString:href]);
8571 NSStringEncoding encoding;
8572 NSError *error(nil);
8574 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8575 return [warning length] == 0 ? nil : warning;
8579 - (void) _endConnection:(NSURLConnection *)connection {
8580 // XXX: the memory management in this method is horribly awkward
8582 NSURLConnection **field = NULL;
8583 if (connection == trivial_bz2_)
8584 field = &trivial_bz2_;
8585 else if (connection == trivial_gz_)
8586 field = &trivial_gz_;
8587 _assert(field != NULL);
8588 [connection release];
8592 trivial_bz2_ == nil &&
8595 NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil);
8597 [delegate_ releaseNetworkActivityIndicator];
8599 [delegate_ removeProgressHUD:hud_];
8603 if (warning != nil) {
8604 UIAlertView *alert = [[[UIAlertView alloc]
8605 initWithTitle:UCLocalize("SOURCE_WARNING")
8608 cancelButtonTitle:UCLocalize("CANCEL")
8610 UCLocalize("ADD_ANYWAY"),
8614 [alert setContext:@"warning"];
8615 [alert setNumberOfRows:1];
8618 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
8624 } else if (error_ != nil) {
8625 UIAlertView *alert = [[[UIAlertView alloc]
8626 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8627 message:[error_ localizedDescription]
8629 cancelButtonTitle:UCLocalize("OK")
8630 otherButtonTitles:nil
8633 [alert setContext:@"urlerror"];
8638 UIAlertView *alert = [[[UIAlertView alloc]
8639 initWithTitle:UCLocalize("NOT_REPOSITORY")
8640 message:UCLocalize("NOT_REPOSITORY_EX")
8642 cancelButtonTitle:UCLocalize("OK")
8643 otherButtonTitles:nil
8646 [alert setContext:@"trivial"];
8656 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8657 switch ([response statusCode]) {
8663 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8664 lprintf("connection:\"%s\" didFailWithError:\"%s\"\n", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8666 [self _endConnection:connection];
8669 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8670 [self _endConnection:connection];
8673 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8674 NSURL *url([NSURL URLWithString:href]);
8676 NSMutableURLRequest *request = [NSMutableURLRequest
8678 cachePolicy:NSURLRequestUseProtocolCachePolicy
8682 [request setHTTPMethod:method];
8684 if (Machine_ != NULL)
8685 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8687 if (UniqueID_ != nil)
8688 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8690 if ([url isCydiaSecure]) {
8691 if (UniqueID_ != nil)
8692 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
8695 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8698 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8699 NSString *context([alert context]);
8701 if ([context isEqualToString:@"source"]) {
8704 NSString *href = [[alert textField] text];
8705 href = VerifySource(href);
8710 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8711 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8715 // XXX: this is stupid
8716 hud_ = [delegate_ addProgressHUD];
8717 [hud_ setText:UCLocalize("VERIFYING_URL")];
8718 [delegate_ retainNetworkActivityIndicator];
8727 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8728 } else if ([context isEqualToString:@"trivial"])
8729 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8730 else if ([context isEqualToString:@"urlerror"])
8731 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8732 else if ([context isEqualToString:@"warning"]) {
8735 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
8744 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8748 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated {
8749 BOOL editing([list_ isEditing]);
8752 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8753 initWithTitle:UCLocalize("ADD")
8754 style:UIBarButtonItemStylePlain
8756 action:@selector(addButtonClicked)
8757 ] autorelease] animated:animated];
8758 else if ([delegate_ updating])
8759 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8760 initWithTitle:UCLocalize("CANCEL")
8761 style:UIBarButtonItemStyleDone
8763 action:@selector(cancelButtonClicked)
8764 ] autorelease] animated:animated];
8766 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8767 initWithTitle:UCLocalize("REFRESH")
8768 style:UIBarButtonItemStylePlain
8770 action:@selector(refreshButtonClicked)
8771 ] autorelease] animated:animated];
8773 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8774 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8775 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8777 action:@selector(editButtonClicked)
8778 ] autorelease] animated:animated];
8782 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease];
8783 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8784 [list_ setRowHeight:53];
8785 [(UITableView *) list_ setDataSource:self];
8786 [list_ setDelegate:self];
8787 [self setView:list_];
8790 - (void) viewDidLoad {
8791 [super viewDidLoad];
8793 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8794 [self updateButtonsForEditingStatusAnimated:NO];
8797 - (void) viewWillAppear:(BOOL)animated {
8798 [super viewWillAppear:animated];
8800 [list_ setEditing:NO];
8801 [self updateButtonsForEditingStatusAnimated:NO];
8804 - (void) releaseSubviews {
8809 [super releaseSubviews];
8812 - (id) initWithDatabase:(Database *)database {
8813 if ((self = [super init]) != nil) {
8814 database_ = database;
8818 - (void) reloadData {
8820 [self updateButtonsForEditingStatusAnimated:YES];
8822 @synchronized (database_) {
8823 era_ = [database_ era];
8825 sources_ = [NSMutableArray arrayWithCapacity:16];
8826 [sources_ addObjectsFromArray:[database_ sources]];
8828 [sources_ sortUsingSelector:@selector(compareByName:)];
8831 int count([sources_ count]);
8833 for (int i = 0; i != count; i++) {
8834 if ([[sources_ objectAtIndex:i] record] == nil)
8842 - (void) showAddSourcePrompt {
8843 UIAlertView *alert = [[[UIAlertView alloc]
8844 initWithTitle:UCLocalize("ENTER_APT_URL")
8847 cancelButtonTitle:UCLocalize("CANCEL")
8849 UCLocalize("ADD_SOURCE"),
8853 [alert setContext:@"source"];
8855 [alert setNumberOfRows:1];
8856 [alert addTextFieldWithValue:@"http://" label:@""];
8858 UITextInputTraits *traits = [[alert textField] textInputTraits];
8859 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8860 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8861 [traits setKeyboardType:UIKeyboardTypeURL];
8862 // XXX: UIReturnKeyDone
8863 [traits setReturnKeyType:UIReturnKeyNext];
8868 - (void) addButtonClicked {
8869 [self showAddSourcePrompt];
8872 - (void) refreshButtonClicked {
8873 if ([delegate_ requestUpdate])
8874 [self updateButtonsForEditingStatusAnimated:YES];
8877 - (void) cancelButtonClicked {
8878 [delegate_ cancelUpdate];
8881 - (void) editButtonClicked {
8882 [list_ setEditing:![list_ isEditing] animated:YES];
8883 [self updateButtonsForEditingStatusAnimated:YES];
8889 /* Stash Controller {{{ */
8890 @interface StashController : CyteViewController {
8891 _H<UIActivityIndicatorView> spinner_;
8892 _H<UILabel> status_;
8893 _H<UILabel> caption_;
8898 @implementation StashController
8901 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8902 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8903 [self setView:view];
8905 [view setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8907 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8908 CGRect spinrect = [spinner_ frame];
8909 spinrect.origin.x = Retina([[self view] frame].size.width / 2 - spinrect.size.width / 2);
8910 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8911 [spinner_ setFrame:spinrect];
8912 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8913 [view addSubview:spinner_];
8914 [spinner_ startAnimating];
8917 captrect.size.width = [[self view] frame].size.width;
8918 captrect.size.height = 40.0f;
8919 captrect.origin.x = 0;
8920 captrect.origin.y = Retina([[self view] frame].size.height / 2 - captrect.size.height * 2);
8921 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8922 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8923 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8924 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8925 [caption_ setTextColor:[UIColor whiteColor]];
8926 [caption_ setBackgroundColor:[UIColor clearColor]];
8927 [caption_ setShadowColor:[UIColor blackColor]];
8928 [caption_ setTextAlignment:NSTextAlignmentCenter];
8929 [view addSubview:caption_];
8932 statusrect.size.width = [[self view] frame].size.width;
8933 statusrect.size.height = 30.0f;
8934 statusrect.origin.x = 0;
8935 statusrect.origin.y = Retina([[self view] frame].size.height / 2 - statusrect.size.height);
8936 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8937 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8938 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8939 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8940 [status_ setTextColor:[UIColor whiteColor]];
8941 [status_ setBackgroundColor:[UIColor clearColor]];
8942 [status_ setShadowColor:[UIColor blackColor]];
8943 [status_ setTextAlignment:NSTextAlignmentCenter];
8944 [view addSubview:status_];
8947 - (void) releaseSubviews {
8952 [super releaseSubviews];
8958 @interface CYURLCache : SDURLCache {
8963 @implementation CYURLCache
8965 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8968 else if ([event isEqualToString:@"no-cache"])
8970 else if ([event isEqualToString:@"store"])
8972 else if ([event isEqualToString:@"invalid"])
8974 else if ([event isEqualToString:@"memory"])
8976 else if ([event isEqualToString:@"disk"])
8978 else if ([event isEqualToString:@"miss"])
8981 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8985 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
8986 if (NSURLResponse *response = [cached response])
8987 if (NSString *mime = [response MIMEType])
8988 if ([mime isEqualToString:@"text/cache-manifest"]) {
8989 NSURL *url([response URL]);
8992 NSLog(@"###: %@", [url absoluteString]);
8995 @synchronized (HostConfig_) {
8996 [CachedURLs_ addObject:url];
9000 [super storeCachedResponse:cached forRequest:request];
9003 - (void) createDiskCachePath {
9004 [super createDiskCachePath];
9009 @interface Cydia : UIApplication <
9010 ConfirmationControllerDelegate,
9014 _H<UIWindow> window_;
9015 _H<CydiaTabBarController> tabbar_;
9016 _H<CyteTabBarController> emulated_;
9017 _H<AppCacheController> appcache_;
9019 _H<NSMutableArray> essential_;
9020 _H<NSMutableArray> broken_;
9022 Database *database_;
9024 _H<NSURL> starturl_;
9029 _H<StashController> stash_;
9038 @implementation Cydia
9040 - (void) lockSuspend {
9041 if (locked_++ == 0) {
9042 if ($SBSSetInterceptsMenuButtonForever != NULL)
9043 (*$SBSSetInterceptsMenuButtonForever)(true);
9045 [self setIdleTimerDisabled:YES];
9049 - (void) unlockSuspend {
9050 if (--locked_ == 0) {
9051 [self setIdleTimerDisabled:NO];
9053 if ($SBSSetInterceptsMenuButtonForever != NULL)
9054 (*$SBSSetInterceptsMenuButtonForever)(false);
9058 - (void) beginUpdate {
9059 [tabbar_ beginUpdate];
9062 - (void) cancelUpdate {
9063 [tabbar_ cancelUpdate];
9066 - (bool) requestUpdate {
9067 if (IsReachable("cydia.saurik.com")) {
9071 UIAlertView *alert = [[[UIAlertView alloc]
9072 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("REFRESH")]
9073 message:@"Host Unreachable" // XXX: Localize
9075 cancelButtonTitle:UCLocalize("OK")
9076 otherButtonTitles:nil
9079 [alert setContext:@"norefresh"];
9087 return [tabbar_ updating];
9091 if ([broken_ count] != 0) {
9092 int count = [broken_ count];
9094 UIAlertView *alert = [[[UIAlertView alloc]
9095 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
9096 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
9098 cancelButtonTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("FORCIBLY_CLEAR"), UCLocalize("UNSAFE")]
9100 UCLocalize("TEMPORARY_IGNORE"),
9104 [alert setContext:@"fixhalf"];
9105 [alert setNumberOfRows:2];
9107 } else if (!Ignored_ && [essential_ count] != 0) {
9108 int count = [essential_ count];
9110 UIAlertView *alert = [[[UIAlertView alloc]
9111 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
9112 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
9114 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
9116 UCLocalize("UPGRADE_ESSENTIAL"),
9117 UCLocalize("COMPLETE_UPGRADE"),
9121 [alert setContext:@"upgrade"];
9126 - (void) returnToCydia {
9130 - (void) reloadSpringBoard {
9131 if (kCFCoreFoundationVersionNumber >= 700) // XXX: iOS 6.x
9132 system("/usr/libexec/cydia/cydo /bin/launchctl stop com.apple.backboardd");
9134 system("/usr/libexec/cydia/cydo /bin/launchctl stop com.apple.SpringBoard");
9136 system("/usr/bin/killall backboardd SpringBoard");
9139 - (void) _saveConfig {
9140 SaveConfig(database_);
9143 // Navigation controller for the queuing badge.
9144 - (UINavigationController *) queueNavigationController {
9145 NSArray *controllers = [tabbar_ viewControllers];
9146 return [controllers objectAtIndex:3];
9149 - (void) unloadData {
9150 [tabbar_ unloadData];
9153 - (void) _updateData {
9157 UINavigationController *navigation = [self queueNavigationController];
9159 id queuedelegate = nil;
9160 if ([[navigation viewControllers] count] > 0)
9161 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9163 [queuedelegate queueStatusDidChange];
9164 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9167 - (void) _refreshIfPossible {
9168 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9170 NSDate *update([[NSDictionary dictionaryWithContentsOfFile:@ CacheState_] objectForKey:@"LastUpdate"]);
9172 bool recently = false;
9173 if (update != nil) {
9174 NSTimeInterval interval([update timeIntervalSinceNow]);
9175 if (interval > -(15*60))
9179 // Don't automatic refresh if:
9180 // - We already refreshed recently.
9181 // - We already auto-refreshed this launch.
9182 // - Auto-refresh is disabled.
9183 // - Cydia's server is not reachable
9184 if (recently || loaded_ || ManualRefresh || !IsReachable("cydia.saurik.com")) {
9185 // If we are cancelling, we need to make sure it knows it's already loaded.
9188 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9190 // We are going to load, so remember that.
9193 [tabbar_ performSelectorOnMainThread:@selector(beginUpdate) withObject:nil waitUntilDone:NO];
9199 - (void) refreshIfPossible {
9200 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
9203 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9204 _profile(reloadDataWithInvocation)
9205 @synchronized (self) {
9206 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9208 [hud setText:UCLocalize("RELOADING_DATA")];
9210 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9214 [essential_ removeAllObjects];
9215 [broken_ removeAllObjects];
9217 _profile(reloadDataWithInvocation$Essential)
9218 NSArray *packages([database_ packages]);
9219 for (Package *package in packages) {
9221 [broken_ addObject:package];
9222 if ([package upgradableAndEssential:YES] && ![package ignored]) {
9223 if ([package essential] && [package installed] != nil)
9224 [essential_ addObject:package];
9230 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9233 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9234 [changesItem setBadgeValue:badge];
9235 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9236 [self setApplicationIconBadgeNumber:changes];
9239 [changesItem setBadgeValue:nil];
9240 [changesItem setAnimatedBadge:NO];
9241 [self setApplicationIconBadgeNumber:0];
9248 [self removeProgressHUD:hud];
9255 - (void) updateData {
9259 - (void) updateDataAndLoad {
9261 if ([database_ progressDelegate] == nil)
9267 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9270 - (void) disemulate {
9271 if (emulated_ == nil)
9274 if ([window_ respondsToSelector:@selector(setRootViewController:)])
9275 [window_ setRootViewController:tabbar_];
9277 [window_ addSubview:[tabbar_ view]];
9278 [[emulated_ view] removeFromSuperview];
9282 [window_ setUserInteractionEnabled:YES];
9285 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9286 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9288 UIViewController *parent;
9289 if (emulated_ == nil)
9299 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9300 [parent presentModalViewController:navigation animated:YES];
9303 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9304 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9306 if (navigation != nil)
9307 [navigation pushViewController:progress animated:YES];
9309 [self presentModalViewController:progress force:YES];
9311 [progress invoke:invocation withTitle:title];
9315 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9316 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9319 - (void) repairWithInvocation:(NSInvocation *)invocation {
9321 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9325 - (void) repairWithSelector:(SEL)selector {
9326 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9329 - (void) reloadData {
9330 [self reloadDataWithInvocation:nil];
9331 if ([database_ progressDelegate] == nil)
9337 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9340 - (void) addSource:(NSDictionary *) source {
9341 CydiaAddSource(source);
9344 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9345 CydiaAddSource(href, distribution, sections);
9348 // XXX: this method should not return anything
9349 - (BOOL) addTrivialSource:(NSString *)href {
9350 CydiaAddSource(href, @"./");
9355 pkgProblemResolver *resolver = [database_ resolver];
9357 resolver->InstallProtect();
9358 if (!resolver->Resolve(true))
9363 // XXX: this is a really crappy way of doing this.
9364 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9365 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9366 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9367 if ([tabbar_ updating])
9368 [tabbar_ cancelUpdate];
9370 if (![database_ prepare])
9373 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9374 [page setDelegate:self];
9375 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9378 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9379 [tabbar_ presentModalViewController:confirm_ animated:YES];
9385 @synchronized (self) {
9390 - (void) clearPackage:(Package *)package {
9391 @synchronized (self) {
9398 - (void) installPackages:(NSArray *)packages {
9399 @synchronized (self) {
9400 for (Package *package in packages)
9407 - (void) installPackage:(Package *)package {
9408 @synchronized (self) {
9415 - (void) removePackage:(Package *)package {
9416 @synchronized (self) {
9423 - (void) distUpgrade {
9424 @synchronized (self) {
9425 if (![database_ upgrade])
9433 system("/usr/bin/uicache");
9438 UIProgressHUD *hud([self addProgressHUD]);
9439 [hud setText:UCLocalize("LOADING")];
9440 [self yieldToSelector:@selector(_uicache)];
9441 [self removeProgressHUD:hud];
9445 [database_ perform];
9446 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9447 [self performSelectorOnMainThread:@selector(uicache) withObject:nil waitUntilDone:YES];
9450 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9453 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9454 [self unlockSuspend];
9457 - (void) retainNetworkActivityIndicator {
9458 if (activity_++ == 0)
9459 [self setNetworkActivityIndicatorVisible:YES];
9462 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9466 - (void) releaseNetworkActivityIndicator {
9467 if (--activity_ == 0)
9468 [self setNetworkActivityIndicatorVisible:NO];
9471 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9476 - (void) cancelAndClear:(bool)clear {
9477 @synchronized (self) {
9489 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9490 NSString *context([alert context]);
9492 if ([context isEqualToString:@"conffile"]) {
9493 FILE *input = [database_ input];
9494 if (button == [alert cancelButtonIndex])
9495 fprintf(input, "N\n");
9496 else if (button == [alert firstOtherButtonIndex])
9497 fprintf(input, "Y\n");
9500 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9501 } else if ([context isEqualToString:@"fixhalf"]) {
9502 if (button == [alert cancelButtonIndex]) {
9503 @synchronized (self) {
9504 for (Package *broken in (id) broken_) {
9506 NSString *id(ShellEscape([broken id]));
9507 system([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /bin/rm -f"
9508 " /var/lib/dpkg/info/%@.prerm"
9509 " /var/lib/dpkg/info/%@.postrm"
9510 " /var/lib/dpkg/info/%@.preinst"
9511 " /var/lib/dpkg/info/%@.postinst"
9512 " /var/lib/dpkg/info/%@.extrainst_"
9513 "", id, id, id, id, id] UTF8String]);
9519 } else if (button == [alert firstOtherButtonIndex]) {
9520 [broken_ removeAllObjects];
9524 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9525 } else if ([context isEqualToString:@"upgrade"]) {
9526 if (button == [alert firstOtherButtonIndex]) {
9527 @synchronized (self) {
9528 for (Package *essential in (id) essential_)
9529 [essential install];
9534 } else if (button == [alert firstOtherButtonIndex] + 1) {
9536 } else if (button == [alert cancelButtonIndex]) {
9540 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9544 - (void) system:(NSString *)command {
9545 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9548 system([command UTF8String]);
9554 - (void) applicationWillSuspend {
9556 [super applicationWillSuspend];
9559 - (BOOL) isSafeToSuspend {
9562 NSLog(@"isSafeToSuspend: locked_ != 0");
9567 if ([tabbar_ modalViewController] != nil)
9570 // Use external process status API internally.
9571 // This is probably a really bad idea.
9572 // XXX: what is the point of this? does this solve anything at all?
9573 uint64_t status = 0;
9575 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9576 notify_get_state(notify_token, &status);
9577 notify_cancel(notify_token);
9582 NSLog(@"isSafeToSuspend: status != 0");
9588 NSLog(@"isSafeToSuspend: -> true");
9593 - (void) suspendReturningToLastApp:(BOOL)returning {
9594 if ([self isSafeToSuspend])
9595 [super suspendReturningToLastApp:returning];
9599 if ([self isSafeToSuspend])
9603 - (void) applicationSuspend {
9604 if ([self isSafeToSuspend])
9605 [super applicationSuspend];
9608 - (void) applicationSuspend:(__GSEvent *)event {
9609 if ([self isSafeToSuspend])
9610 [super applicationSuspend:event];
9613 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9614 if ([self isSafeToSuspend])
9615 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9618 - (void) _setSuspended:(BOOL)value {
9619 if ([self isSafeToSuspend])
9620 [super _setSuspended:value];
9623 - (UIProgressHUD *) addProgressHUD {
9624 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9625 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9627 [window_ setUserInteractionEnabled:NO];
9629 UIViewController *target(tabbar_);
9630 if (UIViewController *modal = [target modalViewController])
9633 [hud showInView:[target view]];
9639 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9640 [self unlockSuspend];
9642 [hud removeFromSuperview];
9643 [window_ setUserInteractionEnabled:YES];
9646 - (CyteViewController *) pageForPackage:(NSString *)name withReferrer:(NSString *)referrer {
9647 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name withReferrer:referrer] autorelease];
9650 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external withReferrer:(NSString *)referrer {
9651 NSString *scheme([[url scheme] lowercaseString]);
9652 if ([[url absoluteString] length] <= [scheme length] + 3)
9654 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9655 NSArray *components([path componentsSeparatedByString:@"/"]);
9657 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"]) {
9658 CyteViewController *controller([self pageForPackage:[components objectAtIndex:1] withReferrer:referrer]);
9659 if (controller != nil)
9660 [controller setDelegate:self];
9664 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9667 NSString *base([components objectAtIndex:0]);
9669 CyteViewController *controller = nil;
9671 if ([base isEqualToString:@"url"]) {
9672 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9673 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9674 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9675 } else if (!external && [components count] == 1) {
9676 if ([base isEqualToString:@"sources"]) {
9677 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9680 if ([base isEqualToString:@"home"]) {
9681 controller = [[[HomeController alloc] init] autorelease];
9684 if ([base isEqualToString:@"sections"]) {
9685 controller = [[[SectionsController alloc] initWithDatabase:database_ source:nil] autorelease];
9688 if ([base isEqualToString:@"search"]) {
9689 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9692 if ([base isEqualToString:@"changes"]) {
9693 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9696 if ([base isEqualToString:@"installed"]) {
9697 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9699 } else if ([components count] == 2) {
9700 NSString *argument = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9702 if ([base isEqualToString:@"package"]) {
9703 controller = [self pageForPackage:argument withReferrer:referrer];
9706 if (!external && [base isEqualToString:@"search"]) {
9707 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9710 if (!external && [base isEqualToString:@"sections"]) {
9711 if ([argument isEqualToString:@"all"] || [argument isEqualToString:@"*"])
9713 controller = [[[SectionController alloc] initWithDatabase:database_ source:nil section:argument] autorelease];
9716 if ([base isEqualToString:@"sources"]) {
9717 if ([argument isEqualToString:@"add"]) {
9718 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9719 [(SourcesController *)controller showAddSourcePrompt];
9721 Source *source([database_ sourceWithKey:argument]);
9722 controller = [[[SectionsController alloc] initWithDatabase:database_ source:source] autorelease];
9726 if (!external && [base isEqualToString:@"launch"]) {
9727 [self launchApplicationWithIdentifier:argument suspended:NO];
9730 } else if (!external && [components count] == 3) {
9731 NSString *arg1 = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9732 NSString *arg2 = [[components objectAtIndex:2] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9734 if ([base isEqualToString:@"package"]) {
9735 if ([arg2 isEqualToString:@"settings"]) {
9736 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9737 } else if ([arg2 isEqualToString:@"files"]) {
9738 if (Package *package = [database_ packageWithName:arg1]) {
9739 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9740 [(FileTable *)controller setPackage:package];
9745 if ([base isEqualToString:@"sections"]) {
9746 Source *source([arg1 isEqualToString:@"*"] ? nil : [database_ sourceWithKey:arg1]);
9747 NSString *section([arg2 isEqualToString:@"*"] ? nil : arg2);
9748 controller = [[[SectionController alloc] initWithDatabase:database_ source:source section:section] autorelease];
9752 [controller setDelegate:self];
9756 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9757 CyteViewController *page([self pageForURL:url forExternal:external withReferrer:nil]);
9760 [tabbar_ setUnselectedViewController:page];
9765 - (void) applicationOpenURL:(NSURL *)url {
9766 [super applicationOpenURL:url];
9771 [self openCydiaURL:url forExternal:YES];
9774 - (void) applicationWillResignActive:(UIApplication *)application {
9775 // Stop refreshing if you get a phone call or lock the device.
9776 if ([tabbar_ updating])
9777 [tabbar_ cancelUpdate];
9779 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9780 [super applicationWillResignActive:application];
9783 - (void) saveState {
9784 [[NSDictionary dictionaryWithObjectsAndKeys:
9785 @"InterfaceState", [tabbar_ navigationURLCollection],
9786 @"LastClosed", [NSDate date],
9787 @"InterfaceIndex", [NSNumber numberWithInt:[tabbar_ selectedIndex]],
9788 nil] writeToFile:@ SavedState_ atomically:YES];
9793 - (void) applicationWillTerminate:(UIApplication *)application {
9797 - (void) applicationDidEnterBackground:(UIApplication *)application {
9798 if (kCFCoreFoundationVersionNumber < 1000 && [self isSafeToSuspend])
9799 return [self terminateWithSuccess];
9800 Backgrounded_ = [NSDate date];
9804 - (void) applicationWillEnterForeground:(UIApplication *)application {
9805 if (Backgrounded_ == nil)
9808 NSTimeInterval interval([Backgrounded_ timeIntervalSinceNow]);
9810 if (interval <= -(30*60)) {
9811 [tabbar_ setSelectedIndex:0];
9812 [[[tabbar_ viewControllers] objectAtIndex:0] popToRootViewControllerAnimated:NO];
9815 if (interval <= -(15*60)) {
9816 if (IsReachable("cydia.saurik.com")) {
9817 [tabbar_ beginUpdate];
9818 [appcache_ reloadURLWithCache:YES];
9822 if ([database_ delocked])
9826 - (void) setConfigurationData:(NSString *)data {
9827 static RegEx conffile_r("'(.*)' '(.*)' ([01]) ([01])");
9829 if (!conffile_r(data)) {
9830 lprintf("E:invalid conffile\n");
9834 NSString *ofile = conffile_r[1];
9835 //NSString *nfile = conffile_r[2];
9837 UIAlertView *alert = [[[UIAlertView alloc]
9838 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9839 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9841 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9843 UCLocalize("ACCEPT_NEW_COPY"),
9844 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9848 [alert setContext:@"conffile"];
9849 [alert setNumberOfRows:2];
9853 - (void) addStashController {
9855 stash_ = [[[StashController alloc] init] autorelease];
9856 [window_ addSubview:[stash_ view]];
9859 - (void) removeStashController {
9860 [[stash_ view] removeFromSuperview];
9862 [self unlockSuspend];
9866 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9867 UpdateExternalStatus(1);
9868 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/cydo /usr/libexec/cydia/free.sh"];
9869 UpdateExternalStatus(0);
9871 [self removeStashController];
9872 [self reloadSpringBoard];
9875 - (void) setupViewControllers {
9876 tabbar_ = [[[CydiaTabBarController alloc] initWithDatabase:database_] autorelease];
9878 NSMutableArray *items;
9879 if (kCFCoreFoundationVersionNumber < 800) {
9880 items = [NSMutableArray arrayWithObjects:
9881 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage imageNamed:@"home.png"] tag:0] autorelease],
9882 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage imageNamed:@"install.png"] tag:0] autorelease],
9883 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage imageNamed:@"changes.png"] tag:0] autorelease],
9884 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage imageNamed:@"manage.png"] tag:0] autorelease],
9885 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage imageNamed:@"search.png"] tag:0] autorelease],
9888 items = [NSMutableArray arrayWithObjects:
9889 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage imageNamed:@"home7.png"] selectedImage:[UIImage imageNamed:@"home7s.png"]] autorelease],
9890 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage imageNamed:@"install7.png"] selectedImage:[UIImage imageNamed:@"install7s.png"]] autorelease],
9891 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage imageNamed:@"changes7.png"] selectedImage:[UIImage imageNamed:@"changes7s.png"]] autorelease],
9892 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage imageNamed:@"manage7.png"] selectedImage:[UIImage imageNamed:@"manage7s.png"]] autorelease],
9893 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage imageNamed:@"search7.png"] selectedImage:[UIImage imageNamed:@"search7s.png"]] autorelease],
9897 NSMutableArray *controllers([NSMutableArray array]);
9898 for (UITabBarItem *item in items) {
9899 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9900 [controller setTabBarItem:item];
9901 [controllers addObject:controller];
9903 [tabbar_ setViewControllers:controllers];
9905 [tabbar_ setUpdateDelegate:self];
9908 - (void) _sendMemoryWarningNotification {
9909 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: maybe 4_0?
9910 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationMemoryWarningNotification" object:[UIApplication sharedApplication]];
9912 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
9915 - (void) _sendMemoryWarningNotifications {
9917 [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO];
9923 - (void) applicationDidReceiveMemoryWarning:(UIApplication *)application {
9925 [[NSURLCache sharedURLCache] removeAllCachedResponses];
9928 - (void) applicationDidFinishLaunching:(id)unused {
9929 //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil];
9932 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9933 [self setApplicationSupportsShakeToEdit:NO];
9935 @synchronized (HostConfig_) {
9936 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9939 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9940 initWithMemoryCapacity:524288
9941 diskCapacity:10485760
9942 diskPath:Cache("SDURLCache")
9945 [CydiaWebViewController _initialize];
9947 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9949 // this would disallow http{,s} URLs from accessing this data
9950 //[WebView registerURLSchemeAsLocal:@"cydia"];
9952 Font12_ = [UIFont systemFontOfSize:12];
9953 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9954 Font14_ = [UIFont systemFontOfSize:14];
9955 Font18_ = [UIFont systemFontOfSize:18];
9956 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9957 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9959 essential_ = [NSMutableArray arrayWithCapacity:4];
9960 broken_ = [NSMutableArray arrayWithCapacity:4];
9962 // XXX: I really need this thing... like, seriously... I'm sorry
9963 appcache_ = [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] autorelease];
9964 [appcache_ reloadData];
9966 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9967 [window_ orderFront:self];
9968 [window_ makeKey:self];
9969 [window_ setHidden:NO];
9971 if (access("/.cydia_no_stash", F_OK) == 0);
9975 [self addStashController];
9976 // XXX: this would be much cleaner as a yieldToSelector:
9977 // that way the removeStashController could happen right here inline
9978 // we also could no longer require the useless stash_ field anymore
9979 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9984 int error(stat("/", &root));
9985 _assert(error != -1);
9987 #define Stash_(path) do { \
9988 struct stat folder; \
9989 int error(lstat((path), &folder)); \
9990 if (error != -1 && ( \
9991 folder.st_dev == root.st_dev && \
9992 S_ISDIR(folder.st_mode) \
9993 ) || error == -1 && ( \
9994 errno == ENOENT || \
9999 Stash_("/Applications");
10000 Stash_("/Library/Ringtones");
10001 Stash_("/Library/Wallpaper");
10002 //Stash_("/usr/bin");
10003 Stash_("/usr/include");
10004 Stash_("/usr/share");
10005 //Stash_("/var/lib");
10009 database_ = [Database sharedInstance];
10010 [database_ setDelegate:self];
10012 [window_ setUserInteractionEnabled:NO];
10013 [self setupViewControllers];
10015 CydiaLoadingViewController *loading([[[CydiaLoadingViewController alloc] init] autorelease]);
10016 UINavigationController *navigation([[[UINavigationController alloc] init] autorelease]);
10017 [navigation setViewControllers:[NSArray arrayWithObject:loading]];
10019 emulated_ = [[[CyteTabBarController alloc] init] autorelease];
10020 [emulated_ setViewControllers:[NSArray arrayWithObject:navigation]];
10021 [emulated_ setSelectedIndex:0];
10023 if ([emulated_ respondsToSelector:@selector(concealTabBarSelection)])
10024 [emulated_ concealTabBarSelection];
10026 if ([window_ respondsToSelector:@selector(setRootViewController:)])
10027 [window_ setRootViewController:emulated_];
10029 [window_ addSubview:[emulated_ view]];
10031 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
10035 - (NSArray *) defaultStartPages {
10036 NSMutableArray *standard = [NSMutableArray array];
10037 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
10038 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
10039 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
10040 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
10041 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
10045 - (void) loadData {
10047 if ([emulated_ modalViewController] != nil)
10048 [emulated_ dismissModalViewControllerAnimated:YES];
10049 [window_ setUserInteractionEnabled:NO];
10051 [self reloadDataWithInvocation:nil];
10052 [self refreshIfPossible];
10055 NSDictionary *state([NSDictionary dictionaryWithContentsOfFile:@ SavedState_]);
10057 int savedIndex = [[state objectForKey:@"InterfaceIndex"] intValue];
10058 NSArray *saved = [[[state objectForKey:@"InterfaceState"] mutableCopy] autorelease];
10059 int standardIndex = 0;
10060 NSArray *standard = [self defaultStartPages];
10067 NSDate *closed = [state objectForKey:@"LastClosed"];
10068 if (valid && closed != nil) {
10069 NSTimeInterval interval([closed timeIntervalSinceNow]);
10070 if (interval <= -(30*60))
10074 if (valid && [saved count] != [standard count])
10078 for (unsigned int i = 0; i < [standard count]; i++) {
10079 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
10080 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
10081 // but it's good enough for now.
10082 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
10089 NSArray *items = nil;
10091 [tabbar_ setSelectedIndex:savedIndex];
10094 [tabbar_ setSelectedIndex:standardIndex];
10098 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
10099 NSArray *stack = [items objectAtIndex:tab];
10100 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
10101 NSMutableArray *current = [NSMutableArray array];
10103 for (unsigned int nav = 0; nav < [stack count]; nav++) {
10104 NSString *addr = [stack objectAtIndex:nav];
10105 NSURL *url = [NSURL URLWithString:addr];
10106 CyteViewController *page = [self pageForURL:url forExternal:NO withReferrer:nil];
10108 [current addObject:page];
10111 [navigation setViewControllers:current];
10114 // (Try to) show the startup URL.
10115 if (starturl_ != nil) {
10116 [self openCydiaURL:starturl_ forExternal:YES];
10121 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
10123 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
10124 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
10127 if (item != nil && IsWildcat_) {
10128 [sheet showFromBarButtonItem:item animated:YES];
10130 [sheet showInView:window_];
10134 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
10135 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
10136 [progress setTitle:task];
10137 [progress addProgressEvent:event];
10140 - (void) addProgressEventForTask:(NSArray *)data {
10141 CydiaProgressEvent *event([data objectAtIndex:0]);
10142 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
10143 [self addProgressEvent:event forTask:task];
10146 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
10147 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
10153 id Alloc_(id self, SEL selector) {
10154 id object = alloc_(self, selector);
10155 lprintf("[%s]A-%p\n", self->isa->name, object);
10160 id Dealloc_(id self, SEL selector) {
10161 id object = dealloc_(self, selector);
10162 lprintf("[%s]D-%p\n", self->isa->name, object);
10166 Class $NSURLConnection;
10168 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
10169 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
10171 NSURL *url([copy URL]);
10173 NSString *host([url host]);
10174 NSString *scheme([[url scheme] lowercaseString]);
10176 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
10178 @synchronized (HostConfig_) {
10179 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
10180 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
10181 [copy setHTTPShouldUsePipelining:YES];
10183 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
10184 if ([control isEqualToString:@"max-age=0"])
10185 if ([CachedURLs_ containsObject:url]) {
10187 NSLog(@"~~~: %@", url);
10190 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
10192 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
10193 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
10194 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
10198 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
10204 static CGSize $WAKWindow$screenSize(WAKWindow *self, SEL _cmd) {
10205 CGSize size([[UIScreen mainScreen] bounds].size);
10206 /*if ([$WAKWindow respondsToSelector:@selector(hasLandscapeOrientation)])
10207 if ([$WAKWindow hasLandscapeOrientation])
10208 std::swap(size.width, size.height);*/
10212 Class $NSUserDefaults;
10214 MSHook(id, NSUserDefaults$objectForKey$, NSUserDefaults *self, SEL _cmd, NSString *key) {
10215 if ([key respondsToSelector:@selector(isEqualToString:)] && [key isEqualToString:@"WebKitLocalStorageDatabasePathPreferenceKey"])
10216 return Cache("LocalStorage");
10217 return _NSUserDefaults$objectForKey$(self, _cmd, key);
10220 static NSMutableDictionary *AutoreleaseDeepMutableCopyOfDictionary(CFTypeRef type) {
10223 if (CFGetTypeID(type) != CFDictionaryGetTypeID())
10225 CFTypeRef copy(CFPropertyListCreateDeepCopy(kCFAllocatorDefault, type, kCFPropertyListMutableContainers));
10227 return [(NSMutableDictionary *) copy autorelease];
10230 int main_store(int, char *argv[]);
10232 int main(int argc, char *argv[]) {
10234 const char *argv0(argv[0]);
10235 if (const char *slash = strrchr(argv0, '/'))
10238 else if (!strcmp(argv0, "store"))
10239 return main_store(argc, argv);
10242 int fd(open("/tmp/cydia.log", O_WRONLY | O_APPEND | O_CREAT, 0644));
10246 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10250 UpdateExternalStatus(0);
10252 UIScreen *screen([UIScreen mainScreen]);
10253 if ([screen respondsToSelector:@selector(scale)])
10254 ScreenScale_ = [screen scale];
10258 UIDevice *device([UIDevice currentDevice]);
10259 if ([device respondsToSelector:@selector(userInterfaceIdiom)]) {
10260 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10261 if (idiom == UIUserInterfaceIdiomPad)
10265 Idiom_ = IsWildcat_ ? @"ipad" : @"iphone";
10267 RegEx pattern("([0-9]+\\.[0-9]+).*");
10269 if (pattern([device systemVersion]))
10270 Firmware_ = pattern[1];
10271 if (pattern(Cydia_))
10272 Major_ = pattern[1];
10274 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
10276 HostConfig_ = [[[NSObject alloc] init] autorelease];
10277 @synchronized (HostConfig_) {
10278 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10279 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
10280 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
10281 CachedURLs_ = [NSMutableSet setWithCapacity:32];
10284 NSString *ui(@"ui/ios");
10286 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
10287 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"/%@", Major_]];
10288 UI_ = CydiaURL(ui);
10290 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10292 /* Library Hacks {{{ */
10293 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10295 $WAKWindow = objc_getClass("WAKWindow");
10296 if ($WAKWindow != NULL)
10297 if (Method method = class_getInstanceMethod($WAKWindow, @selector(screenSize)))
10298 method_setImplementation(method, (IMP) &$WAKWindow$screenSize);
10300 $NSURLConnection = objc_getClass("NSURLConnection");
10301 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10302 if (NSURLConnection$init$ != NULL) {
10303 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10304 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10307 $NSUserDefaults = objc_getClass("NSUserDefaults");
10308 Method NSUserDefaults$objectForKey$(class_getInstanceMethod($NSUserDefaults, @selector(objectForKey:)));
10309 if (NSUserDefaults$objectForKey$ != NULL) {
10310 _NSUserDefaults$objectForKey$ = reinterpret_cast<id (*)(NSUserDefaults *, SEL, NSString *)>(method_getImplementation(NSUserDefaults$objectForKey$));
10311 method_setImplementation(NSUserDefaults$objectForKey$, reinterpret_cast<IMP>(&$NSUserDefaults$objectForKey$));
10314 /* Set Locale {{{ */
10315 Locale_ = CFLocaleCopyCurrent();
10316 Languages_ = [NSLocale preferredLanguages];
10318 std::string languages;
10319 const char *translation(NULL);
10321 // XXX: this isn't really a language, but this is compatible with older Cydia builds
10322 if (Locale_ != NULL)
10323 if (const char *language = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String]) {
10324 RegEx pattern("([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?");
10325 if (pattern(language)) {
10326 translation = strdup([pattern->*@"%1$@%2$@" UTF8String]);
10327 languages += translation;
10332 if (Languages_ != nil)
10333 for (NSString *language : Languages_) {
10334 languages += [language UTF8String];
10339 NSLog(@"Setting Language: [%s] %s", translation, languages.c_str());
10341 /* Index Collation {{{ */
10342 if (Class $UILocalizedIndexedCollation = objc_getClass("UILocalizedIndexedCollation")) { @try {
10343 NSBundle *bundle([NSBundle bundleForClass:$UILocalizedIndexedCollation]);
10344 NSString *path([bundle pathForResource:@"UITableViewLocalizedSectionIndex" ofType:@"plist"]);
10345 //path = @"/System/Library/Frameworks/UIKit.framework/.lproj/UITableViewLocalizedSectionIndex.plist";
10346 NSDictionary *dictionary([NSDictionary dictionaryWithContentsOfFile:path]);
10347 _H<UILocalizedIndexedCollation> collation([[[$UILocalizedIndexedCollation alloc] initWithDictionary:dictionary] autorelease]);
10349 CollationLocale_ = MSHookIvar<NSLocale *>(collation, "_locale");
10351 if (kCFCoreFoundationVersionNumber >= 800 && [[CollationLocale_ localeIdentifier] isEqualToString:@"zh@collation=stroke"]) {
10352 CollationThumbs_ = [NSArray arrayWithObjects:@"1",@"•",@"4",@"•",@"7",@"•",@"10",@"•",@"13",@"•",@"16",@"•",@"19",@"A",@"•",@"E",@"•",@"I",@"•",@"M",@"•",@"R",@"•",@"V",@"•",@"Z",@"#",nil];
10353 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})
10354 CollationOffset_.push_back(offset);
10355 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];
10356 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];
10359 CollationThumbs_ = [collation sectionIndexTitles];
10360 for (size_t index(0), end([CollationThumbs_ count]); index != end; ++index)
10361 CollationOffset_.push_back([collation sectionForSectionIndexTitleAtIndex:index]);
10363 CollationTitles_ = [collation sectionTitles];
10364 CollationStarts_ = MSHookIvar<NSArray *>(collation, "_sectionStartStrings");
10366 NSString *&transform(MSHookIvar<NSString *>(collation, "_transform"));
10367 if (&transform != NULL && transform != nil) {
10368 /*if ([collation respondsToSelector:@selector(transformedCollationStringForString:)])
10369 CollationModify_ = [=](NSString *value) { return [collation transformedCollationStringForString:value]; };*/
10370 const UChar *uid(reinterpret_cast<const UChar *>([transform cStringUsingEncoding:NSUnicodeStringEncoding]));
10371 UErrorCode code(U_ZERO_ERROR);
10372 CollationTransl_ = utrans_openU(uid, -1, UTRANS_FORWARD, NULL, 0, NULL, &code);
10373 if (!U_SUCCESS(code))
10374 NSLog(@"%s", u_errorName(code));
10378 } @catch (NSException *e) {
10382 CollationLocale_ = [[[NSLocale alloc] initWithLocaleIdentifier:@"en@collation=dictionary"] autorelease];
10384 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];
10385 for (NSInteger offset(0); offset != 28; ++offset)
10386 CollationOffset_.push_back(offset);
10388 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];
10389 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];
10392 /* Parse Arguments {{{ */
10393 bool substrate(false);
10399 for (int argi(1); argi != argc; ++argi)
10400 if (strcmp(argv[argi], "--") == 0) {
10402 argv[argi] = argv[0];
10408 for (int argi(1); argi != arge; ++argi)
10409 if (strcmp(args[argi], "--substrate") == 0)
10412 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10416 App_ = [[NSBundle mainBundle] bundlePath];
10419 Cache_ = [[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia", @"/var/mobile"] retain];
10420 mkdir([Cache_ UTF8String], 0755);
10422 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10423 alloc_ = alloc->method_imp;
10424 alloc->method_imp = (IMP) &Alloc_;*/
10426 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10427 dealloc_ = dealloc->method_imp;
10428 dealloc->method_imp = (IMP) &Dealloc_;*/
10430 void *gestalt(dlopen("/usr/lib/libMobileGestalt.dylib", RTLD_GLOBAL | RTLD_LAZY));
10431 $MGCopyAnswer = reinterpret_cast<CFStringRef (*)(CFStringRef)>(dlsym(gestalt, "MGCopyAnswer"));
10433 /* System Information {{{ */
10437 size = sizeof(maxproc);
10438 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10439 perror("sysctlbyname(\"kern.maxproc\", ?)");
10440 else if (maxproc < 64) {
10442 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10443 perror("sysctlbyname(\"kern.maxproc\", #)");
10446 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10447 char *osversion = new char[size];
10448 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10449 perror("sysctlbyname(\"kern.osversion\", ?)");
10451 System_ = [NSString stringWithUTF8String:osversion];
10453 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10454 char *machine = new char[size];
10455 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10456 perror("sysctlbyname(\"hw.machine\", ?)");
10458 Machine_ = machine;
10460 int64_t usermem(0);
10461 size = sizeof(usermem);
10462 if (sysctlbyname("hw.usermem", &usermem, &size, NULL, 0) == -1)
10465 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10466 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10467 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10469 UniqueID_ = UniqueIdentifier(device);
10471 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10472 Product_ = [info objectForKey:@"SafariProductVersion"];
10473 Safari_ = [info objectForKey:@"CFBundleVersion"];
10476 NSString *agent([NSString stringWithFormat:@"Cydia/%@ CyF/%.2f", Cydia_, kCFCoreFoundationVersionNumber]);
10478 if (RegEx match = RegEx("([0-9]+(\\.[0-9]+)+).*", Safari_))
10479 agent = [NSString stringWithFormat:@"Safari/%@ %@", match[1], agent];
10480 if (RegEx match = RegEx("([0-9]+[A-Z][0-9]+[a-z]?).*", System_))
10481 agent = [NSString stringWithFormat:@"Mobile/%@ %@", match[1], agent];
10482 if (RegEx match = RegEx("([0-9]+(\\.[0-9]+)+).*", Product_))
10483 agent = [NSString stringWithFormat:@"Version/%@ %@", match[1], agent];
10485 UserAgent_ = agent;
10487 /* Load Database {{{ */
10488 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10491 mkdir("/var/mobile/Library/Cydia", 0755);
10492 MetaFile_.Open("/var/mobile/Library/Cydia/metadata.cb0");
10495 Values_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaValues"), CFSTR("com.saurik.Cydia")));
10496 Sections_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaSections"), CFSTR("com.saurik.Cydia")));
10497 Sources_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaSources"), CFSTR("com.saurik.Cydia")));
10498 Version_ = [(NSNumber *) CFPreferencesCopyAppValue(CFSTR("CydiaVersion"), CFSTR("com.saurik.Cydia")) autorelease];
10501 NSDictionary *metadata([[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease]);
10503 if (Values_ == nil)
10504 Values_ = [metadata objectForKey:@"Values"];
10505 if (Values_ == nil)
10506 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10508 if (Sections_ == nil)
10509 Sections_ = [metadata objectForKey:@"Sections"];
10510 if (Sections_ == nil)
10511 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10513 if (Sources_ == nil)
10514 Sources_ = [metadata objectForKey:@"Sources"];
10515 if (Sources_ == nil)
10516 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10518 // XXX: this wrong, but in a way that doesn't matter :/
10519 if (Version_ == nil)
10520 Version_ = [metadata objectForKey:@"Version"];
10521 if (Version_ == nil)
10522 Version_ = [NSNumber numberWithUnsignedInt:0];
10524 if (NSDictionary *packages = [metadata objectForKey:@"Packages"]) {
10526 CFDictionaryApplyFunction((CFDictionaryRef) packages, &PackageImport, &fail);
10529 NSLog(@"unable to import package preferences... from 2010? oh well :/");
10532 if ([Version_ unsignedIntValue] == 0) {
10533 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10534 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10535 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10536 CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./");
10538 Version_ = [NSNumber numberWithUnsignedInt:1];
10540 if (NSMutableDictionary *cache = [NSMutableDictionary dictionaryWithContentsOfFile:@ CacheState_]) {
10541 [cache removeObjectForKey:@"LastUpdate"];
10542 [cache writeToFile:@ CacheState_ atomically:YES];
10546 _H<NSMutableArray> broken([NSMutableArray array]);
10547 for (NSString *key in (id) Sources_)
10548 if ([key rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"# "]].location != NSNotFound || ![([[Sources_ objectForKey:key] objectForKey:@"URI"] ?: @"/") hasSuffix:@"/"])
10549 [broken addObject:key];
10550 if ([broken count] != 0)
10551 for (NSString *key in (id) broken)
10552 [Sources_ removeObjectForKey:key];
10556 system("/usr/libexec/cydia/cydo /bin/rm -f /var/lib/cydia/metadata.plist");
10559 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10561 if (kCFCoreFoundationVersionNumber > 1000)
10562 system("/usr/libexec/cydia/cydo /usr/libexec/cydia/setnsfpn /var/lib");
10564 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10566 if (access("/User", F_OK) != 0 || version != 6) {
10568 system("/usr/libexec/cydia/cydo /usr/libexec/cydia/firmware.sh");
10572 if (access("/tmp/cydia.chk", F_OK) == 0) {
10573 if (unlink([Cache("pkgcache.bin") UTF8String]) == -1)
10574 _assert(errno == ENOENT);
10575 if (unlink([Cache("srcpkgcache.bin") UTF8String]) == -1)
10576 _assert(errno == ENOENT);
10579 system("/usr/libexec/cydia/cydo /bin/ln -sf /var/mobile/Library/Caches/com.saurik.Cydia/sources.list /etc/apt/sources.list.d/cydia.list");
10581 /* APT Initialization {{{ */
10582 _assert(pkgInitConfig(*_config));
10583 _assert(pkgInitSystem(*_config, _system));
10585 _config->Set("Acquire::AllowInsecureRepositories", true);
10586 _config->Set("Acquire::Check-Valid-Until", false);
10587 _config->Set("Dir::Bin::Methods::store", "/Applications/Cydia.app/store");
10589 _config->Set("pkgCacheGen::ForceEssential", "");
10591 if (translation != NULL)
10592 _config->Set("APT::Acquire::Translation", translation);
10593 _config->Set("Acquire::Languages", languages);
10595 // XXX: this timeout might be important :(
10596 //_config->Set("Acquire::http::Timeout", 15);
10598 _config->Set("Acquire::http::MaxParallel", usermem >= 384 * 1024 * 1024 ? 16 : 3);
10600 mkdir([Cache("archives") UTF8String], 0755);
10601 mkdir([Cache("archives/partial") UTF8String], 0755);
10602 _config->Set("Dir::Cache", [Cache_ UTF8String]);
10604 symlink("/var/lib/apt/extended_states", [Cache("extended_states") UTF8String]);
10605 _config->Set("Dir::State", [Cache_ UTF8String]);
10607 mkdir([Cache("lists") UTF8String], 0755);
10608 mkdir([Cache("lists/partial") UTF8String], 0755);
10609 mkdir([Cache("periodic") UTF8String], 0755);
10610 _config->Set("Dir::State::Lists", [Cache("lists") UTF8String]);
10612 std::string logs("/var/mobile/Library/Logs/Cydia");
10613 mkdir(logs.c_str(), 0755);
10614 _config->Set("Dir::Log", logs);
10616 _config->Set("Dir::Bin::dpkg", "/usr/libexec/cydia/cydo");
10618 /* Color Choices {{{ */
10619 space_ = CGColorSpaceCreateDeviceRGB();
10621 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10622 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10623 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10624 Folder_.Set(space_, 0x8e/255.f, 0x8e/255.f, 0x93/255.f, 1.0);
10625 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10626 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10627 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10628 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10629 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10630 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10632 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10633 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10635 /* UIKit Configuration {{{ */
10636 // XXX: I have a feeling this was important
10637 //UIKeyboardDisableAutomaticAppearance();
10640 $SBSSetInterceptsMenuButtonForever = reinterpret_cast<void (*)(bool)>(dlsym(RTLD_DEFAULT, "SBSSetInterceptsMenuButtonForever"));
10641 $SBSCopyIconImagePNGDataForDisplayIdentifier = reinterpret_cast<NSData *(*)(NSString *)>(dlsym(RTLD_DEFAULT, "SBSCopyIconImagePNGDataForDisplayIdentifier"));
10643 const char *symbol(kCFCoreFoundationVersionNumber >= 800 ? "MGGetBoolAnswer" : "GSSystemHasCapability");
10644 BOOL (*GSSystemHasCapability)(CFStringRef) = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, symbol));
10645 bool fast = GSSystemHasCapability != NULL && GSSystemHasCapability(CFSTR("armv7"));
10647 PulseInterval_ = fast ? 50000 : 500000;
10649 Colon_ = UCLocalize("COLON_DELIMITED");
10650 Elision_ = UCLocalize("ELISION");
10651 Error_ = UCLocalize("ERROR");
10652 Warning_ = UCLocalize("WARNING");
10655 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10657 CGColorSpaceRelease(space_);
10658 CFRelease(Locale_);