1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2015 Jay Freeman (saurik)
5 /* GNU General Public License, Version 3 {{{ */
7 * Cydia is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published
9 * by the Free Software Foundation, either version 3 of the License,
10 * or (at your option) any later version.
12 * Cydia is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Cydia. If not, see <http://www.gnu.org/licenses/>.
22 // XXX: wtf/FastMalloc.h... wtf?
23 #define USE_SYSTEM_MALLOC 1
25 /* #include Directives {{{ */
26 #include "CyteKit/UCPlatform.h"
27 #include "CyteKit/Localize.h"
29 #include <unicode/ustring.h>
30 #include <unicode/utrans.h>
32 #include <objc/objc.h>
33 #include <objc/runtime.h>
35 #include <CoreGraphics/CoreGraphics.h>
36 #include <Foundation/Foundation.h>
39 #define DEPLOYMENT_TARGET_MACOSX 1
40 #define CF_BUILDING_CF 1
41 #include <CoreFoundation/CFInternal.h>
44 #include <CoreFoundation/CFUniChar.h>
46 #include <SystemConfiguration/SystemConfiguration.h>
48 #include <UIKit/UIKit.h>
49 #include "iPhonePrivate.h"
51 #include <IOKit/IOKitLib.h>
53 #include <QuartzCore/CALayer.h>
55 #include <WebCore/WebCoreThread.h>
64 #include "fdstream.hpp"
69 #include <apt-pkg/acquire.h>
70 #include <apt-pkg/acquire-item.h>
71 #include <apt-pkg/algorithms.h>
72 #include <apt-pkg/cachefile.h>
73 #include <apt-pkg/clean.h>
74 #include <apt-pkg/configuration.h>
75 #include <apt-pkg/debindexfile.h>
76 #include <apt-pkg/debmetaindex.h>
77 #include <apt-pkg/error.h>
78 #include <apt-pkg/init.h>
79 #include <apt-pkg/mmap.h>
80 #include <apt-pkg/pkgrecords.h>
81 #include <apt-pkg/sha1.h>
82 #include <apt-pkg/sourcelist.h>
83 #include <apt-pkg/sptr.h>
84 #include <apt-pkg/strutl.h>
85 #include <apt-pkg/tagfile.h>
87 #include <sys/types.h>
89 #include <sys/sysctl.h>
90 #include <sys/param.h>
91 #include <sys/mount.h>
92 #include <sys/reboot.h>
100 #include <mach-o/nlist.h>
109 #include <Cytore.hpp>
112 #include "Substrate.hpp"
113 #include "Menes/Menes.h"
115 #include "CyteKit/RegEx.hpp"
116 #include "CyteKit/TableViewCell.h"
117 #include "CyteKit/TabBarController.h"
118 #include "CyteKit/WebScriptObject-Cyte.h"
119 #include "CyteKit/WebViewController.h"
120 #include "CyteKit/WebViewTableViewCell.h"
121 #include "CyteKit/stringWithUTF8Bytes.h"
123 #include "Cydia/MIMEAddress.h"
124 #include "Cydia/LoadingViewController.h"
125 #include "Cydia/ProgressEvent.h"
127 #include "SDURLCache/SDURLCache.h"
134 #define _timestamp ({ \
136 gettimeofday(&tv, NULL); \
137 tv.tv_sec * 1000000 + tv.tv_usec; \
140 typedef std::vector<class ProfileTime *> TimeList;
150 ProfileTime(const char *name) :
154 times_.push_back(this);
157 void AddTime(uint64_t time) {
164 std::cerr << std::setw(7) << count_ << ", " << std::setw(8) << total_ << " : " << name_ << std::endl;
176 ProfileTimer(ProfileTime &time) :
183 time_.AddTime(_timestamp - start_);
188 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
190 std::cerr << "========" << std::endl;
193 #define _profile(name) { \
194 static ProfileTime name(#name); \
195 ProfileTimer _ ## name(name);
200 // XXX: I hate clang. Apple: please get over your petty hatred of GPL and fix your gcc fork
201 #define synchronized(lock) \
202 synchronized(static_cast<NSObject *>(lock))
204 extern NSString *Cydia_;
206 #define lprintf(args...) fprintf(stderr, args)
209 #define TraceLogging (1 && !ForRelease)
210 #define HistogramInsertionSort (0 && !ForRelease)
211 #define ProfileTimes (0 && !ForRelease)
212 #define ForSaurik (0 && !ForRelease)
213 #define LogBrowser (0 && !ForRelease)
214 #define TrackResize (0 && !ForRelease)
215 #define ManualRefresh (1 && !ForRelease)
216 #define ShowInternals (0 && !ForRelease)
217 #define AlwaysReload (0 && !ForRelease)
221 #define _trace(args...)
226 #define _profile(name) {
229 #define PrintTimes() do {} while (false)
232 // Hash Functions/Structures {{{
233 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
241 @implementation NSDictionary (Cydia)
242 - (id) invokeUndefinedMethodFromWebScript:(NSString *)name withArguments:(NSArray *)arguments {
244 else if ([name isEqualToString:@"get"])
245 return [self objectForKey:[arguments objectAtIndex:0]];
246 else if ([name isEqualToString:@"keys"])
247 return [self allKeys];
251 static NSString *Colon_;
253 static NSString *Error_;
254 static NSString *Warning_;
256 static NSString *Cache_;
257 #define Cache(file) \
258 [NSString stringWithFormat:@"%@/%s", Cache_, file]
260 static void (*$SBSSetInterceptsMenuButtonForever)(bool);
261 static NSData *(*$SBSCopyIconImagePNGDataForDisplayIdentifier)(NSString *);
263 static CFStringRef (*$MGCopyAnswer)(CFStringRef);
265 static NSString *UniqueIdentifier(UIDevice *device = nil) {
266 if (kCFCoreFoundationVersionNumber < 800) // iOS 7.x
267 return [device ?: [UIDevice currentDevice] uniqueIdentifier];
269 return [(id)$MGCopyAnswer(CFSTR("UniqueDeviceID")) autorelease];
272 static bool IsReachable(const char *name) {
273 SCNetworkReachabilityFlags flags; {
274 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, name));
275 SCNetworkReachabilityGetFlags(reachability, &flags);
276 CFRelease(reachability);
279 // XXX: this elaborate mess is what Apple is using to determine this? :(
280 // XXX: do we care if the user has to intervene? maybe that's ok?
282 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
283 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
284 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
285 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
286 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
287 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
292 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
294 static _finline NSString *CydiaURL(NSString *path) {
296 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
297 page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
298 page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
299 page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
300 page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
302 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
305 static NSString *ShellEscape(NSString *value) {
306 return [NSString stringWithFormat:@"'%@'", [value stringByReplacingOccurrencesOfString:@"'" withString:@"'\\''"]];
309 static _finline void UpdateExternalStatus(uint64_t newStatus) {
311 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
312 notify_set_state(notify_token, newStatus);
313 notify_cancel(notify_token);
315 notify_post("com.saurik.Cydia.status");
318 static CGFloat CYStatusBarHeight() {
319 CGSize size([[UIApplication sharedApplication] statusBarFrame].size);
320 return UIInterfaceOrientationIsPortrait([[UIApplication sharedApplication] statusBarOrientation]) ? size.height : size.width;
323 /* NSForcedOrderingSearch doesn't work on the iPhone */
324 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
325 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
326 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
328 /* Insertion Sort {{{ */
330 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
331 const char *ptr = (const char *)list;
333 CFIndex half = count / 2;
334 const char *probe = ptr + elementSize * half;
335 CFComparisonResult cr = comparator(element, probe, context);
336 if (0 == cr) return (probe - (const char *)list) / elementSize;
337 ptr = (cr < 0) ? ptr : probe + elementSize;
338 count = (cr < 0) ? half : (half + (count & 1) - 1);
340 return (ptr - (const char *)list) / elementSize;
343 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
344 const char *ptr = (const char *)list;
346 CFIndex half = count / 2;
347 const char *probe = ptr + elementSize * half;
348 CFComparisonResult cr = comparator(element, probe, context);
349 if (0 == cr) return (probe - (const char *)list) / elementSize;
350 ptr = (cr < 0) ? ptr : probe + elementSize;
351 count = (cr < 0) ? half : (half + (count & 1) - 1);
353 return (ptr - (const char *)list) / elementSize;
356 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
357 if (range.length == 0)
359 const void **values(new const void *[range.length]);
360 CFArrayGetValues(array, range, values);
362 #if HistogramInsertionSort > 0
363 uint32_t total(0), *offsets(new uint32_t[range.length]);
366 for (CFIndex index(1); index != range.length; ++index) {
367 const void *value(values[index]);
368 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
369 CFIndex correct(index);
370 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
371 #if HistogramInsertionSort > 1
372 NSLog(@"%@ < %@", value, values[correct - 1]);
377 if (correct != index) {
378 size_t offset(index - correct);
379 #if HistogramInsertionSort
383 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
385 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
386 values[correct] = value;
390 CFArrayReplaceValues(array, range, values, range.length);
393 #if HistogramInsertionSort > 0
394 for (CFIndex index(0); index != range.length; ++index)
395 if (offsets[index] != 0)
396 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
397 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
404 /* Apple Bug Fixes {{{ */
405 @implementation UIWebDocumentView (Cydia)
407 - (void) _setScrollerOffset:(CGPoint)offset {
408 UIScroller *scroller([self _scroller]);
410 CGSize size([scroller contentSize]);
411 CGSize bounds([scroller bounds].size);
414 max.x = size.width - bounds.width;
415 max.y = size.height - bounds.height;
423 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
424 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
426 [scroller setOffset:offset];
432 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
433 size_t length([self length] - state->state);
436 else if (length > count)
438 for (size_t i(0); i != length; ++i)
439 objects[i] = [self item:state->state++];
440 state->itemsPtr = objects;
441 state->mutationsPtr = (unsigned long *) self;
445 /* Cydia NSString Additions {{{ */
446 @interface NSString (Cydia)
447 - (NSComparisonResult) compareByPath:(NSString *)other;
448 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
451 @implementation NSString (Cydia)
453 - (NSComparisonResult) compareByPath:(NSString *)other {
454 NSString *prefix = [self commonPrefixWithString:other options:0];
455 size_t length = [prefix length];
457 NSRange lrange = NSMakeRange(length, [self length] - length);
458 NSRange rrange = NSMakeRange(length, [other length] - length);
460 lrange = [self rangeOfString:@"/" options:0 range:lrange];
461 rrange = [other rangeOfString:@"/" options:0 range:rrange];
463 NSComparisonResult value;
465 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
466 value = NSOrderedSame;
467 else if (lrange.location == NSNotFound)
468 value = NSOrderedAscending;
469 else if (rrange.location == NSNotFound)
470 value = NSOrderedDescending;
472 value = NSOrderedSame;
474 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
475 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
476 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
477 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
479 NSComparisonResult result = [lpath compare:rpath];
480 return result == NSOrderedSame ? value : result;
483 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
484 return [(id)CFURLCreateStringByAddingPercentEscapes(
489 kCFStringEncodingUTF8
496 /* C++ NSString Wrapper Cache {{{ */
497 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
498 return size == 0 ? NULL :
499 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
500 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
503 static _finline CFStringRef CYStringCreate(const std::string &data) {
504 return CYStringCreate(data.data(), data.size());
507 static _finline CFStringRef CYStringCreate(const char *data) {
508 return CYStringCreate(data, strlen(data));
517 _finline void clear_() {
518 if (cache_ != NULL) {
525 _finline bool empty() const {
529 _finline size_t size() const {
533 _finline char *data() const {
537 _finline void clear() {
542 _finline CYString() :
549 _finline ~CYString() {
553 void operator =(const CYString &rhs) {
557 if (rhs.cache_ == nil)
560 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
563 void copy(CYPool *pool) {
564 char *temp(pool->malloc<char>(size_ + 1));
565 memcpy(temp, data_, size_);
570 void set(CYPool *pool, const char *data, size_t size) {
576 data_ = const_cast<char *>(data);
584 _finline void set(CYPool *pool, const char *data) {
585 set(pool, data, data == NULL ? 0 : strlen(data));
588 _finline void set(CYPool *pool, const std::string &rhs) {
589 set(pool, rhs.data(), rhs.size());
592 bool operator ==(const CYString &rhs) const {
593 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
596 _finline operator CFStringRef() {
598 cache_ = CYStringCreate(data_, size_);
602 _finline operator id() {
603 return (NSString *) static_cast<CFStringRef>(*this);
606 _finline operator const char *() {
607 return reinterpret_cast<const char *>(data_);
611 /* C++ NSString Algorithm Adapters {{{ */
613 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
616 struct NSStringMapHash :
617 std::unary_function<NSString *, size_t>
619 _finline size_t operator ()(NSString *value) const {
620 return CFStringHashNSString((CFStringRef) value);
624 struct NSStringMapLess :
625 std::binary_function<NSString *, NSString *, bool>
627 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
628 return [lhs compare:rhs] == NSOrderedAscending;
632 struct NSStringMapEqual :
633 std::binary_function<NSString *, NSString *, bool>
635 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
636 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
637 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
638 //[lhs isEqualToString:rhs];
643 /* CoreGraphics Primitives {{{ */
648 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
649 CGFloat color[] = {red, green, blue, alpha};
650 return CGColorCreate(space, color);
659 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
660 color_(Create_(space, red, green, blue, alpha))
662 Set(space, red, green, blue, alpha);
667 CGColorRelease(color_);
674 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
676 color_ = Create_(space, red, green, blue, alpha);
679 operator CGColorRef() {
685 /* Random Global Variables {{{ */
686 static int PulseInterval_ = 500000;
688 static const NSString *UI_;
691 static bool RestartSubstrate_;
692 static NSArray *Finishes_;
694 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
695 #define NotifyConfig_ "/etc/notify.conf"
697 static bool Queuing_;
699 static CYColor Blue_;
700 static CYColor Blueish_;
701 static CYColor Black_;
702 static CYColor Folder_;
704 static CYColor White_;
705 static CYColor Gray_;
706 static CYColor Green_;
707 static CYColor Purple_;
708 static CYColor Purplish_;
710 static UIColor *InstallingColor_;
711 static UIColor *RemovingColor_;
713 static NSString *App_;
715 static BOOL Advanced_;
716 static BOOL Ignored_;
718 static _H<UIFont> Font12_;
719 static _H<UIFont> Font12Bold_;
720 static _H<UIFont> Font14_;
721 static _H<UIFont> Font18_;
722 static _H<UIFont> Font18Bold_;
723 static _H<UIFont> Font22Bold_;
725 static const char *Machine_ = NULL;
726 static _H<NSString> System_;
727 static NSString *SerialNumber_ = nil;
728 static NSString *ChipID_ = nil;
729 static NSString *BBSNum_ = nil;
730 static _H<NSString> UniqueID_;
731 static _H<NSString> UserAgent_;
732 static _H<NSString> Product_;
733 static _H<NSString> Safari_;
735 static _H<NSLocale> CollationLocale_;
736 static _H<NSArray> CollationThumbs_;
737 static std::vector<NSInteger> CollationOffset_;
738 static _H<NSArray> CollationTitles_;
739 static _H<NSArray> CollationStarts_;
740 static UTransliterator *CollationTransl_;
741 //static Function<NSString *, NSString *> CollationModify_;
743 typedef std::basic_string<UChar> ustring;
744 static ustring CollationString_;
746 #define CUC const ustring &str(*reinterpret_cast<const ustring *>(rep))
747 #define UC ustring &str(*reinterpret_cast<ustring *>(rep))
748 static struct UReplaceableCallbacks CollationUCalls_ = {
749 .length = [](const UReplaceable *rep) -> int32_t { CUC;
753 .charAt = [](const UReplaceable *rep, int32_t offset) -> UChar { CUC;
754 //fprintf(stderr, "charAt(%d) : %d\n", offset, str.size());
755 if (offset >= str.size())
760 .char32At = [](const UReplaceable *rep, int32_t offset) -> UChar32 { CUC;
761 //fprintf(stderr, "char32At(%d) : %d\n", offset, str.size());
762 if (offset >= str.size())
765 U16_GET(str.data(), 0, offset, str.size(), c);
769 .replace = [](UReplaceable *rep, int32_t start, int32_t limit, const UChar *text, int32_t length) -> void { UC;
770 //fprintf(stderr, "replace(%d, %d, %d) : %d\n", start, limit, length, str.size());
771 str.replace(start, limit - start, text, length);
774 .extract = [](UReplaceable *rep, int32_t start, int32_t limit, UChar *dst) -> void { UC;
775 //fprintf(stderr, "extract(%d, %d) : %d\n", start, limit, str.size());
776 str.copy(dst, limit - start, start);
779 .copy = [](UReplaceable *rep, int32_t start, int32_t limit, int32_t dest) -> void { UC;
780 //fprintf(stderr, "copy(%d, %d, %d) : %d\n", start, limit, dest, str.size());
781 str.replace(dest, 0, str, start, limit - start);
785 static CFLocaleRef Locale_;
786 static NSArray *Languages_;
787 static CGColorSpaceRef space_;
789 #define CacheState_ "/var/mobile/Library/Caches/com.saurik.Cydia/CacheState.plist"
790 #define SavedState_ "/var/mobile/Library/Caches/com.saurik.Cydia/SavedState.plist"
792 static NSDictionary *SectionMap_;
793 static _H<NSDate> Backgrounded_;
794 static _transient NSMutableDictionary *Values_;
795 static _transient NSMutableDictionary *Sections_;
796 _H<NSMutableDictionary> Sources_;
797 static _transient NSNumber *Version_;
801 CGFloat ScreenScale_;
802 static NSString *Idiom_;
803 static _H<NSString> Firmware_;
804 static NSString *Major_;
806 static _H<NSMutableDictionary> SessionData_;
807 static _H<NSObject> HostConfig_;
808 static _H<NSMutableSet> BridgedHosts_;
809 static _H<NSMutableSet> InsecureHosts_;
810 static _H<NSMutableSet> PipelinedHosts_;
811 static _H<NSMutableSet> CachedURLs_;
813 static NSString *kCydiaProgressEventTypeError = @"Error";
814 static NSString *kCydiaProgressEventTypeInformation = @"Information";
815 static NSString *kCydiaProgressEventTypeStatus = @"Status";
816 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
819 /* Display Helpers {{{ */
820 inline float Interpolate(float begin, float end, float fraction) {
821 return (end - begin) * fraction + begin;
824 static inline double Retina(double value) {
825 value *= ScreenScale_;
826 value = round(value);
827 value /= ScreenScale_;
831 static inline CGRect Retina(CGRect value) {
832 value.origin.x *= ScreenScale_;
833 value.origin.y *= ScreenScale_;
834 value.size.width *= ScreenScale_;
835 value.size.height *= ScreenScale_;
836 value = CGRectIntegral(value);
837 value.origin.x /= ScreenScale_;
838 value.origin.y /= ScreenScale_;
839 value.size.width /= ScreenScale_;
840 value.size.height /= ScreenScale_;
844 static _finline const char *StripVersion_(const char *version) {
845 const char *colon(strchr(version, ':'));
846 return colon == NULL ? version : colon + 1;
849 NSString *LocalizeSection(NSString *section) {
850 static RegEx title_r("(.*?) \\((.*)\\)");
851 if (title_r(section)) {
852 NSString *parent(title_r[1]);
853 NSString *child(title_r[2]);
855 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
856 LocalizeSection(parent),
857 LocalizeSection(child)
861 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
864 NSString *Simplify(NSString *title) {
865 const char *data = [title UTF8String];
866 size_t size = [title lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
868 static RegEx square_r("\\[(.*)\\]");
869 if (square_r(data, size))
870 return Simplify(square_r[1]);
872 static RegEx paren_r("\\((.*)\\)");
873 if (paren_r(data, size))
874 return Simplify(paren_r[1]);
876 static RegEx title_r("(.*?) \\((.*)\\)");
877 if (title_r(data, size))
878 return Simplify(title_r[1]);
884 bool isSectionVisible(NSString *section) {
885 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
886 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
887 return hidden == nil || ![hidden boolValue];
890 static NSObject *CYIOGetValue(const char *path, NSString *property) {
891 io_registry_entry_t entry(IORegistryEntryFromPath(kIOMasterPortDefault, path));
892 if (entry == MACH_PORT_NULL)
895 CFTypeRef value(IORegistryEntryCreateCFProperty(entry, (CFStringRef) property, kCFAllocatorDefault, 0));
896 IOObjectRelease(entry);
900 return [(id) value autorelease];
903 static NSString *CYHex(NSData *data, bool reverse = false) {
907 size_t length([data length]);
908 uint8_t bytes[length];
909 [data getBytes:bytes];
911 char string[length * 2 + 1];
912 for (size_t i(0); i != length; ++i)
913 sprintf(string + i * 2, "%.2x", bytes[reverse ? length - i - 1 : i]);
915 return [NSString stringWithUTF8String:string];
918 static NSString *VerifySource(NSString *href) {
919 static RegEx href_r("(http(s?)://|file:///)[^# ]*");
921 [[[[UIAlertView alloc]
922 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("INVALID_URL")]
923 message:UCLocalize("INVALID_URL_EX")
925 cancelButtonTitle:UCLocalize("OK")
926 otherButtonTitles:nil
927 ] autorelease] show];
932 if (![href hasSuffix:@"/"])
933 href = [href stringByAppendingString:@"/"];
939 /* Delegate Prototypes {{{ */
942 @class CydiaProgressEvent;
944 @protocol DatabaseDelegate
945 - (void) repairWithSelector:(SEL)selector;
946 - (void) setConfigurationData:(NSString *)data;
947 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
950 @class CYPackageController;
952 @protocol SourceDelegate
953 - (void) setFetch:(NSNumber *)fetch;
956 @protocol FetchDelegate
957 - (bool) isSourceCancelled;
958 - (void) startSourceFetch:(NSString *)uri;
959 - (void) stopSourceFetch:(NSString *)uri;
962 @protocol CydiaDelegate
963 - (void) returnToCydia;
965 - (void) retainNetworkActivityIndicator;
966 - (void) releaseNetworkActivityIndicator;
967 - (void) clearPackage:(Package *)package;
968 - (void) installPackage:(Package *)package;
969 - (void) installPackages:(NSArray *)packages;
970 - (void) removePackage:(Package *)package;
971 - (void) beginUpdate;
973 - (bool) requestUpdate;
974 - (void) distUpgrade;
977 - (void) _saveConfig;
979 - (void) addSource:(NSDictionary *)source;
980 - (BOOL) addTrivialSource:(NSString *)href;
981 - (UIProgressHUD *) addProgressHUD;
982 - (void) removeProgressHUD:(UIProgressHUD *)hud;
983 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
984 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
988 /* CancelStatus {{{ */
990 public pkgAcquireStatus
1001 virtual bool MediaChange(std::string media, std::string drive) {
1005 virtual void IMSHit(pkgAcquire::ItemDesc &desc) {
1009 virtual bool Pulse_(pkgAcquire *Owner) = 0;
1011 virtual bool Pulse(pkgAcquire *Owner) {
1012 if (pkgAcquireStatus::Pulse(Owner) && Pulse_(Owner))
1020 _finline bool WasCancelled() const {
1025 /* DelegateStatus {{{ */
1030 _transient NSObject<ProgressDelegate> *delegate_;
1038 void setDelegate(NSObject<ProgressDelegate> *delegate) {
1039 delegate_ = delegate;
1042 virtual void Fetch(pkgAcquire::ItemDesc &desc) {
1043 NSString *name([NSString stringWithUTF8String:desc.ShortDesc.c_str()]);
1044 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItemDesc:desc]);
1045 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1048 virtual void Done(pkgAcquire::ItemDesc &desc) {
1049 NSString *name([NSString stringWithUTF8String:desc.ShortDesc.c_str()]);
1050 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:Colon_, UCLocalize("DONE"), name] ofType:kCydiaProgressEventTypeStatus forItemDesc:desc]);
1051 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1054 virtual void Fail(pkgAcquire::ItemDesc &desc) {
1056 desc.Owner->Status == pkgAcquire::Item::StatIdle ||
1057 desc.Owner->Status == pkgAcquire::Item::StatDone
1061 std::string &error(desc.Owner->ErrorText);
1065 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItemDesc:desc]);
1066 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1069 virtual bool Pulse_(pkgAcquire *Owner) {
1071 double(CurrentBytes + CurrentItems) /
1072 double(TotalBytes + TotalItems)
1075 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
1076 [NSNumber numberWithDouble:percent], @"Percent",
1078 [NSNumber numberWithDouble:CurrentBytes], @"Current",
1079 [NSNumber numberWithDouble:TotalBytes], @"Total",
1080 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
1081 nil] waitUntilDone:YES];
1083 return ![delegate_ isProgressCancelled];
1086 virtual void Start() {
1087 pkgAcquireStatus::Start();
1088 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
1091 virtual void Stop() {
1092 pkgAcquireStatus::Stop();
1093 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
1094 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
1098 /* Database Interface {{{ */
1099 typedef std::map< unsigned long, _H<Source> > SourceMap;
1101 @interface Database : NSObject {
1108 pkgCacheFile cache_;
1109 pkgDepCache::Policy *policy_;
1110 pkgRecords *records_;
1111 pkgProblemResolver *resolver_;
1112 pkgAcquire *fetcher_;
1114 SPtr<pkgPackageManager> manager_;
1115 pkgSourceList *list_;
1117 SourceMap sourceMap_;
1118 _H<NSMutableArray> sourceList_;
1120 CFMutableArrayRef packages_;
1122 _transient NSObject<DatabaseDelegate> *delegate_;
1123 _transient NSObject<ProgressDelegate> *progress_;
1125 CydiaStatus status_;
1131 std::map<const char *, _H<NSString> > sections_;
1134 + (Database *) sharedInstance;
1136 - (bool) hasPackages;
1138 - (void) _readCydia:(NSNumber *)fd;
1139 - (void) _readStatus:(NSNumber *)fd;
1140 - (void) _readOutput:(NSNumber *)fd;
1144 - (Package *) packageWithName:(NSString *)name;
1146 - (pkgCacheFile &) cache;
1147 - (pkgDepCache::Policy *) policy;
1148 - (pkgRecords *) records;
1149 - (pkgProblemResolver *) resolver;
1150 - (pkgAcquire &) fetcher;
1151 - (pkgSourceList &) list;
1152 - (NSArray *) packages;
1153 - (NSArray *) sources;
1154 - (Source *) sourceWithKey:(NSString *)key;
1155 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1163 - (void) updateWithStatus:(CancelStatus &)status;
1165 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1167 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1168 - (NSObject<ProgressDelegate> *) progressDelegate;
1170 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1171 - (void) setFetch:(bool)fetch forURI:(const char *)uri;
1172 - (void) resetFetch;
1174 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1178 /* SourceStatus {{{ */
1179 class SourceStatus :
1183 _transient NSObject<FetchDelegate> *delegate_;
1184 _transient Database *database_;
1185 std::set<std::string> fetches_;
1188 SourceStatus(NSObject<FetchDelegate> *delegate, Database *database) :
1189 delegate_(delegate),
1194 void Set(bool fetch, const std::string &uri) {
1196 if (!fetches_.insert(uri).second)
1199 if (fetches_.erase(uri) == 0)
1203 //printf("Set(%s, %s)\n", fetch ? "true" : "false", uri.c_str());
1204 [database_ setFetch:fetch forURI:uri.c_str()];
1207 _finline void Set(bool fetch, pkgAcquire::Item *item) {
1208 /*unsigned long ID(fetch ? 1 : 0);
1212 Set(fetch, item->DescURI());
1215 void Log(const char *tag, pkgAcquire::Item *item) {
1216 //printf("%s(%s) S:%u Q:%u\n", tag, item->DescURI().c_str(), item->Status, item->QueueCounter);
1219 virtual void Fetch(pkgAcquire::ItemDesc &desc) {
1220 Log("Fetch", desc.Owner);
1221 Set(true, desc.Owner);
1224 virtual void Done(pkgAcquire::ItemDesc &desc) {
1225 Log("Done", desc.Owner);
1226 Set(false, desc.Owner);
1229 virtual void Fail(pkgAcquire::ItemDesc &desc) {
1230 Log("Fail", desc.Owner);
1231 Set(false, desc.Owner);
1234 virtual bool Pulse_(pkgAcquire *Owner) {
1235 std::set<std::string> fetches;
1236 for (pkgAcquire::ItemCIterator item(Owner->ItemsBegin()); item != Owner->ItemsEnd(); ++item) {
1238 if ((*item)->QueueCounter == 0)
1240 else switch ((*item)->Status) {
1241 case pkgAcquire::Item::StatFetching:
1242 fetches.insert((*item)->DescURI());
1251 Log(fetch ? "Pulse<true>" : "Pulse<false>", *item);
1255 std::vector<std::string> stops;
1256 std::set_difference(fetches_.begin(), fetches_.end(), fetches.begin(), fetches.end(), std::back_insert_iterator<std::vector<std::string>>(stops));
1257 for (std::vector<std::string>::const_iterator stop(stops.begin()); stop != stops.end(); ++stop) {
1258 //printf("Stop(%s)\n", stop->c_str());
1262 return ![delegate_ isSourceCancelled];
1265 virtual void Stop() {
1266 pkgAcquireStatus::Stop();
1267 [database_ resetFetch];
1271 /* ProgressEvent Implementation {{{ */
1272 @implementation CydiaProgressEvent
1274 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1275 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1278 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1279 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1280 [event setPackage:package];
1284 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItemDesc:(pkgAcquire::ItemDesc &)desc {
1285 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1287 NSString *description([NSString stringWithUTF8String:desc.Description.c_str()]);
1288 NSArray *fields([description componentsSeparatedByString:@" "]);
1289 [event setItem:fields];
1291 if ([fields count] > 3) {
1292 [event setPackage:[fields objectAtIndex:2]];
1293 [event setVersion:[fields objectAtIndex:3]];
1296 [event setURL:[NSString stringWithUTF8String:desc.URI.c_str()]];
1301 + (NSArray *) _attributeKeys {
1302 return [NSArray arrayWithObjects:
1312 - (NSArray *) attributeKeys {
1313 return [[self class] _attributeKeys];
1316 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1317 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1320 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1321 if ((self = [super init]) != nil) {
1327 - (NSString *) message {
1331 - (NSString *) type {
1335 - (NSArray *) item {
1336 return (id) item_ ?: [NSNull null];
1339 - (void) setItem:(NSArray *)item {
1343 - (NSString *) package {
1344 return (id) package_ ?: [NSNull null];
1347 - (void) setPackage:(NSString *)package {
1351 - (NSString *) url {
1352 return (id) url_ ?: [NSNull null];
1355 - (void) setURL:(NSString *)url {
1359 - (void) setVersion:(NSString *)version {
1363 - (NSString *) version {
1364 return (id) version_ ?: [NSNull null];
1367 - (NSString *) compound:(NSString *)value {
1369 NSString *mode(nil); {
1370 NSString *type([self type]);
1371 if ([type isEqualToString:kCydiaProgressEventTypeError])
1372 mode = UCLocalize("ERROR");
1373 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1374 mode = UCLocalize("WARNING");
1378 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1384 - (NSString *) compoundMessage {
1385 return [self compound:[self message]];
1388 - (NSString *) compoundTitle {
1391 if (package_ == nil)
1393 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1394 title = [package name];
1398 return [self compound:title];
1404 // Cytore Definitions {{{
1405 struct PackageValue :
1408 Cytore::Offset<PackageValue> next_;
1410 uint32_t index_ : 23;
1411 uint32_t subscribed_ : 1;
1428 Cytore::Offset<PackageValue> packages_[1 << 16];
1431 static Cytore::File<MetaValue> MetaFile_;
1433 // Cytore Helper Functions {{{
1434 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1435 SplitHash nhash = { hashlittle(name, length) };
1437 PackageValue *metadata;
1439 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1440 for (;; offset = &metadata->next_) { if (offset->IsNull()) {
1441 *offset = MetaFile_.New<PackageValue>(length + 1);
1442 metadata = &MetaFile_.Get(*offset);
1444 if (metadata == NULL) {
1448 metadata = new PackageValue();
1449 memset(metadata, 0, sizeof(*metadata));
1452 memcpy(metadata->name_, name, length);
1453 metadata->name_[length] = '\0';
1454 metadata->nhash_ = nhash.u16[1];
1456 metadata = &MetaFile_.Get(*offset);
1457 if (metadata->nhash_ != nhash.u16[1])
1459 if (strncmp(metadata->name_, name, length) != 0)
1461 if (metadata->name_[length] != '\0')
1468 static void PackageImport(const void *key, const void *value, void *context) {
1469 bool &fail(*reinterpret_cast<bool *>(context));
1472 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1473 NSLog(@"failed to import package %@", key);
1477 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1478 NSDictionary *package((NSDictionary *) value);
1480 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1481 if ([subscribed boolValue] && !metadata->subscribed_)
1482 metadata->subscribed_ = true;
1484 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1485 time_t time([date timeIntervalSince1970]);
1486 if (metadata->first_ > time || metadata->first_ == 0)
1487 metadata->first_ = time;
1490 NSDate *date([package objectForKey:@"LastSeen"]);
1491 NSString *version([package objectForKey:@"LastVersion"]);
1493 if (date != nil && version != nil) {
1494 time_t time([date timeIntervalSince1970]);
1495 if (metadata->last_ < time || metadata->last_ == 0)
1496 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1497 size_t length(strlen(buffer));
1498 uint16_t vhash(hashlittle(buffer, length));
1500 size_t capped(std::min<size_t>(8, length));
1501 char *latest(buffer + length - capped);
1503 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1504 metadata->vhash_ = vhash;
1506 metadata->last_ = time;
1512 static NSDate *GetStatusDate() {
1513 return [[[NSFileManager defaultManager] attributesOfItemAtPath:@"/var/lib/dpkg/status" error:NULL] fileModificationDate];
1516 static void SaveConfig(NSObject *lock) {
1517 @synchronized (lock) {
1523 CFPreferencesSetMultiple((CFDictionaryRef) [NSDictionary dictionaryWithObjectsAndKeys:
1524 Values_, @"CydiaValues",
1525 Sections_, @"CydiaSections",
1526 (id) Sources_, @"CydiaSources",
1527 Version_, @"CydiaVersion",
1528 nil], NULL, CFSTR("com.saurik.Cydia"), kCFPreferencesCurrentUser, kCFPreferencesCurrentHost);
1530 if (!CFPreferencesAppSynchronize(CFSTR("com.saurik.Cydia")))
1531 NSLog(@"CFPreferencesAppSynchronize(com.saurik.Cydia) == false");
1533 CydiaWriteSources();
1536 /* Source Class {{{ */
1537 @interface Source : NSObject {
1539 Database *database_;
1542 CYString depiction_;
1543 CYString description_;
1549 CYString distribution_;
1555 _H<NSString> authority_;
1557 CYString defaultIcon_;
1559 _H<NSMutableDictionary> record_;
1562 std::set<std::string> fetches_;
1563 std::set<std::string> files_;
1564 _transient NSObject<SourceDelegate> *delegate_;
1567 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(CYPool *)pool;
1569 - (NSComparisonResult) compareByName:(Source *)source;
1571 - (NSString *) depictionForPackage:(NSString *)package;
1572 - (NSString *) supportForPackage:(NSString *)package;
1574 - (metaIndex *) metaIndex;
1575 - (NSDictionary *) record;
1578 - (NSString *) rooturi;
1579 - (NSString *) distribution;
1580 - (NSString *) type;
1583 - (NSString *) host;
1585 - (NSString *) name;
1586 - (NSString *) shortDescription;
1587 - (NSString *) label;
1588 - (NSString *) origin;
1589 - (NSString *) version;
1591 - (NSString *) defaultIcon;
1592 - (NSURL *) iconURL;
1594 - (void) setFetch:(bool)fetch forURI:(const char *)uri;
1595 - (void) resetFetch;
1599 @implementation Source
1601 + (NSString *) webScriptNameForSelector:(SEL)selector {
1603 else if (selector == @selector(addSection:))
1604 return @"addSection";
1605 else if (selector == @selector(getField:))
1607 else if (selector == @selector(removeSection:))
1608 return @"removeSection";
1609 else if (selector == @selector(remove))
1615 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1616 return [self webScriptNameForSelector:selector] == nil;
1619 + (NSArray *) _attributeKeys {
1620 return [NSArray arrayWithObjects:
1631 @"shortDescription",
1638 - (NSArray *) attributeKeys {
1639 return [[self class] _attributeKeys];
1642 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1643 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1646 - (metaIndex *) metaIndex {
1650 - (void) setMetaIndex:(metaIndex *)index inPool:(CYPool *)pool {
1651 trusted_ = index->IsTrusted();
1653 uri_.set(pool, index->GetURI());
1654 distribution_.set(pool, index->GetDist());
1655 type_.set(pool, index->GetType());
1657 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1658 if (dindex != NULL) {
1659 std::string file(dindex->MetaIndexURI(""));
1660 base_.set(pool, file);
1663 _profile(Source$setMetaIndex$GetIndexes)
1664 dindex->GetIndexes(&acquire, true);
1666 _profile(Source$setMetaIndex$DescURI)
1667 for (pkgAcquire::ItemIterator item(acquire.ItemsBegin()); item != acquire.ItemsEnd(); item++) {
1668 std::string file((*item)->DescURI());
1669 files_.insert(file);
1670 if (file.length() < sizeof("Packages.bz2") || file.substr(file.length() - sizeof("Packages.bz2")) != "/Packages.bz2")
1672 file = file.substr(0, file.length() - 4);
1673 files_.insert(file);
1674 files_.insert(file + ".gz");
1675 files_.insert(file + "Index");
1680 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1683 pkgTagFile tags(&fd);
1685 pkgTagSection section;
1692 {"default-icon", &defaultIcon_},
1693 {"depiction", &depiction_},
1694 {"description", &description_},
1696 {"origin", &origin_},
1697 {"support", &support_},
1698 {"version", &version_},
1701 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1702 const char *start, *end;
1704 if (section.Find(names[i].name_, start, end)) {
1705 CYString &value(*names[i].value_);
1706 value.set(pool, start, end - start);
1712 record_ = [Sources_ objectForKey:[self key]];
1714 NSURL *url([NSURL URLWithString:uri_]);
1718 host_ = [host_ lowercaseString];
1723 authority_ = [url path];
1726 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(CYPool *)pool {
1727 if ((self = [super init]) != nil) {
1728 era_ = [database era];
1729 database_ = database;
1732 _profile(Source$initWithMetaIndex$setMetaIndex)
1733 [self setMetaIndex:index inPool:pool];
1738 - (NSString *) getField:(NSString *)name {
1739 @synchronized (database_) {
1740 if ([database_ era] != era_ || index_ == NULL)
1743 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index_));
1748 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly)) {
1753 pkgTagFile tags(&fd);
1755 pkgTagSection section;
1758 const char *start, *end;
1759 if (!section.Find([name UTF8String], start, end))
1760 return (NSString *) [NSNull null];
1762 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
1765 - (NSComparisonResult) compareByName:(Source *)source {
1766 NSString *lhs = [self name];
1767 NSString *rhs = [source name];
1769 if ([lhs length] != 0 && [rhs length] != 0) {
1770 unichar lhc = [lhs characterAtIndex:0];
1771 unichar rhc = [rhs characterAtIndex:0];
1773 if (isalpha(lhc) && !isalpha(rhc))
1774 return NSOrderedAscending;
1775 else if (!isalpha(lhc) && isalpha(rhc))
1776 return NSOrderedDescending;
1779 return [lhs compare:rhs options:LaxCompareOptions_];
1782 - (NSString *) depictionForPackage:(NSString *)package {
1783 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1786 - (NSString *) supportForPackage:(NSString *)package {
1787 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1790 - (NSArray *) sections {
1791 return record_ == nil ? (id) [NSNull null] : [record_ objectForKey:@"Sections"] ?: [NSArray array];
1794 - (void) _addSection:(NSString *)section {
1797 else if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) {
1798 if (![sections containsObject:section])
1799 [sections addObject:section];
1801 [record_ setObject:[NSMutableArray arrayWithObject:section] forKey:@"Sections"];
1804 - (bool) addSection:(NSString *)section {
1808 [self performSelectorOnMainThread:@selector(_addSection:) withObject:section waitUntilDone:NO];
1812 - (void) _removeSection:(NSString *)section {
1816 if (NSMutableArray *sections = [record_ objectForKey:@"Sections"])
1817 if ([sections containsObject:section])
1818 [sections removeObject:section];
1821 - (bool) removeSection:(NSString *)section {
1825 [self performSelectorOnMainThread:@selector(_removeSection:) withObject:section waitUntilDone:NO];
1830 [Sources_ removeObjectForKey:[self key]];
1834 bool value(record_ != nil);
1835 [self performSelectorOnMainThread:@selector(_remove) withObject:nil waitUntilDone:NO];
1839 - (NSDictionary *) record {
1847 - (NSString *) rooturi {
1851 - (NSString *) distribution {
1852 return distribution_;
1855 - (NSString *) type {
1859 - (NSString *) baseuri {
1860 return base_.empty() ? nil : (id) base_;
1863 - (NSString *) iconuri {
1864 if (NSString *base = [self baseuri])
1865 return [base stringByAppendingString:@"CydiaIcon.png"];
1870 - (NSURL *) iconURL {
1871 if (NSString *uri = [self iconuri])
1872 return [NSURL URLWithString:uri];
1876 - (NSString *) key {
1877 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1880 - (NSString *) host {
1884 - (NSString *) name {
1885 return origin_.empty() ? (id) authority_ : origin_;
1888 - (NSString *) shortDescription {
1889 return description_;
1892 - (NSString *) label {
1893 return label_.empty() ? (id) authority_ : label_;
1896 - (NSString *) origin {
1900 - (NSString *) version {
1904 - (NSString *) defaultIcon {
1905 return defaultIcon_;
1908 - (void) setDelegate:(NSObject<SourceDelegate> *)delegate {
1909 delegate_ = delegate;
1913 return !fetches_.empty();
1916 - (void) setFetch:(bool)fetch forURI:(const char *)uri {
1918 if (fetches_.erase(uri) == 0)
1920 } else if (files_.find(uri) == files_.end())
1922 else if (!fetches_.insert(uri).second)
1925 [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:[self fetch]] waitUntilDone:NO];
1928 - (void) resetFetch {
1930 [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:NO];
1935 /* CydiaOperation Class {{{ */
1936 @interface CydiaOperation : NSObject {
1937 _H<NSString> operator_;
1938 _H<NSString> value_;
1941 - (NSString *) operator;
1942 - (NSString *) value;
1946 @implementation CydiaOperation
1948 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1949 if ((self = [super init]) != nil) {
1950 operator_ = [NSString stringWithUTF8String:_operator];
1951 value_ = [NSString stringWithUTF8String:value];
1955 + (NSArray *) _attributeKeys {
1956 return [NSArray arrayWithObjects:
1962 - (NSArray *) attributeKeys {
1963 return [[self class] _attributeKeys];
1966 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1967 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1970 - (NSString *) operator {
1974 - (NSString *) value {
1980 /* CydiaClause Class {{{ */
1981 @interface CydiaClause : NSObject {
1982 _H<NSString> package_;
1983 _H<CydiaOperation> version_;
1986 - (NSString *) package;
1987 - (CydiaOperation *) version;
1991 @implementation CydiaClause
1993 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1994 if ((self = [super init]) != nil) {
1995 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1997 if (const char *version = dep.TargetVer())
1998 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
2000 version_ = (id) [NSNull null];
2004 + (NSArray *) _attributeKeys {
2005 return [NSArray arrayWithObjects:
2011 - (NSArray *) attributeKeys {
2012 return [[self class] _attributeKeys];
2015 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2016 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2019 - (NSString *) package {
2023 - (CydiaOperation *) version {
2029 /* CydiaRelation Class {{{ */
2030 @interface CydiaRelation : NSObject {
2031 _H<NSString> relationship_;
2032 _H<NSMutableArray> clauses_;
2035 - (NSString *) relationship;
2036 - (NSArray *) clauses;
2040 @implementation CydiaRelation
2042 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
2043 if ((self = [super init]) != nil) {
2044 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
2045 clauses_ = [NSMutableArray arrayWithCapacity:8];
2047 pkgCache::DepIterator start;
2048 pkgCache::DepIterator end;
2049 dep.GlobOr(start, end); // ++dep
2052 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
2054 // yes, seriously. (wtf?)
2062 + (NSArray *) _attributeKeys {
2063 return [NSArray arrayWithObjects:
2069 - (NSArray *) attributeKeys {
2070 return [[self class] _attributeKeys];
2073 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2074 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2077 - (NSString *) relationship {
2078 return relationship_;
2081 - (NSArray *) clauses {
2085 - (void) addClause:(CydiaClause *)clause {
2086 [clauses_ addObject:clause];
2091 /* Package Class {{{ */
2092 struct ParsedPackage {
2096 CYString architecture_;
2099 CYString depiction_;
2106 @interface Package : NSObject {
2108 @public uint32_t role_ : 3;
2109 uint32_t essential_ : 1;
2110 uint32_t obsolete_ : 1;
2111 uint32_t ignored_ : 1;
2112 uint32_t pooled_ : 1;
2118 _transient Database *database_;
2120 pkgCache::VerIterator version_;
2121 pkgCache::PkgIterator iterator_;
2122 pkgCache::VerFileIterator file_;
2126 CYString transform_;
2129 CYString installed_;
2132 const char *section_;
2133 _transient NSString *section$_;
2137 PackageValue *metadata_;
2138 ParsedPackage *parsed_;
2140 _H<NSMutableArray> tags_;
2143 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database;
2144 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database;
2146 - (pkgCache::PkgIterator) iterator;
2149 - (NSString *) section;
2150 - (NSString *) simpleSection;
2152 - (NSString *) longSection;
2153 - (NSString *) shortSection;
2157 - (MIMEAddress *) maintainer;
2159 - (NSString *) longDescription;
2160 - (NSString *) shortDescription;
2163 - (PackageValue *) metadata;
2166 - (bool) subscribed;
2167 - (bool) setSubscribed:(bool)subscribed;
2171 - (NSString *) latest;
2172 - (NSString *) installed;
2173 - (BOOL) uninstalled;
2175 - (BOOL) upgradableAndEssential:(BOOL)essential;
2178 - (BOOL) unfiltered;
2182 - (BOOL) halfConfigured;
2183 - (BOOL) halfInstalled;
2185 - (NSString *) mode;
2188 - (NSString *) name;
2190 - (NSString *) homepage;
2191 - (NSString *) depiction;
2192 - (MIMEAddress *) author;
2194 - (NSString *) support;
2196 - (NSArray *) files;
2197 - (NSArray *) warnings;
2198 - (NSArray *) applications;
2200 - (Source *) source;
2203 - (BOOL) matches:(NSArray *)query;
2205 - (BOOL) hasTag:(NSString *)tag;
2206 - (NSString *) primaryPurpose;
2207 - (NSArray *) purposes;
2208 - (bool) isCommercial;
2210 - (void) setIndex:(size_t)index;
2212 - (CYString &) cyname;
2214 - (uint32_t) compareBySection:(NSArray *)sections;
2221 uint32_t PackageChangesRadix(Package *self, void *) {
2226 uint32_t timestamp : 30;
2227 uint32_t ignored : 1;
2228 uint32_t upgradable : 1;
2232 bool upgradable([self upgradableAndEssential:YES]);
2233 value.bits.upgradable = upgradable ? 1 : 0;
2236 value.bits.timestamp = 0;
2237 value.bits.ignored = [self ignored] ? 0 : 1;
2238 value.bits.upgradable = 1;
2240 value.bits.timestamp = [self seen] >> 2;
2241 value.bits.ignored = 0;
2242 value.bits.upgradable = 0;
2245 return _not(uint32_t) - value.key;
2248 CYString &(*PackageName)(Package *self, SEL sel);
2250 uint32_t PackagePrefixRadix(Package *self, void *context) {
2251 size_t offset(reinterpret_cast<size_t>(context));
2252 CYString &name(PackageName(self, @selector(cyname)));
2254 size_t size(name.size());
2257 char *text(name.data());
2260 if (!isdigit(text[0]))
2264 while (size != digits && isdigit(text[digits]))
2272 if (offset == 0 && zeros != 0) {
2273 memset(data, '0', zeros);
2274 memcpy(data + zeros, text, 4 - zeros);
2276 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2277 if (size <= offset - zeros)
2280 text += offset - zeros;
2281 size -= offset - zeros;
2284 memcpy(data, text, 4);
2286 memcpy(data, text, size);
2287 memset(data + size, 0, 4 - size);
2290 for (size_t i(0); i != 4; ++i)
2291 if (isalpha(data[i]))
2299 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2301 /* XXX: ntohl may be more honest */
2302 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2305 CFComparisonResult StringNameCompare(CFStringRef lhn, CFStringRef rhn, size_t length) {
2306 _profile(PackageNameCompare)
2308 return rhn == NULL ? kCFCompareEqualTo : kCFCompareLessThan;
2309 else if (rhn == NULL)
2310 return kCFCompareGreaterThan;
2312 CFIndex length(CFStringGetLength(lhn));
2314 _profile(PackageNameCompare$NumbersLast)
2315 if (length != 0 && CFStringGetLength(rhn) != 0) {
2316 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2317 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2318 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2319 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2320 return lha ? kCFCompareLessThan : kCFCompareGreaterThan;
2324 _profile(PackageNameCompare$Compare)
2325 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, (CFLocaleRef) (id) CollationLocale_);
2330 _finline CFComparisonResult StringNameCompare(NSString *lhn, NSString*rhn, size_t length) {
2331 return StringNameCompare((CFStringRef) lhn, (CFStringRef) rhn, length);
2334 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2335 CYString &lhn(PackageName(lhs, @selector(cyname)));
2336 NSString *rhn(PackageName(rhs, @selector(cyname)));
2337 return StringNameCompare(lhn, rhn, lhn.size());
2340 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *arg) {
2341 return PackageNameCompare(*lhs, *rhs, arg);
2344 struct PackageNameOrdering :
2345 std::binary_function<Package *, Package *, bool>
2347 _finline bool operator ()(Package *lhs, Package *rhs) const {
2348 return PackageNameCompare(lhs, rhs, NULL) == kCFCompareLessThan;
2352 @implementation Package
2354 - (NSString *) description {
2355 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2361 if (parsed_ != NULL)
2366 + (NSString *) webScriptNameForSelector:(SEL)selector {
2368 else if (selector == @selector(clear))
2370 else if (selector == @selector(getField:))
2372 else if (selector == @selector(getRecord))
2373 return @"getRecord";
2374 else if (selector == @selector(hasTag:))
2376 else if (selector == @selector(install))
2378 else if (selector == @selector(remove))
2384 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2385 return [self webScriptNameForSelector:selector] == nil;
2388 + (NSArray *) _attributeKeys {
2389 return [NSArray arrayWithObjects:
2410 @"shortDescription",
2423 - (NSArray *) attributeKeys {
2424 return [[self class] _attributeKeys];
2427 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2428 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2431 - (NSArray *) relations {
2432 @synchronized (database_) {
2433 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2434 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2435 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2439 - (NSString *) architecture {
2441 @synchronized (database_) {
2442 return parsed_->architecture_.empty() ? [NSNull null] : (id) parsed_->architecture_;
2445 - (NSString *) getField:(NSString *)name {
2446 @synchronized (database_) {
2447 if ([database_ era] != era_ || file_.end())
2450 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2452 const char *start, *end;
2453 if (!parser.Find([name UTF8String], start, end))
2454 return (NSString *) [NSNull null];
2456 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2459 - (NSString *) getRecord {
2460 @synchronized (database_) {
2461 if ([database_ era] != era_ || file_.end())
2464 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2466 const char *start, *end;
2467 parser.GetRec(start, end);
2469 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2473 if (parsed_ != NULL)
2475 @synchronized (database_) {
2476 if ([database_ era] != era_ || file_.end())
2479 ParsedPackage *parsed(new ParsedPackage);
2482 _profile(Package$parse)
2483 pkgRecords::Parser *parser;
2485 _profile(Package$parse$Lookup)
2486 parser = &[database_ records]->Lookup(file_);
2492 _profile(Package$parse$Find)
2497 {"architecture", &parsed->architecture_},
2498 {"icon", &parsed->icon_},
2499 {"depiction", &parsed->depiction_},
2500 {"homepage", &parsed->homepage_},
2501 {"website", &website},
2503 {"support", &parsed->support_},
2504 {"author", &parsed->author_},
2505 {"md5sum", &parsed->md5sum_},
2508 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2509 const char *start, *end;
2511 if (parser->Find(names[i].name_, start, end)) {
2512 CYString &value(*names[i].value_);
2513 _profile(Package$parse$Value)
2514 value.set(pool_, start, end - start);
2520 _profile(Package$parse$Tagline)
2521 parsed->tagline_.set(pool_, parser->ShortDesc());
2524 _profile(Package$parse$Retain)
2525 if (parsed->homepage_.empty())
2526 parsed->homepage_ = website;
2527 if (parsed->homepage_ == parsed->depiction_)
2528 parsed->homepage_.clear();
2529 if (parsed->support_.empty())
2530 parsed->support_ = bugs;
2535 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database {
2536 if ((self = [super init]) != nil) {
2537 _profile(Package$initWithVersion)
2539 pool_ = new CYPool();
2545 database_ = database;
2546 era_ = [database era];
2550 pkgCache::PkgIterator iterator(version_.ParentPkg());
2551 iterator_ = iterator;
2553 _profile(Package$initWithVersion$Version)
2554 file_ = version_.FileList();
2557 _profile(Package$initWithVersion$Cache)
2558 name_.set(NULL, version_.Display());
2560 latest_.set(NULL, StripVersion_(version_.VerStr()));
2562 pkgCache::VerIterator current(iterator.CurrentVer());
2564 installed_.set(NULL, StripVersion_(current.VerStr()));
2567 _profile(Package$initWithVersion$Transliterate) do {
2568 if (CollationTransl_ == NULL)
2573 _profile(Package$initWithVersion$Transliterate$utf8)
2574 const uint8_t *data(reinterpret_cast<const uint8_t *>(name_.data()));
2575 for (size_t i(0), e(name_.size()); i != e; ++i)
2576 if (data[i] >= 0x80)
2581 UErrorCode code(U_ZERO_ERROR);
2584 _profile(Package$initWithVersion$Transliterate$u_strFromUTF8WithSub)
2585 CollationString_.resize(name_.size());
2586 u_strFromUTF8WithSub(&CollationString_[0], CollationString_.size(), &length, name_.data(), name_.size(), 0xfffd, NULL, &code);
2587 if (!U_SUCCESS(code))
2589 CollationString_.resize(length);
2592 _profile(Package$initWithVersion$Transliterate$utrans_trans)
2593 length = CollationString_.size();
2594 utrans_trans(CollationTransl_, reinterpret_cast<UReplaceable *>(&CollationString_), &CollationUCalls_, 0, &length, &code);
2595 if (!U_SUCCESS(code))
2597 _assert(CollationString_.size() == length);
2600 _profile(Package$initWithVersion$Transliterate$u_strToUTF8WithSub$preflight)
2601 u_strToUTF8WithSub(NULL, 0, &length, CollationString_.data(), CollationString_.size(), 0xfffd, NULL, &code);
2602 if (code == U_BUFFER_OVERFLOW_ERROR)
2603 code = U_ZERO_ERROR;
2604 else if (!U_SUCCESS(code))
2609 _profile(Package$initWithVersion$Transliterate$apr_palloc)
2610 transform = pool_->malloc<char>(length);
2612 _profile(Package$initWithVersion$Transliterate$u_strToUTF8WithSub$transform)
2613 u_strToUTF8WithSub(transform, length, NULL, CollationString_.data(), CollationString_.size(), 0xfffd, NULL, &code);
2614 if (!U_SUCCESS(code))
2618 transform_.set(NULL, transform, length);
2619 } while (false); _end
2621 _profile(Package$initWithVersion$Tags)
2623 pkgCache::TagIterator tag(version_.TagList());
2625 pkgCache::TagIterator tag(iterator.TagList());
2628 tags_ = [NSMutableArray arrayWithCapacity:8];
2630 goto tag; for (; !tag.end(); ++tag) tag: {
2631 const char *name(tag.Name());
2632 NSString *string((NSString *) CYStringCreate(name));
2636 [tags_ addObject:[string autorelease]];
2638 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2639 if (strcmp(name + 6, "enduser") == 0)
2641 else if (strcmp(name + 6, "hacker") == 0)
2643 else if (strcmp(name + 6, "developer") == 0)
2645 else if (strcmp(name + 6, "cydia") == 0)
2651 if (strncmp(name, "cydia::", 7) == 0) {
2652 if (strcmp(name + 7, "essential") == 0)
2654 else if (strcmp(name + 7, "obsolete") == 0)
2661 _profile(Package$initWithVersion$Metadata)
2662 const char *mixed(iterator.Name());
2663 size_t size(strlen(mixed));
2664 static const size_t prefix(sizeof("/var/lib/dpkg/info/") - 1);
2665 char lower[prefix + size + 5 + 1];
2667 for (size_t i(0); i != size; ++i)
2668 lower[prefix + i] = mixed[i] | 0x20;
2670 if (!installed_.empty()) {
2671 memcpy(lower, "/var/lib/dpkg/info/", prefix);
2672 memcpy(lower + prefix + size, ".list", 6);
2674 if (stat(lower, &info) != -1)
2675 upgraded_ = info.st_birthtime;
2678 PackageValue *metadata(PackageFind(lower + prefix, size));
2679 metadata_ = metadata;
2681 id_.set(NULL, metadata->name_, size);
2683 const char *latest(version_.VerStr());
2684 size_t length(strlen(latest));
2686 uint16_t vhash(hashlittle(latest, length));
2688 size_t capped(std::min<size_t>(8, length));
2689 latest = latest + length - capped;
2691 if (metadata->first_ == 0)
2692 metadata->first_ = now_;
2694 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2695 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2696 metadata->vhash_ = vhash;
2697 metadata->last_ = now_;
2698 } else if (metadata->last_ == 0)
2699 metadata->last_ = metadata->first_;
2702 _profile(Package$initWithVersion$Section)
2703 section_ = version_.Section();
2706 _profile(Package$initWithVersion$Flags)
2707 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2708 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2713 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database {
2714 pkgCache::VerIterator version;
2716 _profile(Package$packageWithIterator$GetCandidateVer)
2717 version = [database policy]->GetCandidateVer(iterator);
2725 _profile(Package$packageWithIterator$Allocate)
2726 package = [Package allocWithZone:zone];
2729 _profile(Package$packageWithIterator$Initialize)
2731 initWithVersion:version
2738 _profile(Package$packageWithIterator$Autorelease)
2739 package = [package autorelease];
2745 - (pkgCache::PkgIterator) iterator {
2749 - (NSArray *) downgrades {
2750 NSMutableArray *versions([NSMutableArray arrayWithCapacity:4]);
2752 for (auto version(iterator_.VersionList()); !version.end(); ++version) {
2753 if (version == version_)
2755 Package *package([[[Package allocWithZone:NULL] initWithVersion:version withZone:NULL inPool:NULL database:database_] autorelease]);
2756 if ([package source] == nil)
2758 [versions addObject:package];
2764 - (NSString *) section {
2765 if (section$_ == nil) {
2766 if (section_ == NULL)
2769 _profile(Package$section$mappedSectionForPointer)
2770 section$_ = [database_ mappedSectionForPointer:section_];
2775 - (NSString *) simpleSection {
2776 if (NSString *section = [self section])
2777 return Simplify(section);
2782 - (NSString *) longSection {
2783 if (NSString *section = [self section])
2784 return LocalizeSection(section);
2789 - (NSString *) shortSection {
2790 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2793 - (NSString *) uri {
2796 pkgIndexFile *index;
2797 pkgCache::PkgFileIterator file(file_.File());
2798 if (![database_ list].FindIndex(file, index))
2800 return [NSString stringWithUTF8String:iterator_->Path];
2801 //return [NSString stringWithUTF8String:file.Site()];
2802 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2806 - (MIMEAddress *) maintainer {
2807 @synchronized (database_) {
2808 if ([database_ era] != era_ || file_.end())
2811 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2812 const std::string &maintainer(parser->Maintainer());
2813 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2816 - (NSString *) md5sum {
2817 return parsed_ == NULL ? nil : (id) parsed_->md5sum_;
2821 @synchronized (database_) {
2822 if ([database_ era] != era_ || version_.end())
2825 return version_->InstalledSize;
2828 - (NSString *) longDescription {
2829 @synchronized (database_) {
2830 if ([database_ era] != era_ || file_.end())
2833 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2834 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2836 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2837 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2838 if ([lines count] < 2)
2841 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2842 for (size_t i(1), e([lines count]); i != e; ++i) {
2843 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2844 [trimmed addObject:trim];
2847 return [trimmed componentsJoinedByString:@"\n"];
2850 - (NSString *) shortDescription {
2851 if (parsed_ != NULL)
2852 return static_cast<NSString *>(parsed_->tagline_);
2854 @synchronized (database_) {
2855 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2856 std::string value(parser.ShortDesc());
2859 if (value.size() > 200)
2861 return [(id) CYStringCreate(value) autorelease];
2865 _profile(Package$index)
2866 CFStringRef name((CFStringRef) [self name]);
2867 if (CFStringGetLength(name) == 0)
2869 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2870 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2872 return toupper(character);
2876 - (PackageValue *) metadata {
2881 PackageValue *metadata([self metadata]);
2882 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2885 - (bool) subscribed {
2886 return [self metadata]->subscribed_;
2889 - (bool) setSubscribed:(bool)subscribed {
2890 PackageValue *metadata([self metadata]);
2891 if (metadata->subscribed_ == subscribed)
2893 metadata->subscribed_ = subscribed;
2901 - (NSString *) latest {
2905 - (NSString *) installed {
2909 - (BOOL) uninstalled {
2910 return installed_.empty();
2913 - (BOOL) upgradableAndEssential:(BOOL)essential {
2914 _profile(Package$upgradableAndEssential)
2915 pkgCache::VerIterator current(iterator_.CurrentVer());
2917 return essential && essential_;
2919 return version_ != current;
2923 - (BOOL) essential {
2928 return [database_ cache][iterator_].InstBroken();
2931 - (BOOL) unfiltered {
2932 _profile(Package$unfiltered$obsolete)
2933 if (_unlikely(obsolete_))
2937 _profile(Package$unfiltered$role)
2938 if (_unlikely(role_ > 3))
2946 if (![self unfiltered])
2951 _profile(Package$visible$section)
2952 section = [self section];
2955 _profile(Package$visible$isSectionVisible)
2956 if (!isSectionVisible(section))
2964 unsigned char current(iterator_->CurrentState);
2965 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2968 - (BOOL) halfConfigured {
2969 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2972 - (BOOL) halfInstalled {
2973 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2977 @synchronized (database_) {
2978 if ([database_ era] != era_ || iterator_.end())
2981 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2982 return state.Mode != pkgDepCache::ModeKeep;
2985 - (NSString *) mode {
2986 @synchronized (database_) {
2987 if ([database_ era] != era_ || iterator_.end())
2990 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2992 switch (state.Mode) {
2993 case pkgDepCache::ModeDelete:
2994 if ((state.iFlags & pkgDepCache::Purge) != 0)
2998 case pkgDepCache::ModeKeep:
2999 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
3000 return @"REINSTALL";
3001 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
3005 case pkgDepCache::ModeInstall:
3006 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
3007 return @"REINSTALL";
3008 else*/ switch (state.Status) {
3010 return @"DOWNGRADE";
3016 return @"NEW_INSTALL";
3027 - (NSString *) name {
3028 return name_.empty() ? id_ : name_;
3031 - (UIImage *) icon {
3032 NSString *section = [self simpleSection];
3035 if (parsed_ != NULL)
3036 if (NSString *href = parsed_->icon_)
3037 if ([href hasPrefix:@"file:///"])
3038 icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
3039 if (icon == nil) if (section != nil)
3040 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]];
3041 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
3042 if ([dicon hasPrefix:@"file:///"])
3043 icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
3045 icon = [UIImage imageNamed:@"unknown.png"];
3049 - (NSString *) homepage {
3050 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
3053 - (NSString *) depiction {
3054 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
3057 - (MIMEAddress *) author {
3058 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
3061 - (NSString *) support {
3062 return parsed_ != NULL && !parsed_->support_.empty() ? parsed_->support_ : [[self source] supportForPackage:id_];
3065 - (NSArray *) files {
3066 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
3067 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
3070 fin.open([path UTF8String]);
3075 while (std::getline(fin, line))
3076 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
3081 - (NSString *) state {
3082 @synchronized (database_) {
3083 if ([database_ era] != era_ || file_.end())
3086 switch (iterator_->CurrentState) {
3087 case pkgCache::State::NotInstalled:
3088 return @"NotInstalled";
3089 case pkgCache::State::UnPacked:
3091 case pkgCache::State::HalfConfigured:
3092 return @"HalfConfigured";
3093 case pkgCache::State::HalfInstalled:
3094 return @"HalfInstalled";
3095 case pkgCache::State::ConfigFiles:
3096 return @"ConfigFiles";
3097 case pkgCache::State::Installed:
3098 return @"Installed";
3099 case pkgCache::State::TriggersAwaited:
3100 return @"TriggersAwaited";
3101 case pkgCache::State::TriggersPending:
3102 return @"TriggersPending";
3105 return (NSString *) [NSNull null];
3108 - (NSString *) selection {
3109 @synchronized (database_) {
3110 if ([database_ era] != era_ || file_.end())
3113 switch (iterator_->SelectedState) {
3114 case pkgCache::State::Unknown:
3116 case pkgCache::State::Install:
3118 case pkgCache::State::Hold:
3120 case pkgCache::State::DeInstall:
3121 return @"DeInstall";
3122 case pkgCache::State::Purge:
3126 return (NSString *) [NSNull null];
3129 - (NSArray *) warnings {
3130 @synchronized (database_) {
3131 if ([database_ era] != era_ || file_.end())
3134 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
3135 const char *name(iterator_.Name());
3137 size_t length(strlen(name));
3138 if (length < 2) invalid:
3139 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
3140 else for (size_t i(0); i != length; ++i)
3142 /* XXX: technically this is not allowed */
3143 (name[i] < 'A' || name[i] > 'Z') &&
3144 (name[i] < 'a' || name[i] > 'z') &&
3145 (name[i] < '0' || name[i] > '9') &&
3146 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
3149 if (strcmp(name, "cydia") != 0) {
3152 bool _private = false;
3154 bool dbstash = false;
3155 bool dsstore = false;
3157 bool repository = [[self section] isEqualToString:@"Repositories"];
3159 if (NSArray *files = [self files])
3160 for (NSString *file in files)
3161 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
3163 else if (!user && [file isEqualToString:@"/User"])
3165 else if (!_private && [file isEqualToString:@"/private"])
3167 else if (!stash && [file isEqualToString:@"/var/stash"])
3169 else if (!dbstash && [file isEqualToString:@"/var/db/stash"])
3171 else if (!dsstore && [file hasSuffix:@"/.DS_Store"])
3174 /* XXX: this is not sensitive enough. only some folders are valid. */
3175 if (cydia && !repository)
3176 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
3178 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
3180 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
3182 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
3184 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/db/stash"]];
3186 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @".DS_Store"]];
3189 return [warnings count] == 0 ? nil : warnings;
3192 - (NSArray *) applications {
3193 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
3195 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
3197 static RegEx application_r("/Applications/(.*)\\.app/Info.plist");
3198 if (NSArray *files = [self files])
3199 for (NSString *file in files)
3200 if (application_r(file)) {
3201 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
3204 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
3205 if (id == nil || [id isEqualToString:me])
3208 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
3210 display = application_r[1];
3212 NSString *bundle([file stringByDeletingLastPathComponent]);
3213 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
3214 // XXX: maybe this should check if this is really a string, not just for length
3215 if (icon == nil || ![icon respondsToSelector:@selector(length)] || [icon length] == 0)
3217 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
3219 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
3220 [applications addObject:application];
3222 [application addObject:id];
3223 [application addObject:display];
3224 [application addObject:url];
3227 return [applications count] == 0 ? nil : applications;
3230 - (Source *) source {
3231 if (source_ == nil) {
3232 @synchronized (database_) {
3233 if ([database_ era] != era_ || file_.end())
3234 source_ = (Source *) [NSNull null];
3236 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
3240 return source_ == (Source *) [NSNull null] ? nil : source_;
3243 - (time_t) upgraded {
3247 - (uint32_t) recent {
3248 return std::numeric_limits<uint32_t>::max() - upgraded_;
3255 - (BOOL) matches:(NSArray *)query {
3256 if (query == nil || [query count] == 0)
3265 string = [self name];
3266 length = [string length];
3269 for (NSString *term in query) {
3270 range = [string rangeOfString:term options:MatchCompareOptions_];
3271 if (range.location != NSNotFound)
3272 rank_ -= 6 * 1000000 / length;
3277 length = [string length];
3280 for (NSString *term in query) {
3281 range = [string rangeOfString:term options:MatchCompareOptions_];
3282 if (range.location != NSNotFound)
3283 rank_ -= 6 * 1000000 / length;
3287 string = [self shortDescription];
3288 length = [string length];
3289 NSUInteger stop(std::min<NSUInteger>(length, 200));
3292 for (NSString *term in query) {
3293 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
3294 if (range.location != NSNotFound)
3295 rank_ -= 2 * 100000;
3301 - (NSArray *) tags {
3305 - (BOOL) hasTag:(NSString *)tag {
3306 return tags_ == nil ? NO : [tags_ containsObject:tag];
3309 - (NSString *) primaryPurpose {
3310 for (NSString *tag in (NSArray *) tags_)
3311 if ([tag hasPrefix:@"purpose::"])
3312 return [tag substringFromIndex:9];
3316 - (NSArray *) purposes {
3317 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
3318 for (NSString *tag in (NSArray *) tags_)
3319 if ([tag hasPrefix:@"purpose::"])
3320 [purposes addObject:[tag substringFromIndex:9]];
3321 return [purposes count] == 0 ? nil : purposes;
3324 - (bool) isCommercial {
3325 return [self hasTag:@"cydia::commercial"];
3328 - (void) setIndex:(size_t)index {
3329 if (metadata_->index_ != index)
3330 metadata_->index_ = index;
3333 - (CYString &) cyname {
3334 return !transform_.empty() ? transform_ : !name_.empty() ? name_ : id_;
3337 - (uint32_t) compareBySection:(NSArray *)sections {
3338 NSString *section([self section]);
3339 for (size_t i(0), e([sections count]); i != e; ++i) {
3340 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3344 return _not(uint32_t);
3348 @synchronized (database_) {
3349 if ([database_ era] != era_ || file_.end())
3352 pkgProblemResolver *resolver = [database_ resolver];
3353 resolver->Clear(iterator_);
3355 pkgCacheFile &cache([database_ cache]);
3356 cache->SetReInstall(iterator_, false);
3357 cache->MarkKeep(iterator_, false);
3361 @synchronized (database_) {
3362 if ([database_ era] != era_ || file_.end())
3365 pkgProblemResolver *resolver = [database_ resolver];
3366 resolver->Clear(iterator_);
3367 resolver->Protect(iterator_);
3369 pkgCacheFile &cache([database_ cache]);
3370 cache->SetCandidateVersion(version_);
3371 cache->SetReInstall(iterator_, false);
3372 cache->MarkInstall(iterator_, false);
3374 pkgDepCache::StateCache &state((*cache)[iterator_]);
3375 if (!state.Install())
3376 cache->SetReInstall(iterator_, true);
3380 @synchronized (database_) {
3381 if ([database_ era] != era_ || file_.end())
3384 pkgProblemResolver *resolver = [database_ resolver];
3385 resolver->Clear(iterator_);
3386 resolver->Remove(iterator_);
3387 resolver->Protect(iterator_);
3389 pkgCacheFile &cache([database_ cache]);
3390 cache->SetReInstall(iterator_, false);
3391 cache->MarkDelete(iterator_, true);
3396 /* Section Class {{{ */
3397 @interface Section : NSObject {
3401 _H<NSString> localized_;
3404 - (NSComparisonResult) compareByLocalized:(Section *)section;
3405 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3406 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3407 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3409 - (NSString *) name;
3410 - (void) setName:(NSString *)name;
3416 - (void) addToCount;
3418 - (void) setCount:(size_t)count;
3419 - (NSString *) localized;
3423 @implementation Section
3425 - (NSComparisonResult) compareByLocalized:(Section *)section {
3426 NSString *lhs(localized_);
3427 NSString *rhs([section localized]);
3429 /*if ([lhs length] != 0 && [rhs length] != 0) {
3430 unichar lhc = [lhs characterAtIndex:0];
3431 unichar rhc = [rhs characterAtIndex:0];
3433 if (isalpha(lhc) && !isalpha(rhc))
3434 return NSOrderedAscending;
3435 else if (!isalpha(lhc) && isalpha(rhc))
3436 return NSOrderedDescending;
3439 return [lhs compare:rhs options:LaxCompareOptions_];
3442 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3443 if ((self = [self initWithName:name localize:NO]) != nil) {
3444 if (localized != nil)
3445 localized_ = localized;
3449 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3450 return [self initWithName:name row:0 localize:localize];
3453 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3454 if ((self = [super init]) != nil) {
3458 localized_ = LocalizeSection(name_);
3462 - (NSString *) name {
3466 - (void) setName:(NSString *)name {
3482 - (void) addToCount {
3486 - (void) setCount:(size_t)count {
3490 - (NSString *) localized {
3497 class CydiaLogCleaner :
3498 public pkgArchiveCleaner
3501 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3506 /* Database Implementation {{{ */
3507 @implementation Database
3509 + (Database *) sharedInstance {
3510 static _H<Database> instance;
3511 if (instance == nil)
3512 instance = [[[Database alloc] init] autorelease];
3520 - (void) releasePackages {
3521 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3522 CFArrayRemoveAllValues(packages_);
3525 - (bool) hasPackages {
3526 return CFArrayGetCount(packages_) != 0;
3530 // XXX: actually implement this thing
3532 [self releasePackages];
3533 NSRecycleZone(zone_);
3537 - (void) _readCydia:(NSNumber *)fd {
3538 boost::fdistream is([fd intValue]);
3541 static RegEx finish_r("finish:([^:]*)");
3543 while (std::getline(is, line)) {
3544 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3546 const char *data(line.c_str());
3547 size_t size = line.size();
3548 lprintf("C:%s\n", data);
3550 if (finish_r(data, size)) {
3551 NSString *finish = finish_r[1];
3552 int index = [Finishes_ indexOfObject:finish];
3553 if (index != INT_MAX && index > Finish_)
3563 - (void) _readStatus:(NSNumber *)fd {
3564 boost::fdistream is([fd intValue]);
3567 static RegEx conffile_r("status: [^ ]* : conffile-prompt : (.*?) *");
3568 static RegEx pmstatus_r("([^:]*):([^:]*):([^:]*):(.*)");
3570 while (std::getline(is, line)) {
3571 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3573 const char *data(line.c_str());
3574 size_t size(line.size());
3575 lprintf("S:%s\n", data);
3577 if (conffile_r(data, size)) {
3578 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3579 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3580 } else if (strncmp(data, "status: ", 8) == 0) {
3581 // status: <package>: {unpacked,half-configured,installed}
3582 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3583 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3584 } else if (strncmp(data, "processing: ", 12) == 0) {
3585 // processing: configure: config-test
3586 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3587 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3588 } else if (pmstatus_r(data, size)) {
3589 std::string type([pmstatus_r[1] UTF8String]);
3591 NSString *package = pmstatus_r[2];
3592 if ([package isEqualToString:@"dpkg-exec"])
3595 float percent([pmstatus_r[3] floatValue]);
3596 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3598 NSString *string = pmstatus_r[4];
3600 if (type == "pmerror") {
3601 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3602 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3603 } else if (type == "pmstatus") {
3604 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3605 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3606 } else if (type == "pmconffile")
3607 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3609 lprintf("E:unknown pmstatus\n");
3611 lprintf("E:unknown status\n");
3619 - (void) _readOutput:(NSNumber *)fd {
3620 boost::fdistream is([fd intValue]);
3623 while (std::getline(is, line)) {
3624 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3626 lprintf("O:%s\n", line.c_str());
3628 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3629 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3641 - (Package *) packageWithName:(NSString *)name {
3644 @synchronized (self) {
3645 if (static_cast<pkgDepCache *>(cache_) == NULL)
3647 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]
3652 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:NULL database:self];
3656 if ((self = [super init]) != nil) {
3663 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3665 size_t capacity(MetaFile_->active_);
3671 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3672 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3676 _assert(pipe(fds) != -1);
3679 _config->Set("APT::Keep-Fds::", cydiafd_);
3680 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3683 detachNewThreadSelector:@selector(_readCydia:)
3685 withObject:[NSNumber numberWithInt:fds[0]]
3688 _assert(pipe(fds) != -1);
3692 detachNewThreadSelector:@selector(_readStatus:)
3694 withObject:[NSNumber numberWithInt:fds[0]]
3697 _assert(pipe(fds) != -1);
3698 _assert(dup2(fds[0], 0) != -1);
3699 _assert(close(fds[0]) != -1);
3701 input_ = fdopen(fds[1], "a");
3703 _assert(pipe(fds) != -1);
3704 _assert(dup2(fds[1], 1) != -1);
3705 _assert(close(fds[1]) != -1);
3708 detachNewThreadSelector:@selector(_readOutput:)
3710 withObject:[NSNumber numberWithInt:fds[0]]
3715 - (pkgCacheFile &) cache {
3719 - (pkgDepCache::Policy *) policy {
3723 - (pkgRecords *) records {
3727 - (pkgProblemResolver *) resolver {
3731 - (pkgAcquire &) fetcher {
3735 - (pkgSourceList &) list {
3739 - (NSArray *) packages {
3740 return (NSArray *) packages_;
3743 - (NSArray *) sources {
3747 - (Source *) sourceWithKey:(NSString *)key {
3748 for (Source *source in [self sources]) {
3749 if ([[source key] isEqualToString:key])
3754 - (bool) popErrorWithTitle:(NSString *)title {
3757 while (!_error->empty()) {
3759 bool warning(!_error->PopMessage(error));
3764 size_t size(error.size());
3765 if (size == 0 || error[size - 1] != '\n')
3767 error.resize(size - 1);
3770 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3772 static RegEx no_pubkey("GPG error:.* NO_PUBKEY .*");
3773 if (warning && no_pubkey(error.c_str()))
3776 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3782 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3783 return [self popErrorWithTitle:title] || !success;
3786 - (bool) popErrorWithTitle:(NSString *)title forReadList:(pkgSourceList &)list {
3787 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3795 if (access("/etc/apt/sources.list", F_OK) == 0)
3796 error |= [self popErrorWithTitle:title forOperation:list.ReadAppend("/etc/apt/sources.list")];
3798 std::string base("/etc/apt/sources.list.d");
3799 if (DIR *sources = opendir(base.c_str())) {
3800 while (dirent *source = readdir(sources))
3801 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)
3802 error |= [self popErrorWithTitle:title forOperation:list.ReadAppend((base + "/" + source->d_name).c_str())];
3806 error |= [self popErrorWithTitle:title forOperation:list.ReadAppend(SOURCES_LIST)];
3811 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3812 @synchronized (self) {
3815 [self releasePackages];
3818 [sourceList_ removeAllObjects];
3839 new (&pool_) CYPool();
3841 NSRecycleZone(zone_);
3842 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3844 int chk(creat("/tmp/cydia.chk", 0644));
3848 if (invocation != nil)
3849 [invocation invoke];
3851 NSString *title(UCLocalize("DATABASE"));
3853 list_ = new pkgSourceList();
3854 _profile(reloadDataWithInvocation$ReadMainList)
3855 if ([self popErrorWithTitle:title forReadList:*list_])
3859 _profile(reloadDataWithInvocation$Source$initWithMetaIndex)
3860 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3861 Source *object([[[Source alloc] initWithMetaIndex:*source forDatabase:self inPool:&pool_] autorelease]);
3862 [sourceList_ addObject:object];
3867 OpProgress progress;
3870 delock_ = GetStatusDate();
3871 _profile(reloadDataWithInvocation$pkgCacheFile)
3872 opened = cache_.Open(progress, false);
3875 // XXX: this block should probably be merged with popError: in some way
3876 while (!_error->empty()) {
3878 bool warning(!_error->PopMessage(error));
3880 lprintf("cache_.Open():[%s]\n", error.c_str());
3882 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3886 else if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3887 repair = @selector(configure);
3888 //else if (error == "The package lists or status file could not be parsed or opened.")
3889 // repair = @selector(update);
3890 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3891 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3892 // else if (error == "Malformed Status line")
3893 // else if (error == "The list of sources could not be read.")
3895 if (repair != NULL) {
3897 [delegate_ repairWithSelector:repair];
3903 } else if ([self popErrorWithTitle:title forOperation:true])
3907 unlink("/tmp/cydia.chk");
3909 now_ = [[NSDate date] timeIntervalSince1970];
3911 policy_ = new pkgDepCache::Policy();
3912 records_ = new pkgRecords(cache_);
3913 resolver_ = new pkgProblemResolver(cache_);
3914 fetcher_ = new pkgAcquire(&status_);
3917 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3918 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3922 _profile(reloadDataWithInvocation$pkgApplyStatus)
3923 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3927 if (cache_->BrokenCount() != 0) {
3928 _profile(pkgApplyStatus$pkgFixBroken)
3929 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3933 if (cache_->BrokenCount() != 0) {
3934 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3938 _profile(pkgApplyStatus$pkgMinimizeUpgrade)
3939 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3944 for (Source *object in (id) sourceList_) {
3945 metaIndex *source([object metaIndex]);
3946 std::vector<pkgIndexFile *> *indices = source->GetIndexFiles();
3947 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3948 // XXX: this could be more intelligent
3949 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3950 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3952 sourceMap_[cached->ID] = object;
3957 /*std::vector<Package *> packages;
3958 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3961 _profile(reloadDataWithInvocation$packageWithIterator)
3962 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3963 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:&pool_ database:self])
3964 //packages.push_back(package);
3965 CFArrayAppendValue(packages_, CFRetain(package));
3969 /*if (packages.empty())
3970 packages_ = [[NSArray alloc] init];
3972 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3975 _profile(reloadDataWithInvocation$radix$8)
3976 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(8)];
3979 _profile(reloadDataWithInvocation$radix$4)
3980 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3983 _profile(reloadDataWithInvocation$radix$0)
3984 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3987 _profile(reloadDataWithInvocation$insertion)
3988 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3991 /*_profile(reloadDataWithInvocation$CFQSortArray)
3992 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);
3995 /*_profile(reloadDataWithInvocation$stdsort)
3996 std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3999 /*_profile(reloadDataWithInvocation$CFArraySortValues)
4000 CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
4003 /*_profile(reloadDataWithInvocation$sortUsingFunction)
4004 [packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
4008 size_t count(CFArrayGetCount(packages_));
4009 MetaFile_->active_ = count;
4010 for (size_t index(0); index != count; ++index)
4011 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
4016 @synchronized (self) {
4018 resolver_ = new pkgProblemResolver(cache_);
4020 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
4021 if (!cache_[iterator].Keep())
4022 cache_->MarkKeep(iterator, false);
4023 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
4024 cache_->SetReInstall(iterator, false);
4027 - (void) configure {
4028 NSString *dpkg = [NSString stringWithFormat:@"/usr/libexec/cydo --configure -a --status-fd %u", statusfd_];
4030 system([dpkg UTF8String]);
4035 @synchronized (self) {
4036 // XXX: I don't remember this condition
4041 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
4043 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
4045 if ([self popErrorWithTitle:title])
4049 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
4051 CydiaLogCleaner cleaner;
4052 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
4059 fetcher_->Shutdown();
4061 pkgRecords records(cache_);
4063 lock_ = new FileFd();
4064 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
4066 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
4068 if ([self popErrorWithTitle:title])
4072 if ([self popErrorWithTitle:title forReadList:list])
4075 manager_ = (_system->CreatePM(cache_));
4076 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
4083 bool substrate(RestartSubstrate_);
4084 RestartSubstrate_ = false;
4086 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
4088 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
4090 if ([self popErrorWithTitle:title forReadList:list])
4092 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
4093 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
4096 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4098 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
4100 [self popErrorWithTitle:title];
4104 bool failed = false;
4105 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
4106 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
4108 if ((*item)->Status == pkgAcquire::Item::StatIdle)
4111 std::string uri = (*item)->DescURI();
4112 std::string error = (*item)->ErrorText;
4114 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
4117 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError]);
4118 [delegate_ addProgressEventOnMainThread:event forTask:title];
4121 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4129 RestartSubstrate_ = true;
4131 if (![delock_ isEqual:GetStatusDate()]) {
4132 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("DPKG_LOCKED") ofType:kCydiaProgressEventTypeError] forTask:title];
4138 pkgPackageManager::OrderResult result(manager_->DoInstall(statusfd_));
4140 NSString *oextended(@"/var/lib/apt/extended_states");
4141 NSString *nextended(Cache("extended_states"));
4144 if (stat([nextended UTF8String], &info) != -1 && (info.st_mode & S_IFMT) == S_IFREG)
4145 system([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /bin/cp --remove-destination %@ %@", ShellEscape(nextended), ShellEscape(oextended)] UTF8String]);
4147 unlink([nextended UTF8String]);
4148 symlink([oextended UTF8String], [nextended UTF8String]);
4150 if ([self popErrorWithTitle:title])
4153 if (result == pkgPackageManager::Failed) {
4158 if (result != pkgPackageManager::Completed) {
4163 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
4165 if ([self popErrorWithTitle:title forReadList:list])
4167 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
4168 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
4171 if (![before isEqualToArray:after])
4176 return ![delock_ isEqual:GetStatusDate()];
4180 NSString *title(UCLocalize("UPGRADE"));
4181 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
4187 [self updateWithStatus:status_];
4190 - (void) updateWithStatus:(CancelStatus &)status {
4191 NSString *title(UCLocalize("REFRESHING_DATA"));
4194 if ([self popErrorWithTitle:title forReadList:list])
4198 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
4199 if ([self popErrorWithTitle:title])
4202 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4204 bool success(ListUpdate(status, list, PulseInterval_));
4205 if (status.WasCancelled())
4208 [self popErrorWithTitle:title forOperation:success];
4210 [[NSDictionary dictionaryWithObjectsAndKeys:
4211 [NSDate date], @"LastUpdate",
4212 nil] writeToFile:@ CacheState_ atomically:YES];
4215 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4218 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
4219 delegate_ = delegate;
4222 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
4223 progress_ = delegate;
4224 status_.setDelegate(delegate);
4227 - (NSObject<ProgressDelegate> *) progressDelegate {
4231 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
4232 SourceMap::const_iterator i(sourceMap_.find(file->ID));
4233 return i == sourceMap_.end() ? nil : i->second;
4236 - (void) setFetch:(bool)fetch forURI:(const char *)uri {
4237 for (Source *source in (id) sourceList_)
4238 [source setFetch:fetch forURI:uri];
4241 - (void) resetFetch {
4242 for (Source *source in (id) sourceList_)
4243 [source resetFetch];
4246 - (NSString *) mappedSectionForPointer:(const char *)section {
4247 _H<NSString> *mapped;
4249 _profile(Database$mappedSectionForPointer$Cache)
4250 mapped = §ions_[section];
4253 if (*mapped == NULL) {
4254 size_t length(strlen(section));
4255 char spaced[length + 1];
4257 _profile(Database$mappedSectionForPointer$Replace)
4258 for (size_t index(0); index != length; ++index)
4259 spaced[index] = section[index] == '_' ? ' ' : section[index];
4260 spaced[length] = '\0';
4265 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
4266 string = [NSString stringWithUTF8String:spaced];
4269 _profile(Database$mappedSectionForPointer$Map)
4270 string = [SectionMap_ objectForKey:string] ?: string;
4280 static _H<NSMutableSet> Diversions_;
4282 @interface Diversion : NSObject {
4285 _H<NSString> format_;
4290 @implementation Diversion
4292 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
4293 if ((self = [super init]) != nil) {
4294 pattern_ = [from UTF8String];
4300 - (NSString *) divert:(NSString *)url {
4301 return !pattern_(url) ? nil : pattern_->*format_;
4304 + (NSURL *) divertURL:(NSURL *)url {
4306 NSString *href([url absoluteString]);
4308 for (Diversion *diversion in (id) Diversions_)
4309 if (NSString *diverted = [diversion divert:href]) {
4311 NSLog(@"div: %@", diverted);
4313 url = [NSURL URLWithString:diverted];
4320 - (NSString *) key {
4324 - (NSUInteger) hash {
4328 - (BOOL) isEqual:(Diversion *)object {
4329 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
4334 @interface CydiaObject : NSObject {
4335 _H<CyteWebViewController> indirect_;
4336 _transient id delegate_;
4339 - (id) initWithDelegate:(CyteWebViewController *)indirect;
4345 @interface CydiaWebViewController : CyteWebViewController {
4346 _H<CydiaObject> cydia_;
4349 + (void) addDiversion:(Diversion *)diversion;
4350 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request;
4351 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia;
4352 - (void) setDelegate:(id)delegate;
4356 /* Web Scripting {{{ */
4357 @implementation CydiaObject
4359 - (id) initWithDelegate:(CyteWebViewController *)indirect {
4360 if ((self = [super init]) != nil) {
4361 indirect_ = indirect;
4365 - (void) setDelegate:(id)delegate {
4366 delegate_ = delegate;
4369 + (NSArray *) _attributeKeys {
4370 return [NSArray arrayWithObjects:
4375 @"coreFoundationVersionNumber",
4391 - (NSArray *) attributeKeys {
4392 return [[self class] _attributeKeys];
4395 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4396 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4399 - (NSString *) version {
4403 - (unsigned) bittage {
4405 #elif defined(__arm64__)
4407 #elif defined(__arm__)
4414 - (NSString *) build {
4418 - (NSString *) coreFoundationVersionNumber {
4419 return [NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber];
4422 - (NSString *) device {
4423 return UniqueIdentifier();
4426 - (NSString *) firmware {
4427 return [[UIDevice currentDevice] systemVersion];
4430 - (NSString *) hostname {
4431 return [[UIDevice currentDevice] name];
4434 - (NSString *) idiom {
4435 return (id) Idiom_ ?: [NSNull null];
4438 - (NSArray *) cells {
4439 auto *$_CTServerConnectionCreate(reinterpret_cast<id (*)(void *, void *, void *)>(dlsym(RTLD_DEFAULT, "_CTServerConnectionCreate")));
4440 if ($_CTServerConnectionCreate == NULL)
4443 struct CTResult { int flag; int error; };
4444 auto *$_CTServerConnectionCellMonitorCopyCellInfo(reinterpret_cast<CTResult (*)(CFTypeRef, void *, CFArrayRef *)>(dlsym(RTLD_DEFAULT, "_CTServerConnectionCellMonitorCopyCellInfo")));
4445 if ($_CTServerConnectionCellMonitorCopyCellInfo == NULL)
4448 _H<const void> connection($_CTServerConnectionCreate(NULL, NULL, NULL), true);
4449 if (connection == nil)
4453 CFArrayRef cells(NULL);
4454 auto result($_CTServerConnectionCellMonitorCopyCellInfo(connection, &count, &cells));
4455 if (result.flag != 0)
4458 return [(NSArray *) cells autorelease];
4461 - (NSString *) mcc {
4462 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode")))
4463 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault) autorelease];
4467 - (NSString *) mnc {
4468 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberNetworkCode")))
4469 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault) autorelease];
4473 - (NSString *) operator {
4474 if (CFStringRef (*$CTRegistrationCopyOperatorName)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTRegistrationCopyOperatorName")))
4475 return [(NSString *) (*$CTRegistrationCopyOperatorName)(kCFAllocatorDefault) autorelease];
4479 - (NSString *) bbsnum {
4480 return (id) BBSNum_ ?: [NSNull null];
4483 - (NSString *) ecid {
4484 return (id) ChipID_ ?: [NSNull null];
4487 - (NSString *) serial {
4488 return SerialNumber_;
4491 - (NSString *) role {
4492 return (id) [NSNull null];
4495 - (NSString *) model {
4496 return [NSString stringWithUTF8String:Machine_];
4499 + (NSString *) webScriptNameForSelector:(SEL)selector {
4501 else if (selector == @selector(addBridgedHost:))
4502 return @"addBridgedHost";
4503 else if (selector == @selector(addInsecureHost:))
4504 return @"addInsecureHost";
4505 else if (selector == @selector(addInternalRedirect::))
4506 return @"addInternalRedirect";
4507 else if (selector == @selector(addPipelinedHost:scheme:))
4508 return @"addPipelinedHost";
4509 else if (selector == @selector(addSource:::))
4510 return @"addSource";
4511 else if (selector == @selector(addTrivialSource:))
4512 return @"addTrivialSource";
4513 else if (selector == @selector(close))
4515 else if (selector == @selector(du:))
4517 else if (selector == @selector(stringWithFormat:arguments:))
4519 else if (selector == @selector(getAllSources))
4520 return @"getAllSources";
4521 else if (selector == @selector(getApplicationInfo:value:))
4522 return @"getApplicationInfoValue";
4523 else if (selector == @selector(getDisplayIdentifiers))
4524 return @"getDisplayIdentifiers";
4525 else if (selector == @selector(getLocalizedNameForDisplayIdentifier:))
4526 return @"getLocalizedNameForDisplayIdentifier";
4527 else if (selector == @selector(getKernelNumber:))
4528 return @"getKernelNumber";
4529 else if (selector == @selector(getKernelString:))
4530 return @"getKernelString";
4531 else if (selector == @selector(getInstalledPackages))
4532 return @"getInstalledPackages";
4533 else if (selector == @selector(getIORegistryEntry::))
4534 return @"getIORegistryEntry";
4535 else if (selector == @selector(getLocaleIdentifier))
4536 return @"getLocaleIdentifier";
4537 else if (selector == @selector(getPreferredLanguages))
4538 return @"getPreferredLanguages";
4539 else if (selector == @selector(getPackageById:))
4540 return @"getPackageById";
4541 else if (selector == @selector(getMetadataKeys))
4542 return @"getMetadataKeys";
4543 else if (selector == @selector(getMetadataValue:))
4544 return @"getMetadataValue";
4545 else if (selector == @selector(getSessionValue:))
4546 return @"getSessionValue";
4547 else if (selector == @selector(installPackages:))
4548 return @"installPackages";
4549 else if (selector == @selector(isReachable:))
4550 return @"isReachable";
4551 else if (selector == @selector(localizedStringForKey:value:table:))
4553 else if (selector == @selector(popViewController:))
4554 return @"popViewController";
4555 else if (selector == @selector(refreshSources))
4556 return @"refreshSources";
4557 else if (selector == @selector(registerFrame:))
4558 return @"registerFrame";
4559 else if (selector == @selector(removeButton))
4560 return @"removeButton";
4561 else if (selector == @selector(saveConfig))
4562 return @"saveConfig";
4563 else if (selector == @selector(setMetadataValue::))
4564 return @"setMetadataValue";
4565 else if (selector == @selector(setSessionValue::))
4566 return @"setSessionValue";
4567 else if (selector == @selector(substitutePackageNames:))
4568 return @"substitutePackageNames";
4569 else if (selector == @selector(scrollToBottom:))
4570 return @"scrollToBottom";
4571 else if (selector == @selector(setAllowsNavigationAction:))
4572 return @"setAllowsNavigationAction";
4573 else if (selector == @selector(setBadgeValue:))
4574 return @"setBadgeValue";
4575 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4576 return @"setButtonImage";
4577 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4578 return @"setButtonTitle";
4579 else if (selector == @selector(setHidesBackButton:))
4580 return @"setHidesBackButton";
4581 else if (selector == @selector(setHidesNavigationBar:))
4582 return @"setHidesNavigationBar";
4583 else if (selector == @selector(setNavigationBarStyle:))
4584 return @"setNavigationBarStyle";
4585 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4586 return @"setNavigationBarTintColor";
4587 else if (selector == @selector(setPasteboardString:))
4588 return @"setPasteboardString";
4589 else if (selector == @selector(setPasteboardURL:))
4590 return @"setPasteboardURL";
4591 else if (selector == @selector(setScrollAlwaysBounceVertical:))
4592 return @"setScrollAlwaysBounceVertical";
4593 else if (selector == @selector(setScrollIndicatorStyle:))
4594 return @"setScrollIndicatorStyle";
4595 else if (selector == @selector(setToken:))
4597 else if (selector == @selector(setViewportWidth:))
4598 return @"setViewportWidth";
4599 else if (selector == @selector(statfs:))
4601 else if (selector == @selector(supports:))
4603 else if (selector == @selector(unload))
4609 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4610 return [self webScriptNameForSelector:selector] == nil;
4613 - (BOOL) supports:(NSString *)feature {
4614 return [feature isEqualToString:@"window.open"];
4618 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4621 - (void) setScrollAlwaysBounceVertical:(NSNumber *)value {
4622 [indirect_ performSelectorOnMainThread:@selector(setScrollAlwaysBounceVerticalNumber:) withObject:value waitUntilDone:NO];
4625 - (void) setScrollIndicatorStyle:(NSString *)style {
4626 [indirect_ performSelectorOnMainThread:@selector(setScrollIndicatorStyleWithName:) withObject:style waitUntilDone:NO];
4629 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4630 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4633 - (NSDictionary *) getApplicationInfo:(NSString *)display value:(NSString *)key {
4635 if (SBBundlePathForDisplayIdentifier(SBSSpringBoardServerPort(), [display UTF8String], path) != 0)
4636 return (id) [NSNull null];
4637 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:[[NSString stringWithUTF8String:path] stringByAppendingString:@"/Info.plist"]]);
4639 return (id) [NSNull null];
4640 return [info objectForKey:key];
4643 - (NSArray *) getDisplayIdentifiers {
4644 return SBSCopyApplicationDisplayIdentifiers(false, false);
4647 - (NSString *) getLocalizedNameForDisplayIdentifier:(NSString *)identifier {
4648 return [SBSCopyLocalizedApplicationNameForDisplayIdentifier(identifier) autorelease] ?: (id) [NSNull null];
4651 - (NSNumber *) getKernelNumber:(NSString *)name {
4652 const char *string([name UTF8String]);
4655 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4656 return (id) [NSNull null];
4658 if (size != sizeof(int))
4659 return (id) [NSNull null];
4662 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4663 return (id) [NSNull null];
4665 return [NSNumber numberWithInt:value];
4668 - (NSString *) getKernelString:(NSString *)name {
4669 const char *string([name UTF8String]);
4672 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4673 return (id) [NSNull null];
4675 char value[size + 1];
4676 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4677 return (id) [NSNull null];
4679 // XXX: just in case you request something ludicrous
4682 return [NSString stringWithCString:value];
4685 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4686 NSObject *value(CYIOGetValue([path UTF8String], entry));
4689 if ([value isKindOfClass:[NSData class]])
4690 value = CYHex((NSData *) value);
4695 - (NSArray *) getMetadataKeys {
4696 @synchronized (Values_) {
4697 return [Values_ allKeys];
4700 - (void) registerFrame:(DOMHTMLIFrameElement *)iframe {
4701 WebFrame *frame([iframe contentFrame]);
4702 [indirect_ registerFrame:frame];
4705 - (id) getMetadataValue:(NSString *)key {
4706 @synchronized (Values_) {
4707 return [Values_ objectForKey:key];
4710 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4711 @synchronized (Values_) {
4712 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4713 [Values_ removeObjectForKey:key];
4715 [Values_ setObject:value forKey:key];
4718 - (id) getSessionValue:(NSString *)key {
4719 @synchronized (SessionData_) {
4720 return [SessionData_ objectForKey:key];
4723 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4724 @synchronized (SessionData_) {
4725 if (value == (id) [WebUndefined undefined])
4726 [SessionData_ removeObjectForKey:key];
4728 [SessionData_ setObject:value forKey:key];
4731 - (void) addBridgedHost:(NSString *)host {
4732 @synchronized (HostConfig_) {
4733 [BridgedHosts_ addObject:host];
4736 - (void) addInsecureHost:(NSString *)host {
4737 @synchronized (HostConfig_) {
4738 [InsecureHosts_ addObject:host];
4741 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4742 @synchronized (HostConfig_) {
4743 if (scheme != (id) [WebUndefined undefined])
4744 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4746 [PipelinedHosts_ addObject:host];
4749 - (void) popViewController:(NSNumber *)value {
4750 if (value == (id) [WebUndefined undefined])
4751 value = [NSNumber numberWithBool:YES];
4752 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4755 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4756 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4758 for (NSString *section in sections)
4759 [array addObject:section];
4761 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4764 distribution, @"Distribution",
4766 nil] waitUntilDone:NO];
4769 - (BOOL) addTrivialSource:(NSString *)href {
4770 href = VerifySource(href);
4773 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4777 - (void) refreshSources {
4778 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4781 - (void) saveConfig {
4782 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4785 - (NSArray *) getAllSources {
4786 return [[Database sharedInstance] sources];
4789 - (NSArray *) getInstalledPackages {
4790 Database *database([Database sharedInstance]);
4791 @synchronized (database) {
4792 NSArray *packages([database packages]);
4793 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4794 for (Package *package in packages)
4795 if (![package uninstalled])
4796 [installed addObject:package];
4800 - (Package *) getPackageById:(NSString *)id {
4801 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4805 return (Package *) [NSNull null];
4808 - (NSString *) getLocaleIdentifier {
4809 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4812 - (NSArray *) getPreferredLanguages {
4816 - (NSArray *) statfs:(NSString *)path {
4819 if (path == nil || statfs([path UTF8String], &stat) == -1)
4822 return [NSArray arrayWithObjects:
4823 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4824 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4825 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4829 - (NSNumber *) du:(NSString *)path {
4830 NSNumber *value(nil);
4832 FILE *du(popen([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /usr/libexec/cydia/du -ks %@", ShellEscape(path)] UTF8String], "r"));
4835 while (fgets(line, sizeof(line), du) != NULL) {
4836 size_t length(strlen(line));
4837 while (length != 0 && line[length - 1] == '\n')
4838 line[--length] = '\0';
4839 if (char *tab = strchr(line, '\t')) {
4841 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4851 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4854 - (NSNumber *) isReachable:(NSString *)name {
4855 return [NSNumber numberWithBool:IsReachable([name UTF8String])];
4858 - (void) installPackages:(NSArray *)packages {
4859 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4862 - (NSString *) substitutePackageNames:(NSString *)message {
4863 auto database([Database sharedInstance]);
4865 // XXX: this check is less racy than you'd expect, but this entire concept is a little awkward
4866 if (![database hasPackages])
4869 NSMutableArray *words([[[message componentsSeparatedByString:@" "] mutableCopy] autorelease]);
4870 for (size_t i(0), e([words count]); i != e; ++i) {
4871 NSString *word([words objectAtIndex:i]);
4872 if (Package *package = [database packageWithName:word])
4873 [words replaceObjectAtIndex:i withObject:[package name]];
4876 return [words componentsJoinedByString:@" "];
4879 - (void) removeButton {
4880 [indirect_ removeButton];
4883 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4884 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4887 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4888 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4891 - (void) setBadgeValue:(id)value {
4892 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4895 - (void) setAllowsNavigationAction:(NSString *)value {
4896 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4899 - (void) setHidesBackButton:(NSString *)value {
4900 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4903 - (void) setHidesNavigationBar:(NSString *)value {
4904 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4907 - (void) setNavigationBarStyle:(NSString *)value {
4908 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4911 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4912 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4913 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4914 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4917 - (void) setPasteboardString:(NSString *)value {
4918 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4921 - (void) setPasteboardURL:(NSString *)value {
4922 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4925 - (void) setToken:(NSString *)token {
4926 // XXX: the website expects this :/
4929 - (void) scrollToBottom:(NSNumber *)animated {
4930 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4933 - (void) setViewportWidth:(float)width {
4934 [indirect_ setViewportWidthOnMainThread:width];
4937 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4938 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4939 unsigned count([arguments count]);
4941 for (unsigned i(0); i != count; ++i)
4942 values[i] = [arguments objectAtIndex:i];
4943 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4946 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4947 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4949 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4951 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4957 @interface NSURL (CydiaSecure)
4960 @implementation NSURL (CydiaSecure)
4962 - (bool) isCydiaSecure {
4963 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4966 @synchronized (HostConfig_) {
4967 if ([InsecureHosts_ containsObject:[self host]])
4976 /* Cydia Browser Controller {{{ */
4977 @implementation CydiaWebViewController
4979 - (NSURL *) navigationURL {
4980 if (NSURLRequest *request = self.request)
4981 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request URL] absoluteString]]];
4986 + (void) _initialize {
4987 [super _initialize];
4989 Diversions_ = [NSMutableSet setWithCapacity:0];
4992 + (void) addDiversion:(Diversion *)diversion {
4993 [Diversions_ addObject:diversion];
4996 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4997 [super webView:view didClearWindowObject:window forFrame:frame];
4998 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
5001 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia {
5002 WebDataSource *source([frame dataSource]);
5003 NSURLResponse *response([source response]);
5004 NSURL *url([response URL]);
5005 NSString *scheme([[url scheme] lowercaseString]);
5007 bool bridged(false);
5009 @synchronized (HostConfig_) {
5010 if ([scheme isEqualToString:@"file"])
5012 else if ([scheme isEqualToString:@"https"])
5013 if ([BridgedHosts_ containsObject:[url host]])
5018 [window setValue:cydia forKey:@"cydia"];
5021 - (void) _setupMail:(MFMailComposeViewController *)controller {
5022 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
5024 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
5025 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
5028 - (NSURL *) URLWithURL:(NSURL *)url {
5029 return [Diversion divertURL:url];
5032 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
5033 return [CydiaWebViewController requestWithHeaders:[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
5036 - (NSURLRequest *) webThreadWebView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
5037 return [CydiaWebViewController requestWithHeaders:[super webThreadWebView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
5040 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request {
5041 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
5043 NSURL *url([copy URL]);
5044 NSString *href([url absoluteString]);
5045 NSString *host([url host]);
5047 if ([href hasPrefix:@"https://cydia.saurik.com/TSS/"]) {
5048 if (NSString *agent = [copy valueForHTTPHeaderField:@"X-User-Agent"]) {
5049 [copy setValue:agent forHTTPHeaderField:@"User-Agent"];
5050 [copy setValue:nil forHTTPHeaderField:@"X-User-Agent"];
5053 [copy setValue:nil forHTTPHeaderField:@"Referer"];
5054 [copy setValue:nil forHTTPHeaderField:@"Origin"];
5056 [copy setURL:[NSURL URLWithString:[@"http://gs.apple.com/TSS/" stringByAppendingString:[href substringFromIndex:29]]]];
5060 if ([copy valueForHTTPHeaderField:@"X-Cydia-Cf"] == nil)
5061 [copy setValue:[NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber] forHTTPHeaderField:@"X-Cydia-Cf"];
5062 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
5063 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
5065 bool bridged; @synchronized (HostConfig_) {
5066 bridged = [BridgedHosts_ containsObject:host];
5069 if ([url isCydiaSecure] && bridged && UniqueID_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Id"] == nil)
5070 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
5075 - (void) setDelegate:(id)delegate {
5076 [super setDelegate:delegate];
5077 [cydia_ setDelegate:delegate];
5080 - (NSString *) applicationNameForUserAgent {
5085 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
5086 cydia_ = [[[CydiaObject alloc] initWithDelegate:self.indirect] autorelease];
5092 @interface AppCacheController : CydiaWebViewController {
5097 @implementation AppCacheController
5099 - (void) didReceiveMemoryWarning {
5100 // XXX: this doesn't work
5103 - (bool) retainsNetworkActivityIndicator {
5111 @interface NSObject (CydiaScript)
5112 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
5115 @implementation NSObject (CydiaScript)
5117 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5123 @implementation NSArray (CydiaScript)
5125 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5126 WebScriptObject *object([context evaluateWebScript:@"[]"]);
5127 for (size_t i(0), e([self count]); i != e; ++i)
5128 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
5134 @implementation NSDictionary (CydiaScript)
5136 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5137 WebScriptObject *object([context evaluateWebScript:@"({})"]);
5139 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
5146 /* Confirmation Controller {{{ */
5147 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
5148 if (!iterator.end())
5149 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
5150 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
5152 pkgCache::PkgIterator package(dep.TargetPkg());
5155 if (strcmp(package.Name(), "mobilesubstrate") == 0)
5162 @protocol ConfirmationControllerDelegate
5163 - (void) cancelAndClear:(bool)clear;
5164 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
5168 @interface ConfirmationController : CydiaWebViewController {
5169 _transient Database *database_;
5171 _H<UIAlertView> essential_;
5173 _H<NSDictionary> changes_;
5174 _H<NSMutableArray> issues_;
5175 _H<NSDictionary> sizes_;
5180 - (id) initWithDatabase:(Database *)database;
5184 @implementation ConfirmationController
5188 RestartSubstrate_ = true;
5189 [self.delegate confirmWithNavigationController:[self navigationController]];
5192 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
5193 NSString *context([alert context]);
5195 if ([context isEqualToString:@"remove"]) {
5196 if (button == [alert cancelButtonIndex])
5198 else if (button == [alert firstOtherButtonIndex]) {
5199 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
5202 [alert dismissWithClickedButtonIndex:-1 animated:YES];
5203 } else if ([context isEqualToString:@"unable"]) {
5204 [self dismissModalViewControllerAnimated:YES];
5205 [alert dismissWithClickedButtonIndex:-1 animated:YES];
5207 [super alertView:alert clickedButtonAtIndex:button];
5211 - (void) _doContinue {
5212 [self.delegate cancelAndClear:NO];
5213 [self dismissModalViewControllerAnimated:YES];
5216 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
5217 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
5221 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5222 [super webView:view didClearWindowObject:window forFrame:frame];
5224 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
5225 (id) changes_, @"changes",
5226 (id) issues_, @"issues",
5227 (id) sizes_, @"sizes",
5229 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
5232 - (id) initWithDatabase:(Database *)database {
5233 if ((self = [super init]) != nil) {
5234 database_ = database;
5236 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
5237 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
5238 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
5239 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
5240 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
5244 pkgCacheFile &cache([database_ cache]);
5245 NSArray *packages([database_ packages]);
5246 pkgDepCache::Policy *policy([database_ policy]);
5248 issues_ = [NSMutableArray arrayWithCapacity:4];
5250 for (Package *package in packages) {
5251 pkgCache::PkgIterator iterator([package iterator]);
5252 NSString *name([package id]);
5254 if ([package broken]) {
5255 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
5257 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5259 reasons, @"reasons",
5262 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
5266 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
5267 pkgCache::DepIterator start;
5268 pkgCache::DepIterator end;
5269 dep.GlobOr(start, end); // ++dep
5271 if (!cache->IsImportantDep(end))
5273 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
5276 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
5278 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5279 [NSString stringWithUTF8String:start.DepType()], @"relationship",
5280 clauses, @"clauses",
5284 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
5286 pkgCache::PkgIterator target(start.TargetPkg());
5287 if (target->ProvidesList != 0)
5288 reason = @"missing";
5290 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
5292 reason = @"installed";
5293 installed = [NSString stringWithUTF8String:ver.VerStr()];
5294 } else if (!cache[target].CandidateVerIter(cache).end())
5295 reason = @"uninstalled";
5296 else if (target->ProvidesList == 0)
5297 reason = @"uninstallable";
5299 reason = @"virtual";
5302 NSDictionary *version(start.TargetVer() == 0 ? (NSDictionary *) [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
5303 [NSString stringWithUTF8String:start.CompType()], @"operator",
5304 [NSString stringWithUTF8String:start.TargetVer()], @"value",
5307 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5308 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
5309 version, @"version",
5311 installed, @"installed",
5314 // yes, seriously. (wtf?)
5322 pkgDepCache::StateCache &state(cache[iterator]);
5324 static RegEx special_r("(firmware|gsc\\..*|cy\\+.*)");
5326 if (state.NewInstall())
5327 [installs addObject:name];
5328 // XXX: else if (state.Install())
5329 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
5330 [reinstalls addObject:name];
5331 // XXX: move before previous if
5332 else if (state.Upgrade())
5333 [upgrades addObject:name];
5334 else if (state.Downgrade())
5335 [downgrades addObject:name];
5336 else if (!state.Delete())
5337 // XXX: _assert(state.Keep());
5339 else if (special_r(name))
5340 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5341 [NSNull null], @"package",
5342 [NSArray arrayWithObjects:
5343 [NSDictionary dictionaryWithObjectsAndKeys:
5344 @"Conflicts", @"relationship",
5345 [NSArray arrayWithObjects:
5346 [NSDictionary dictionaryWithObjectsAndKeys:
5348 [NSNull null], @"version",
5349 @"installed", @"reason",
5356 if ([package essential])
5358 [removes addObject:name];
5361 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
5362 substrate_ |= DepSubstrate(iterator.CurrentVer());
5367 else if (Advanced_) {
5368 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
5370 essential_ = [[[UIAlertView alloc]
5371 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
5372 message:UCLocalize("REMOVING_ESSENTIALS_EX")
5374 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
5376 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
5380 [essential_ setContext:@"remove"];
5381 [essential_ setNumberOfRows:2];
5383 essential_ = [[[UIAlertView alloc]
5384 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
5385 message:UCLocalize("UNABLE_TO_COMPLY_EX")
5387 cancelButtonTitle:UCLocalize("OKAY")
5388 otherButtonTitles:nil
5391 [essential_ setContext:@"unable"];
5394 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5395 installs, @"installs",
5396 reinstalls, @"reinstalls",
5397 upgrades, @"upgrades",
5398 downgrades, @"downgrades",
5399 removes, @"removes",
5402 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5403 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
5404 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
5407 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
5411 - (UIBarButtonItem *) leftButton {
5412 return [[[UIBarButtonItem alloc]
5413 initWithTitle:UCLocalize("CANCEL")
5414 style:UIBarButtonItemStylePlain
5416 action:@selector(cancelButtonClicked)
5421 - (void) applyRightButton {
5422 if ([issues_ count] == 0 && ![self isLoading])
5423 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
5424 initWithTitle:UCLocalize("CONFIRM")
5425 style:UIBarButtonItemStyleDone
5427 action:@selector(confirmButtonClicked)
5430 [[self navigationItem] setRightBarButtonItem:nil];
5434 - (void) cancelButtonClicked {
5435 [self.delegate cancelAndClear:YES];
5436 [self dismissModalViewControllerAnimated:YES];
5440 - (void) confirmButtonClicked {
5441 if (essential_ != nil)
5451 /* Progress Data {{{ */
5452 @interface CydiaProgressData : NSObject {
5453 _transient id delegate_;
5462 _H<NSMutableArray> events_;
5463 _H<NSString> title_;
5465 _H<NSString> status_;
5466 _H<NSString> finish_;
5471 @implementation CydiaProgressData
5473 + (NSArray *) _attributeKeys {
5474 return [NSArray arrayWithObjects:
5486 - (NSArray *) attributeKeys {
5487 return [[self class] _attributeKeys];
5490 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5491 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5495 if ((self = [super init]) != nil) {
5496 events_ = [NSMutableArray arrayWithCapacity:32];
5504 - (void) setDelegate:(id)delegate {
5505 delegate_ = delegate;
5508 - (void) setPercent:(float)value {
5512 - (NSNumber *) percent {
5513 return [NSNumber numberWithFloat:percent_];
5516 - (void) setCurrent:(float)value {
5520 - (NSNumber *) current {
5521 return [NSNumber numberWithFloat:current_];
5524 - (void) setTotal:(float)value {
5528 - (NSNumber *) total {
5529 return [NSNumber numberWithFloat:total_];
5532 - (void) setSpeed:(float)value {
5536 - (NSNumber *) speed {
5537 return [NSNumber numberWithFloat:speed_];
5540 - (NSArray *) events {
5544 - (void) removeAllEvents {
5545 [events_ removeAllObjects];
5548 - (void) addEvent:(CydiaProgressEvent *)event {
5549 [events_ addObject:event];
5552 - (void) setTitle:(NSString *)text {
5556 - (NSString *) title {
5560 - (void) setFinish:(NSString *)text {
5564 - (NSString *) finish {
5565 return (id) finish_ ?: [NSNull null];
5568 - (void) setRunning:(bool)running {
5572 - (NSNumber *) running {
5573 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5578 /* Progress Controller {{{ */
5579 @interface ProgressController : CydiaWebViewController <
5582 _transient Database *database_;
5583 _H<CydiaProgressData, 1> progress_;
5587 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5589 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5591 - (void) setTitle:(NSString *)title;
5592 - (void) setCancellable:(bool)cancellable;
5596 @implementation ProgressController
5599 [database_ setProgressDelegate:nil];
5603 - (UIBarButtonItem *) leftButton {
5604 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5605 initWithTitle:UCLocalize("CANCEL")
5606 style:UIBarButtonItemStylePlain
5608 action:@selector(cancel)
5609 ] autorelease] : nil;
5612 - (void) updateCancel {
5613 [super applyLeftButton];
5616 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5617 if ((self = [super init]) != nil) {
5618 database_ = database;
5619 self.delegate = delegate;
5621 [database_ setProgressDelegate:self];
5623 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5624 [progress_ setDelegate:self];
5626 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5628 [self setPageColor:[UIColor blackColor]];
5630 [[self navigationItem] setHidesBackButton:YES];
5632 [self updateCancel];
5636 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5637 [super webView:view didClearWindowObject:window forFrame:frame];
5638 [window setValue:progress_ forKey:@"cydiaProgress"];
5641 - (void) updateProgress {
5642 [self dispatchEvent:@"CydiaProgressUpdate"];
5645 - (void) viewWillAppear:(BOOL)animated {
5646 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5647 [super viewWillAppear:animated];
5651 UpdateExternalStatus(0);
5654 [self.delegate saveState];
5658 [self.delegate returnToCydia];
5662 [self.delegate terminateWithSuccess];
5663 /*if ([self.delegate respondsToSelector:@selector(suspendWithAnimation:)])
5664 [self.delegate suspendWithAnimation:YES];
5666 [self.delegate suspend];*/
5678 UIProgressHUD *hud([self.delegate addProgressHUD]);
5679 [hud setText:UCLocalize("LOADING")];
5680 [self.delegate performSelector:@selector(reloadSpringBoard) withObject:nil afterDelay:0.5];
5686 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5687 SBReboot(SBSSpringBoardServerPort());
5689 reboot2(RB_AUTOBOOT);
5696 - (void) setTitle:(NSString *)title {
5697 [progress_ setTitle:title];
5698 [self updateProgress];
5701 - (UIBarButtonItem *) rightButton {
5702 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5703 initWithTitle:UCLocalize("CLOSE")
5704 style:UIBarButtonItemStylePlain
5706 action:@selector(close)
5710 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5711 UpdateExternalStatus(1);
5713 [progress_ setRunning:true];
5714 [self setTitle:title];
5715 // implicit updateProgress
5717 SHA1SumValue notifyconf; {
5719 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5722 MMap mmap(file, MMap::ReadOnly);
5724 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5725 notifyconf = sha1.Result();
5729 SHA1SumValue springlist; {
5731 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5734 MMap mmap(file, MMap::ReadOnly);
5736 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5737 springlist = sha1.Result();
5741 if (invocation != nil) {
5742 [invocation yieldToSelector:@selector(invoke)];
5743 [self setTitle:@"COMPLETE"];
5748 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5751 MMap mmap(file, MMap::ReadOnly);
5753 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5754 if (!(notifyconf == sha1.Result()))
5761 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5764 MMap mmap(file, MMap::ReadOnly);
5766 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5767 if (!(springlist == sha1.Result()))
5773 if (RestartSubstrate_)
5777 RestartSubstrate_ = false;
5780 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5781 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5782 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5783 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5784 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5787 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5789 [progress_ setRunning:false];
5790 [self updateProgress];
5792 [self applyRightButton];
5795 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5796 [progress_ addEvent:event];
5797 [self updateProgress];
5800 - (bool) isProgressCancelled {
5801 return cancel_ == 2;
5806 [self updateCancel];
5809 - (void) setCancellable:(bool)cancellable {
5810 unsigned cancel(cancel_);
5814 else if (cancel_ == 0)
5817 if (cancel != cancel_)
5818 [self updateCancel];
5821 - (void) setProgressCancellable:(NSNumber *)cancellable {
5822 [self setCancellable:[cancellable boolValue]];
5825 - (void) setProgressPercent:(NSNumber *)percent {
5826 [progress_ setPercent:[percent floatValue]];
5827 [self updateProgress];
5830 - (void) setProgressStatus:(NSDictionary *)status {
5831 if (status == nil) {
5832 [progress_ setCurrent:0];
5833 [progress_ setTotal:0];
5834 [progress_ setSpeed:0];
5836 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5838 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5839 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5840 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5843 [self updateProgress];
5849 /* Package Cell {{{ */
5850 @interface PackageCell : CyteTableViewCell <
5851 CyteTableViewCellDelegate
5855 _H<NSString> description_;
5857 _H<NSString> source_;
5859 _H<UIImage> placard_;
5863 - (PackageCell *) init;
5864 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5866 - (void) drawContentRect:(CGRect)rect;
5870 @implementation PackageCell
5872 - (PackageCell *) init {
5873 CGRect frame(CGRectMake(0, 0, 320, 74));
5874 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5875 UIView *content([self contentView]);
5876 CGRect bounds([content bounds]);
5878 self.content = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5879 [self.content setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5880 [content addSubview:self.content];
5882 [self.content setDelegate:self];
5883 [self.content setOpaque:YES];
5887 - (NSString *) accessibilityLabel {
5891 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5892 summarized_ = summary;
5902 [self.content setBackgroundColor:[UIColor whiteColor]];
5906 Source *source = [package source];
5908 icon_ = [package icon];
5910 if (NSString *name = [package name])
5911 name_ = [NSString stringWithString:name];
5913 if (NSString *description = [package shortDescription])
5914 description_ = [NSString stringWithString:description];
5916 commercial_ = [package isCommercial];
5918 NSString *label = nil;
5919 bool trusted = false;
5921 if (source != nil) {
5922 label = [source label];
5923 trusted = [source trusted];
5924 } else if ([[package id] isEqualToString:@"firmware"])
5925 label = UCLocalize("APPLE");
5927 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5929 NSString *from(label);
5931 NSString *section = [package simpleSection];
5932 if (section != nil && ![section isEqualToString:label]) {
5933 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5934 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5937 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5939 if (NSString *purpose = [package primaryPurpose])
5940 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5945 if (NSString *mode = [package mode]) {
5946 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5947 color = RemovingColor_;
5948 placard = @"removing";
5950 color = InstallingColor_;
5951 placard = @"installing";
5954 color = [UIColor whiteColor];
5956 if ([package installed] != nil)
5957 placard = @"installed";
5962 [self.content setBackgroundColor:color];
5965 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5968 [self setNeedsDisplay];
5969 [self.content setNeedsDisplay];
5972 - (void) drawSummaryContentRect:(CGRect)rect {
5973 bool highlighted(self.highlighted);
5974 float width([self bounds].size.width);
5978 rect.size = [(UIImage *) icon_ size];
5980 while (rect.size.width > 16 || rect.size.height > 16) {
5981 rect.size.width /= 2;
5982 rect.size.height /= 2;
5985 rect.origin.x = 19 - rect.size.width / 2;
5986 rect.origin.y = 19 - rect.size.height / 2;
5988 [icon_ drawInRect:Retina(rect)];
5991 if (badge_ != nil) {
5993 rect.size = [(UIImage *) badge_ size];
5995 rect.size.width /= 4;
5996 rect.size.height /= 4;
5998 rect.origin.x = 25 - rect.size.width / 2;
5999 rect.origin.y = 25 - rect.size.height / 2;
6001 [badge_ drawInRect:Retina(rect)];
6004 if (highlighted && kCFCoreFoundationVersionNumber < 800)
6008 UISetColor(commercial_ ? Purple_ : Black_);
6009 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
6011 if (placard_ != nil)
6012 [placard_ drawAtPoint:CGPointMake(width - 52, 11)];
6015 - (void) drawNormalContentRect:(CGRect)rect {
6016 bool highlighted(self.highlighted);
6017 float width([self bounds].size.width);
6021 rect.size = [(UIImage *) icon_ size];
6023 while (rect.size.width > 32 || rect.size.height > 32) {
6024 rect.size.width /= 2;
6025 rect.size.height /= 2;
6028 rect.origin.x = 25 - rect.size.width / 2;
6029 rect.origin.y = 25 - rect.size.height / 2;
6031 [icon_ drawInRect:Retina(rect)];
6034 if (badge_ != nil) {
6036 rect.size = [(UIImage *) badge_ size];
6038 rect.size.width /= 2;
6039 rect.size.height /= 2;
6041 rect.origin.x = 36 - rect.size.width / 2;
6042 rect.origin.y = 36 - rect.size.height / 2;
6044 [badge_ drawInRect:Retina(rect)];
6047 if (highlighted && kCFCoreFoundationVersionNumber < 800)
6051 UISetColor(commercial_ ? Purple_ : Black_);
6052 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
6053 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
6056 UISetColor(commercial_ ? Purplish_ : Gray_);
6057 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:NSLineBreakByTruncatingTail];
6059 if (placard_ != nil)
6060 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
6063 - (void) drawContentRect:(CGRect)rect {
6065 [self drawSummaryContentRect:rect];
6067 [self drawNormalContentRect:rect];
6072 /* Section Cell {{{ */
6073 @interface SectionCell : CyteTableViewCell <
6074 CyteTableViewCellDelegate
6076 _H<NSString> basic_;
6077 _H<NSString> section_;
6079 _H<NSString> count_;
6081 _H<UISwitch> switch_;
6085 - (void) setSection:(Section *)section editing:(BOOL)editing;
6089 @implementation SectionCell
6091 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
6092 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
6093 icon_ = [UIImage imageNamed:@"folder.png"];
6094 // XXX: this initial frame is wrong, but is fixed later
6095 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
6096 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
6098 UIView *content([self contentView]);
6099 CGRect bounds([content bounds]);
6101 self.content = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
6102 [self.content setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6103 [content addSubview:self.content];
6104 [self.content setBackgroundColor:[UIColor whiteColor]];
6106 [self.content setDelegate:self];
6110 - (void) onSwitch:(id)sender {
6111 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
6112 if (metadata == nil) {
6113 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
6114 [Sections_ setObject:metadata forKey:basic_];
6117 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
6120 - (void) setSection:(Section *)section editing:(BOOL)editing {
6121 if (editing != editing_) {
6123 [switch_ removeFromSuperview];
6125 [self addSubview:switch_];
6134 if (section == nil) {
6135 name_ = UCLocalize("ALL_PACKAGES");
6138 basic_ = [section name];
6139 section_ = [section localized];
6141 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
6142 count_ = [NSString stringWithFormat:@"%zd", [section count]];
6145 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
6148 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
6149 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
6151 [self.content setNeedsDisplay];
6154 - (void) setFrame:(CGRect)frame {
6155 [super setFrame:frame];
6157 CGRect rect([switch_ frame]);
6158 [switch_ setFrame:CGRectMake(frame.size.width - rect.size.width - 9, 9, rect.size.width, rect.size.height)];
6161 - (NSString *) accessibilityLabel {
6165 - (void) drawContentRect:(CGRect)rect {
6166 bool highlighted(self.highlighted && !editing_);
6168 [icon_ drawInRect:CGRectMake(7, 7, 32, 32)];
6170 if (highlighted && kCFCoreFoundationVersionNumber < 800)
6173 float width(rect.size.width);
6175 width -= 9 + [switch_ frame].size.width;
6179 [name_ drawAtPoint:CGPointMake(48, 12) forWidth:(width - 58) withFont:Font18_ lineBreakMode:NSLineBreakByTruncatingTail];
6181 CGSize size = [count_ sizeWithFont:Font14_];
6183 UISetColor(Folder_);
6185 [count_ drawAtPoint:CGPointMake(Retina(10 + (30 - size.width) / 2), 18) withFont:Font12Bold_];
6191 /* File Table {{{ */
6192 @interface FileTable : CyteViewController <
6193 UITableViewDataSource,
6196 _transient Database *database_;
6197 _H<Package> package_;
6199 _H<NSMutableArray> files_;
6200 _H<UITableView, 2> list_;
6203 - (id) initWithDatabase:(Database *)database;
6204 - (void) setPackage:(Package *)package;
6208 @implementation FileTable
6210 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6211 return files_ == nil ? 0 : [files_ count];
6214 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6218 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6219 static NSString *reuseIdentifier = @"Cell";
6221 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6223 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6224 [cell setFont:[UIFont systemFontOfSize:16]];
6226 [cell setText:[files_ objectAtIndex:indexPath.row]];
6227 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
6232 - (NSURL *) navigationURL {
6233 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
6237 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
6238 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6239 [list_ setRowHeight:24.0f];
6240 [(UITableView *) list_ setDataSource:self];
6241 [list_ setDelegate:self];
6242 [self setView:list_];
6245 - (void) viewDidLoad {
6246 [super viewDidLoad];
6248 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
6251 - (void) releaseSubviews {
6257 [super releaseSubviews];
6260 - (id) initWithDatabase:(Database *)database {
6261 if ((self = [super init]) != nil) {
6262 database_ = database;
6266 - (void) setPackage:(Package *)package {
6270 files_ = [NSMutableArray arrayWithCapacity:32];
6272 if (package != nil) {
6274 name_ = [package id];
6276 if (NSArray *files = [package files])
6277 [files_ addObjectsFromArray:files];
6279 if ([files_ count] != 0) {
6280 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
6281 [files_ removeObjectAtIndex:0];
6282 [files_ sortUsingSelector:@selector(compareByPath:)];
6284 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
6285 [stack addObject:@"/"];
6287 for (int i(0), e([files_ count]); i != e; ++i) {
6288 NSString *file = [files_ objectAtIndex:i];
6289 while (![file hasPrefix:[stack lastObject]])
6290 [stack removeLastObject];
6291 NSString *directory = [stack lastObject];
6292 [stack addObject:[file stringByAppendingString:@"/"]];
6293 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
6294 int(([stack count] - 2) * 3), "",
6295 [file substringFromIndex:[directory length]]
6304 - (void) reloadData {
6307 [self setPackage:[database_ packageWithName:name_]];
6312 /* Package Controller {{{ */
6313 @interface CYPackageController : CydiaWebViewController <
6314 UIActionSheetDelegate
6316 _transient Database *database_;
6317 _H<Package> package_;
6320 std::vector<std::pair<_H<NSString>, _H<NSString>>> buttons_;
6321 _H<UIActionSheet> sheet_;
6322 _H<UIBarButtonItem> button_;
6323 _H<NSArray> versions_;
6326 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer;
6330 @implementation CYPackageController
6332 - (NSURL *) navigationURL {
6333 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
6336 - (void) _clickButtonWithPackage:(Package *)package {
6337 [self.delegate installPackage:package];
6340 - (void) _clickButtonWithName:(NSString *)name {
6341 if ([name isEqualToString:@"CLEAR"])
6342 return [self.delegate clearPackage:package_];
6343 else if ([name isEqualToString:@"REMOVE"])
6344 return [self.delegate removePackage:package_];
6345 else if ([name isEqualToString:@"DOWNGRADE"]) {
6346 sheet_ = [[[UIActionSheet alloc]
6349 cancelButtonTitle:nil
6350 destructiveButtonTitle:nil
6351 otherButtonTitles:nil
6354 for (Package *version in (id) versions_)
6355 [sheet_ addButtonWithTitle:[version latest]];
6356 [sheet_ setContext:@"version"];
6358 [self.delegate showActionSheet:sheet_ fromItem:[[self navigationItem] rightBarButtonItem]];
6362 else if ([name isEqualToString:@"INSTALL"]);
6363 else if ([name isEqualToString:@"REINSTALL"]);
6364 else if ([name isEqualToString:@"UPGRADE"]);
6365 else _assert(false);
6367 [self.delegate installPackage:package_];
6370 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
6371 NSString *context([sheet context]);
6372 if (sheet_ == sheet)
6375 if ([context isEqualToString:@"modify"]) {
6376 if (button != [sheet cancelButtonIndex]) {
6378 [self performSelector:@selector(_clickButtonWithName:) withObject:buttons_[button].first afterDelay:0];
6380 [self _clickButtonWithName:buttons_[button].first];
6383 [sheet dismissWithClickedButtonIndex:button animated:YES];
6384 } else if ([context isEqualToString:@"version"]) {
6385 if (button != [sheet cancelButtonIndex]) {
6386 Package *version([versions_ objectAtIndex:button]);
6388 [self performSelector:@selector(_clickButtonWithPackage:) withObject:version afterDelay:0];
6390 [self _clickButtonWithPackage:version];
6393 [sheet dismissWithClickedButtonIndex:button animated:YES];
6397 - (bool) _allowJavaScriptPanel {
6402 - (void) _customButtonClicked {
6403 if (commercial_ && [package_ uninstalled])
6404 return [self reloadURLWithCache:NO];
6406 size_t count(buttons_.size());
6411 [self _clickButtonWithName:buttons_[0].first];
6413 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
6414 for (const auto &button : buttons_)
6415 [buttons addObject:button.second];
6417 sheet_ = [[[UIActionSheet alloc]
6420 cancelButtonTitle:nil
6421 destructiveButtonTitle:nil
6422 otherButtonTitles:nil
6425 for (NSString *button in buttons)
6426 [sheet_ addButtonWithTitle:button];
6427 [sheet_ setContext:@"modify"];
6429 [self.delegate showActionSheet:sheet_ fromItem:[[self navigationItem] rightBarButtonItem]];
6433 - (void) applyLoadingTitle {
6434 // Don't show "Loading" as the title. Ever.
6437 - (UIBarButtonItem *) rightButton {
6442 - (void) setPageColor:(UIColor *)color {
6443 return [super setPageColor:nil];
6446 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer {
6447 if ((self = [super init]) != nil) {
6448 database_ = database;
6449 name_ = name == nil ? @"" : [NSString stringWithString:name];
6450 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]] withReferrer:referrer];
6454 - (void) reloadData {
6457 [sheet_ dismissWithClickedButtonIndex:[sheet_ cancelButtonIndex] animated:YES];
6460 package_ = [database_ packageWithName:name_];
6461 versions_ = [package_ downgrades];
6465 if (package_ != nil) {
6466 [(Package *) package_ parse];
6468 commercial_ = [package_ isCommercial];
6470 if ([package_ mode] != nil)
6471 buttons_.push_back(std::make_pair(@"CLEAR", UCLocalize("CLEAR")));
6472 if ([package_ source] == nil);
6473 else if ([package_ upgradableAndEssential:NO])
6474 buttons_.push_back(std::make_pair(@"UPGRADE", UCLocalize("UPGRADE")));
6475 else if ([package_ uninstalled])
6476 buttons_.push_back(std::make_pair(@"INSTALL", UCLocalize("INSTALL")));
6478 buttons_.push_back(std::make_pair(@"REINSTALL", UCLocalize("REINSTALL")));
6479 if (![package_ uninstalled])
6480 buttons_.push_back(std::make_pair(@"REMOVE", UCLocalize("REMOVE")));
6481 if ([versions_ count] != 0)
6482 buttons_.push_back(std::make_pair(@"DOWNGRADE", UCLocalize("DOWNGRADE")));
6486 switch (buttons_.size()) {
6487 case 0: title = nil; break;
6488 case 1: title = buttons_[0].second; break;
6489 default: title = UCLocalize("MODIFY"); break;
6492 button_ = [[[UIBarButtonItem alloc]
6494 style:UIBarButtonItemStylePlain
6496 action:@selector(customButtonClicked)
6500 - (bool) isLoading {
6501 return commercial_ ? [super isLoading] : false;
6507 /* Package List Controller {{{ */
6508 @interface PackageListController : CyteViewController <
6509 UITableViewDataSource,
6512 _transient Database *database_;
6514 _H<NSArray> packages_;
6515 _H<NSArray> sections_;
6516 _H<UITableView, 2> list_;
6518 _H<NSArray> thumbs_;
6519 std::vector<NSInteger> offset_;
6521 _H<NSString> title_;
6522 unsigned reloading_;
6525 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6526 - (void) resetCursor;
6529 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages;
6533 @implementation PackageListController
6535 - (NSURL *) referrerURL {
6536 return [self navigationURL];
6539 - (bool) isSummarized {
6543 - (bool) showsSections {
6547 - (void) deselectWithAnimation:(BOOL)animated {
6548 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6551 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6552 CGRect base = [[self view] bounds];
6553 base.size.height -= bounds.size.height;
6554 base.origin = [list_ frame].origin;
6556 [UIView beginAnimations:nil context:NULL];
6557 [UIView setAnimationBeginsFromCurrentState:YES];
6558 [UIView setAnimationCurve:curve];
6559 [UIView setAnimationDuration:duration];
6560 [list_ setFrame:base];
6561 [UIView commitAnimations];
6564 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6565 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6568 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6569 [self resizeForKeyboardBounds:bounds duration:0];
6572 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6573 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6574 *curve = UIViewAnimationCurveEaseInOut;
6576 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6578 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6581 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6584 - (void) keyboardWillShow:(NSNotification *)notification {
6587 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6588 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6590 NSTimeInterval duration;
6591 UIViewAnimationCurve curve;
6592 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6594 CGRect kbframe = CGRectMake(Retina(center.x - bounds.size.width / 2), Retina(center.y - bounds.size.height / 2), bounds.size.width, bounds.size.height);
6595 UIViewController *base = self;
6596 while ([base parentOrPresentingViewController] != nil)
6597 base = [base parentOrPresentingViewController];
6598 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6599 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6601 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6602 intersection.size.height += CYStatusBarHeight();
6604 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6607 - (void) keyboardWillHide:(NSNotification *)notification {
6608 NSTimeInterval duration;
6609 UIViewAnimationCurve curve;
6610 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6612 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6615 - (void) viewWillAppear:(BOOL)animated {
6616 [super viewWillAppear:animated];
6618 [self resizeForKeyboardBounds:CGRectZero];
6619 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6620 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6623 - (void) viewWillDisappear:(BOOL)animated {
6624 [super viewWillDisappear:animated];
6626 [self resizeForKeyboardBounds:CGRectZero];
6627 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6628 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6631 - (void) viewDidAppear:(BOOL)animated {
6632 [super viewDidAppear:animated];
6633 [self deselectWithAnimation:animated];
6636 - (void) didSelectPackage:(Package *)package {
6637 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[[self referrerURL] absoluteString]] autorelease]);
6638 [view setDelegate:self.delegate];
6639 [[self navigationController] pushViewController:view animated:YES];
6642 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6643 NSInteger count([sections_ count]);
6644 return count == 0 ? 1 : count;
6647 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6648 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6650 return [[sections_ objectAtIndex:section] name];
6653 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6654 if ([sections_ count] == 0)
6656 return [[sections_ objectAtIndex:section] count];
6659 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6660 @synchronized (database_) {
6661 if ([database_ era] != era_)
6664 Section *section([sections_ objectAtIndex:[path section]]);
6665 NSInteger row([path row]);
6666 Package *package([packages_ objectAtIndex:([section row] + row)]);
6667 return [[package retain] autorelease];
6670 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6671 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6673 cell = [[[PackageCell alloc] init] autorelease];
6675 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6676 [cell setPackage:package asSummary:[self isSummarized]];
6680 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6681 Package *package([self packageAtIndexPath:path]);
6682 package = [database_ packageWithName:[package id]];
6683 [self didSelectPackage:package];
6686 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6690 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6691 return offset_[index];
6694 - (void) updateHeight {
6695 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6698 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6699 if ((self = [super init]) != nil) {
6700 database_ = database;
6701 title_ = [title copy];
6702 [[self navigationItem] setTitle:title_];
6707 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
6708 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
6709 [self setView:view];
6711 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6712 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6713 [view addSubview:list_];
6715 // XXX: is 20 the most optimal number here?
6716 [list_ setSectionIndexMinimumDisplayRowCount:20];
6718 [(UITableView *) list_ setDataSource:self];
6719 [list_ setDelegate:self];
6721 [self updateHeight];
6724 - (void) releaseSubviews {
6733 [super releaseSubviews];
6736 - (bool) shouldYield {
6740 - (bool) shouldBlock {
6744 - (NSMutableArray *) _reloadPackages {
6745 @synchronized (database_) {
6746 era_ = [database_ era];
6747 NSArray *packages([database_ packages]);
6749 return [NSMutableArray arrayWithArray:packages];
6752 - (void) _reloadData {
6753 if (reloading_ != 0) {
6758 NSMutableArray *packages;
6761 if ([self shouldYield]) {
6765 if (![self shouldBlock])
6768 hud = [self.delegate addProgressHUD];
6769 [hud setText:UCLocalize("LOADING")];
6773 packages = [self yieldToSelector:@selector(_reloadPackages)];
6776 [self.delegate removeProgressHUD:hud];
6777 } while (reloading_ == 2);
6779 packages = [self _reloadPackages];
6782 @synchronized (database_) {
6783 if (era_ != [database_ era])
6790 packages_ = packages;
6792 if ([self showsSections])
6793 sections_ = [self sectionsForPackages:packages];
6795 Section *section([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6796 [section setCount:[packages_ count]];
6797 sections_ = [NSArray arrayWithObject:section];
6800 [self updateHeight];
6802 _profile(PackageTable$reloadData$List)
6803 [(UITableView *) list_ setDataSource:self];
6811 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
6812 Section *prefix([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6813 size_t end([packages count]);
6815 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
6816 Section *section(prefix);
6818 thumbs_ = CollationThumbs_;
6819 offset_ = CollationOffset_;
6822 size_t offsets([CollationStarts_ count]);
6824 NSString *start([CollationStarts_ objectAtIndex:offset]);
6825 size_t length([start length]);
6827 for (size_t index(0); index != end; ++index) {
6829 Package *package([packages objectAtIndex:index]);
6830 NSString *name(PackageName(package, @selector(cyname)));
6832 //while ([start compare:name options:NSNumericSearch range:NSMakeRange(0, length) locale:CollationLocale_] != NSOrderedDescending) {
6833 while (StringNameCompare(start, name, length) != kCFCompareGreaterThan) {
6834 NSString *title([CollationTitles_ objectAtIndex:offset]);
6835 section = [[[Section alloc] initWithName:title row:index localize:NO] autorelease];
6836 [sections addObject:section];
6838 start = ++offset == offsets ? nil : [CollationStarts_ objectAtIndex:offset];
6841 length = [start length];
6845 [section addToCount];
6848 for (; offset != offsets; ++offset) {
6849 NSString *title([CollationTitles_ objectAtIndex:offset]);
6850 Section *section([[[Section alloc] initWithName:title row:end localize:NO] autorelease]);
6851 [sections addObject:section];
6854 if ([prefix count] != 0) {
6855 Section *suffix([sections lastObject]);
6856 [prefix setName:[suffix name]];
6857 [suffix setName:nil];
6858 [sections insertObject:prefix atIndex:(offsets - 1)];
6864 - (void) reloadData {
6867 if ([self shouldYield])
6868 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6873 - (void) resetCursor {
6874 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6877 - (void) clearData {
6878 [self updateHeight];
6880 [list_ setDataSource:nil];
6888 /* Filtered Package List Controller {{{ */
6889 typedef Function<bool, Package *> PackageFilter;
6890 typedef Function<void, NSMutableArray *> PackageSorter;
6891 @interface FilteredPackageListController : PackageListController {
6892 PackageFilter filter_;
6893 PackageSorter sorter_;
6896 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter;
6898 - (void) setFilter:(PackageFilter)filter;
6899 - (void) setSorter:(PackageSorter)sorter;
6903 @implementation FilteredPackageListController
6905 - (void) setFilter:(PackageFilter)filter {
6906 @synchronized (self) {
6910 - (void) setSorter:(PackageSorter)sorter {
6911 @synchronized (self) {
6915 - (NSMutableArray *) _reloadPackages {
6916 @synchronized (database_) {
6917 era_ = [database_ era];
6919 NSArray *packages([database_ packages]);
6920 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6922 PackageFilter filter;
6923 PackageSorter sorter;
6925 @synchronized (self) {
6930 _profile(PackageTable$reloadData$Filter)
6931 for (Package *package in packages)
6932 if (filter(package))
6933 [filtered addObject:package];
6941 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter {
6942 if ((self = [super initWithDatabase:database title:title]) != nil) {
6943 [self setFilter:filter];
6950 /* Home Controller {{{ */
6951 @interface HomeController : CydiaWebViewController {
6952 CFRunLoopRef runloop_;
6953 SCNetworkReachabilityRef reachability_;
6958 @implementation HomeController
6960 static void HomeControllerReachabilityCallback(SCNetworkReachabilityRef reachability, SCNetworkReachabilityFlags flags, void *info) {
6961 [(HomeController *) info dispatchEvent:@"CydiaReachabilityCallback"];
6965 if ((self = [super init]) != nil) {
6966 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6969 reachability_ = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "cydia.saurik.com");
6970 if (reachability_ != NULL) {
6971 SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
6972 SCNetworkReachabilitySetCallback(reachability_, HomeControllerReachabilityCallback, &context);
6974 CFRunLoopRef runloop(CFRunLoopGetCurrent());
6975 if (SCNetworkReachabilityScheduleWithRunLoop(reachability_, runloop, kCFRunLoopDefaultMode))
6982 if (reachability_ != NULL && runloop_ != NULL)
6983 SCNetworkReachabilityUnscheduleFromRunLoop(reachability_, runloop_, kCFRunLoopDefaultMode);
6987 - (NSURL *) navigationURL {
6988 return [NSURL URLWithString:@"cydia://home"];
6991 - (void) aboutButtonClicked {
6992 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6994 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6995 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6996 [alert setCancelButtonIndex:0];
6999 @"Copyright \u00a9 2008-2015\n"
7002 "Jay Freeman (saurik)\n"
7003 "saurik@saurik.com\n"
7004 "http://www.saurik.com/"
7010 - (UIBarButtonItem *) leftButton {
7011 return [[[UIBarButtonItem alloc]
7012 initWithTitle:UCLocalize("ABOUT")
7013 style:UIBarButtonItemStylePlain
7015 action:@selector(aboutButtonClicked)
7022 /* Cydia Navigation Controller Interface {{{ */
7023 @interface UINavigationController (Cydia)
7025 - (NSArray *) navigationURLCollection;
7026 - (void) unloadData;
7031 /* Cydia Tab Bar Controller {{{ */
7032 @interface CydiaTabBarController : CyteTabBarController <
7033 UITabBarControllerDelegate,
7036 _transient Database *database_;
7038 _H<UIActivityIndicatorView> indicator_;
7041 // XXX: ok, "updatedelegate_"?...
7042 _transient NSObject<CydiaDelegate> *updatedelegate_;
7045 - (NSArray *) navigationURLCollection;
7046 - (void) beginUpdate;
7051 @implementation CydiaTabBarController
7053 - (NSArray *) navigationURLCollection {
7054 NSMutableArray *items([NSMutableArray array]);
7056 // XXX: Should this deal with transient view controllers?
7057 for (id navigation in [self viewControllers]) {
7058 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
7060 [items addObject:stack];
7066 - (id) initWithDatabase:(Database *)database {
7067 if ((self = [super init]) != nil) {
7068 database_ = database;
7069 [self setDelegate:self];
7071 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteTiny] autorelease];
7072 [indicator_ setOrigin:CGPointMake(kCFCoreFoundationVersionNumber >= 800 ? 2 : 4, 2)];
7074 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7078 - (void) beginUpdate {
7082 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
7083 UITabBarItem *item([controller tabBarItem]);
7085 [item setBadgeValue:@""];
7086 UIView *badge(MSHookIvar<UIView *>([item view], "_badge"));
7088 [indicator_ startAnimating];
7089 [badge addSubview:indicator_];
7091 [updatedelegate_ retainNetworkActivityIndicator];
7095 detachNewThreadSelector:@selector(performUpdate)
7101 - (void) performUpdate {
7102 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
7104 SourceStatus status(self, database_);
7105 [database_ updateWithStatus:status];
7108 performSelectorOnMainThread:@selector(completeUpdate)
7116 - (void) stopUpdateWithSelector:(SEL)selector {
7118 [updatedelegate_ releaseNetworkActivityIndicator];
7120 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
7121 [[controller tabBarItem] setBadgeValue:nil];
7123 [indicator_ removeFromSuperview];
7124 [indicator_ stopAnimating];
7126 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
7129 - (void) completeUpdate {
7132 [self stopUpdateWithSelector:@selector(reloadData)];
7135 - (void) cancelUpdate {
7136 [self stopUpdateWithSelector:@selector(updateDataAndLoad)];
7139 - (void) cancelPressed {
7140 [self cancelUpdate];
7147 - (bool) isSourceCancelled {
7151 - (void) startSourceFetch:(NSString *)uri {
7154 - (void) stopSourceFetch:(NSString *)uri {
7157 - (void) setUpdateDelegate:(id)delegate {
7158 updatedelegate_ = delegate;
7164 /* Cydia Navigation Controller Implementation {{{ */
7165 @implementation UINavigationController (Cydia)
7167 - (NSArray *) navigationURLCollection {
7168 NSMutableArray *stack([NSMutableArray array]);
7170 for (CyteViewController *controller in [self viewControllers]) {
7171 NSString *url = [[controller navigationURL] absoluteString];
7173 [stack addObject:url];
7179 - (void) reloadData {
7182 UIViewController *visible([self visibleViewController]);
7184 [visible reloadData];
7186 // on the iPad, this view controller is ALSO visible. :(
7188 if (UIViewController *modal = [self modalViewController])
7189 if ([modal modalPresentationStyle] == UIModalPresentationFormSheet)
7190 if (UIViewController *top = [self topViewController])
7195 - (void) unloadData {
7196 for (CyteViewController *page in [self viewControllers])
7205 /* Cydia:// Protocol {{{ */
7206 @interface CydiaURLProtocol : NSURLProtocol {
7211 @implementation CydiaURLProtocol
7213 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7214 NSURL *url([request URL]);
7218 NSString *scheme([[url scheme] lowercaseString]);
7219 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7221 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7227 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7231 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7232 id<NSURLProtocolClient> client([self client]);
7234 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7236 NSData *data(UIImagePNGRepresentation(icon));
7238 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7239 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7240 [client URLProtocol:self didLoadData:data];
7241 [client URLProtocolDidFinishLoading:self];
7245 - (void) startLoading {
7246 id<NSURLProtocolClient> client([self client]);
7247 NSURLRequest *request([self request]);
7249 NSURL *url([request URL]);
7250 NSString *href([url absoluteString]);
7251 NSString *scheme([[url scheme] lowercaseString]);
7255 if ([scheme isEqualToString:@"cydia"])
7256 path = [href substringFromIndex:8];
7257 else if ([scheme isEqualToString:@"about"])
7258 path = [href substringFromIndex:12];
7259 else _assert(false);
7261 NSRange slash([path rangeOfString:@"/"]);
7264 if (slash.location == NSNotFound) {
7268 command = [path substringToIndex:slash.location];
7269 path = [path substringFromIndex:(slash.location + 1)];
7272 Database *database([Database sharedInstance]);
7275 else if ([command isEqualToString:@"application-icon"]) {
7278 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7282 if (icon == nil && $SBSCopyIconImagePNGDataForDisplayIdentifier != NULL) {
7283 NSData *data([$SBSCopyIconImagePNGDataForDisplayIdentifier(path) autorelease]);
7284 icon = [UIImage imageWithData:data];
7288 if (NSString *file = SBSCopyIconImagePathForDisplayIdentifier(path))
7289 icon = [UIImage imageAtPath:file];
7292 icon = [UIImage imageNamed:@"unknown.png"];
7294 [self _returnPNGWithImage:icon forRequest:request];
7295 } else if ([command isEqualToString:@"package-icon"]) {
7298 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7299 Package *package([database packageWithName:path]);
7303 UIImage *icon([package icon]);
7304 [self _returnPNGWithImage:icon forRequest:request];
7305 } else if ([command isEqualToString:@"uikit-image"]) {
7308 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7309 UIImage *icon(_UIImageWithName(path));
7310 [self _returnPNGWithImage:icon forRequest:request];
7311 } else if ([command isEqualToString:@"section-icon"]) {
7314 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7315 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7317 icon = [UIImage imageNamed:@"unknown.png"];
7318 [self _returnPNGWithImage:icon forRequest:request];
7320 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7324 - (void) stopLoading {
7330 /* Section Controller {{{ */
7331 @interface SectionController : FilteredPackageListController {
7333 _H<NSString> section_;
7336 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section;
7340 @implementation SectionController
7342 - (NSURL *) referrerURL {
7343 NSString *name(section_);
7344 name = name ?: @"*";
7345 NSString *key(key_);
7347 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sections/%@/%@", UI_, [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7350 - (NSURL *) navigationURL {
7351 NSString *name(section_);
7352 name = name ?: @"*";
7353 NSString *key(key_);
7355 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@/%@", [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7358 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section {
7361 title = UCLocalize("ALL_PACKAGES");
7362 else if (![section isEqual:@""])
7363 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(section) value:nil table:@"Sections"];
7365 title = UCLocalize("NO_SECTION");
7367 if ((self = [super initWithDatabase:database title:title]) != nil) {
7368 key_ = [source key];
7373 - (void) reloadData {
7374 Source *source([database_ sourceWithKey:key_]);
7375 _H<NSString> name(section_);
7377 [self setFilter:[=](Package *package) {
7378 NSString *section([package section]);
7382 section == nil && [name length] == 0 ||
7383 [name isEqualToString:section]
7386 [package source] == source
7387 ) && [package visible];
7395 /* Sections Controller {{{ */
7396 @interface SectionsController : CyteViewController <
7397 UITableViewDataSource,
7400 _transient Database *database_;
7402 _H<NSMutableArray> sections_;
7403 _H<NSMutableArray> filtered_;
7404 _H<UITableView, 2> list_;
7407 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7408 - (void) editButtonClicked;
7412 @implementation SectionsController
7414 - (NSURL *) navigationURL {
7415 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
7418 - (Source *) source {
7421 return [database_ sourceWithKey:key_];
7424 - (void) updateNavigationItem {
7425 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7426 if ([sections_ count] == 0) {
7427 [[self navigationItem] setRightBarButtonItem:nil];
7429 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7430 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7432 action:@selector(editButtonClicked)
7433 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7437 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7438 [super setEditing:editing animated:animated];
7443 [self.delegate updateData];
7445 [self updateNavigationItem];
7448 - (void) viewDidAppear:(BOOL)animated {
7449 [super viewDidAppear:animated];
7450 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7453 - (void) viewWillDisappear:(BOOL)animated {
7454 [super viewWillDisappear:animated];
7455 [self setEditing:NO];
7458 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7459 Section *section = nil;
7460 int index = [indexPath row];
7461 if (![self isEditing]) {
7464 section = [filtered_ objectAtIndex:index];
7466 section = [sections_ objectAtIndex:index];
7471 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7472 if ([self isEditing])
7473 return [sections_ count];
7475 return [filtered_ count] + 1;
7478 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7482 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7483 static NSString *reuseIdentifier = @"SectionCell";
7485 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7487 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7489 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7494 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7495 if ([self isEditing])
7498 Section *section = [self sectionAtIndexPath:indexPath];
7500 SectionController *controller = [[[SectionController alloc]
7501 initWithDatabase:database_
7502 source:[self source]
7503 section:[section name]
7505 [controller setDelegate:self.delegate];
7507 [[self navigationController] pushViewController:controller animated:YES];
7511 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
7512 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7513 [list_ setRowHeight:46];
7514 [(UITableView *) list_ setDataSource:self];
7515 [list_ setDelegate:self];
7516 [self setView:list_];
7519 - (void) viewDidLoad {
7520 [super viewDidLoad];
7522 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7525 - (void) releaseSubviews {
7531 [super releaseSubviews];
7534 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7535 if ((self = [super init]) != nil) {
7536 database_ = database;
7537 key_ = [source key];
7541 - (void) reloadData {
7544 NSArray *packages = [database_ packages];
7546 sections_ = [NSMutableArray arrayWithCapacity:16];
7547 filtered_ = [NSMutableArray arrayWithCapacity:16];
7549 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7551 Source *source([self source]);
7554 for (Package *package in packages) {
7555 if (source != nil && [package source] != source)
7558 NSString *name([package section]);
7559 NSString *key(name == nil ? @"" : name);
7563 _profile(SectionsView$reloadData$Section)
7564 section = [sections objectForKey:key];
7565 if (section == nil) {
7566 _profile(SectionsView$reloadData$Section$Allocate)
7567 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7568 [sections setObject:section forKey:key];
7573 [section addToCount];
7575 _profile(SectionsView$reloadData$Filter)
7576 if (![package visible])
7584 [sections_ addObjectsFromArray:[sections allValues]];
7586 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7588 for (Section *section in (id) sections_) {
7589 size_t count([section row]);
7593 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7594 [section setCount:count];
7595 [filtered_ addObject:section];
7598 [self updateNavigationItem];
7603 - (void) editButtonClicked {
7604 [self setEditing:![self isEditing] animated:YES];
7610 /* Changes Controller {{{ */
7611 @interface ChangesController : FilteredPackageListController {
7615 - (id) initWithDatabase:(Database *)database;
7619 @implementation ChangesController
7621 - (NSURL *) referrerURL {
7622 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/changes/", UI_]];
7625 - (NSURL *) navigationURL {
7626 return [NSURL URLWithString:@"cydia://changes"];
7629 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7630 @synchronized (database_) {
7631 if ([database_ era] != era_)
7634 NSUInteger sectionIndex([path section]);
7635 if (sectionIndex >= [sections_ count])
7637 Section *section([sections_ objectAtIndex:sectionIndex]);
7638 NSInteger row([path row]);
7639 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7642 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7643 NSString *context([alert context]);
7645 if ([context isEqualToString:@"norefresh"])
7646 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7649 - (void) setLeftBarButtonItem {
7650 if ([self.delegate updating])
7651 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7652 initWithTitle:UCLocalize("CANCEL")
7653 style:UIBarButtonItemStyleDone
7655 action:@selector(cancelButtonClicked)
7656 ] autorelease] animated:YES];
7658 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7659 initWithTitle:UCLocalize("REFRESH")
7660 style:UIBarButtonItemStylePlain
7662 action:@selector(refreshButtonClicked)
7663 ] autorelease] animated:YES];
7666 - (void) refreshButtonClicked {
7667 if ([self.delegate requestUpdate])
7668 [self setLeftBarButtonItem];
7671 - (void) cancelButtonClicked {
7672 [self.delegate cancelUpdate];
7675 - (void) upgradeButtonClicked {
7676 [self.delegate distUpgrade];
7677 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7680 - (bool) shouldYield {
7684 - (bool) shouldBlock {
7688 - (void) useFilter {
7689 @synchronized (self) {
7690 [self setFilter:[](Package *package) {
7691 return [package upgradableAndEssential:YES] || [package visible];
7694 [self setSorter:[](NSMutableArray *packages) {
7695 [packages radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7699 - (id) initWithDatabase:(Database *)database {
7700 if ((self = [super initWithDatabase:database title:UCLocalize("CHANGES")]) != nil) {
7705 - (void) viewDidLoad {
7706 [super viewDidLoad];
7707 [self setLeftBarButtonItem];
7710 - (void) viewWillAppear:(BOOL)animated {
7711 [super viewWillAppear:animated];
7712 [self setLeftBarButtonItem];
7715 - (void) reloadData {
7716 [self setLeftBarButtonItem];
7720 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
7721 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
7723 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7724 Section *ignored = nil;
7725 Section *section = nil;
7729 bool unseens = false;
7731 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7733 for (size_t offset = 0, count = [packages count]; offset != count; ++offset) {
7734 Package *package = [packages objectAtIndex:offset];
7736 BOOL uae = [package upgradableAndEssential:YES];
7740 time_t seen([package seen]);
7742 if (section == nil || last != seen) {
7746 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7749 _profile(ChangesController$reloadData$Allocate)
7750 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7751 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7752 [sections addObject:section];
7756 [section addToCount];
7757 } else if ([package ignored]) {
7758 if (ignored == nil) {
7759 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7761 [ignored addToCount];
7764 [upgradable addToCount];
7769 CFRelease(formatter);
7772 Section *last = [sections lastObject];
7773 size_t count = [last count];
7774 [packages removeObjectsInRange:NSMakeRange([packages count] - count, count)];
7775 [sections removeLastObject];
7778 if ([ignored count] != 0)
7779 [sections insertObject:ignored atIndex:0];
7781 [sections insertObject:upgradable atIndex:0];
7785 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7786 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7787 style:UIBarButtonItemStylePlain
7789 action:@selector(upgradeButtonClicked)
7790 ] autorelease]) animated:YES];
7797 /* Search Controller {{{ */
7798 @interface SearchController : FilteredPackageListController <
7801 _H<UISearchBar, 1> search_;
7806 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7807 - (void) reloadData;
7811 @implementation SearchController
7813 - (NSURL *) referrerURL {
7814 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/search?q=%@", UI_, [([search_ text] ?: @"") stringByAddingPercentEscapesIncludingReserved]]];
7817 - (NSURL *) navigationURL {
7818 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7819 return [NSURL URLWithString:@"cydia://search"];
7821 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [[search_ text] stringByAddingPercentEscapesIncludingReserved]]];
7824 - (NSArray *) termsForQuery:(NSString *)query {
7825 NSMutableArray *terms([NSMutableArray arrayWithCapacity:2]);
7826 for (NSString *component in [query componentsSeparatedByString:@" "])
7827 if ([component length] != 0)
7828 [terms addObject:component];
7833 - (void) useSearch {
7834 _H<NSArray> query([self termsForQuery:[search_ text]]);
7837 @synchronized (self) {
7838 [self setFilter:[=](Package *package) {
7839 if (![package unfiltered])
7841 if (![package matches:query])
7846 [self setSorter:[](NSMutableArray *packages) {
7847 [packages radixSortUsingSelector:@selector(rank)];
7855 - (void) usePrefix:(NSString *)prefix {
7856 _H<NSString> query(prefix);
7859 @synchronized (self) {
7860 [self setFilter:[=](Package *package) {
7861 if ([query length] == 0)
7863 if (![package unfiltered])
7865 if ([[package name] compare:query options:MatchCompareOptions_ range:NSMakeRange(0, [query length])] != NSOrderedSame)
7870 [self setSorter:nullptr];
7876 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7878 [self usePrefix:[search_ text]];
7881 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7882 [search_ resignFirstResponder];
7886 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7887 [search_ setText:@""];
7888 [self searchBarButtonClicked:searchBar];
7891 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7892 [self searchBarButtonClicked:searchBar];
7895 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7896 [self usePrefix:text];
7899 - (bool) shouldYield {
7903 - (bool) shouldBlock {
7907 - (bool) isSummarized {
7911 - (bool) showsSections {
7915 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7916 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH")])) {
7917 search_ = [[[UISearchBar alloc] init] autorelease];
7918 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7919 [search_ setDelegate:self];
7921 UITextField *textField;
7922 if ([search_ respondsToSelector:@selector(searchField)])
7923 textField = [search_ searchField];
7925 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7927 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7928 [textField setEnablesReturnKeyAutomatically:NO];
7929 [[self navigationItem] setTitleView:textField];
7932 [search_ setText:query];
7937 - (void) viewDidAppear:(BOOL)animated {
7938 [super viewDidAppear:animated];
7940 if (!searchloaded_) {
7941 searchloaded_ = YES;
7942 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7943 [search_ layoutSubviews];
7946 if ([self isSummarized])
7947 [search_ becomeFirstResponder];
7950 - (void) reloadData {
7955 - (void) didSelectPackage:(Package *)package {
7956 [search_ resignFirstResponder];
7957 [super didSelectPackage:package];
7962 /* Package Settings Controller {{{ */
7963 @interface PackageSettingsController : CyteViewController <
7964 UITableViewDataSource,
7967 _transient Database *database_;
7969 _H<Package> package_;
7970 _H<UITableView, 2> table_;
7971 _H<UISwitch> subscribedSwitch_;
7972 _H<UISwitch> ignoredSwitch_;
7973 _H<UITableViewCell> subscribedCell_;
7974 _H<UITableViewCell> ignoredCell_;
7977 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7981 @implementation PackageSettingsController
7983 - (NSURL *) navigationURL {
7984 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
7987 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7988 if (package_ == nil)
7991 if ([package_ installed] == nil)
7997 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7998 if (package_ == nil)
8001 // both sections contain just one item right now.
8005 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8009 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8011 return UCLocalize("SHOW_ALL_CHANGES_EX");
8013 return UCLocalize("IGNORE_UPGRADES_EX");
8016 - (void) onSubscribed:(id)control {
8017 bool value([control isOn]);
8018 if (package_ == nil)
8020 if ([package_ setSubscribed:value])
8021 [self.delegate updateData];
8024 - (void) _updateIgnored {
8025 const char *package([name_ UTF8String]);
8026 bool on([ignoredSwitch_ isOn]);
8028 FILE *dpkg(popen("/usr/libexec/cydia/cydo --set-selections", "w"));
8029 fwrite(package, strlen(package), 1, dpkg);
8032 fwrite(" hold\n", 6, 1, dpkg);
8034 fwrite(" install\n", 9, 1, dpkg);
8039 - (void) onIgnored:(id)control {
8040 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
8041 [invocation setTarget:self];
8042 [invocation setSelector:@selector(_updateIgnored)];
8044 [self.delegate reloadDataWithInvocation:invocation];
8047 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8048 if (package_ == nil)
8051 switch ([indexPath section]) {
8052 case 0: return subscribedCell_;
8053 case 1: return ignoredCell_;
8062 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8063 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8064 [self setView:view];
8066 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
8067 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8068 [(UITableView *) table_ setDataSource:self];
8069 [table_ setDelegate:self];
8070 [view addSubview:table_];
8072 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
8073 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
8074 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
8076 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
8077 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
8078 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
8080 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
8081 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
8082 [subscribedCell_ setAccessoryView:subscribedSwitch_];
8083 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
8085 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
8086 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
8087 [ignoredCell_ setAccessoryView:ignoredSwitch_];
8088 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
8091 - (void) viewDidLoad {
8092 [super viewDidLoad];
8094 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
8097 - (void) releaseSubviews {
8099 subscribedCell_ = nil;
8101 ignoredSwitch_ = nil;
8102 subscribedSwitch_ = nil;
8104 [super releaseSubviews];
8107 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
8108 if ((self = [super init]) != nil) {
8109 database_ = database;
8114 - (void) reloadData {
8117 package_ = [database_ packageWithName:name_];
8119 if (package_ != nil) {
8120 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
8121 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
8122 } // XXX: what now, G?
8124 [table_ reloadData];
8130 /* Installed Controller {{{ */
8131 @interface InstalledController : FilteredPackageListController {
8135 - (id) initWithDatabase:(Database *)database;
8136 - (void) queueStatusDidChange;
8140 @implementation InstalledController
8142 - (NSURL *) referrerURL {
8143 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/installed/", UI_]];
8146 - (NSURL *) navigationURL {
8147 return [NSURL URLWithString:@"cydia://installed"];
8150 - (void) useRecent {
8153 @synchronized (self) {
8154 [self setFilter:[](Package *package) {
8155 return ![package uninstalled] && package->role_ < 7;
8158 [self setSorter:[](NSMutableArray *packages) {
8159 [packages radixSortUsingSelector:@selector(recent)];
8163 - (void) useFilter:(UISegmentedControl *)segmented {
8164 NSInteger selected([segmented selectedSegmentIndex]);
8166 return [self useRecent];
8167 bool simple(selected == 0);
8170 @synchronized (self) {
8171 [self setFilter:[=](Package *package) {
8172 return ![package uninstalled] && package->role_ <= (simple ? 1 : 3);
8175 [self setSorter:nullptr];
8178 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
8180 return [super sectionsForPackages:packages];
8182 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterLongStyle, kCFDateFormatterNoStyle));
8184 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
8185 Section *section(nil);
8188 for (size_t offset(0), count([packages count]); offset != count; ++offset) {
8189 Package *package([packages objectAtIndex:offset]);
8191 time_t upgraded([package upgraded]);
8192 if (upgraded < 1168364520)
8195 upgraded -= upgraded % (60 * 60 * 24);
8197 if (section == nil || upgraded != last) {
8202 continue; // XXX: name = UCLocalize("...");
8204 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:upgraded]);
8208 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
8209 [sections addObject:section];
8212 [section addToCount];
8215 CFRelease(formatter);
8219 - (id) initWithDatabase:(Database *)database {
8220 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED")]) != nil) {
8221 UISegmentedControl *segmented([[[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:UCLocalize("USER"), UCLocalize("EXPERT"), UCLocalize("RECENT"), nil]] autorelease]);
8222 [segmented setSelectedSegmentIndex:0];
8223 [segmented setSegmentedControlStyle:UISegmentedControlStyleBar];
8224 [[self navigationItem] setTitleView:segmented];
8226 [segmented addTarget:self action:@selector(modeChanged:) forEvents:UIControlEventValueChanged];
8227 [self useFilter:segmented];
8229 [self queueStatusDidChange];
8234 - (void) queueButtonClicked {
8235 [self.delegate queue];
8239 - (void) queueStatusDidChange {
8242 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8243 initWithTitle:UCLocalize("QUEUE")
8244 style:UIBarButtonItemStyleDone
8246 action:@selector(queueButtonClicked)
8249 [[self navigationItem] setRightBarButtonItem:nil];
8254 - (void) modeChanged:(UISegmentedControl *)segmented {
8255 [self useFilter:segmented];
8262 /* Source Cell {{{ */
8263 @interface SourceCell : CyteTableViewCell <
8264 CyteTableViewCellDelegate,
8267 _H<Source, 1> source_;
8270 _H<NSString> origin_;
8271 _H<NSString> label_;
8272 _H<UIActivityIndicatorView> indicator_;
8275 - (void) setSource:(Source *)source;
8276 - (void) setFetch:(NSNumber *)fetch;
8280 @implementation SourceCell
8282 - (void) _setImage:(NSArray *)data {
8283 if ([url_ isEqual:[data objectAtIndex:0]]) {
8284 icon_ = [data objectAtIndex:1];
8285 [self.content setNeedsDisplay];
8289 - (void) _setSource:(NSURL *) url {
8290 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8292 if (NSData *data = [NSURLConnection
8293 sendSynchronousRequest:[NSURLRequest
8295 cachePolicy:NSURLRequestUseProtocolCachePolicy
8299 returningResponse:NULL
8302 if (UIImage *image = [UIImage imageWithData:data])
8303 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
8308 - (void) setSource:(Source *)source {
8310 [source_ setDelegate:self];
8312 [self setFetch:[NSNumber numberWithBool:[source_ fetch]]];
8314 icon_ = [UIImage imageNamed:@"unknown.png"];
8316 origin_ = [source name];
8317 label_ = [source rooturi];
8319 [self.content setNeedsDisplay];
8321 url_ = [source iconURL];
8322 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
8325 - (void) setAllSource {
8327 [indicator_ stopAnimating];
8329 icon_ = [UIImage imageNamed:@"folder.png"];
8330 origin_ = UCLocalize("ALL_SOURCES");
8331 label_ = UCLocalize("ALL_SOURCES_EX");
8332 [self.content setNeedsDisplay];
8335 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8336 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8337 UIView *content([self contentView]);
8338 CGRect bounds([content bounds]);
8340 self.content = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8341 [self.content setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8342 [self.content setBackgroundColor:[UIColor whiteColor]];
8343 [content addSubview:self.content];
8345 [self.content setDelegate:self];
8346 [self.content setOpaque:YES];
8348 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGraySmall] autorelease];
8349 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin];// | UIViewAutoresizingFlexibleBottomMargin];
8350 [content addSubview:indicator_];
8352 [[self.content layer] setContentsGravity:kCAGravityTopLeft];
8356 - (void) layoutSubviews {
8357 [super layoutSubviews];
8359 UIView *content([self contentView]);
8360 CGRect bounds([content bounds]);
8362 CGRect frame([indicator_ frame]);
8363 frame.origin.x = bounds.size.width - frame.size.width;
8364 frame.origin.y = Retina((bounds.size.height - frame.size.height) / 2);
8366 if (kCFCoreFoundationVersionNumber < 800)
8367 frame.origin.x -= 8;
8368 [indicator_ setFrame:frame];
8371 - (NSString *) accessibilityLabel {
8375 - (void) drawContentRect:(CGRect)rect {
8376 bool highlighted(self.highlighted);
8377 float width(rect.size.width);
8381 rect.size = [(UIImage *) icon_ size];
8383 while (rect.size.width > 32 || rect.size.height > 32) {
8384 rect.size.width /= 2;
8385 rect.size.height /= 2;
8388 rect.origin.x = 26 - rect.size.width / 2;
8389 rect.origin.y = 26 - rect.size.height / 2;
8391 [icon_ drawInRect:Retina(rect)];
8394 if (highlighted && kCFCoreFoundationVersionNumber < 800)
8399 [origin_ drawAtPoint:CGPointMake(52, 8) forWidth:(width - 49) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
8403 [label_ drawAtPoint:CGPointMake(52, 29) forWidth:(width - 49) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
8406 - (void) setFetch:(NSNumber *)fetch {
8407 if ([fetch boolValue])
8408 [indicator_ startAnimating];
8410 [indicator_ stopAnimating];
8415 /* Sources Controller {{{ */
8416 @interface SourcesController : CyteViewController <
8417 UITableViewDataSource,
8420 _transient Database *database_;
8423 _H<UITableView, 2> list_;
8424 _H<NSMutableArray> sources_;
8428 _H<UIProgressHUD> hud_;
8431 NSURLConnection *trivial_bz2_;
8432 NSURLConnection *trivial_gz_;
8437 - (id) initWithDatabase:(Database *)database;
8438 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated;
8442 @implementation SourcesController
8444 - (void) _releaseConnection:(NSURLConnection *)connection {
8445 if (connection != nil) {
8446 [connection cancel];
8447 //[connection setDelegate:nil];
8448 [connection release];
8453 [self _releaseConnection:trivial_gz_];
8454 [self _releaseConnection:trivial_bz2_];
8459 - (NSURL *) navigationURL {
8460 return [NSURL URLWithString:@"cydia://sources"];
8463 - (void) viewDidAppear:(BOOL)animated {
8464 [super viewDidAppear:animated];
8465 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8468 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8472 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8474 return UCLocalize("INDIVIDUAL_SOURCES");
8478 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8481 case 1: return [sources_ count];
8486 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8487 @synchronized (database_) {
8488 if ([database_ era] != era_)
8490 if ([indexPath section] != 1)
8492 NSUInteger index([indexPath row]);
8493 if (index >= [sources_ count])
8495 return [sources_ objectAtIndex:index];
8498 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8499 static NSString *cellIdentifier = @"SourceCell";
8501 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8502 if (cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8503 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8505 Source *source([self sourceAtIndexPath:indexPath]);
8507 [cell setAllSource];
8509 [cell setSource:source];
8514 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8515 SectionsController *controller([[[SectionsController alloc]
8516 initWithDatabase:database_
8517 source:[self sourceAtIndexPath:indexPath]
8520 [controller setDelegate:self.delegate];
8521 [[self navigationController] pushViewController:controller animated:YES];
8524 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8525 if ([indexPath section] != 1)
8527 Source *source = [self sourceAtIndexPath:indexPath];
8528 return [source record] != nil;
8531 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8532 _assert([indexPath section] == 1);
8533 if (editingStyle == UITableViewCellEditingStyleDelete) {
8534 Source *source = [self sourceAtIndexPath:indexPath];
8535 if (source == nil) return;
8537 [Sources_ removeObjectForKey:[source key]];
8539 [self.delegate syncData];
8543 - (void) tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath {
8544 [self updateButtonsForEditingStatusAnimated:YES];
8548 [self.delegate addTrivialSource:href_];
8551 [self.delegate syncData];
8554 - (NSString *) getWarning {
8555 NSString *href(href_);
8556 NSRange colon([href rangeOfString:@"://"]);
8557 if (colon.location != NSNotFound)
8558 href = [href substringFromIndex:(colon.location + 3)];
8559 href = [href stringByAddingPercentEscapes];
8560 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8562 NSURL *url([NSURL URLWithString:href]);
8564 NSStringEncoding encoding;
8565 NSError *error(nil);
8567 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8568 return [warning length] == 0 ? nil : warning;
8572 - (void) _endConnection:(NSURLConnection *)connection {
8573 // XXX: the memory management in this method is horribly awkward
8575 NSURLConnection **field = NULL;
8576 if (connection == trivial_bz2_)
8577 field = &trivial_bz2_;
8578 else if (connection == trivial_gz_)
8579 field = &trivial_gz_;
8580 _assert(field != NULL);
8581 [connection release];
8585 trivial_bz2_ == nil &&
8588 NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil);
8590 [self.delegate releaseNetworkActivityIndicator];
8592 [self.delegate removeProgressHUD:hud_];
8596 if (warning != nil) {
8597 UIAlertView *alert = [[[UIAlertView alloc]
8598 initWithTitle:UCLocalize("SOURCE_WARNING")
8601 cancelButtonTitle:UCLocalize("CANCEL")
8603 UCLocalize("ADD_ANYWAY"),
8607 [alert setContext:@"warning"];
8608 [alert setNumberOfRows:1];
8611 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
8617 } else if (error_ != nil) {
8618 UIAlertView *alert = [[[UIAlertView alloc]
8619 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8620 message:[error_ localizedDescription]
8622 cancelButtonTitle:UCLocalize("OK")
8623 otherButtonTitles:nil
8626 [alert setContext:@"urlerror"];
8631 UIAlertView *alert = [[[UIAlertView alloc]
8632 initWithTitle:UCLocalize("NOT_REPOSITORY")
8633 message:UCLocalize("NOT_REPOSITORY_EX")
8635 cancelButtonTitle:UCLocalize("OK")
8636 otherButtonTitles:nil
8639 [alert setContext:@"trivial"];
8649 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8650 switch ([response statusCode]) {
8656 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8657 lprintf("connection:\"%s\" didFailWithError:\"%s\"\n", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8659 [self _endConnection:connection];
8662 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8663 [self _endConnection:connection];
8666 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8667 NSURL *url([NSURL URLWithString:href]);
8669 NSMutableURLRequest *request = [NSMutableURLRequest
8671 cachePolicy:NSURLRequestUseProtocolCachePolicy
8675 [request setHTTPMethod:method];
8677 if (Machine_ != NULL)
8678 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8680 if (UniqueID_ != nil)
8681 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8683 if ([url isCydiaSecure]) {
8684 if (UniqueID_ != nil)
8685 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
8688 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8691 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8692 NSString *context([alert context]);
8694 if ([context isEqualToString:@"source"]) {
8697 NSString *href = [[alert textField] text];
8698 href = VerifySource(href);
8703 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8704 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8708 // XXX: this is stupid
8709 hud_ = [self.delegate addProgressHUD];
8710 [hud_ setText:UCLocalize("VERIFYING_URL")];
8711 [self.delegate retainNetworkActivityIndicator];
8720 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8721 } else if ([context isEqualToString:@"trivial"])
8722 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8723 else if ([context isEqualToString:@"urlerror"])
8724 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8725 else if ([context isEqualToString:@"warning"]) {
8728 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
8737 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8741 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated {
8742 BOOL editing([list_ isEditing]);
8745 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8746 initWithTitle:UCLocalize("ADD")
8747 style:UIBarButtonItemStylePlain
8749 action:@selector(addButtonClicked)
8750 ] autorelease] animated:animated];
8751 else if ([self.delegate updating])
8752 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8753 initWithTitle:UCLocalize("CANCEL")
8754 style:UIBarButtonItemStyleDone
8756 action:@selector(cancelButtonClicked)
8757 ] autorelease] animated:animated];
8759 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8760 initWithTitle:UCLocalize("REFRESH")
8761 style:UIBarButtonItemStylePlain
8763 action:@selector(refreshButtonClicked)
8764 ] autorelease] animated:animated];
8766 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8767 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8768 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8770 action:@selector(editButtonClicked)
8771 ] autorelease] animated:animated];
8775 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease];
8776 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8777 [list_ setRowHeight:53];
8778 [(UITableView *) list_ setDataSource:self];
8779 [list_ setDelegate:self];
8780 [self setView:list_];
8783 - (void) viewDidLoad {
8784 [super viewDidLoad];
8786 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8787 [self updateButtonsForEditingStatusAnimated:NO];
8790 - (void) viewWillAppear:(BOOL)animated {
8791 [super viewWillAppear:animated];
8793 [list_ setEditing:NO];
8794 [self updateButtonsForEditingStatusAnimated:NO];
8797 - (void) releaseSubviews {
8802 [super releaseSubviews];
8805 - (id) initWithDatabase:(Database *)database {
8806 if ((self = [super init]) != nil) {
8807 database_ = database;
8811 - (void) reloadData {
8813 [self updateButtonsForEditingStatusAnimated:YES];
8815 @synchronized (database_) {
8816 era_ = [database_ era];
8818 sources_ = [NSMutableArray arrayWithCapacity:16];
8819 [sources_ addObjectsFromArray:[database_ sources]];
8821 [sources_ sortUsingSelector:@selector(compareByName:)];
8824 int count([sources_ count]);
8826 for (int i = 0; i != count; i++) {
8827 if ([[sources_ objectAtIndex:i] record] == nil)
8835 - (void) showAddSourcePrompt {
8836 UIAlertView *alert = [[[UIAlertView alloc]
8837 initWithTitle:UCLocalize("ENTER_APT_URL")
8840 cancelButtonTitle:UCLocalize("CANCEL")
8842 UCLocalize("ADD_SOURCE"),
8846 [alert setContext:@"source"];
8848 [alert setNumberOfRows:1];
8849 [alert addTextFieldWithValue:@"http://" label:@""];
8851 NSObject<UITextInputTraits> *traits = [[alert textField] textInputTraits];
8852 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8853 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8854 [traits setKeyboardType:UIKeyboardTypeURL];
8855 // XXX: UIReturnKeyDone
8856 [traits setReturnKeyType:UIReturnKeyNext];
8861 - (void) addButtonClicked {
8862 [self showAddSourcePrompt];
8865 - (void) refreshButtonClicked {
8866 if ([self.delegate requestUpdate])
8867 [self updateButtonsForEditingStatusAnimated:YES];
8870 - (void) cancelButtonClicked {
8871 [self.delegate cancelUpdate];
8874 - (void) editButtonClicked {
8875 [list_ setEditing:![list_ isEditing] animated:YES];
8876 [self updateButtonsForEditingStatusAnimated:YES];
8882 /* Stash Controller {{{ */
8883 @interface StashController : CyteViewController {
8884 _H<UIActivityIndicatorView> spinner_;
8885 _H<UILabel> status_;
8886 _H<UILabel> caption_;
8891 @implementation StashController
8894 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8895 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8896 [self setView:view];
8898 [view setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8900 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8901 CGRect spinrect = [spinner_ frame];
8902 spinrect.origin.x = Retina([[self view] frame].size.width / 2 - spinrect.size.width / 2);
8903 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8904 [spinner_ setFrame:spinrect];
8905 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8906 [view addSubview:spinner_];
8907 [spinner_ startAnimating];
8910 captrect.size.width = [[self view] frame].size.width;
8911 captrect.size.height = 40.0f;
8912 captrect.origin.x = 0;
8913 captrect.origin.y = Retina([[self view] frame].size.height / 2 - captrect.size.height * 2);
8914 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8915 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8916 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8917 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8918 [caption_ setTextColor:[UIColor whiteColor]];
8919 [caption_ setBackgroundColor:[UIColor clearColor]];
8920 [caption_ setShadowColor:[UIColor blackColor]];
8921 [caption_ setTextAlignment:NSTextAlignmentCenter];
8922 [view addSubview:caption_];
8925 statusrect.size.width = [[self view] frame].size.width;
8926 statusrect.size.height = 30.0f;
8927 statusrect.origin.x = 0;
8928 statusrect.origin.y = Retina([[self view] frame].size.height / 2 - statusrect.size.height);
8929 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8930 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8931 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8932 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8933 [status_ setTextColor:[UIColor whiteColor]];
8934 [status_ setBackgroundColor:[UIColor clearColor]];
8935 [status_ setShadowColor:[UIColor blackColor]];
8936 [status_ setTextAlignment:NSTextAlignmentCenter];
8937 [view addSubview:status_];
8940 - (void) releaseSubviews {
8945 [super releaseSubviews];
8951 @interface CYURLCache : SDURLCache {
8956 @implementation CYURLCache
8958 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8961 else if ([event isEqualToString:@"no-cache"])
8963 else if ([event isEqualToString:@"store"])
8965 else if ([event isEqualToString:@"invalid"])
8967 else if ([event isEqualToString:@"memory"])
8969 else if ([event isEqualToString:@"disk"])
8971 else if ([event isEqualToString:@"miss"])
8974 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8978 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
8979 if (NSURLResponse *response = [cached response])
8980 if (NSString *mime = [response MIMEType])
8981 if ([mime isEqualToString:@"text/cache-manifest"]) {
8982 NSURL *url([response URL]);
8985 NSLog(@"###: %@", [url absoluteString]);
8988 @synchronized (HostConfig_) {
8989 [CachedURLs_ addObject:url];
8993 [super storeCachedResponse:cached forRequest:request];
8996 - (void) createDiskCachePath {
8997 [super createDiskCachePath];
9002 @interface Cydia : UIApplication <
9003 ConfirmationControllerDelegate,
9007 _H<UIWindow> window_;
9008 _H<CydiaTabBarController> tabbar_;
9009 _H<CyteTabBarController> emulated_;
9010 _H<AppCacheController> appcache_;
9012 _H<NSMutableArray> essential_;
9013 _H<NSMutableArray> broken_;
9015 Database *database_;
9017 _H<NSURL> starturl_;
9022 _H<StashController> stash_;
9031 @implementation Cydia
9033 - (void) lockSuspend {
9034 if (locked_++ == 0) {
9035 if ($SBSSetInterceptsMenuButtonForever != NULL)
9036 (*$SBSSetInterceptsMenuButtonForever)(true);
9038 [self setIdleTimerDisabled:YES];
9042 - (void) unlockSuspend {
9043 if (--locked_ == 0) {
9044 [self setIdleTimerDisabled:NO];
9046 if ($SBSSetInterceptsMenuButtonForever != NULL)
9047 (*$SBSSetInterceptsMenuButtonForever)(false);
9051 - (void) beginUpdate {
9052 [tabbar_ beginUpdate];
9055 - (void) cancelUpdate {
9056 [tabbar_ cancelUpdate];
9059 - (bool) requestUpdate {
9060 if (IsReachable("cydia.saurik.com")) {
9064 UIAlertView *alert = [[[UIAlertView alloc]
9065 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("REFRESH")]
9066 message:@"Host Unreachable" // XXX: Localize
9068 cancelButtonTitle:UCLocalize("OK")
9069 otherButtonTitles:nil
9072 [alert setContext:@"norefresh"];
9080 return [tabbar_ updating];
9084 if ([broken_ count] != 0) {
9085 int count = [broken_ count];
9087 UIAlertView *alert = [[[UIAlertView alloc]
9088 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
9089 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
9091 cancelButtonTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("FORCIBLY_CLEAR"), UCLocalize("UNSAFE")]
9093 UCLocalize("TEMPORARY_IGNORE"),
9097 [alert setContext:@"fixhalf"];
9098 [alert setNumberOfRows:2];
9100 } else if (!Ignored_ && [essential_ count] != 0) {
9101 int count = [essential_ count];
9103 UIAlertView *alert = [[[UIAlertView alloc]
9104 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
9105 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
9107 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
9109 UCLocalize("UPGRADE_ESSENTIAL"),
9110 UCLocalize("COMPLETE_UPGRADE"),
9114 [alert setContext:@"upgrade"];
9119 - (void) returnToCydia {
9123 - (void) reloadSpringBoard {
9124 if (kCFCoreFoundationVersionNumber >= 700) // XXX: iOS 6.x
9125 system("/usr/libexec/cydia/cydo /bin/launchctl stop com.apple.backboardd");
9127 system("/usr/libexec/cydia/cydo /bin/launchctl stop com.apple.SpringBoard");
9129 system("/usr/bin/killall backboardd SpringBoard");
9132 - (void) _saveConfig {
9133 SaveConfig(database_);
9136 // Navigation controller for the queuing badge.
9137 - (UINavigationController *) queueNavigationController {
9138 NSArray *controllers = [tabbar_ viewControllers];
9139 return [controllers objectAtIndex:3];
9142 - (void) unloadData {
9143 [tabbar_ unloadData];
9146 - (void) _updateData {
9150 UINavigationController *navigation = [self queueNavigationController];
9152 id queuedelegate = nil;
9153 if ([[navigation viewControllers] count] > 0)
9154 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9156 [queuedelegate queueStatusDidChange];
9157 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9160 - (void) _refreshIfPossible {
9161 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9163 NSDate *update([[NSDictionary dictionaryWithContentsOfFile:@ CacheState_] objectForKey:@"LastUpdate"]);
9165 bool recently = false;
9166 if (update != nil) {
9167 NSTimeInterval interval([update timeIntervalSinceNow]);
9168 if (interval > -(15*60))
9172 // Don't automatic refresh if:
9173 // - We already refreshed recently.
9174 // - We already auto-refreshed this launch.
9175 // - Auto-refresh is disabled.
9176 // - Cydia's server is not reachable
9177 if (recently || loaded_ || ManualRefresh || !IsReachable("cydia.saurik.com")) {
9178 // If we are cancelling, we need to make sure it knows it's already loaded.
9181 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9183 // We are going to load, so remember that.
9186 [tabbar_ performSelectorOnMainThread:@selector(beginUpdate) withObject:nil waitUntilDone:NO];
9192 - (void) refreshIfPossible {
9193 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
9196 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9197 _profile(reloadDataWithInvocation)
9198 @synchronized (self) {
9199 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9201 [hud setText:UCLocalize("RELOADING_DATA")];
9203 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9207 [essential_ removeAllObjects];
9208 [broken_ removeAllObjects];
9210 _profile(reloadDataWithInvocation$Essential)
9211 NSArray *packages([database_ packages]);
9212 for (Package *package in packages) {
9214 [broken_ addObject:package];
9215 if ([package upgradableAndEssential:YES] && ![package ignored]) {
9216 if ([package essential] && [package installed] != nil)
9217 [essential_ addObject:package];
9223 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9226 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9227 [changesItem setBadgeValue:badge];
9228 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9229 [self setApplicationIconBadgeNumber:changes];
9232 [changesItem setBadgeValue:nil];
9233 [changesItem setAnimatedBadge:NO];
9234 [self setApplicationIconBadgeNumber:0];
9241 [self removeProgressHUD:hud];
9248 - (void) updateData {
9252 - (void) updateDataAndLoad {
9254 if ([database_ progressDelegate] == nil)
9260 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9263 - (void) disemulate {
9264 if (emulated_ == nil)
9267 if ([window_ respondsToSelector:@selector(setRootViewController:)])
9268 [window_ setRootViewController:tabbar_];
9270 [window_ addSubview:[tabbar_ view]];
9271 [[emulated_ view] removeFromSuperview];
9275 [window_ setUserInteractionEnabled:YES];
9278 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9279 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9281 UIViewController *parent;
9282 if (emulated_ == nil)
9292 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9293 [parent presentModalViewController:navigation animated:YES];
9296 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9297 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9299 if (navigation != nil)
9300 [navigation pushViewController:progress animated:YES];
9302 [self presentModalViewController:progress force:YES];
9304 [progress invoke:invocation withTitle:title];
9308 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9309 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9312 - (void) repairWithInvocation:(NSInvocation *)invocation {
9314 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9318 - (void) repairWithSelector:(SEL)selector {
9319 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9322 - (void) reloadData {
9323 [self reloadDataWithInvocation:nil];
9324 if ([database_ progressDelegate] == nil)
9330 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9333 - (void) addSource:(NSDictionary *) source {
9334 CydiaAddSource(source);
9337 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9338 CydiaAddSource(href, distribution, sections);
9341 // XXX: this method should not return anything
9342 - (BOOL) addTrivialSource:(NSString *)href {
9343 CydiaAddSource(href, @"./");
9348 pkgProblemResolver *resolver = [database_ resolver];
9350 resolver->InstallProtect();
9351 if (!resolver->Resolve(true))
9356 // XXX: this is a really crappy way of doing this.
9357 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9358 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9359 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9360 if ([tabbar_ updating])
9361 [tabbar_ cancelUpdate];
9363 if (![database_ prepare])
9366 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9367 [page setDelegate:self];
9368 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9371 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9372 [tabbar_ presentModalViewController:confirm_ animated:YES];
9378 @synchronized (self) {
9383 - (void) clearPackage:(Package *)package {
9384 @synchronized (self) {
9391 - (void) installPackages:(NSArray *)packages {
9392 @synchronized (self) {
9393 for (Package *package in packages)
9400 - (void) installPackage:(Package *)package {
9401 @synchronized (self) {
9408 - (void) removePackage:(Package *)package {
9409 @synchronized (self) {
9416 - (void) distUpgrade {
9417 @synchronized (self) {
9418 if (![database_ upgrade])
9426 system("/usr/bin/uicache");
9431 UIProgressHUD *hud([self addProgressHUD]);
9432 [hud setText:UCLocalize("LOADING")];
9433 [self yieldToSelector:@selector(_uicache)];
9434 [self removeProgressHUD:hud];
9438 [database_ perform];
9439 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9440 [self performSelectorOnMainThread:@selector(uicache) withObject:nil waitUntilDone:YES];
9443 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9446 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9447 [self unlockSuspend];
9450 - (void) retainNetworkActivityIndicator {
9451 if (activity_++ == 0)
9452 [self setNetworkActivityIndicatorVisible:YES];
9455 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9459 - (void) releaseNetworkActivityIndicator {
9460 if (--activity_ == 0)
9461 [self setNetworkActivityIndicatorVisible:NO];
9464 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9469 - (void) cancelAndClear:(bool)clear {
9470 @synchronized (self) {
9482 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9483 NSString *context([alert context]);
9485 if ([context isEqualToString:@"conffile"]) {
9486 FILE *input = [database_ input];
9487 if (button == [alert cancelButtonIndex])
9488 fprintf(input, "N\n");
9489 else if (button == [alert firstOtherButtonIndex])
9490 fprintf(input, "Y\n");
9493 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9494 } else if ([context isEqualToString:@"fixhalf"]) {
9495 if (button == [alert cancelButtonIndex]) {
9496 @synchronized (self) {
9497 for (Package *broken in (id) broken_) {
9499 NSString *id(ShellEscape([broken id]));
9500 system([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /bin/rm -f"
9501 " /var/lib/dpkg/info/%@.prerm"
9502 " /var/lib/dpkg/info/%@.postrm"
9503 " /var/lib/dpkg/info/%@.preinst"
9504 " /var/lib/dpkg/info/%@.postinst"
9505 " /var/lib/dpkg/info/%@.extrainst_"
9506 "", id, id, id, id, id] UTF8String]);
9512 } else if (button == [alert firstOtherButtonIndex]) {
9513 [broken_ removeAllObjects];
9517 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9518 } else if ([context isEqualToString:@"upgrade"]) {
9519 if (button == [alert firstOtherButtonIndex]) {
9520 @synchronized (self) {
9521 for (Package *essential in (id) essential_)
9522 [essential install];
9527 } else if (button == [alert firstOtherButtonIndex] + 1) {
9529 } else if (button == [alert cancelButtonIndex]) {
9533 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9537 - (void) system:(NSString *)command {
9538 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9541 system([command UTF8String]);
9547 - (void) applicationWillSuspend {
9549 [super applicationWillSuspend];
9552 - (BOOL) isSafeToSuspend {
9555 NSLog(@"isSafeToSuspend: locked_ != 0");
9560 if ([tabbar_ modalViewController] != nil)
9563 // Use external process status API internally.
9564 // This is probably a really bad idea.
9565 // XXX: what is the point of this? does this solve anything at all?
9566 uint64_t status = 0;
9568 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9569 notify_get_state(notify_token, &status);
9570 notify_cancel(notify_token);
9575 NSLog(@"isSafeToSuspend: status != 0");
9581 NSLog(@"isSafeToSuspend: -> true");
9586 - (void) suspendReturningToLastApp:(BOOL)returning {
9587 if ([self isSafeToSuspend])
9588 [super suspendReturningToLastApp:returning];
9592 if ([self isSafeToSuspend])
9596 - (void) applicationSuspend {
9597 if ([self isSafeToSuspend])
9598 [super applicationSuspend];
9601 - (void) applicationSuspend:(GSEventRef)event {
9602 if ([self isSafeToSuspend])
9603 [super applicationSuspend:event];
9606 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9607 if ([self isSafeToSuspend])
9608 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9611 - (void) _setSuspended:(BOOL)value {
9612 if ([self isSafeToSuspend])
9613 [super _setSuspended:value];
9616 - (UIProgressHUD *) addProgressHUD {
9617 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9618 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9620 [window_ setUserInteractionEnabled:NO];
9622 UIViewController *target(tabbar_);
9623 if (UIViewController *modal = [target modalViewController])
9626 [hud showInView:[target view]];
9632 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9633 [self unlockSuspend];
9635 [hud removeFromSuperview];
9636 [window_ setUserInteractionEnabled:YES];
9639 - (CyteViewController *) pageForPackage:(NSString *)name withReferrer:(NSString *)referrer {
9640 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name withReferrer:referrer] autorelease];
9643 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external withReferrer:(NSString *)referrer {
9644 NSString *scheme([[url scheme] lowercaseString]);
9645 if ([[url absoluteString] length] <= [scheme length] + 3)
9647 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9648 NSArray *components([path componentsSeparatedByString:@"/"]);
9650 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"]) {
9651 CyteViewController *controller([self pageForPackage:[components objectAtIndex:1] withReferrer:referrer]);
9652 if (controller != nil)
9653 [controller setDelegate:self];
9657 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9660 NSString *base([components objectAtIndex:0]);
9662 CyteViewController *controller = nil;
9664 if ([base isEqualToString:@"url"]) {
9665 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9666 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9667 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9668 } else if (!external && [components count] == 1) {
9669 if ([base isEqualToString:@"sources"]) {
9670 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9673 if ([base isEqualToString:@"home"]) {
9674 controller = [[[HomeController alloc] init] autorelease];
9677 if ([base isEqualToString:@"sections"]) {
9678 controller = [[[SectionsController alloc] initWithDatabase:database_ source:nil] autorelease];
9681 if ([base isEqualToString:@"search"]) {
9682 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9685 if ([base isEqualToString:@"changes"]) {
9686 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9689 if ([base isEqualToString:@"installed"]) {
9690 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9692 } else if ([components count] == 2) {
9693 NSString *argument = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9695 if ([base isEqualToString:@"package"]) {
9696 controller = [self pageForPackage:argument withReferrer:referrer];
9699 if (!external && [base isEqualToString:@"search"]) {
9700 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9703 if (!external && [base isEqualToString:@"sections"]) {
9704 if ([argument isEqualToString:@"all"] || [argument isEqualToString:@"*"])
9706 controller = [[[SectionController alloc] initWithDatabase:database_ source:nil section:argument] autorelease];
9709 if ([base isEqualToString:@"sources"]) {
9710 if ([argument isEqualToString:@"add"]) {
9711 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9712 [(SourcesController *)controller showAddSourcePrompt];
9714 Source *source([database_ sourceWithKey:argument]);
9715 controller = [[[SectionsController alloc] initWithDatabase:database_ source:source] autorelease];
9719 if (!external && [base isEqualToString:@"launch"]) {
9720 [self launchApplicationWithIdentifier:argument suspended:NO];
9723 } else if (!external && [components count] == 3) {
9724 NSString *arg1 = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9725 NSString *arg2 = [[components objectAtIndex:2] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9727 if ([base isEqualToString:@"package"]) {
9728 if ([arg2 isEqualToString:@"settings"]) {
9729 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9730 } else if ([arg2 isEqualToString:@"files"]) {
9731 if (Package *package = [database_ packageWithName:arg1]) {
9732 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9733 [(FileTable *)controller setPackage:package];
9738 if ([base isEqualToString:@"sections"]) {
9739 Source *source([arg1 isEqualToString:@"*"] ? nil : [database_ sourceWithKey:arg1]);
9740 NSString *section([arg2 isEqualToString:@"*"] ? nil : arg2);
9741 controller = [[[SectionController alloc] initWithDatabase:database_ source:source section:section] autorelease];
9745 [controller setDelegate:self];
9749 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9750 CyteViewController *page([self pageForURL:url forExternal:external withReferrer:nil]);
9753 [tabbar_ setUnselectedViewController:page];
9758 - (void) applicationOpenURL:(NSURL *)url {
9759 [super applicationOpenURL:url];
9764 [self openCydiaURL:url forExternal:YES];
9767 - (void) applicationWillResignActive:(UIApplication *)application {
9768 // Stop refreshing if you get a phone call or lock the device.
9769 if ([tabbar_ updating])
9770 [tabbar_ cancelUpdate];
9772 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9773 [super applicationWillResignActive:application];
9776 - (void) saveState {
9777 [[NSDictionary dictionaryWithObjectsAndKeys:
9778 @"InterfaceState", [tabbar_ navigationURLCollection],
9779 @"LastClosed", [NSDate date],
9780 @"InterfaceIndex", [NSNumber numberWithInt:[tabbar_ selectedIndex]],
9781 nil] writeToFile:@ SavedState_ atomically:YES];
9786 - (void) applicationWillTerminate:(UIApplication *)application {
9790 - (void) applicationDidEnterBackground:(UIApplication *)application {
9791 if (kCFCoreFoundationVersionNumber < 1000 && [self isSafeToSuspend])
9792 return [self terminateWithSuccess];
9793 Backgrounded_ = [NSDate date];
9797 - (void) applicationWillEnterForeground:(UIApplication *)application {
9798 if (Backgrounded_ == nil)
9801 NSTimeInterval interval([Backgrounded_ timeIntervalSinceNow]);
9803 if (interval <= -(30*60)) {
9804 [tabbar_ setSelectedIndex:0];
9805 [[[tabbar_ viewControllers] objectAtIndex:0] popToRootViewControllerAnimated:NO];
9808 if (interval <= -(15*60)) {
9809 if (IsReachable("cydia.saurik.com")) {
9810 [tabbar_ beginUpdate];
9811 [appcache_ reloadURLWithCache:YES];
9815 if ([database_ delocked])
9819 - (void) setConfigurationData:(NSString *)data {
9820 static RegEx conffile_r("'(.*)' '(.*)' ([01]) ([01])");
9822 if (!conffile_r(data)) {
9823 lprintf("E:invalid conffile\n");
9827 NSString *ofile = conffile_r[1];
9828 //NSString *nfile = conffile_r[2];
9830 UIAlertView *alert = [[[UIAlertView alloc]
9831 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9832 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9834 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9836 UCLocalize("ACCEPT_NEW_COPY"),
9837 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9841 [alert setContext:@"conffile"];
9842 [alert setNumberOfRows:2];
9846 - (void) addStashController {
9848 stash_ = [[[StashController alloc] init] autorelease];
9849 [window_ addSubview:[stash_ view]];
9852 - (void) removeStashController {
9853 [[stash_ view] removeFromSuperview];
9855 [self unlockSuspend];
9859 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9860 UpdateExternalStatus(1);
9861 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/cydo /usr/libexec/cydia/free.sh"];
9862 UpdateExternalStatus(0);
9864 [self removeStashController];
9865 [self reloadSpringBoard];
9868 - (void) setupViewControllers {
9869 tabbar_ = [[[CydiaTabBarController alloc] initWithDatabase:database_] autorelease];
9871 NSMutableArray *items;
9872 if (kCFCoreFoundationVersionNumber < 800) {
9873 items = [NSMutableArray arrayWithObjects:
9874 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage imageNamed:@"home.png"] tag:0] autorelease],
9875 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage imageNamed:@"install.png"] tag:0] autorelease],
9876 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage imageNamed:@"changes.png"] tag:0] autorelease],
9877 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage imageNamed:@"manage.png"] tag:0] autorelease],
9878 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage imageNamed:@"search.png"] tag:0] autorelease],
9881 items = [NSMutableArray arrayWithObjects:
9882 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage imageNamed:@"home7.png"] selectedImage:[UIImage imageNamed:@"home7s.png"]] autorelease],
9883 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage imageNamed:@"install7.png"] selectedImage:[UIImage imageNamed:@"install7s.png"]] autorelease],
9884 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage imageNamed:@"changes7.png"] selectedImage:[UIImage imageNamed:@"changes7s.png"]] autorelease],
9885 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage imageNamed:@"manage7.png"] selectedImage:[UIImage imageNamed:@"manage7s.png"]] autorelease],
9886 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage imageNamed:@"search7.png"] selectedImage:[UIImage imageNamed:@"search7s.png"]] autorelease],
9890 NSMutableArray *controllers([NSMutableArray array]);
9891 for (UITabBarItem *item in items) {
9892 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9893 [controller setTabBarItem:item];
9894 [controllers addObject:controller];
9896 [tabbar_ setViewControllers:controllers];
9898 [tabbar_ setUpdateDelegate:self];
9901 - (void) _sendMemoryWarningNotification {
9902 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: maybe 4_0?
9903 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationMemoryWarningNotification" object:[UIApplication sharedApplication]];
9905 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
9908 - (void) _sendMemoryWarningNotifications {
9910 [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO];
9916 - (void) applicationDidReceiveMemoryWarning:(UIApplication *)application {
9918 [[NSURLCache sharedURLCache] removeAllCachedResponses];
9921 - (void) applicationDidFinishLaunching:(id)unused {
9922 //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil];
9925 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9926 [self setApplicationSupportsShakeToEdit:NO];
9928 @synchronized (HostConfig_) {
9929 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9932 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9933 initWithMemoryCapacity:524288
9934 diskCapacity:10485760
9935 diskPath:Cache("SDURLCache")
9938 [CydiaWebViewController _initialize];
9940 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9942 // this would disallow http{,s} URLs from accessing this data
9943 //[WebView registerURLSchemeAsLocal:@"cydia"];
9945 Font12_ = [UIFont systemFontOfSize:12];
9946 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9947 Font14_ = [UIFont systemFontOfSize:14];
9948 Font18_ = [UIFont systemFontOfSize:18];
9949 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9950 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9952 essential_ = [NSMutableArray arrayWithCapacity:4];
9953 broken_ = [NSMutableArray arrayWithCapacity:4];
9955 // XXX: I really need this thing... like, seriously... I'm sorry
9956 appcache_ = [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] autorelease];
9957 [appcache_ reloadData];
9959 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9960 [window_ orderFront:self];
9961 [window_ makeKey:self];
9962 [window_ setHidden:NO];
9964 if (access("/.cydia_no_stash", F_OK) == 0);
9968 [self addStashController];
9969 // XXX: this would be much cleaner as a yieldToSelector:
9970 // that way the removeStashController could happen right here inline
9971 // we also could no longer require the useless stash_ field anymore
9972 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9977 int error(stat("/", &root));
9978 _assert(error != -1);
9980 #define Stash_(path) do { \
9981 struct stat folder; \
9982 int error(lstat((path), &folder)); \
9983 if (error != -1 && ( \
9984 folder.st_dev == root.st_dev && \
9985 S_ISDIR(folder.st_mode) \
9986 ) || error == -1 && ( \
9987 errno == ENOENT || \
9992 Stash_("/Applications");
9993 Stash_("/Library/Ringtones");
9994 Stash_("/Library/Wallpaper");
9995 //Stash_("/usr/bin");
9996 Stash_("/usr/include");
9997 Stash_("/usr/share");
9998 //Stash_("/var/lib");
10002 database_ = [Database sharedInstance];
10003 [database_ setDelegate:self];
10005 [window_ setUserInteractionEnabled:NO];
10006 [self setupViewControllers];
10008 CydiaLoadingViewController *loading([[[CydiaLoadingViewController alloc] init] autorelease]);
10009 UINavigationController *navigation([[[UINavigationController alloc] init] autorelease]);
10010 [navigation setViewControllers:[NSArray arrayWithObject:loading]];
10012 emulated_ = [[[CyteTabBarController alloc] init] autorelease];
10013 [emulated_ setViewControllers:[NSArray arrayWithObject:navigation]];
10014 [emulated_ setSelectedIndex:0];
10016 if ([emulated_ respondsToSelector:@selector(concealTabBarSelection)])
10017 [emulated_ concealTabBarSelection];
10019 if ([window_ respondsToSelector:@selector(setRootViewController:)])
10020 [window_ setRootViewController:emulated_];
10022 [window_ addSubview:[emulated_ view]];
10024 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
10028 - (NSArray *) defaultStartPages {
10029 NSMutableArray *standard = [NSMutableArray array];
10030 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
10031 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
10032 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
10033 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
10034 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
10038 - (void) loadData {
10040 if ([emulated_ modalViewController] != nil)
10041 [emulated_ dismissModalViewControllerAnimated:YES];
10042 [window_ setUserInteractionEnabled:NO];
10044 [self reloadDataWithInvocation:nil];
10045 [self refreshIfPossible];
10048 NSDictionary *state([NSDictionary dictionaryWithContentsOfFile:@ SavedState_]);
10050 int savedIndex = [[state objectForKey:@"InterfaceIndex"] intValue];
10051 NSArray *saved = [[[state objectForKey:@"InterfaceState"] mutableCopy] autorelease];
10052 int standardIndex = 0;
10053 NSArray *standard = [self defaultStartPages];
10060 NSDate *closed = [state objectForKey:@"LastClosed"];
10061 if (valid && closed != nil) {
10062 NSTimeInterval interval([closed timeIntervalSinceNow]);
10063 if (interval <= -(30*60))
10067 if (valid && [saved count] != [standard count])
10071 for (unsigned int i = 0; i < [standard count]; i++) {
10072 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
10073 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
10074 // but it's good enough for now.
10075 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
10082 NSArray *items = nil;
10084 [tabbar_ setSelectedIndex:savedIndex];
10087 [tabbar_ setSelectedIndex:standardIndex];
10091 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
10092 NSArray *stack = [items objectAtIndex:tab];
10093 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
10094 NSMutableArray *current = [NSMutableArray array];
10096 for (unsigned int nav = 0; nav < [stack count]; nav++) {
10097 NSString *addr = [stack objectAtIndex:nav];
10098 NSURL *url = [NSURL URLWithString:addr];
10099 CyteViewController *page = [self pageForURL:url forExternal:NO withReferrer:nil];
10101 [current addObject:page];
10104 [navigation setViewControllers:current];
10107 // (Try to) show the startup URL.
10108 if (starturl_ != nil) {
10109 [self openCydiaURL:starturl_ forExternal:YES];
10114 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
10116 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
10117 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
10120 if (item != nil && IsWildcat_) {
10121 [sheet showFromBarButtonItem:item animated:YES];
10123 [sheet showInView:window_];
10127 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
10128 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
10129 [progress setTitle:task];
10130 [progress addProgressEvent:event];
10133 - (void) addProgressEventForTask:(NSArray *)data {
10134 CydiaProgressEvent *event([data objectAtIndex:0]);
10135 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
10136 [self addProgressEvent:event forTask:task];
10139 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
10140 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
10146 id Alloc_(id self, SEL selector) {
10147 id object = alloc_(self, selector);
10148 lprintf("[%s]A-%p\n", self->isa->name, object);
10153 id Dealloc_(id self, SEL selector) {
10154 id object = dealloc_(self, selector);
10155 lprintf("[%s]D-%p\n", self->isa->name, object);
10159 Class $NSURLConnection;
10161 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
10162 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
10164 NSURL *url([copy URL]);
10166 NSString *host([url host]);
10167 NSString *scheme([[url scheme] lowercaseString]);
10169 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
10171 @synchronized (HostConfig_) {
10172 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
10173 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
10174 [copy setHTTPShouldUsePipelining:YES];
10176 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
10177 if ([control isEqualToString:@"max-age=0"])
10178 if ([CachedURLs_ containsObject:url]) {
10180 NSLog(@"~~~: %@", url);
10183 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
10185 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
10186 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
10187 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
10191 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
10197 static CGSize $WAKWindow$screenSize(WAKWindow *self, SEL _cmd) {
10198 CGSize size([[UIScreen mainScreen] bounds].size);
10199 /*if ([$WAKWindow respondsToSelector:@selector(hasLandscapeOrientation)])
10200 if ([$WAKWindow hasLandscapeOrientation])
10201 std::swap(size.width, size.height);*/
10205 Class $NSUserDefaults;
10207 MSHook(id, NSUserDefaults$objectForKey$, NSUserDefaults *self, SEL _cmd, NSString *key) {
10208 if ([key respondsToSelector:@selector(isEqualToString:)] && [key isEqualToString:@"WebKitLocalStorageDatabasePathPreferenceKey"])
10209 return Cache("LocalStorage");
10210 return _NSUserDefaults$objectForKey$(self, _cmd, key);
10213 static NSMutableDictionary *AutoreleaseDeepMutableCopyOfDictionary(CFTypeRef type) {
10216 if (CFGetTypeID(type) != CFDictionaryGetTypeID())
10218 CFTypeRef copy(CFPropertyListCreateDeepCopy(kCFAllocatorDefault, type, kCFPropertyListMutableContainers));
10220 return [(NSMutableDictionary *) copy autorelease];
10223 int main_store(int, char *argv[]);
10225 int main(int argc, char *argv[]) {
10227 const char *argv0(argv[0]);
10228 if (const char *slash = strrchr(argv0, '/'))
10231 else if (!strcmp(argv0, "store"))
10232 return main_store(argc, argv);
10235 int fd(open("/tmp/cydia.log", O_WRONLY | O_APPEND | O_CREAT, 0644));
10239 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10243 UpdateExternalStatus(0);
10245 UIScreen *screen([UIScreen mainScreen]);
10246 if ([screen respondsToSelector:@selector(scale)])
10247 ScreenScale_ = [screen scale];
10251 UIDevice *device([UIDevice currentDevice]);
10252 if ([device respondsToSelector:@selector(userInterfaceIdiom)]) {
10253 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10254 if (idiom == UIUserInterfaceIdiomPad)
10258 Idiom_ = IsWildcat_ ? @"ipad" : @"iphone";
10260 RegEx pattern("([0-9]+\\.[0-9]+).*");
10262 if (pattern([device systemVersion]))
10263 Firmware_ = pattern[1];
10264 if (pattern(Cydia_))
10265 Major_ = pattern[1];
10267 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
10269 HostConfig_ = [[[NSObject alloc] init] autorelease];
10270 @synchronized (HostConfig_) {
10271 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10272 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
10273 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
10274 CachedURLs_ = [NSMutableSet setWithCapacity:32];
10277 NSString *ui(@"ui/ios");
10279 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
10280 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"/%@", Major_]];
10281 UI_ = CydiaURL(ui);
10283 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10285 /* Library Hacks {{{ */
10286 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10288 $WAKWindow = objc_getClass("WAKWindow");
10289 if ($WAKWindow != NULL)
10290 if (Method method = class_getInstanceMethod($WAKWindow, @selector(screenSize)))
10291 method_setImplementation(method, (IMP) &$WAKWindow$screenSize);
10293 $NSURLConnection = objc_getClass("NSURLConnection");
10294 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10295 if (NSURLConnection$init$ != NULL) {
10296 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10297 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10300 $NSUserDefaults = objc_getClass("NSUserDefaults");
10301 Method NSUserDefaults$objectForKey$(class_getInstanceMethod($NSUserDefaults, @selector(objectForKey:)));
10302 if (NSUserDefaults$objectForKey$ != NULL) {
10303 _NSUserDefaults$objectForKey$ = reinterpret_cast<id (*)(NSUserDefaults *, SEL, NSString *)>(method_getImplementation(NSUserDefaults$objectForKey$));
10304 method_setImplementation(NSUserDefaults$objectForKey$, reinterpret_cast<IMP>(&$NSUserDefaults$objectForKey$));
10307 /* Set Locale {{{ */
10308 Locale_ = CFLocaleCopyCurrent();
10309 Languages_ = [NSLocale preferredLanguages];
10311 std::string languages;
10312 const char *translation(NULL);
10314 // XXX: this isn't really a language, but this is compatible with older Cydia builds
10315 if (Locale_ != NULL)
10316 if (const char *language = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String]) {
10317 RegEx pattern("([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?");
10318 if (pattern(language)) {
10319 translation = strdup([pattern->*@"%1$@%2$@" UTF8String]);
10320 languages += translation;
10325 if (Languages_ != nil)
10326 for (NSString *language : Languages_) {
10327 languages += [language UTF8String];
10332 NSLog(@"Setting Language: [%s] %s", translation, languages.c_str());
10334 /* Index Collation {{{ */
10335 if (Class $UILocalizedIndexedCollation = objc_getClass("UILocalizedIndexedCollation")) { @try {
10336 NSBundle *bundle([NSBundle bundleForClass:$UILocalizedIndexedCollation]);
10337 NSString *path([bundle pathForResource:@"UITableViewLocalizedSectionIndex" ofType:@"plist"]);
10338 //path = @"/System/Library/Frameworks/UIKit.framework/.lproj/UITableViewLocalizedSectionIndex.plist";
10339 NSDictionary *dictionary([NSDictionary dictionaryWithContentsOfFile:path]);
10340 _H<UILocalizedIndexedCollation> collation([[[$UILocalizedIndexedCollation alloc] initWithDictionary:dictionary] autorelease]);
10342 CollationLocale_ = MSHookIvar<NSLocale *>(collation, "_locale");
10344 if (kCFCoreFoundationVersionNumber >= 800 && [[CollationLocale_ localeIdentifier] isEqualToString:@"zh@collation=stroke"]) {
10345 CollationThumbs_ = [NSArray arrayWithObjects:@"1",@"•",@"4",@"•",@"7",@"•",@"10",@"•",@"13",@"•",@"16",@"•",@"19",@"A",@"•",@"E",@"•",@"I",@"•",@"M",@"•",@"R",@"•",@"V",@"•",@"Z",@"#",nil];
10346 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})
10347 CollationOffset_.push_back(offset);
10348 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];
10349 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];
10352 CollationThumbs_ = [collation sectionIndexTitles];
10353 for (size_t index(0), end([CollationThumbs_ count]); index != end; ++index)
10354 CollationOffset_.push_back([collation sectionForSectionIndexTitleAtIndex:index]);
10356 CollationTitles_ = [collation sectionTitles];
10357 CollationStarts_ = MSHookIvar<NSArray *>(collation, "_sectionStartStrings");
10359 NSString *&transform(MSHookIvar<NSString *>(collation, "_transform"));
10360 if (&transform != NULL && transform != nil) {
10361 /*if ([collation respondsToSelector:@selector(transformedCollationStringForString:)])
10362 CollationModify_ = [=](NSString *value) { return [collation transformedCollationStringForString:value]; };*/
10363 const UChar *uid(reinterpret_cast<const UChar *>([transform cStringUsingEncoding:NSUnicodeStringEncoding]));
10364 UErrorCode code(U_ZERO_ERROR);
10365 CollationTransl_ = utrans_openU(uid, -1, UTRANS_FORWARD, NULL, 0, NULL, &code);
10366 if (!U_SUCCESS(code))
10367 NSLog(@"%s", u_errorName(code));
10371 } @catch (NSException *e) {
10375 CollationLocale_ = [[[NSLocale alloc] initWithLocaleIdentifier:@"en@collation=dictionary"] autorelease];
10377 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];
10378 for (NSInteger offset(0); offset != 28; ++offset)
10379 CollationOffset_.push_back(offset);
10381 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];
10382 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];
10385 /* Parse Arguments {{{ */
10386 bool substrate(false);
10392 for (int argi(1); argi != argc; ++argi)
10393 if (strcmp(argv[argi], "--") == 0) {
10395 argv[argi] = argv[0];
10401 for (int argi(1); argi != arge; ++argi)
10402 if (strcmp(args[argi], "--substrate") == 0)
10405 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10409 App_ = [[NSBundle mainBundle] bundlePath];
10412 Cache_ = [[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia", @"/var/mobile"] retain];
10413 mkdir([Cache_ UTF8String], 0755);
10415 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10416 alloc_ = alloc->method_imp;
10417 alloc->method_imp = (IMP) &Alloc_;*/
10419 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10420 dealloc_ = dealloc->method_imp;
10421 dealloc->method_imp = (IMP) &Dealloc_;*/
10423 void *gestalt(dlopen("/usr/lib/libMobileGestalt.dylib", RTLD_GLOBAL | RTLD_LAZY));
10424 $MGCopyAnswer = reinterpret_cast<CFStringRef (*)(CFStringRef)>(dlsym(gestalt, "MGCopyAnswer"));
10426 /* System Information {{{ */
10430 size = sizeof(maxproc);
10431 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10432 perror("sysctlbyname(\"kern.maxproc\", ?)");
10433 else if (maxproc < 64) {
10435 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10436 perror("sysctlbyname(\"kern.maxproc\", #)");
10439 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10440 char *osversion = new char[size];
10441 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10442 perror("sysctlbyname(\"kern.osversion\", ?)");
10444 System_ = [NSString stringWithUTF8String:osversion];
10446 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10447 char *machine = new char[size];
10448 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10449 perror("sysctlbyname(\"hw.machine\", ?)");
10451 Machine_ = machine;
10453 int64_t usermem(0);
10454 size = sizeof(usermem);
10455 if (sysctlbyname("hw.usermem", &usermem, &size, NULL, 0) == -1)
10458 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10459 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10460 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10462 UniqueID_ = UniqueIdentifier(device);
10464 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10465 Product_ = [info objectForKey:@"SafariProductVersion"];
10466 Safari_ = [info objectForKey:@"CFBundleVersion"];
10469 NSString *agent([NSString stringWithFormat:@"Cydia/%@ CyF/%.2f", Cydia_, kCFCoreFoundationVersionNumber]);
10471 if (RegEx match = RegEx("([0-9]+(\\.[0-9]+)+).*", Safari_))
10472 agent = [NSString stringWithFormat:@"Safari/%@ %@", match[1], agent];
10473 if (RegEx match = RegEx("([0-9]+[A-Z][0-9]+[a-z]?).*", System_))
10474 agent = [NSString stringWithFormat:@"Mobile/%@ %@", match[1], agent];
10475 if (RegEx match = RegEx("([0-9]+(\\.[0-9]+)+).*", Product_))
10476 agent = [NSString stringWithFormat:@"Version/%@ %@", match[1], agent];
10478 UserAgent_ = agent;
10480 /* Load Database {{{ */
10481 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10484 mkdir("/var/mobile/Library/Cydia", 0755);
10485 MetaFile_.Open("/var/mobile/Library/Cydia/metadata.cb0");
10488 Values_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaValues"), CFSTR("com.saurik.Cydia")));
10489 Sections_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaSections"), CFSTR("com.saurik.Cydia")));
10490 Sources_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaSources"), CFSTR("com.saurik.Cydia")));
10491 Version_ = [(NSNumber *) CFPreferencesCopyAppValue(CFSTR("CydiaVersion"), CFSTR("com.saurik.Cydia")) autorelease];
10494 NSDictionary *metadata([[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease]);
10496 if (Values_ == nil)
10497 Values_ = [metadata objectForKey:@"Values"];
10498 if (Values_ == nil)
10499 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10501 if (Sections_ == nil)
10502 Sections_ = [metadata objectForKey:@"Sections"];
10503 if (Sections_ == nil)
10504 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10506 if (Sources_ == nil)
10507 Sources_ = [metadata objectForKey:@"Sources"];
10508 if (Sources_ == nil)
10509 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10511 // XXX: this wrong, but in a way that doesn't matter :/
10512 if (Version_ == nil)
10513 Version_ = [metadata objectForKey:@"Version"];
10514 if (Version_ == nil)
10515 Version_ = [NSNumber numberWithUnsignedInt:0];
10517 if (NSDictionary *packages = [metadata objectForKey:@"Packages"]) {
10519 CFDictionaryApplyFunction((CFDictionaryRef) packages, &PackageImport, &fail);
10522 NSLog(@"unable to import package preferences... from 2010? oh well :/");
10525 if ([Version_ unsignedIntValue] == 0) {
10526 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10527 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10528 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10529 CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./");
10531 Version_ = [NSNumber numberWithUnsignedInt:1];
10533 if (NSMutableDictionary *cache = [NSMutableDictionary dictionaryWithContentsOfFile:@ CacheState_]) {
10534 [cache removeObjectForKey:@"LastUpdate"];
10535 [cache writeToFile:@ CacheState_ atomically:YES];
10539 _H<NSMutableArray> broken([NSMutableArray array]);
10540 for (NSString *key in (id) Sources_)
10541 if ([key rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"# "]].location != NSNotFound || ![([[Sources_ objectForKey:key] objectForKey:@"URI"] ?: @"/") hasSuffix:@"/"])
10542 [broken addObject:key];
10543 if ([broken count] != 0)
10544 for (NSString *key in (id) broken)
10545 [Sources_ removeObjectForKey:key];
10549 system("/usr/libexec/cydia/cydo /bin/rm -f /var/lib/cydia/metadata.plist");
10552 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10554 if (kCFCoreFoundationVersionNumber > 1000)
10555 system("/usr/libexec/cydia/cydo /usr/libexec/cydia/setnsfpn /var/lib");
10557 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10559 if (access("/User", F_OK) != 0 || version != 6) {
10561 system("/usr/libexec/cydia/cydo /usr/libexec/cydia/firmware.sh");
10565 if (access("/tmp/cydia.chk", F_OK) == 0) {
10566 if (unlink([Cache("pkgcache.bin") UTF8String]) == -1)
10567 _assert(errno == ENOENT);
10568 if (unlink([Cache("srcpkgcache.bin") UTF8String]) == -1)
10569 _assert(errno == ENOENT);
10572 system("/usr/libexec/cydia/cydo /bin/ln -sf /var/mobile/Library/Caches/com.saurik.Cydia/sources.list /etc/apt/sources.list.d/cydia.list");
10574 /* APT Initialization {{{ */
10575 _assert(pkgInitConfig(*_config));
10576 _assert(pkgInitSystem(*_config, _system));
10578 _config->Set("Acquire::AllowInsecureRepositories", true);
10579 _config->Set("Acquire::Check-Valid-Until", false);
10580 _config->Set("Dir::Bin::Methods::store", "/Applications/Cydia.app/store");
10582 _config->Set("pkgCacheGen::ForceEssential", "");
10584 if (translation != NULL)
10585 _config->Set("APT::Acquire::Translation", translation);
10586 _config->Set("Acquire::Languages", languages);
10588 // XXX: this timeout might be important :(
10589 //_config->Set("Acquire::http::Timeout", 15);
10591 _config->Set("Acquire::http::MaxParallel", usermem >= 384 * 1024 * 1024 ? 16 : 3);
10593 mkdir([Cache("archives") UTF8String], 0755);
10594 mkdir([Cache("archives/partial") UTF8String], 0755);
10595 _config->Set("Dir::Cache", [Cache_ UTF8String]);
10597 symlink("/var/lib/apt/extended_states", [Cache("extended_states") UTF8String]);
10598 _config->Set("Dir::State", [Cache_ UTF8String]);
10600 mkdir([Cache("lists") UTF8String], 0755);
10601 mkdir([Cache("lists/partial") UTF8String], 0755);
10602 mkdir([Cache("periodic") UTF8String], 0755);
10603 _config->Set("Dir::State::Lists", [Cache("lists") UTF8String]);
10605 std::string logs("/var/mobile/Library/Logs/Cydia");
10606 mkdir(logs.c_str(), 0755);
10607 _config->Set("Dir::Log", logs);
10609 _config->Set("Dir::Bin::dpkg", "/usr/libexec/cydia/cydo");
10611 /* Color Choices {{{ */
10612 space_ = CGColorSpaceCreateDeviceRGB();
10614 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10615 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10616 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10617 Folder_.Set(space_, 0x8e/255.f, 0x8e/255.f, 0x93/255.f, 1.0);
10618 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10619 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10620 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10621 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10622 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10623 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10625 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10626 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10628 /* UIKit Configuration {{{ */
10629 // XXX: I have a feeling this was important
10630 //UIKeyboardDisableAutomaticAppearance();
10633 $SBSSetInterceptsMenuButtonForever = reinterpret_cast<void (*)(bool)>(dlsym(RTLD_DEFAULT, "SBSSetInterceptsMenuButtonForever"));
10634 $SBSCopyIconImagePNGDataForDisplayIdentifier = reinterpret_cast<NSData *(*)(NSString *)>(dlsym(RTLD_DEFAULT, "SBSCopyIconImagePNGDataForDisplayIdentifier"));
10636 const char *symbol(kCFCoreFoundationVersionNumber >= 800 ? "MGGetBoolAnswer" : "GSSystemHasCapability");
10637 BOOL (*GSSystemHasCapability)(CFStringRef) = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, symbol));
10638 bool fast = GSSystemHasCapability != NULL && GSSystemHasCapability(CFSTR("armv7"));
10640 PulseInterval_ = fast ? 50000 : 500000;
10642 Colon_ = UCLocalize("COLON_DELIMITED");
10643 Elision_ = UCLocalize("ELISION");
10644 Error_ = UCLocalize("ERROR");
10645 Warning_ = UCLocalize("WARNING");
10648 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10650 CGColorSpaceRelease(space_);
10651 CFRelease(Locale_);