1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2014 Jay Freeman (saurik)
5 /* GNU General Public License, Version 3 {{{ */
7 * Cydia is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published
9 * by the Free Software Foundation, either version 3 of the License,
10 * or (at your option) any later version.
12 * Cydia is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Cydia. If not, see <http://www.gnu.org/licenses/>.
22 // XXX: wtf/FastMalloc.h... wtf?
23 #define USE_SYSTEM_MALLOC 1
25 /* #include Directives {{{ */
26 #include "CyteKit/UCPlatform.h"
27 #include "CyteKit/Localize.h"
29 #include <unicode/ustring.h>
30 #include <unicode/utrans.h>
32 #include <objc/objc.h>
33 #include <objc/runtime.h>
35 #include <CoreGraphics/CoreGraphics.h>
36 #include <Foundation/Foundation.h>
39 #define DEPLOYMENT_TARGET_MACOSX 1
40 #define CF_BUILDING_CF 1
41 #include <CoreFoundation/CFInternal.h>
44 #include <CoreFoundation/CFUniChar.h>
46 #include <SystemConfiguration/SystemConfiguration.h>
48 #include <UIKit/UIKit.h>
49 #include "iPhonePrivate.h"
51 #include <IOKit/IOKitLib.h>
53 #include <QuartzCore/CALayer.h>
55 #include <WebCore/WebCoreThread.h>
56 #include <WebKit/DOMHTMLIFrameElement.h>
64 #include <ext/stdio_filebuf.h>
68 #include <apt-pkg/acquire.h>
69 #include <apt-pkg/acquire-item.h>
70 #include <apt-pkg/algorithms.h>
71 #include <apt-pkg/cachefile.h>
72 #include <apt-pkg/clean.h>
73 #include <apt-pkg/configuration.h>
74 #include <apt-pkg/debindexfile.h>
75 #include <apt-pkg/debmetaindex.h>
76 #include <apt-pkg/error.h>
77 #include <apt-pkg/init.h>
78 #include <apt-pkg/mmap.h>
79 #include <apt-pkg/pkgrecords.h>
80 #include <apt-pkg/sha1.h>
81 #include <apt-pkg/sourcelist.h>
82 #include <apt-pkg/sptr.h>
83 #include <apt-pkg/strutl.h>
84 #include <apt-pkg/tagfile.h>
86 #include <apr-1/apr_pools.h>
88 #include <sys/types.h>
90 #include <sys/sysctl.h>
91 #include <sys/param.h>
92 #include <sys/mount.h>
93 #include <sys/reboot.h>
100 #include <mach-o/nlist.h>
109 #include <Cytore.hpp>
112 #include <CydiaSubstrate/CydiaSubstrate.h>
113 #include "Menes/Menes.h"
115 #include "CyteKit/IndirectDelegate.h"
116 #include "CyteKit/PerlCompatibleRegEx.hpp"
117 #include "CyteKit/TableViewCell.h"
118 #include "CyteKit/TabBarController.h"
119 #include "CyteKit/WebScriptObject-Cyte.h"
120 #include "CyteKit/WebViewController.h"
121 #include "CyteKit/WebViewTableViewCell.h"
122 #include "CyteKit/stringWithUTF8Bytes.h"
124 #include "Cydia/MIMEAddress.h"
125 #include "Cydia/LoadingViewController.h"
126 #include "Cydia/ProgressEvent.h"
128 #include "SDURLCache/SDURLCache.h"
135 #define _timestamp ({ \
137 gettimeofday(&tv, NULL); \
138 tv.tv_sec * 1000000 + tv.tv_usec; \
141 typedef std::vector<class ProfileTime *> TimeList;
151 ProfileTime(const char *name) :
155 times_.push_back(this);
158 void AddTime(uint64_t time) {
165 std::cerr << std::setw(7) << count_ << ", " << std::setw(8) << total_ << " : " << name_ << std::endl;
177 ProfileTimer(ProfileTime &time) :
184 time_.AddTime(_timestamp - start_);
189 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
191 std::cerr << "========" << std::endl;
194 #define _profile(name) { \
195 static ProfileTime name(#name); \
196 ProfileTimer _ ## name(name);
201 // XXX: I hate clang. Apple: please get over your petty hatred of GPL and fix your gcc fork
202 #define synchronized(lock) \
203 synchronized(static_cast<NSObject *>(lock))
205 extern NSString *Cydia_;
207 #define lprintf(args...) fprintf(stderr, args)
210 #define TraceLogging (1 && !ForRelease)
211 #define HistogramInsertionSort (0 && !ForRelease)
212 #define ProfileTimes (0 && !ForRelease)
213 #define ForSaurik (0 && !ForRelease)
214 #define LogBrowser (0 && !ForRelease)
215 #define TrackResize (0 && !ForRelease)
216 #define ManualRefresh (1 && !ForRelease)
217 #define ShowInternals (0 && !ForRelease)
218 #define AlwaysReload (0 && !ForRelease)
222 #define _trace(args...)
227 #define _profile(name) {
230 #define PrintTimes() do {} while (false)
233 // Hash Functions/Structures {{{
234 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
242 static NSString *Colon_;
244 static NSString *Error_;
245 static NSString *Warning_;
247 static NSString *Cache_;
249 static void (*$SBSSetInterceptsMenuButtonForever)(bool);
251 static CFStringRef (*$MGCopyAnswer)(CFStringRef);
253 static NSString *UniqueIdentifier(UIDevice *device = nil) {
254 if (kCFCoreFoundationVersionNumber < 800) // iOS 7.x
255 return [device ?: [UIDevice currentDevice] uniqueIdentifier];
257 return [(id)$MGCopyAnswer(CFSTR("UniqueDeviceID")) autorelease];
260 static bool IsReachable(const char *name) {
261 SCNetworkReachabilityFlags flags; {
262 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, name));
263 SCNetworkReachabilityGetFlags(reachability, &flags);
264 CFRelease(reachability);
267 // XXX: this elaborate mess is what Apple is using to determine this? :(
268 // XXX: do we care if the user has to intervene? maybe that's ok?
270 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
271 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
272 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
273 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
274 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
275 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
280 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
282 static _finline NSString *CydiaURL(NSString *path) {
284 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
285 page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
286 page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
287 page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
288 page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
290 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
293 static void ReapZombie(pid_t pid) {
296 if (waitpid(pid, &status, 0) == -1)
302 static _finline void UpdateExternalStatus(uint64_t newStatus) {
304 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
305 notify_set_state(notify_token, newStatus);
306 notify_cancel(notify_token);
308 notify_post("com.saurik.Cydia.status");
311 static CGFloat CYStatusBarHeight() {
312 CGSize size([[UIApplication sharedApplication] statusBarFrame].size);
313 return UIInterfaceOrientationIsPortrait([[UIApplication sharedApplication] statusBarOrientation]) ? size.height : size.width;
316 /* NSForcedOrderingSearch doesn't work on the iPhone */
317 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
318 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
319 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
321 /* Insertion Sort {{{ */
323 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
324 const char *ptr = (const char *)list;
326 CFIndex half = count / 2;
327 const char *probe = ptr + elementSize * half;
328 CFComparisonResult cr = comparator(element, probe, context);
329 if (0 == cr) return (probe - (const char *)list) / elementSize;
330 ptr = (cr < 0) ? ptr : probe + elementSize;
331 count = (cr < 0) ? half : (half + (count & 1) - 1);
333 return (ptr - (const char *)list) / elementSize;
336 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
337 const char *ptr = (const char *)list;
339 CFIndex half = count / 2;
340 const char *probe = ptr + elementSize * half;
341 CFComparisonResult cr = comparator(element, probe, context);
342 if (0 == cr) return (probe - (const char *)list) / elementSize;
343 ptr = (cr < 0) ? ptr : probe + elementSize;
344 count = (cr < 0) ? half : (half + (count & 1) - 1);
346 return (ptr - (const char *)list) / elementSize;
349 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
350 if (range.length == 0)
352 const void **values(new const void *[range.length]);
353 CFArrayGetValues(array, range, values);
355 #if HistogramInsertionSort > 0
356 uint32_t total(0), *offsets(new uint32_t[range.length]);
359 for (CFIndex index(1); index != range.length; ++index) {
360 const void *value(values[index]);
361 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
362 CFIndex correct(index);
363 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
364 #if HistogramInsertionSort > 1
365 NSLog(@"%@ < %@", value, values[correct - 1]);
370 if (correct != index) {
371 size_t offset(index - correct);
372 #if HistogramInsertionSort
376 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
378 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
379 values[correct] = value;
383 CFArrayReplaceValues(array, range, values, range.length);
386 #if HistogramInsertionSort > 0
387 for (CFIndex index(0); index != range.length; ++index)
388 if (offsets[index] != 0)
389 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
390 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
397 /* Apple Bug Fixes {{{ */
398 @implementation UIWebDocumentView (Cydia)
400 - (void) _setScrollerOffset:(CGPoint)offset {
401 UIScroller *scroller([self _scroller]);
403 CGSize size([scroller contentSize]);
404 CGSize bounds([scroller bounds].size);
407 max.x = size.width - bounds.width;
408 max.y = size.height - bounds.height;
416 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
417 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
419 [scroller setOffset:offset];
425 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
426 size_t length([self length] - state->state);
429 else if (length > count)
431 for (size_t i(0); i != length; ++i)
432 objects[i] = [self item:state->state++];
433 state->itemsPtr = objects;
434 state->mutationsPtr = (unsigned long *) self;
438 /* Cydia NSString Additions {{{ */
439 @interface NSString (Cydia)
440 - (NSComparisonResult) compareByPath:(NSString *)other;
441 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
444 @implementation NSString (Cydia)
446 - (NSComparisonResult) compareByPath:(NSString *)other {
447 NSString *prefix = [self commonPrefixWithString:other options:0];
448 size_t length = [prefix length];
450 NSRange lrange = NSMakeRange(length, [self length] - length);
451 NSRange rrange = NSMakeRange(length, [other length] - length);
453 lrange = [self rangeOfString:@"/" options:0 range:lrange];
454 rrange = [other rangeOfString:@"/" options:0 range:rrange];
456 NSComparisonResult value;
458 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
459 value = NSOrderedSame;
460 else if (lrange.location == NSNotFound)
461 value = NSOrderedAscending;
462 else if (rrange.location == NSNotFound)
463 value = NSOrderedDescending;
465 value = NSOrderedSame;
467 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
468 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
469 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
470 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
472 NSComparisonResult result = [lpath compare:rpath];
473 return result == NSOrderedSame ? value : result;
476 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
477 return [(id)CFURLCreateStringByAddingPercentEscapes(
482 kCFStringEncodingUTF8
489 /* C++ NSString Wrapper Cache {{{ */
490 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
491 return size == 0 ? NULL :
492 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
493 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
496 static _finline CFStringRef CYStringCreate(const char *data) {
497 return CYStringCreate(data, strlen(data));
506 _finline void clear_() {
507 if (cache_ != NULL) {
514 _finline bool empty() const {
518 _finline size_t size() const {
522 _finline char *data() const {
526 _finline void clear() {
531 _finline CYString() :
538 _finline ~CYString() {
542 void operator =(const CYString &rhs) {
546 if (rhs.cache_ == nil)
549 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
552 void copy(apr_pool_t *pool) {
553 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
554 memcpy(temp, data_, size_);
559 void set(apr_pool_t *pool, const char *data, size_t size) {
565 data_ = const_cast<char *>(data);
573 _finline void set(apr_pool_t *pool, const char *data) {
574 set(pool, data, data == NULL ? 0 : strlen(data));
577 _finline void set(apr_pool_t *pool, const std::string &rhs) {
578 set(pool, rhs.data(), rhs.size());
581 bool operator ==(const CYString &rhs) const {
582 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
585 _finline operator CFStringRef() {
587 cache_ = CYStringCreate(data_, size_);
591 _finline operator id() {
592 return (NSString *) static_cast<CFStringRef>(*this);
595 _finline operator const char *() {
596 return reinterpret_cast<const char *>(data_);
600 /* C++ NSString Algorithm Adapters {{{ */
602 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
605 struct NSStringMapHash :
606 std::unary_function<NSString *, size_t>
608 _finline size_t operator ()(NSString *value) const {
609 return CFStringHashNSString((CFStringRef) value);
613 struct NSStringMapLess :
614 std::binary_function<NSString *, NSString *, bool>
616 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
617 return [lhs compare:rhs] == NSOrderedAscending;
621 struct NSStringMapEqual :
622 std::binary_function<NSString *, NSString *, bool>
624 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
625 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
626 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
627 //[lhs isEqualToString:rhs];
632 /* CoreGraphics Primitives {{{ */
637 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
638 CGFloat color[] = {red, green, blue, alpha};
639 return CGColorCreate(space, color);
648 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
649 color_(Create_(space, red, green, blue, alpha))
651 Set(space, red, green, blue, alpha);
656 CGColorRelease(color_);
663 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
665 color_ = Create_(space, red, green, blue, alpha);
668 operator CGColorRef() {
674 /* Random Global Variables {{{ */
675 static int PulseInterval_ = 500000;
677 static const NSString *UI_;
680 static bool RestartSubstrate_;
681 static NSArray *Finishes_;
683 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
684 #define NotifyConfig_ "/etc/notify.conf"
686 static bool Queuing_;
688 static CYColor Blue_;
689 static CYColor Blueish_;
690 static CYColor Black_;
691 static CYColor Folder_;
693 static CYColor White_;
694 static CYColor Gray_;
695 static CYColor Green_;
696 static CYColor Purple_;
697 static CYColor Purplish_;
699 static UIColor *InstallingColor_;
700 static UIColor *RemovingColor_;
702 static NSString *App_;
704 static BOOL Advanced_;
705 static BOOL Ignored_;
707 static _H<UIFont> Font12_;
708 static _H<UIFont> Font12Bold_;
709 static _H<UIFont> Font14_;
710 static _H<UIFont> Font18_;
711 static _H<UIFont> Font18Bold_;
712 static _H<UIFont> Font22Bold_;
714 static const char *Machine_ = NULL;
715 static _H<NSString> System_;
716 static NSString *SerialNumber_ = nil;
717 static NSString *ChipID_ = nil;
718 static NSString *BBSNum_ = nil;
719 static _H<NSString> Token_;
720 static _H<NSString> UniqueID_;
721 static _H<NSString> UserAgent_;
722 static _H<NSString> Product_;
723 static _H<NSString> Safari_;
725 static _H<NSLocale> CollationLocale_;
726 static _H<NSArray> CollationThumbs_;
727 static std::vector<NSInteger> CollationOffset_;
728 static _H<NSArray> CollationTitles_;
729 static _H<NSArray> CollationStarts_;
730 static UTransliterator *CollationTransl_;
731 //static Function<NSString *, NSString *> CollationModify_;
733 typedef std::basic_string<UChar> ustring;
734 static ustring CollationString_;
736 #define CUC const ustring &str(*reinterpret_cast<const ustring *>(rep))
737 #define UC ustring &str(*reinterpret_cast<ustring *>(rep))
738 static struct UReplaceableCallbacks CollationUCalls_ = {
739 .length = [](const UReplaceable *rep) -> int32_t { CUC;
743 .charAt = [](const UReplaceable *rep, int32_t offset) -> UChar { CUC;
744 //fprintf(stderr, "charAt(%d) : %d\n", offset, str.size());
745 if (offset >= str.size())
750 .char32At = [](const UReplaceable *rep, int32_t offset) -> UChar32 { CUC;
751 //fprintf(stderr, "char32At(%d) : %d\n", offset, str.size());
752 if (offset >= str.size())
755 U16_GET(str.data(), 0, offset, str.size(), c);
759 .replace = [](UReplaceable *rep, int32_t start, int32_t limit, const UChar *text, int32_t length) -> void { UC;
760 //fprintf(stderr, "replace(%d, %d, %d) : %d\n", start, limit, length, str.size());
761 str.replace(start, limit - start, text, length);
764 .extract = [](UReplaceable *rep, int32_t start, int32_t limit, UChar *dst) -> void { UC;
765 //fprintf(stderr, "extract(%d, %d) : %d\n", start, limit, str.size());
766 str.copy(dst, limit - start, start);
769 .copy = [](UReplaceable *rep, int32_t start, int32_t limit, int32_t dest) -> void { UC;
770 //fprintf(stderr, "copy(%d, %d, %d) : %d\n", start, limit, dest, str.size());
771 str.replace(dest, 0, str, start, limit - start);
775 static CFLocaleRef Locale_;
776 static NSArray *Languages_;
777 static CGColorSpaceRef space_;
779 static NSDictionary *SectionMap_;
780 static NSMutableDictionary *Metadata_;
781 static _transient NSMutableDictionary *Settings_;
782 static _transient NSMutableDictionary *Packages_;
783 static _transient NSMutableDictionary *Values_;
784 static _transient NSMutableDictionary *Sections_;
785 _H<NSMutableDictionary> Sources_;
786 static _transient NSNumber *Version_;
791 static CGFloat ScreenScale_;
792 static NSString *Idiom_;
793 static _H<NSString> Firmware_;
794 static NSString *Major_;
796 static _H<NSMutableDictionary> SessionData_;
797 static _H<NSObject> HostConfig_;
798 static _H<NSMutableSet> BridgedHosts_;
799 static _H<NSMutableSet> TokenHosts_;
800 static _H<NSMutableSet> InsecureHosts_;
801 static _H<NSMutableSet> PipelinedHosts_;
802 static _H<NSMutableSet> CachedURLs_;
804 static NSString *kCydiaProgressEventTypeError = @"Error";
805 static NSString *kCydiaProgressEventTypeInformation = @"Information";
806 static NSString *kCydiaProgressEventTypeStatus = @"Status";
807 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
810 /* Display Helpers {{{ */
811 inline float Interpolate(float begin, float end, float fraction) {
812 return (end - begin) * fraction + begin;
815 static inline double Retina(double value) {
816 value *= ScreenScale_;
817 value = round(value);
818 value /= ScreenScale_;
822 static inline CGRect Retina(CGRect value) {
823 value.origin.x *= ScreenScale_;
824 value.origin.y *= ScreenScale_;
825 value.size.width *= ScreenScale_;
826 value.size.height *= ScreenScale_;
827 value = CGRectIntegral(value);
828 value.origin.x /= ScreenScale_;
829 value.origin.y /= ScreenScale_;
830 value.size.width /= ScreenScale_;
831 value.size.height /= ScreenScale_;
835 static _finline const char *StripVersion_(const char *version) {
836 const char *colon(strchr(version, ':'));
837 return colon == NULL ? version : colon + 1;
840 NSString *LocalizeSection(NSString *section) {
841 static Pcre title_r("^(.*?) \\((.*)\\)$");
842 if (title_r(section)) {
843 NSString *parent(title_r[1]);
844 NSString *child(title_r[2]);
846 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
847 LocalizeSection(parent),
848 LocalizeSection(child)
852 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
855 NSString *Simplify(NSString *title) {
856 const char *data = [title UTF8String];
857 size_t size = [title lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
859 static Pcre square_r("^\\[(.*)\\]$");
860 if (square_r(data, size))
861 return Simplify(square_r[1]);
863 static Pcre paren_r("^\\((.*)\\)$");
864 if (paren_r(data, size))
865 return Simplify(paren_r[1]);
867 static Pcre title_r("^(.*?) \\((.*)\\)$");
868 if (title_r(data, size))
869 return Simplify(title_r[1]);
875 NSString *GetLastUpdate() {
876 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
879 return UCLocalize("NEVER_OR_UNKNOWN");
881 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
882 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
884 CFRelease(formatter);
886 return [(NSString *) formatted autorelease];
889 bool isSectionVisible(NSString *section) {
890 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
891 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
892 return hidden == nil || ![hidden boolValue];
895 static NSObject *CYIOGetValue(const char *path, NSString *property) {
896 io_registry_entry_t entry(IORegistryEntryFromPath(kIOMasterPortDefault, path));
897 if (entry == MACH_PORT_NULL)
900 CFTypeRef value(IORegistryEntryCreateCFProperty(entry, (CFStringRef) property, kCFAllocatorDefault, 0));
901 IOObjectRelease(entry);
905 return [(id) value autorelease];
908 static NSString *CYHex(NSData *data, bool reverse = false) {
912 size_t length([data length]);
913 uint8_t bytes[length];
914 [data getBytes:bytes];
916 char string[length * 2 + 1];
917 for (size_t i(0); i != length; ++i)
918 sprintf(string + i * 2, "%.2x", bytes[reverse ? length - i - 1 : i]);
920 return [NSString stringWithUTF8String:string];
925 /* Delegate Prototypes {{{ */
928 @class CydiaProgressEvent;
930 @protocol DatabaseDelegate
931 - (void) repairWithSelector:(SEL)selector;
932 - (void) setConfigurationData:(NSString *)data;
933 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
936 @class CYPackageController;
938 @protocol SourceDelegate
939 - (void) setFetch:(NSNumber *)fetch;
942 @protocol FetchDelegate
943 - (bool) isSourceCancelled;
944 - (void) startSourceFetch:(NSString *)uri;
945 - (void) stopSourceFetch:(NSString *)uri;
948 @protocol CydiaDelegate
949 - (void) returnToCydia;
951 - (void) retainNetworkActivityIndicator;
952 - (void) releaseNetworkActivityIndicator;
953 - (void) clearPackage:(Package *)package;
954 - (void) installPackage:(Package *)package;
955 - (void) installPackages:(NSArray *)packages;
956 - (void) removePackage:(Package *)package;
957 - (void) beginUpdate;
959 - (bool) requestUpdate;
960 - (void) distUpgrade;
963 - (void) _saveConfig;
965 - (void) addSource:(NSDictionary *)source;
966 - (void) addTrivialSource:(NSString *)href;
967 - (UIProgressHUD *) addProgressHUD;
968 - (void) removeProgressHUD:(UIProgressHUD *)hud;
969 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
970 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
974 /* CancelStatus {{{ */
976 public pkgAcquireStatus
987 virtual bool MediaChange(std::string media, std::string drive) {
991 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
995 virtual bool Pulse_(pkgAcquire *Owner) = 0;
997 virtual bool Pulse(pkgAcquire *Owner) {
998 if (pkgAcquireStatus::Pulse(Owner) && Pulse_(Owner))
1006 _finline bool WasCancelled() const {
1011 /* DelegateStatus {{{ */
1016 _transient NSObject<ProgressDelegate> *delegate_;
1024 void setDelegate(NSObject<ProgressDelegate> *delegate) {
1025 delegate_ = delegate;
1028 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1029 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1030 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
1031 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1034 virtual void Done(pkgAcquire::ItemDesc &item) {
1035 NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1036 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:Colon_, UCLocalize("DONE"), name] ofType:kCydiaProgressEventTypeStatus forItem:item]);
1037 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1040 virtual void Fail(pkgAcquire::ItemDesc &item) {
1042 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1043 item.Owner->Status == pkgAcquire::Item::StatDone
1047 std::string &error(item.Owner->ErrorText);
1051 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItem:item]);
1052 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1055 virtual bool Pulse_(pkgAcquire *Owner) {
1057 double(CurrentBytes + CurrentItems) /
1058 double(TotalBytes + TotalItems)
1061 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
1062 [NSNumber numberWithDouble:percent], @"Percent",
1064 [NSNumber numberWithDouble:CurrentBytes], @"Current",
1065 [NSNumber numberWithDouble:TotalBytes], @"Total",
1066 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
1067 nil] waitUntilDone:YES];
1069 return ![delegate_ isProgressCancelled];
1072 virtual void Start() {
1073 pkgAcquireStatus::Start();
1074 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
1077 virtual void Stop() {
1078 pkgAcquireStatus::Stop();
1079 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
1080 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
1084 /* Database Interface {{{ */
1085 typedef std::map< unsigned long, _H<Source> > SourceMap;
1087 @interface Database : NSObject {
1093 pkgCacheFile cache_;
1094 pkgDepCache::Policy *policy_;
1095 pkgRecords *records_;
1096 pkgProblemResolver *resolver_;
1097 pkgAcquire *fetcher_;
1099 SPtr<pkgPackageManager> manager_;
1100 pkgSourceList *list_;
1102 SourceMap sourceMap_;
1103 _H<NSMutableArray> sourceList_;
1105 CFMutableArrayRef packages_;
1107 _transient NSObject<DatabaseDelegate> *delegate_;
1108 _transient NSObject<ProgressDelegate> *progress_;
1110 CydiaStatus status_;
1116 std::map<const char *, _H<NSString> > sections_;
1119 + (Database *) sharedInstance;
1122 - (void) _readCydia:(NSNumber *)fd;
1123 - (void) _readStatus:(NSNumber *)fd;
1124 - (void) _readOutput:(NSNumber *)fd;
1128 - (Package *) packageWithName:(NSString *)name;
1130 - (pkgCacheFile &) cache;
1131 - (pkgDepCache::Policy *) policy;
1132 - (pkgRecords *) records;
1133 - (pkgProblemResolver *) resolver;
1134 - (pkgAcquire &) fetcher;
1135 - (pkgSourceList &) list;
1136 - (NSArray *) packages;
1137 - (NSArray *) sources;
1138 - (Source *) sourceWithKey:(NSString *)key;
1139 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1147 - (void) updateWithStatus:(CancelStatus &)status;
1149 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1151 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1152 - (NSObject<ProgressDelegate> *) progressDelegate;
1154 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1155 - (void) setFetch:(bool)fetch forURI:(const char *)uri;
1156 - (void) resetFetch;
1158 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1162 /* SourceStatus {{{ */
1163 class SourceStatus :
1167 _transient NSObject<FetchDelegate> *delegate_;
1168 _transient Database *database_;
1171 SourceStatus(NSObject<FetchDelegate> *delegate, Database *database) :
1172 delegate_(delegate),
1177 void Set(bool fetch, pkgAcquire::ItemDesc &desc) {
1179 [database_ setFetch:fetch forURI:desc.Owner->DescURI().c_str()];
1182 virtual void Fetch(pkgAcquire::ItemDesc &desc) {
1186 virtual void Done(pkgAcquire::ItemDesc &desc) {
1190 virtual void Fail(pkgAcquire::ItemDesc &desc) {
1194 virtual bool Pulse_(pkgAcquire *Owner) {
1195 for (pkgAcquire::ItemCIterator item = Owner->ItemsBegin(); item != Owner->ItemsEnd(); ++item)
1196 if ((*item)->ID != 0);
1197 else if ((*item)->Status == pkgAcquire::Item::StatIdle) {
1199 [database_ setFetch:true forURI:(*item)->DescURI().c_str()];
1200 } else (*item)->ID = 0;
1201 return ![delegate_ isSourceCancelled];
1204 virtual void Stop() {
1205 pkgAcquireStatus::Stop();
1206 [database_ resetFetch];
1210 /* ProgressEvent Implementation {{{ */
1211 @implementation CydiaProgressEvent
1213 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1214 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1217 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1218 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1219 [event setPackage:package];
1223 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItem:(pkgAcquire::ItemDesc &)item {
1224 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1226 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1227 NSArray *fields([description componentsSeparatedByString:@" "]);
1228 [event setItem:fields];
1230 if ([fields count] > 3) {
1231 [event setPackage:[fields objectAtIndex:2]];
1232 [event setVersion:[fields objectAtIndex:3]];
1235 [event setURL:[NSString stringWithUTF8String:item.URI.c_str()]];
1240 + (NSArray *) _attributeKeys {
1241 return [NSArray arrayWithObjects:
1251 - (NSArray *) attributeKeys {
1252 return [[self class] _attributeKeys];
1255 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1256 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1259 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1260 if ((self = [super init]) != nil) {
1266 - (NSString *) message {
1270 - (NSString *) type {
1274 - (NSArray *) item {
1275 return (id) item_ ?: [NSNull null];
1278 - (void) setItem:(NSArray *)item {
1282 - (NSString *) package {
1283 return (id) package_ ?: [NSNull null];
1286 - (void) setPackage:(NSString *)package {
1290 - (NSString *) url {
1291 return (id) url_ ?: [NSNull null];
1294 - (void) setURL:(NSString *)url {
1298 - (void) setVersion:(NSString *)version {
1302 - (NSString *) version {
1303 return (id) version_ ?: [NSNull null];
1306 - (NSString *) compound:(NSString *)value {
1308 NSString *mode(nil); {
1309 NSString *type([self type]);
1310 if ([type isEqualToString:kCydiaProgressEventTypeError])
1311 mode = UCLocalize("ERROR");
1312 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1313 mode = UCLocalize("WARNING");
1317 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1323 - (NSString *) compoundMessage {
1324 return [self compound:[self message]];
1327 - (NSString *) compoundTitle {
1330 if (package_ == nil)
1332 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1333 title = [package name];
1337 return [self compound:title];
1343 // Cytore Definitions {{{
1344 struct PackageValue :
1347 Cytore::Offset<PackageValue> next_;
1349 uint32_t index_ : 23;
1350 uint32_t subscribed_ : 1;
1367 Cytore::Offset<PackageValue> packages_[1 << 16];
1370 static Cytore::File<MetaValue> MetaFile_;
1372 // Cytore Helper Functions {{{
1373 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1374 SplitHash nhash = { hashlittle(name, length) };
1376 PackageValue *metadata;
1378 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1379 for (;; offset = &metadata->next_) { if (offset->IsNull()) {
1380 *offset = MetaFile_.New<PackageValue>(length + 1);
1381 metadata = &MetaFile_.Get(*offset);
1383 if (metadata == NULL) {
1387 metadata = new PackageValue();
1388 memset(metadata, 0, sizeof(*metadata));
1391 memcpy(metadata->name_, name, length);
1392 metadata->name_[length] = '\0';
1393 metadata->nhash_ = nhash.u16[1];
1395 metadata = &MetaFile_.Get(*offset);
1396 if (metadata->nhash_ != nhash.u16[1])
1398 if (strncmp(metadata->name_, name, length) != 0)
1400 if (metadata->name_[length] != '\0')
1407 static void PackageImport(const void *key, const void *value, void *context) {
1408 bool &fail(*reinterpret_cast<bool *>(context));
1411 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1412 NSLog(@"failed to import package %@", key);
1416 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1417 NSDictionary *package((NSDictionary *) value);
1419 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1420 if ([subscribed boolValue] && !metadata->subscribed_)
1421 metadata->subscribed_ = true;
1423 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1424 time_t time([date timeIntervalSince1970]);
1425 if (metadata->first_ > time || metadata->first_ == 0)
1426 metadata->first_ = time;
1429 NSDate *date([package objectForKey:@"LastSeen"]);
1430 NSString *version([package objectForKey:@"LastVersion"]);
1432 if (date != nil && version != nil) {
1433 time_t time([date timeIntervalSince1970]);
1434 if (metadata->last_ < time || metadata->last_ == 0)
1435 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1436 size_t length(strlen(buffer));
1437 uint16_t vhash(hashlittle(buffer, length));
1439 size_t capped(std::min<size_t>(8, length));
1440 char *latest(buffer + length - capped);
1442 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1443 metadata->vhash_ = vhash;
1445 metadata->last_ = time;
1451 /* Source Class {{{ */
1452 @interface Source : NSObject {
1454 Database *database_;
1457 CYString depiction_;
1458 CYString description_;
1464 CYString distribution_;
1470 _H<NSString> authority_;
1472 CYString defaultIcon_;
1474 _H<NSMutableDictionary> record_;
1477 std::set<std::string> fetches_;
1478 std::set<std::string> files_;
1479 _transient NSObject<SourceDelegate> *delegate_;
1482 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool;
1484 - (NSComparisonResult) compareByName:(Source *)source;
1486 - (NSString *) depictionForPackage:(NSString *)package;
1487 - (NSString *) supportForPackage:(NSString *)package;
1489 - (metaIndex *) metaIndex;
1490 - (NSDictionary *) record;
1493 - (NSString *) rooturi;
1494 - (NSString *) distribution;
1495 - (NSString *) type;
1498 - (NSString *) host;
1500 - (NSString *) name;
1501 - (NSString *) shortDescription;
1502 - (NSString *) label;
1503 - (NSString *) origin;
1504 - (NSString *) version;
1506 - (NSString *) defaultIcon;
1507 - (NSURL *) iconURL;
1509 - (void) setFetch:(bool)fetch forURI:(const char *)uri;
1510 - (void) resetFetch;
1514 @implementation Source
1516 + (NSString *) webScriptNameForSelector:(SEL)selector {
1518 else if (selector == @selector(addSection:))
1519 return @"addSection";
1520 else if (selector == @selector(getField:))
1522 else if (selector == @selector(removeSection:))
1523 return @"removeSection";
1524 else if (selector == @selector(remove))
1530 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1531 return [self webScriptNameForSelector:selector] == nil;
1534 + (NSArray *) _attributeKeys {
1535 return [NSArray arrayWithObjects:
1546 @"shortDescription",
1553 - (NSArray *) attributeKeys {
1554 return [[self class] _attributeKeys];
1557 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1558 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1561 - (metaIndex *) metaIndex {
1565 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1566 trusted_ = index->IsTrusted();
1568 uri_.set(pool, index->GetURI());
1569 distribution_.set(pool, index->GetDist());
1570 type_.set(pool, index->GetType());
1572 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1573 if (dindex != NULL) {
1574 std::string file(dindex->MetaIndexURI(""));
1575 base_.set(pool, file);
1578 _profile(Source$setMetaIndex$GetIndexes)
1579 dindex->GetIndexes(&acquire, true);
1581 _profile(Source$setMetaIndex$DescURI)
1582 for (pkgAcquire::ItemIterator item(acquire.ItemsBegin()); item != acquire.ItemsEnd(); item++) {
1583 std::string file((*item)->DescURI());
1584 files_.insert(file);
1585 if (file.length() < sizeof("Packages.bz2") || file.substr(file.length() - sizeof("Packages.bz2")) != "/Packages.bz2")
1587 file = file.substr(0, file.length() - 4);
1588 files_.insert(file);
1589 files_.insert(file + ".gz");
1590 files_.insert(file + "Index");
1595 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1598 pkgTagFile tags(&fd);
1600 pkgTagSection section;
1607 {"default-icon", &defaultIcon_},
1608 {"depiction", &depiction_},
1609 {"description", &description_},
1611 {"origin", &origin_},
1612 {"support", &support_},
1613 {"version", &version_},
1616 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1617 const char *start, *end;
1619 if (section.Find(names[i].name_, start, end)) {
1620 CYString &value(*names[i].value_);
1621 value.set(pool, start, end - start);
1627 record_ = [Sources_ objectForKey:[self key]];
1629 NSURL *url([NSURL URLWithString:uri_]);
1633 host_ = [host_ lowercaseString];
1638 authority_ = [url path];
1641 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool {
1642 if ((self = [super init]) != nil) {
1643 era_ = [database era];
1644 database_ = database;
1647 _profile(Source$initWithMetaIndex$setMetaIndex)
1648 [self setMetaIndex:index inPool:pool];
1653 - (NSString *) getField:(NSString *)name {
1654 @synchronized (database_) {
1655 if ([database_ era] != era_ || index_ == NULL)
1658 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index_));
1663 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly)) {
1668 pkgTagFile tags(&fd);
1670 pkgTagSection section;
1673 const char *start, *end;
1674 if (!section.Find([name UTF8String], start, end))
1675 return (NSString *) [NSNull null];
1677 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
1680 - (NSComparisonResult) compareByName:(Source *)source {
1681 NSString *lhs = [self name];
1682 NSString *rhs = [source name];
1684 if ([lhs length] != 0 && [rhs length] != 0) {
1685 unichar lhc = [lhs characterAtIndex:0];
1686 unichar rhc = [rhs characterAtIndex:0];
1688 if (isalpha(lhc) && !isalpha(rhc))
1689 return NSOrderedAscending;
1690 else if (!isalpha(lhc) && isalpha(rhc))
1691 return NSOrderedDescending;
1694 return [lhs compare:rhs options:LaxCompareOptions_];
1697 - (NSString *) depictionForPackage:(NSString *)package {
1698 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1701 - (NSString *) supportForPackage:(NSString *)package {
1702 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1705 - (NSArray *) sections {
1706 return record_ == nil ? (id) [NSNull null] : [record_ objectForKey:@"Sections"] ?: [NSArray array];
1709 - (void) _addSection:(NSString *)section {
1712 else if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) {
1713 if (![sections containsObject:section]) {
1714 [sections addObject:section];
1718 [record_ setObject:[NSMutableArray arrayWithObject:section] forKey:@"Sections"];
1723 - (bool) addSection:(NSString *)section {
1727 [self performSelectorOnMainThread:@selector(_addSection:) withObject:section waitUntilDone:NO];
1731 - (void) _removeSection:(NSString *)section {
1735 if (NSMutableArray *sections = [record_ objectForKey:@"Sections"])
1736 if ([sections containsObject:section]) {
1737 [sections removeObject:section];
1742 - (bool) removeSection:(NSString *)section {
1746 [self performSelectorOnMainThread:@selector(_removeSection:) withObject:section waitUntilDone:NO];
1751 [Sources_ removeObjectForKey:[self key]];
1756 bool value(record_ != nil);
1757 [self performSelectorOnMainThread:@selector(_remove) withObject:nil waitUntilDone:NO];
1761 - (NSDictionary *) record {
1769 - (NSString *) rooturi {
1773 - (NSString *) distribution {
1774 return distribution_;
1777 - (NSString *) type {
1781 - (NSString *) baseuri {
1782 return base_.empty() ? nil : (id) base_;
1785 - (NSString *) iconuri {
1786 if (NSString *base = [self baseuri])
1787 return [base stringByAppendingString:@"CydiaIcon.png"];
1792 - (NSURL *) iconURL {
1793 if (NSString *uri = [self iconuri])
1794 return [NSURL URLWithString:uri];
1798 - (NSString *) key {
1799 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1802 - (NSString *) host {
1806 - (NSString *) name {
1807 return origin_.empty() ? (id) authority_ : origin_;
1810 - (NSString *) shortDescription {
1811 return description_;
1814 - (NSString *) label {
1815 return label_.empty() ? (id) authority_ : label_;
1818 - (NSString *) origin {
1822 - (NSString *) version {
1826 - (NSString *) defaultIcon {
1827 return defaultIcon_;
1830 - (void) setDelegate:(NSObject<SourceDelegate> *)delegate {
1831 delegate_ = delegate;
1835 return !fetches_.empty();
1838 - (void) setFetch:(bool)fetch forURI:(const char *)uri {
1840 if (fetches_.erase(uri) == 0)
1842 } else if (files_.find(uri) == files_.end())
1844 else if (!fetches_.insert(uri).second)
1847 [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:[self fetch]] waitUntilDone:NO];
1850 - (void) resetFetch {
1852 [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:NO];
1857 /* CydiaOperation Class {{{ */
1858 @interface CydiaOperation : NSObject {
1859 _H<NSString> operator_;
1860 _H<NSString> value_;
1863 - (NSString *) operator;
1864 - (NSString *) value;
1868 @implementation CydiaOperation
1870 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1871 if ((self = [super init]) != nil) {
1872 operator_ = [NSString stringWithUTF8String:_operator];
1873 value_ = [NSString stringWithUTF8String:value];
1877 + (NSArray *) _attributeKeys {
1878 return [NSArray arrayWithObjects:
1884 - (NSArray *) attributeKeys {
1885 return [[self class] _attributeKeys];
1888 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1889 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1892 - (NSString *) operator {
1896 - (NSString *) value {
1902 /* CydiaClause Class {{{ */
1903 @interface CydiaClause : NSObject {
1904 _H<NSString> package_;
1905 _H<CydiaOperation> version_;
1908 - (NSString *) package;
1909 - (CydiaOperation *) version;
1913 @implementation CydiaClause
1915 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1916 if ((self = [super init]) != nil) {
1917 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1919 if (const char *version = dep.TargetVer())
1920 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1922 version_ = (id) [NSNull null];
1926 + (NSArray *) _attributeKeys {
1927 return [NSArray arrayWithObjects:
1933 - (NSArray *) attributeKeys {
1934 return [[self class] _attributeKeys];
1937 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1938 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1941 - (NSString *) package {
1945 - (CydiaOperation *) version {
1951 /* CydiaRelation Class {{{ */
1952 @interface CydiaRelation : NSObject {
1953 _H<NSString> relationship_;
1954 _H<NSMutableArray> clauses_;
1957 - (NSString *) relationship;
1958 - (NSArray *) clauses;
1962 @implementation CydiaRelation
1964 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1965 if ((self = [super init]) != nil) {
1966 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
1967 clauses_ = [NSMutableArray arrayWithCapacity:8];
1969 pkgCache::DepIterator start;
1970 pkgCache::DepIterator end;
1971 dep.GlobOr(start, end); // ++dep
1974 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
1976 // yes, seriously. (wtf?)
1984 + (NSArray *) _attributeKeys {
1985 return [NSArray arrayWithObjects:
1991 - (NSArray *) attributeKeys {
1992 return [[self class] _attributeKeys];
1995 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1996 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1999 - (NSString *) relationship {
2000 return relationship_;
2003 - (NSArray *) clauses {
2007 - (void) addClause:(CydiaClause *)clause {
2008 [clauses_ addObject:clause];
2013 /* Package Class {{{ */
2014 struct ParsedPackage {
2018 CYString architecture_;
2021 CYString depiction_;
2028 @interface Package : NSObject {
2030 @public uint32_t role_ : 3;
2031 uint32_t essential_ : 1;
2032 uint32_t obsolete_ : 1;
2033 uint32_t ignored_ : 1;
2034 uint32_t pooled_ : 1;
2040 _transient Database *database_;
2042 pkgCache::VerIterator version_;
2043 pkgCache::PkgIterator iterator_;
2044 pkgCache::VerFileIterator file_;
2048 CYString transform_;
2051 CYString installed_;
2054 const char *section_;
2055 _transient NSString *section$_;
2059 PackageValue *metadata_;
2060 ParsedPackage *parsed_;
2062 _H<NSMutableArray> tags_;
2065 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
2066 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
2068 - (pkgCache::PkgIterator) iterator;
2071 - (NSString *) section;
2072 - (NSString *) simpleSection;
2074 - (NSString *) longSection;
2075 - (NSString *) shortSection;
2079 - (MIMEAddress *) maintainer;
2081 - (NSString *) longDescription;
2082 - (NSString *) shortDescription;
2085 - (PackageValue *) metadata;
2088 - (bool) subscribed;
2089 - (bool) setSubscribed:(bool)subscribed;
2093 - (NSString *) latest;
2094 - (NSString *) installed;
2095 - (BOOL) uninstalled;
2098 - (BOOL) upgradableAndEssential:(BOOL)essential;
2101 - (BOOL) unfiltered;
2105 - (BOOL) halfConfigured;
2106 - (BOOL) halfInstalled;
2108 - (NSString *) mode;
2111 - (NSString *) name;
2113 - (NSString *) homepage;
2114 - (NSString *) depiction;
2115 - (MIMEAddress *) author;
2117 - (NSString *) support;
2119 - (NSArray *) files;
2120 - (NSArray *) warnings;
2121 - (NSArray *) applications;
2123 - (Source *) source;
2126 - (BOOL) matches:(NSArray *)query;
2128 - (BOOL) hasTag:(NSString *)tag;
2129 - (NSString *) primaryPurpose;
2130 - (NSArray *) purposes;
2131 - (bool) isCommercial;
2133 - (void) setIndex:(size_t)index;
2135 - (CYString &) cyname;
2137 - (uint32_t) compareBySection:(NSArray *)sections;
2144 uint32_t PackageChangesRadix(Package *self, void *) {
2149 uint32_t timestamp : 30;
2150 uint32_t ignored : 1;
2151 uint32_t upgradable : 1;
2155 bool upgradable([self upgradableAndEssential:YES]);
2156 value.bits.upgradable = upgradable ? 1 : 0;
2159 value.bits.timestamp = 0;
2160 value.bits.ignored = [self ignored] ? 0 : 1;
2161 value.bits.upgradable = 1;
2163 value.bits.timestamp = [self seen] >> 2;
2164 value.bits.ignored = 0;
2165 value.bits.upgradable = 0;
2168 return _not(uint32_t) - value.key;
2171 CYString &(*PackageName)(Package *self, SEL sel);
2173 uint32_t PackagePrefixRadix(Package *self, void *context) {
2174 size_t offset(reinterpret_cast<size_t>(context));
2175 CYString &name(PackageName(self, @selector(cyname)));
2177 size_t size(name.size());
2180 char *text(name.data());
2183 if (!isdigit(text[0]))
2187 while (size != digits && isdigit(text[digits]))
2195 if (offset == 0 && zeros != 0) {
2196 memset(data, '0', zeros);
2197 memcpy(data + zeros, text, 4 - zeros);
2199 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2200 if (size <= offset - zeros)
2203 text += offset - zeros;
2204 size -= offset - zeros;
2207 memcpy(data, text, 4);
2209 memcpy(data, text, size);
2210 memset(data + size, 0, 4 - size);
2213 for (size_t i(0); i != 4; ++i)
2214 if (isalpha(data[i]))
2222 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2224 /* XXX: ntohl may be more honest */
2225 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2228 CFComparisonResult StringNameCompare(CFStringRef lhn, CFStringRef rhn, size_t length) {
2229 _profile(PackageNameCompare)
2231 return rhn == NULL ? kCFCompareEqualTo : kCFCompareLessThan;
2232 else if (rhn == NULL)
2233 return kCFCompareGreaterThan;
2235 CFIndex length(CFStringGetLength(lhn));
2237 _profile(PackageNameCompare$NumbersLast)
2238 if (length != 0 && CFStringGetLength(rhn) != 0) {
2239 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2240 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2241 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2242 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2243 return lha ? kCFCompareLessThan : kCFCompareGreaterThan;
2247 _profile(PackageNameCompare$Compare)
2248 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, (CFLocaleRef) (id) CollationLocale_);
2253 _finline CFComparisonResult StringNameCompare(NSString *lhn, NSString*rhn, size_t length) {
2254 return StringNameCompare((CFStringRef) lhn, (CFStringRef) rhn, length);
2257 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2258 CYString &lhn(PackageName(lhs, @selector(cyname)));
2259 NSString *rhn(PackageName(rhs, @selector(cyname)));
2260 return StringNameCompare(lhn, rhn, lhn.size());
2263 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *arg) {
2264 return PackageNameCompare(*lhs, *rhs, arg);
2267 struct PackageNameOrdering :
2268 std::binary_function<Package *, Package *, bool>
2270 _finline bool operator ()(Package *lhs, Package *rhs) const {
2271 return PackageNameCompare(lhs, rhs, NULL) == kCFCompareLessThan;
2275 @implementation Package
2277 - (NSString *) description {
2278 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2283 apr_pool_destroy(pool_);
2284 if (parsed_ != NULL)
2289 + (NSString *) webScriptNameForSelector:(SEL)selector {
2291 else if (selector == @selector(clear))
2293 else if (selector == @selector(getField:))
2295 else if (selector == @selector(getRecord))
2296 return @"getRecord";
2297 else if (selector == @selector(hasTag:))
2299 else if (selector == @selector(install))
2301 else if (selector == @selector(remove))
2307 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2308 return [self webScriptNameForSelector:selector] == nil;
2311 + (NSArray *) _attributeKeys {
2312 return [NSArray arrayWithObjects:
2333 @"shortDescription",
2346 - (NSArray *) attributeKeys {
2347 return [[self class] _attributeKeys];
2350 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2351 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2354 - (NSArray *) relations {
2355 @synchronized (database_) {
2356 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2357 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2358 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2362 - (NSString *) architecture {
2364 @synchronized (database_) {
2365 return parsed_->architecture_.empty() ? [NSNull null] : (id) parsed_->architecture_;
2368 - (NSString *) getField:(NSString *)name {
2369 @synchronized (database_) {
2370 if ([database_ era] != era_ || file_.end())
2373 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2375 const char *start, *end;
2376 if (!parser.Find([name UTF8String], start, end))
2377 return (NSString *) [NSNull null];
2379 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2382 - (NSString *) getRecord {
2383 @synchronized (database_) {
2384 if ([database_ era] != era_ || file_.end())
2387 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2389 const char *start, *end;
2390 parser.GetRec(start, end);
2392 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2396 if (parsed_ != NULL)
2398 @synchronized (database_) {
2399 if ([database_ era] != era_ || file_.end())
2402 ParsedPackage *parsed(new ParsedPackage);
2405 _profile(Package$parse)
2406 pkgRecords::Parser *parser;
2408 _profile(Package$parse$Lookup)
2409 parser = &[database_ records]->Lookup(file_);
2415 _profile(Package$parse$Find)
2420 {"architecture", &parsed->architecture_},
2421 {"icon", &parsed->icon_},
2422 {"depiction", &parsed->depiction_},
2423 {"homepage", &parsed->homepage_},
2424 {"website", &website},
2426 {"support", &parsed->support_},
2427 {"author", &parsed->author_},
2428 {"md5sum", &parsed->md5sum_},
2431 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2432 const char *start, *end;
2434 if (parser->Find(names[i].name_, start, end)) {
2435 CYString &value(*names[i].value_);
2436 _profile(Package$parse$Value)
2437 value.set(pool_, start, end - start);
2443 _profile(Package$parse$Tagline)
2444 const char *start, *end;
2445 if (parser->ShortDesc(start, end)) {
2446 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2449 while (stop != start && stop[-1] == '\r')
2451 parsed->tagline_.set(pool_, start, stop - start);
2455 _profile(Package$parse$Retain)
2456 if (parsed->homepage_.empty())
2457 parsed->homepage_ = website;
2458 if (parsed->homepage_ == parsed->depiction_)
2459 parsed->homepage_.clear();
2460 if (parsed->support_.empty())
2461 parsed->support_ = bugs;
2466 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2467 if ((self = [super init]) != nil) {
2468 _profile(Package$initWithVersion)
2470 apr_pool_create(&pool_, NULL);
2476 database_ = database;
2477 era_ = [database era];
2481 pkgCache::PkgIterator iterator(version.ParentPkg());
2482 iterator_ = iterator;
2484 _profile(Package$initWithVersion$Version)
2485 if (!version_.end())
2486 file_ = version_.FileList();
2488 pkgCache &cache([database_ cache]);
2489 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2493 _profile(Package$initWithVersion$Cache)
2494 name_.set(NULL, iterator.Display());
2496 latest_.set(NULL, StripVersion_(version_.VerStr()));
2498 pkgCache::VerIterator current(iterator.CurrentVer());
2500 installed_.set(NULL, StripVersion_(current.VerStr()));
2503 _profile(Package$initWithVersion$Transliterate) do {
2504 if (CollationTransl_ == NULL)
2509 _profile(Package$initWithVersion$Transliterate$utf8)
2510 const uint8_t *data(reinterpret_cast<const uint8_t *>(name_.data()));
2511 for (size_t i(0), e(name_.size()); i != e; ++i)
2512 if (data[i] >= 0x80)
2517 UErrorCode code(U_ZERO_ERROR);
2520 _profile(Package$initWithVersion$Transliterate$u_strFromUTF8WithSub)
2521 CollationString_.resize(name_.size());
2522 u_strFromUTF8WithSub(&CollationString_[0], CollationString_.size(), &length, name_.data(), name_.size(), 0xfffd, NULL, &code);
2523 if (!U_SUCCESS(code))
2525 CollationString_.resize(length);
2528 _profile(Package$initWithVersion$Transliterate$utrans_trans)
2529 length = CollationString_.size();
2530 utrans_trans(CollationTransl_, reinterpret_cast<UReplaceable *>(&CollationString_), &CollationUCalls_, 0, &length, &code);
2531 if (!U_SUCCESS(code))
2533 _assert(CollationString_.size() == length);
2536 _profile(Package$initWithVersion$Transliterate$u_strToUTF8WithSub$preflight)
2537 u_strToUTF8WithSub(NULL, 0, &length, CollationString_.data(), CollationString_.size(), 0xfffd, NULL, &code);
2538 if (code == U_BUFFER_OVERFLOW_ERROR)
2539 code = U_ZERO_ERROR;
2540 else if (!U_SUCCESS(code))
2545 _profile(Package$initWithVersion$Transliterate$apr_palloc)
2546 transform = static_cast<char *>(apr_palloc(pool_, length));
2548 _profile(Package$initWithVersion$Transliterate$u_strToUTF8WithSub$transform)
2549 u_strToUTF8WithSub(transform, length, NULL, CollationString_.data(), CollationString_.size(), 0xfffd, NULL, &code);
2550 if (!U_SUCCESS(code))
2554 transform_.set(NULL, transform, length);
2555 } while (false); _end
2557 _profile(Package$initWithVersion$Tags)
2558 pkgCache::TagIterator tag(iterator.TagList());
2560 tags_ = [NSMutableArray arrayWithCapacity:8];
2562 goto tag; for (; !tag.end(); ++tag) tag: {
2563 const char *name(tag.Name());
2564 NSString *string((NSString *) CYStringCreate(name));
2568 [tags_ addObject:[string autorelease]];
2570 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2571 if (strcmp(name + 6, "enduser") == 0)
2573 else if (strcmp(name + 6, "hacker") == 0)
2575 else if (strcmp(name + 6, "developer") == 0)
2577 else if (strcmp(name + 6, "cydia") == 0)
2583 if (strncmp(name, "cydia::", 7) == 0) {
2584 if (strcmp(name + 7, "essential") == 0)
2586 else if (strcmp(name + 7, "obsolete") == 0)
2593 _profile(Package$initWithVersion$Metadata)
2594 const char *mixed(iterator.Name());
2595 size_t size(strlen(mixed));
2596 static const size_t prefix(sizeof("/var/lib/dpkg/info/") - 1);
2597 char lower[prefix + size + 5 + 1];
2599 for (size_t i(0); i != size; ++i)
2600 lower[prefix + i] = mixed[i] | 0x20;
2602 if (!installed_.empty()) {
2603 memcpy(lower, "/var/lib/dpkg/info/", prefix);
2604 memcpy(lower + prefix + size, ".list", 6);
2606 if (stat(lower, &info) != -1)
2607 upgraded_ = info.st_birthtime;
2610 PackageValue *metadata(PackageFind(lower + prefix, size));
2611 metadata_ = metadata;
2613 id_.set(NULL, metadata->name_, size);
2615 const char *latest(version_.VerStr());
2616 size_t length(strlen(latest));
2618 uint16_t vhash(hashlittle(latest, length));
2620 size_t capped(std::min<size_t>(8, length));
2621 latest = latest + length - capped;
2623 if (metadata->first_ == 0)
2624 metadata->first_ = now_;
2626 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2627 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2628 metadata->vhash_ = vhash;
2629 metadata->last_ = now_;
2630 } else if (metadata->last_ == 0)
2631 metadata->last_ = metadata->first_;
2634 _profile(Package$initWithVersion$Section)
2635 section_ = version_.Section();
2638 _profile(Package$initWithVersion$Flags)
2639 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2640 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2645 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2646 pkgCache::VerIterator version;
2648 _profile(Package$packageWithIterator$GetCandidateVer)
2649 version = [database policy]->GetCandidateVer(iterator);
2657 _profile(Package$packageWithIterator$Allocate)
2658 package = [Package allocWithZone:zone];
2661 _profile(Package$packageWithIterator$Initialize)
2663 initWithVersion:version
2670 _profile(Package$packageWithIterator$Autorelease)
2671 package = [package autorelease];
2677 - (pkgCache::PkgIterator) iterator {
2681 - (NSString *) section {
2682 if (section$_ == nil) {
2683 if (section_ == NULL)
2686 _profile(Package$section$mappedSectionForPointer)
2687 section$_ = [database_ mappedSectionForPointer:section_];
2692 - (NSString *) simpleSection {
2693 if (NSString *section = [self section])
2694 return Simplify(section);
2699 - (NSString *) longSection {
2700 return LocalizeSection([self section]);
2703 - (NSString *) shortSection {
2704 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2707 - (NSString *) uri {
2710 pkgIndexFile *index;
2711 pkgCache::PkgFileIterator file(file_.File());
2712 if (![database_ list].FindIndex(file, index))
2714 return [NSString stringWithUTF8String:iterator_->Path];
2715 //return [NSString stringWithUTF8String:file.Site()];
2716 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2720 - (MIMEAddress *) maintainer {
2721 @synchronized (database_) {
2722 if ([database_ era] != era_ || file_.end())
2725 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2726 const std::string &maintainer(parser->Maintainer());
2727 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2730 - (NSString *) md5sum {
2731 return parsed_ == NULL ? nil : (id) parsed_->md5sum_;
2735 @synchronized (database_) {
2736 if ([database_ era] != era_ || version_.end())
2739 return version_->InstalledSize;
2742 - (NSString *) longDescription {
2743 @synchronized (database_) {
2744 if ([database_ era] != era_ || file_.end())
2747 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2748 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2750 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2751 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2752 if ([lines count] < 2)
2755 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2756 for (size_t i(1), e([lines count]); i != e; ++i) {
2757 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2758 [trimmed addObject:trim];
2761 return [trimmed componentsJoinedByString:@"\n"];
2764 - (NSString *) shortDescription {
2765 if (parsed_ != NULL)
2766 return static_cast<NSString *>(parsed_->tagline_);
2768 @synchronized (database_) {
2769 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2771 const char *start, *end;
2772 if (!parser.ShortDesc(start, end))
2775 if (end - start > 200)
2779 if (const char *stop = reinterpret_cast<const char *>(memchr(start, '\n', end - start)))
2782 while (end != start && end[-1] == '\r')
2786 return [(id) CYStringCreate(start, end - start) autorelease];
2790 _profile(Package$index)
2791 CFStringRef name((CFStringRef) [self name]);
2792 if (CFStringGetLength(name) == 0)
2794 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2795 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2797 return toupper(character);
2801 - (PackageValue *) metadata {
2806 PackageValue *metadata([self metadata]);
2807 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2810 - (bool) subscribed {
2811 return [self metadata]->subscribed_;
2814 - (bool) setSubscribed:(bool)subscribed {
2815 PackageValue *metadata([self metadata]);
2816 if (metadata->subscribed_ == subscribed)
2818 metadata->subscribed_ = subscribed;
2826 - (NSString *) latest {
2830 - (NSString *) installed {
2834 - (BOOL) uninstalled {
2835 return installed_.empty();
2839 return !version_.end();
2842 - (BOOL) upgradableAndEssential:(BOOL)essential {
2843 _profile(Package$upgradableAndEssential)
2844 pkgCache::VerIterator current(iterator_.CurrentVer());
2846 return essential && essential_;
2848 return !version_.end() && version_ != current;
2852 - (BOOL) essential {
2857 return [database_ cache][iterator_].InstBroken();
2860 - (BOOL) unfiltered {
2861 _profile(Package$unfiltered$obsolete)
2862 if (_unlikely(obsolete_))
2866 _profile(Package$unfiltered$role)
2867 if (_unlikely(role_ > 3))
2875 if (![self unfiltered])
2880 _profile(Package$visible$section)
2881 section = [self section];
2884 _profile(Package$visible$isSectionVisible)
2885 if (!isSectionVisible(section))
2893 unsigned char current(iterator_->CurrentState);
2894 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2897 - (BOOL) halfConfigured {
2898 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2901 - (BOOL) halfInstalled {
2902 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2906 @synchronized (database_) {
2907 if ([database_ era] != era_ || iterator_.end())
2910 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2911 return state.Mode != pkgDepCache::ModeKeep;
2914 - (NSString *) mode {
2915 @synchronized (database_) {
2916 if ([database_ era] != era_ || iterator_.end())
2919 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2921 switch (state.Mode) {
2922 case pkgDepCache::ModeDelete:
2923 if ((state.iFlags & pkgDepCache::Purge) != 0)
2927 case pkgDepCache::ModeKeep:
2928 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2929 return @"REINSTALL";
2930 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2934 case pkgDepCache::ModeInstall:
2935 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2936 return @"REINSTALL";
2937 else*/ switch (state.Status) {
2939 return @"DOWNGRADE";
2945 return @"NEW_INSTALL";
2956 - (NSString *) name {
2957 return name_.empty() ? id_ : name_;
2960 - (UIImage *) icon {
2961 NSString *section = [self simpleSection];
2964 if (parsed_ != NULL)
2965 if (NSString *href = parsed_->icon_)
2966 if ([href hasPrefix:@"file:///"])
2967 icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2968 if (icon == nil) if (section != nil)
2969 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]];
2970 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2971 if ([dicon hasPrefix:@"file:///"])
2972 icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
2974 icon = [UIImage applicationImageNamed:@"unknown.png"];
2978 - (NSString *) homepage {
2979 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2982 - (NSString *) depiction {
2983 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2986 - (MIMEAddress *) author {
2987 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
2990 - (NSString *) support {
2991 return parsed_ != NULL && !parsed_->support_.empty() ? parsed_->support_ : [[self source] supportForPackage:id_];
2994 - (NSArray *) files {
2995 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2996 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2999 fin.open([path UTF8String]);
3004 while (std::getline(fin, line))
3005 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
3010 - (NSString *) state {
3011 @synchronized (database_) {
3012 if ([database_ era] != era_ || file_.end())
3015 switch (iterator_->CurrentState) {
3016 case pkgCache::State::NotInstalled:
3017 return @"NotInstalled";
3018 case pkgCache::State::UnPacked:
3020 case pkgCache::State::HalfConfigured:
3021 return @"HalfConfigured";
3022 case pkgCache::State::HalfInstalled:
3023 return @"HalfInstalled";
3024 case pkgCache::State::ConfigFiles:
3025 return @"ConfigFiles";
3026 case pkgCache::State::Installed:
3027 return @"Installed";
3028 case pkgCache::State::TriggersAwaited:
3029 return @"TriggersAwaited";
3030 case pkgCache::State::TriggersPending:
3031 return @"TriggersPending";
3034 return (NSString *) [NSNull null];
3037 - (NSString *) selection {
3038 @synchronized (database_) {
3039 if ([database_ era] != era_ || file_.end())
3042 switch (iterator_->SelectedState) {
3043 case pkgCache::State::Unknown:
3045 case pkgCache::State::Install:
3047 case pkgCache::State::Hold:
3049 case pkgCache::State::DeInstall:
3050 return @"DeInstall";
3051 case pkgCache::State::Purge:
3055 return (NSString *) [NSNull null];
3058 - (NSArray *) warnings {
3059 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
3060 const char *name(iterator_.Name());
3062 size_t length(strlen(name));
3063 if (length < 2) invalid:
3064 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
3065 else for (size_t i(0); i != length; ++i)
3067 /* XXX: technically this is not allowed */
3068 (name[i] < 'A' || name[i] > 'Z') &&
3069 (name[i] < 'a' || name[i] > 'z') &&
3070 (name[i] < '0' || name[i] > '9') &&
3071 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
3074 if (strcmp(name, "cydia") != 0) {
3077 bool _private = false;
3079 bool dsstore = false;
3081 bool repository = [[self section] isEqualToString:@"Repositories"];
3083 if (NSArray *files = [self files])
3084 for (NSString *file in files)
3085 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
3087 else if (!user && [file isEqualToString:@"/User"])
3089 else if (!_private && [file isEqualToString:@"/private"])
3091 else if (!stash && [file isEqualToString:@"/var/stash"])
3093 else if (!dsstore && [file hasSuffix:@"/.DS_Store"])
3096 /* XXX: this is not sensitive enough. only some folders are valid. */
3097 if (cydia && !repository)
3098 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
3100 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
3102 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
3104 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
3106 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @".DS_Store"]];
3109 return [warnings count] == 0 ? nil : warnings;
3112 - (NSArray *) applications {
3113 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
3115 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
3117 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
3118 if (NSArray *files = [self files])
3119 for (NSString *file in files)
3120 if (application_r(file)) {
3121 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
3122 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
3123 if ([id isEqualToString:me])
3126 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
3128 display = application_r[1];
3130 NSString *bundle([file stringByDeletingLastPathComponent]);
3131 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
3132 // XXX: maybe this should check if this is really a string, not just for length
3133 if (icon == nil || ![icon respondsToSelector:@selector(length)] || [icon length] == 0)
3135 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
3137 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
3138 [applications addObject:application];
3140 [application addObject:id];
3141 [application addObject:display];
3142 [application addObject:url];
3145 return [applications count] == 0 ? nil : applications;
3148 - (Source *) source {
3149 if (source_ == nil) {
3150 @synchronized (database_) {
3151 if ([database_ era] != era_ || file_.end())
3152 source_ = (Source *) [NSNull null];
3154 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
3158 return source_ == (Source *) [NSNull null] ? nil : source_;
3161 - (time_t) upgraded {
3165 - (uint32_t) recent {
3166 return std::numeric_limits<uint32_t>::max() - upgraded_;
3173 - (BOOL) matches:(NSArray *)query {
3174 if (query == nil || [query count] == 0)
3183 string = [self name];
3184 length = [string length];
3187 for (NSString *term in query) {
3188 range = [string rangeOfString:term options:MatchCompareOptions_];
3189 if (range.location != NSNotFound)
3190 rank_ -= 6 * 1000000 / length;
3195 length = [string length];
3198 for (NSString *term in query) {
3199 range = [string rangeOfString:term options:MatchCompareOptions_];
3200 if (range.location != NSNotFound)
3201 rank_ -= 6 * 1000000 / length;
3205 string = [self shortDescription];
3206 length = [string length];
3207 NSUInteger stop(std::min<NSUInteger>(length, 200));
3210 for (NSString *term in query) {
3211 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
3212 if (range.location != NSNotFound)
3213 rank_ -= 2 * 100000;
3219 - (NSArray *) tags {
3223 - (BOOL) hasTag:(NSString *)tag {
3224 return tags_ == nil ? NO : [tags_ containsObject:tag];
3227 - (NSString *) primaryPurpose {
3228 for (NSString *tag in (NSArray *) tags_)
3229 if ([tag hasPrefix:@"purpose::"])
3230 return [tag substringFromIndex:9];
3234 - (NSArray *) purposes {
3235 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
3236 for (NSString *tag in (NSArray *) tags_)
3237 if ([tag hasPrefix:@"purpose::"])
3238 [purposes addObject:[tag substringFromIndex:9]];
3239 return [purposes count] == 0 ? nil : purposes;
3242 - (bool) isCommercial {
3243 return [self hasTag:@"cydia::commercial"];
3246 - (void) setIndex:(size_t)index {
3247 if (metadata_->index_ != index)
3248 metadata_->index_ = index;
3251 - (CYString &) cyname {
3252 return !transform_.empty() ? transform_ : !name_.empty() ? name_ : id_;
3255 - (uint32_t) compareBySection:(NSArray *)sections {
3256 NSString *section([self section]);
3257 for (size_t i(0), e([sections count]); i != e; ++i) {
3258 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3262 return _not(uint32_t);
3266 @synchronized (database_) {
3267 pkgProblemResolver *resolver = [database_ resolver];
3268 resolver->Clear(iterator_);
3270 pkgCacheFile &cache([database_ cache]);
3271 cache->SetReInstall(iterator_, false);
3272 cache->MarkKeep(iterator_, false);
3276 @synchronized (database_) {
3277 pkgProblemResolver *resolver = [database_ resolver];
3278 resolver->Clear(iterator_);
3279 resolver->Protect(iterator_);
3281 pkgCacheFile &cache([database_ cache]);
3282 cache->SetReInstall(iterator_, false);
3283 cache->MarkInstall(iterator_, false);
3285 pkgDepCache::StateCache &state((*cache)[iterator_]);
3286 if (!state.Install())
3287 cache->SetReInstall(iterator_, true);
3291 @synchronized (database_) {
3292 pkgProblemResolver *resolver = [database_ resolver];
3293 resolver->Clear(iterator_);
3294 resolver->Remove(iterator_);
3295 resolver->Protect(iterator_);
3297 pkgCacheFile &cache([database_ cache]);
3298 cache->SetReInstall(iterator_, false);
3299 cache->MarkDelete(iterator_, true);
3304 /* Section Class {{{ */
3305 @interface Section : NSObject {
3309 _H<NSString> localized_;
3312 - (NSComparisonResult) compareByLocalized:(Section *)section;
3313 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3314 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3315 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3317 - (NSString *) name;
3318 - (void) setName:(NSString *)name;
3324 - (void) addToCount;
3326 - (void) setCount:(size_t)count;
3327 - (NSString *) localized;
3331 @implementation Section
3333 - (NSComparisonResult) compareByLocalized:(Section *)section {
3334 NSString *lhs(localized_);
3335 NSString *rhs([section localized]);
3337 /*if ([lhs length] != 0 && [rhs length] != 0) {
3338 unichar lhc = [lhs characterAtIndex:0];
3339 unichar rhc = [rhs characterAtIndex:0];
3341 if (isalpha(lhc) && !isalpha(rhc))
3342 return NSOrderedAscending;
3343 else if (!isalpha(lhc) && isalpha(rhc))
3344 return NSOrderedDescending;
3347 return [lhs compare:rhs options:LaxCompareOptions_];
3350 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3351 if ((self = [self initWithName:name localize:NO]) != nil) {
3352 if (localized != nil)
3353 localized_ = localized;
3357 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3358 return [self initWithName:name row:0 localize:localize];
3361 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3362 if ((self = [super init]) != nil) {
3366 localized_ = LocalizeSection(name_);
3370 - (NSString *) name {
3374 - (void) setName:(NSString *)name {
3390 - (void) addToCount {
3394 - (void) setCount:(size_t)count {
3398 - (NSString *) localized {
3405 class CydiaLogCleaner :
3406 public pkgArchiveCleaner
3409 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3414 /* Database Implementation {{{ */
3415 @implementation Database
3417 + (Database *) sharedInstance {
3418 static _H<Database> instance;
3419 if (instance == nil)
3420 instance = [[[Database alloc] init] autorelease];
3428 - (void) releasePackages {
3429 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3430 CFArrayRemoveAllValues(packages_);
3434 // XXX: actually implement this thing
3436 [self releasePackages];
3437 apr_pool_destroy(pool_);
3438 NSRecycleZone(zone_);
3442 - (void) _readCydia:(NSNumber *)fd {
3443 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3444 std::istream is(&ib);
3447 static Pcre finish_r("^finish:([^:]*)$");
3449 while (std::getline(is, line)) {
3450 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3452 const char *data(line.c_str());
3453 size_t size = line.size();
3454 lprintf("C:%s\n", data);
3456 if (finish_r(data, size)) {
3457 NSString *finish = finish_r[1];
3458 int index = [Finishes_ indexOfObject:finish];
3459 if (index != INT_MAX && index > Finish_)
3469 - (void) _readStatus:(NSNumber *)fd {
3470 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3471 std::istream is(&ib);
3474 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3475 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3477 while (std::getline(is, line)) {
3478 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3480 const char *data(line.c_str());
3481 size_t size(line.size());
3482 lprintf("S:%s\n", data);
3484 if (conffile_r(data, size)) {
3485 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3486 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3487 } else if (strncmp(data, "status: ", 8) == 0) {
3488 // status: <package>: {unpacked,half-configured,installed}
3489 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3490 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3491 } else if (strncmp(data, "processing: ", 12) == 0) {
3492 // processing: configure: config-test
3493 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3494 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3495 } else if (pmstatus_r(data, size)) {
3496 std::string type([pmstatus_r[1] UTF8String]);
3498 NSString *package = pmstatus_r[2];
3499 if ([package isEqualToString:@"dpkg-exec"])
3502 float percent([pmstatus_r[3] floatValue]);
3503 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3505 NSString *string = pmstatus_r[4];
3507 if (type == "pmerror") {
3508 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3509 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3510 } else if (type == "pmstatus") {
3511 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3512 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3513 } else if (type == "pmconffile")
3514 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3516 lprintf("E:unknown pmstatus\n");
3518 lprintf("E:unknown status\n");
3526 - (void) _readOutput:(NSNumber *)fd {
3527 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3528 std::istream is(&ib);
3531 while (std::getline(is, line)) {
3532 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3534 lprintf("O:%s\n", line.c_str());
3536 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3537 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3549 - (Package *) packageWithName:(NSString *)name {
3552 @synchronized (self) {
3553 if (static_cast<pkgDepCache *>(cache_) == NULL)
3555 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3556 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:NULL database:self];
3560 if ((self = [super init]) != nil) {
3567 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3568 apr_pool_create(&pool_, NULL);
3570 size_t capacity(MetaFile_->active_);
3576 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3577 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3581 _assert(pipe(fds) != -1);
3584 _config->Set("APT::Keep-Fds::", cydiafd_);
3585 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3588 detachNewThreadSelector:@selector(_readCydia:)
3590 withObject:[NSNumber numberWithInt:fds[0]]
3593 _assert(pipe(fds) != -1);
3597 detachNewThreadSelector:@selector(_readStatus:)
3599 withObject:[NSNumber numberWithInt:fds[0]]
3602 _assert(pipe(fds) != -1);
3603 _assert(dup2(fds[0], 0) != -1);
3604 _assert(close(fds[0]) != -1);
3606 input_ = fdopen(fds[1], "a");
3608 _assert(pipe(fds) != -1);
3609 _assert(dup2(fds[1], 1) != -1);
3610 _assert(close(fds[1]) != -1);
3613 detachNewThreadSelector:@selector(_readOutput:)
3615 withObject:[NSNumber numberWithInt:fds[0]]
3620 - (pkgCacheFile &) cache {
3624 - (pkgDepCache::Policy *) policy {
3628 - (pkgRecords *) records {
3632 - (pkgProblemResolver *) resolver {
3636 - (pkgAcquire &) fetcher {
3640 - (pkgSourceList &) list {
3644 - (NSArray *) packages {
3645 return (NSArray *) packages_;
3648 - (NSArray *) sources {
3652 - (Source *) sourceWithKey:(NSString *)key {
3653 for (Source *source in [self sources]) {
3654 if ([[source key] isEqualToString:key])
3659 - (bool) popErrorWithTitle:(NSString *)title {
3662 while (!_error->empty()) {
3664 bool warning(!_error->PopMessage(error));
3669 size_t size(error.size());
3670 if (size == 0 || error[size - 1] != '\n')
3672 error.resize(size - 1);
3675 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3677 static Pcre no_pubkey("^GPG error:.* NO_PUBKEY .*$");
3678 if (warning && no_pubkey(error.c_str()))
3681 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3687 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3688 return [self popErrorWithTitle:title] || !success;
3691 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3692 @synchronized (self) {
3695 [self releasePackages];
3698 [sourceList_ removeAllObjects];
3718 apr_pool_clear(pool_);
3720 NSRecycleZone(zone_);
3721 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3723 int chk(creat("/tmp/cydia.chk", 0644));
3727 if (invocation != nil)
3728 [invocation invoke];
3730 NSString *title(UCLocalize("DATABASE"));
3732 list_ = new pkgSourceList();
3733 _profile(reloadDataWithInvocation$ReadMainList)
3734 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3738 _profile(reloadDataWithInvocation$Source$initWithMetaIndex)
3739 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3740 Source *object([[[Source alloc] initWithMetaIndex:*source forDatabase:self inPool:pool_] autorelease]);
3741 [sourceList_ addObject:object];
3746 OpProgress progress;
3749 _profile(reloadDataWithInvocation$pkgCacheFile)
3750 opened = cache_.Open(progress, true);
3753 // XXX: what if there are errors, but Open() == true? this should be merged with popError:
3754 while (!_error->empty()) {
3756 bool warning(!_error->PopMessage(error));
3758 lprintf("cache_.Open():[%s]\n", error.c_str());
3760 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3764 else if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3765 repair = @selector(configure);
3766 //else if (error == "The package lists or status file could not be parsed or opened.")
3767 // repair = @selector(update);
3768 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3769 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3770 // else if (error == "Malformed Status line")
3771 // else if (error == "The list of sources could not be read.")
3773 if (repair != NULL) {
3775 [delegate_ repairWithSelector:repair];
3784 unlink("/tmp/cydia.chk");
3786 now_ = [[NSDate date] timeIntervalSince1970];
3788 policy_ = new pkgDepCache::Policy();
3789 records_ = new pkgRecords(cache_);
3790 resolver_ = new pkgProblemResolver(cache_);
3791 fetcher_ = new pkgAcquire(&status_);
3794 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3795 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3799 _profile(reloadDataWithInvocation$pkgApplyStatus)
3800 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3804 if (cache_->BrokenCount() != 0) {
3805 _profile(pkgApplyStatus$pkgFixBroken)
3806 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3810 if (cache_->BrokenCount() != 0) {
3811 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3815 _profile(pkgApplyStatus$pkgMinimizeUpgrade)
3816 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3821 for (Source *object in (id) sourceList_) {
3822 metaIndex *source([object metaIndex]);
3823 std::vector<pkgIndexFile *> *indices = source->GetIndexFiles();
3824 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3825 // XXX: this could be more intelligent
3826 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3827 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3829 sourceMap_[cached->ID] = object;
3834 /*std::vector<Package *> packages;
3835 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3838 _profile(reloadDataWithInvocation$packageWithIterator)
3839 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3840 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3841 //packages.push_back(package);
3842 CFArrayAppendValue(packages_, CFRetain(package));
3846 /*if (packages.empty())
3847 packages_ = [[NSArray alloc] init];
3849 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3852 _profile(reloadDataWithInvocation$radix$8)
3853 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(8)];
3856 _profile(reloadDataWithInvocation$radix$4)
3857 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3860 _profile(reloadDataWithInvocation$radix$0)
3861 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3864 _profile(reloadDataWithInvocation$insertion)
3865 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3868 /*_profile(reloadDataWithInvocation$CFQSortArray)
3869 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);
3872 /*_profile(reloadDataWithInvocation$stdsort)
3873 std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3876 /*_profile(reloadDataWithInvocation$CFArraySortValues)
3877 CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3880 /*_profile(reloadDataWithInvocation$sortUsingFunction)
3881 [packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3885 size_t count(CFArrayGetCount(packages_));
3886 MetaFile_->active_ = count;
3887 for (size_t index(0); index != count; ++index)
3888 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3893 @synchronized (self) {
3895 resolver_ = new pkgProblemResolver(cache_);
3897 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3898 if (!cache_[iterator].Keep())
3899 cache_->MarkKeep(iterator, false);
3900 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3901 cache_->SetReInstall(iterator, false);
3904 - (void) configure {
3905 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3907 system([dpkg UTF8String]);
3912 @synchronized (self) {
3913 // XXX: I don't remember this condition
3918 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3920 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3922 if ([self popErrorWithTitle:title])
3926 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3928 CydiaLogCleaner cleaner;
3929 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3936 fetcher_->Shutdown();
3938 pkgRecords records(cache_);
3940 lock_ = new FileFd();
3941 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3943 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3945 if ([self popErrorWithTitle:title])
3949 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3952 manager_ = (_system->CreatePM(cache_));
3953 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3960 bool substrate(RestartSubstrate_);
3961 RestartSubstrate_ = false;
3963 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3965 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3967 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3969 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3970 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3973 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
3975 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3977 [self popErrorWithTitle:title];
3981 bool failed = false;
3982 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3983 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3985 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3988 std::string uri = (*item)->DescURI();
3989 std::string error = (*item)->ErrorText;
3991 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3994 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError]);
3995 [delegate_ addProgressEventOnMainThread:event forTask:title];
3998 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4006 RestartSubstrate_ = true;
4009 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
4010 if ([self popErrorWithTitle:title])
4013 if (result == pkgPackageManager::Failed) {
4018 if (result != pkgPackageManager::Completed) {
4023 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
4025 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
4027 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
4028 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
4031 if (![before isEqualToArray:after])
4036 NSString *title(UCLocalize("UPGRADE"));
4037 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
4043 [self updateWithStatus:status_];
4046 - (void) updateWithStatus:(CancelStatus &)status {
4047 NSString *title(UCLocalize("REFRESHING_DATA"));
4050 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
4054 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
4055 if ([self popErrorWithTitle:title])
4058 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4060 bool success(ListUpdate(status, list, PulseInterval_));
4061 if (status.WasCancelled())
4064 [self popErrorWithTitle:title forOperation:success];
4065 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
4069 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4072 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
4073 delegate_ = delegate;
4076 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
4077 progress_ = delegate;
4078 status_.setDelegate(delegate);
4081 - (NSObject<ProgressDelegate> *) progressDelegate {
4085 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
4086 SourceMap::const_iterator i(sourceMap_.find(file->ID));
4087 return i == sourceMap_.end() ? nil : i->second;
4090 - (void) setFetch:(bool)fetch forURI:(const char *)uri {
4091 for (Source *source in (id) sourceList_)
4092 [source setFetch:fetch forURI:uri];
4095 - (void) resetFetch {
4096 for (Source *source in (id) sourceList_)
4097 [source resetFetch];
4100 - (NSString *) mappedSectionForPointer:(const char *)section {
4101 _H<NSString> *mapped;
4103 _profile(Database$mappedSectionForPointer$Cache)
4104 mapped = §ions_[section];
4107 if (*mapped == NULL) {
4108 size_t length(strlen(section));
4109 char spaced[length + 1];
4111 _profile(Database$mappedSectionForPointer$Replace)
4112 for (size_t index(0); index != length; ++index)
4113 spaced[index] = section[index] == '_' ? ' ' : section[index];
4114 spaced[length] = '\0';
4119 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
4120 string = [NSString stringWithUTF8String:spaced];
4123 _profile(Database$mappedSectionForPointer$Map)
4124 string = [SectionMap_ objectForKey:string] ?: string;
4134 static _H<NSMutableSet> Diversions_;
4136 @interface Diversion : NSObject {
4139 _H<NSString> format_;
4144 @implementation Diversion
4146 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
4147 if ((self = [super init]) != nil) {
4148 pattern_ = [from UTF8String];
4154 - (NSString *) divert:(NSString *)url {
4155 return !pattern_(url) ? nil : pattern_->*format_;
4158 + (NSURL *) divertURL:(NSURL *)url {
4160 NSString *href([url absoluteString]);
4162 for (Diversion *diversion in (id) Diversions_)
4163 if (NSString *diverted = [diversion divert:href]) {
4165 NSLog(@"div: %@", diverted);
4167 url = [NSURL URLWithString:diverted];
4174 - (NSString *) key {
4178 - (NSUInteger) hash {
4182 - (BOOL) isEqual:(Diversion *)object {
4183 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
4188 @interface CydiaObject : NSObject {
4189 _H<CyteWebViewController> indirect_;
4190 _transient id delegate_;
4193 - (id) initWithDelegate:(IndirectDelegate *)indirect;
4199 @interface CydiaWebViewController : CyteWebViewController {
4200 _H<CydiaObject> cydia_;
4203 + (void) addDiversion:(Diversion *)diversion;
4204 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request;
4205 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia;
4206 - (void) setDelegate:(id)delegate;
4210 /* Web Scripting {{{ */
4211 @implementation CydiaObject
4213 - (id) initWithDelegate:(IndirectDelegate *)indirect {
4214 if ((self = [super init]) != nil) {
4215 indirect_ = (CyteWebViewController *) indirect;
4219 - (void) setDelegate:(id)delegate {
4220 delegate_ = delegate;
4223 + (NSArray *) _attributeKeys {
4224 return [NSArray arrayWithObjects:
4227 @"coreFoundationVersionNumber",
4244 - (NSArray *) attributeKeys {
4245 return [[self class] _attributeKeys];
4248 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4249 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4252 - (NSString *) version {
4256 - (NSString *) build {
4260 - (NSString *) coreFoundationVersionNumber {
4261 return [NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber];
4264 - (NSString *) device {
4265 return UniqueIdentifier();
4268 - (NSString *) firmware {
4269 return [[UIDevice currentDevice] systemVersion];
4272 - (NSString *) hostname {
4273 return [[UIDevice currentDevice] name];
4276 - (NSString *) idiom {
4277 return (id) Idiom_ ?: [NSNull null];
4280 - (NSString *) mcc {
4281 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode")))
4282 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault) autorelease];
4286 - (NSString *) mnc {
4287 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberNetworkCode")))
4288 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault) autorelease];
4292 - (NSString *) operator {
4293 if (CFStringRef (*$CTRegistrationCopyOperatorName)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTRegistrationCopyOperatorName")))
4294 return [(NSString *) (*$CTRegistrationCopyOperatorName)(kCFAllocatorDefault) autorelease];
4298 - (NSString *) bbsnum {
4299 return (id) BBSNum_ ?: [NSNull null];
4302 - (NSString *) ecid {
4303 return (id) ChipID_ ?: [NSNull null];
4306 - (NSString *) serial {
4307 return SerialNumber_;
4310 - (NSString *) role {
4311 return (id) [NSNull null];
4314 - (NSString *) model {
4315 return [NSString stringWithUTF8String:Machine_];
4318 - (NSString *) token {
4319 return (id) Token_ ?: [NSNull null];
4322 + (NSString *) webScriptNameForSelector:(SEL)selector {
4324 else if (selector == @selector(addBridgedHost:))
4325 return @"addBridgedHost";
4326 else if (selector == @selector(addInsecureHost:))
4327 return @"addInsecureHost";
4328 else if (selector == @selector(addInternalRedirect::))
4329 return @"addInternalRedirect";
4330 else if (selector == @selector(addPipelinedHost:scheme:))
4331 return @"addPipelinedHost";
4332 else if (selector == @selector(addSource:::))
4333 return @"addSource";
4334 else if (selector == @selector(addTokenHost:))
4335 return @"addTokenHost";
4336 else if (selector == @selector(addTrivialSource:))
4337 return @"addTrivialSource";
4338 else if (selector == @selector(close))
4340 else if (selector == @selector(du:))
4342 else if (selector == @selector(stringWithFormat:arguments:))
4344 else if (selector == @selector(getAllSources))
4345 return @"getAllSources";
4346 else if (selector == @selector(getApplicationInfo:value:))
4347 return @"getApplicationInfoValue";
4348 else if (selector == @selector(getKernelNumber:))
4349 return @"getKernelNumber";
4350 else if (selector == @selector(getKernelString:))
4351 return @"getKernelString";
4352 else if (selector == @selector(getInstalledPackages))
4353 return @"getInstalledPackages";
4354 else if (selector == @selector(getIORegistryEntry::))
4355 return @"getIORegistryEntry";
4356 else if (selector == @selector(getLocaleIdentifier))
4357 return @"getLocaleIdentifier";
4358 else if (selector == @selector(getPreferredLanguages))
4359 return @"getPreferredLanguages";
4360 else if (selector == @selector(getPackageById:))
4361 return @"getPackageById";
4362 else if (selector == @selector(getMetadataKeys))
4363 return @"getMetadataKeys";
4364 else if (selector == @selector(getMetadataValue:))
4365 return @"getMetadataValue";
4366 else if (selector == @selector(getSessionValue:))
4367 return @"getSessionValue";
4368 else if (selector == @selector(installPackages:))
4369 return @"installPackages";
4370 else if (selector == @selector(isReachable:))
4371 return @"isReachable";
4372 else if (selector == @selector(localizedStringForKey:value:table:))
4374 else if (selector == @selector(popViewController:))
4375 return @"popViewController";
4376 else if (selector == @selector(refreshSources))
4377 return @"refreshSources";
4378 else if (selector == @selector(registerFrame:))
4379 return @"registerFrame";
4380 else if (selector == @selector(removeButton))
4381 return @"removeButton";
4382 else if (selector == @selector(saveConfig))
4383 return @"saveConfig";
4384 else if (selector == @selector(setMetadataValue::))
4385 return @"setMetadataValue";
4386 else if (selector == @selector(setSessionValue::))
4387 return @"setSessionValue";
4388 else if (selector == @selector(substitutePackageNames:))
4389 return @"substitutePackageNames";
4390 else if (selector == @selector(scrollToBottom:))
4391 return @"scrollToBottom";
4392 else if (selector == @selector(setAllowsNavigationAction:))
4393 return @"setAllowsNavigationAction";
4394 else if (selector == @selector(setBadgeValue:))
4395 return @"setBadgeValue";
4396 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4397 return @"setButtonImage";
4398 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4399 return @"setButtonTitle";
4400 else if (selector == @selector(setHidesBackButton:))
4401 return @"setHidesBackButton";
4402 else if (selector == @selector(setHidesNavigationBar:))
4403 return @"setHidesNavigationBar";
4404 else if (selector == @selector(setNavigationBarStyle:))
4405 return @"setNavigationBarStyle";
4406 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4407 return @"setNavigationBarTintColor";
4408 else if (selector == @selector(setPasteboardString:))
4409 return @"setPasteboardString";
4410 else if (selector == @selector(setPasteboardURL:))
4411 return @"setPasteboardURL";
4412 else if (selector == @selector(setScrollAlwaysBounceVertical:))
4413 return @"setScrollAlwaysBounceVertical";
4414 else if (selector == @selector(setScrollIndicatorStyle:))
4415 return @"setScrollIndicatorStyle";
4416 else if (selector == @selector(setToken:))
4418 else if (selector == @selector(setViewportWidth:))
4419 return @"setViewportWidth";
4420 else if (selector == @selector(statfs:))
4422 else if (selector == @selector(supports:))
4424 else if (selector == @selector(unload))
4430 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4431 return [self webScriptNameForSelector:selector] == nil;
4434 - (BOOL) supports:(NSString *)feature {
4435 return [feature isEqualToString:@"window.open"];
4439 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4442 - (void) setScrollAlwaysBounceVertical:(NSNumber *)value {
4443 [indirect_ performSelectorOnMainThread:@selector(setScrollAlwaysBounceVerticalNumber:) withObject:value waitUntilDone:NO];
4446 - (void) setScrollIndicatorStyle:(NSString *)style {
4447 [indirect_ performSelectorOnMainThread:@selector(setScrollIndicatorStyleWithName:) withObject:style waitUntilDone:NO];
4450 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4451 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4454 - (NSDictionary *) getApplicationInfo:(NSString *)display value:(NSString *)key {
4456 if (SBBundlePathForDisplayIdentifier(SBSSpringBoardServerPort(), [display UTF8String], path) != 0)
4457 return (id) [NSNull null];
4458 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:[[NSString stringWithUTF8String:path] stringByAppendingString:@"/Info.plist"]]);
4460 return (id) [NSNull null];
4461 return [info objectForKey:key];
4464 - (NSNumber *) getKernelNumber:(NSString *)name {
4465 const char *string([name UTF8String]);
4468 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4469 return (id) [NSNull null];
4471 if (size != sizeof(int))
4472 return (id) [NSNull null];
4475 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4476 return (id) [NSNull null];
4478 return [NSNumber numberWithInt:value];
4481 - (NSString *) getKernelString:(NSString *)name {
4482 const char *string([name UTF8String]);
4485 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4486 return (id) [NSNull null];
4488 char value[size + 1];
4489 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4490 return (id) [NSNull null];
4492 // XXX: just in case you request something ludicrous
4495 return [NSString stringWithCString:value];
4498 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4499 NSObject *value(CYIOGetValue([path UTF8String], entry));
4502 if ([value isKindOfClass:[NSData class]])
4503 value = CYHex((NSData *) value);
4508 - (NSArray *) getMetadataKeys {
4509 @synchronized (Values_) {
4510 return [Values_ allKeys];
4513 - (void) registerFrame:(DOMHTMLIFrameElement *)iframe {
4514 WebFrame *frame([iframe contentFrame]);
4515 [indirect_ registerFrame:frame];
4518 - (id) getMetadataValue:(NSString *)key {
4519 @synchronized (Values_) {
4520 return [Values_ objectForKey:key];
4523 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4524 @synchronized (Values_) {
4525 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4526 [Values_ removeObjectForKey:key];
4528 [Values_ setObject:value forKey:key];
4530 [delegate_ performSelectorOnMainThread:@selector(updateValues) withObject:nil waitUntilDone:YES];
4533 - (id) getSessionValue:(NSString *)key {
4534 @synchronized (SessionData_) {
4535 return [SessionData_ objectForKey:key];
4538 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4539 @synchronized (SessionData_) {
4540 if (value == (id) [WebUndefined undefined])
4541 [SessionData_ removeObjectForKey:key];
4543 [SessionData_ setObject:value forKey:key];
4546 - (void) addBridgedHost:(NSString *)host {
4547 @synchronized (HostConfig_) {
4548 [BridgedHosts_ addObject:host];
4551 - (void) addInsecureHost:(NSString *)host {
4552 @synchronized (HostConfig_) {
4553 [InsecureHosts_ addObject:host];
4556 - (void) addTokenHost:(NSString *)host {
4557 @synchronized (HostConfig_) {
4558 [TokenHosts_ addObject:host];
4561 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4562 @synchronized (HostConfig_) {
4563 if (scheme != (id) [WebUndefined undefined])
4564 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4566 [PipelinedHosts_ addObject:host];
4569 - (void) popViewController:(NSNumber *)value {
4570 if (value == (id) [WebUndefined undefined])
4571 value = [NSNumber numberWithBool:YES];
4572 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4575 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4576 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4578 for (NSString *section in sections)
4579 [array addObject:section];
4581 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4584 distribution, @"Distribution",
4586 nil] waitUntilDone:NO];
4589 - (void) addTrivialSource:(NSString *)href {
4590 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4593 - (void) refreshSources {
4594 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4597 - (void) saveConfig {
4598 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4601 - (NSArray *) getAllSources {
4602 return [[Database sharedInstance] sources];
4605 - (NSArray *) getInstalledPackages {
4606 Database *database([Database sharedInstance]);
4607 @synchronized (database) {
4608 NSArray *packages([database packages]);
4609 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4610 for (Package *package in packages)
4611 if (![package uninstalled])
4612 [installed addObject:package];
4616 - (Package *) getPackageById:(NSString *)id {
4617 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4621 return (Package *) [NSNull null];
4624 - (NSString *) getLocaleIdentifier {
4625 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4628 - (NSArray *) getPreferredLanguages {
4632 - (NSArray *) statfs:(NSString *)path {
4635 if (path == nil || statfs([path UTF8String], &stat) == -1)
4638 return [NSArray arrayWithObjects:
4639 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4640 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4641 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4645 - (NSNumber *) du:(NSString *)path {
4646 NSNumber *value(nil);
4649 _assert(pipe(fds) != -1);
4651 pid_t pid(ExecFork());
4653 _assert(dup2(fds[1], 1) != -1);
4654 _assert(close(fds[0]) != -1);
4655 _assert(close(fds[1]) != -1);
4656 /* XXX: this should probably not use du */
4657 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4660 _assert(close(fds[1]) != -1);
4662 if (FILE *du = fdopen(fds[0], "r")) {
4664 while (fgets(line, sizeof(line), du) != NULL) {
4665 size_t length(strlen(line));
4666 while (length != 0 && line[length - 1] == '\n')
4667 line[--length] = '\0';
4668 if (char *tab = strchr(line, '\t')) {
4670 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4676 _assert(close(fds[0]) != -1);
4683 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4686 - (NSNumber *) isReachable:(NSString *)name {
4687 return [NSNumber numberWithBool:IsReachable([name UTF8String])];
4690 - (void) installPackages:(NSArray *)packages {
4691 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4694 - (NSString *) substitutePackageNames:(NSString *)message {
4695 NSMutableArray *words([[[message componentsSeparatedByString:@" "] mutableCopy] autorelease]);
4696 for (size_t i(0), e([words count]); i != e; ++i) {
4697 NSString *word([words objectAtIndex:i]);
4698 if (Package *package = [[Database sharedInstance] packageWithName:word])
4699 [words replaceObjectAtIndex:i withObject:[package name]];
4702 return [words componentsJoinedByString:@" "];
4705 - (void) removeButton {
4706 [indirect_ removeButton];
4709 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4710 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4713 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4714 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4717 - (void) setBadgeValue:(id)value {
4718 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4721 - (void) setAllowsNavigationAction:(NSString *)value {
4722 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4725 - (void) setHidesBackButton:(NSString *)value {
4726 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4729 - (void) setHidesNavigationBar:(NSString *)value {
4730 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4733 - (void) setNavigationBarStyle:(NSString *)value {
4734 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4737 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4738 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4739 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4740 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4743 - (void) setPasteboardString:(NSString *)value {
4744 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4747 - (void) setPasteboardURL:(NSString *)value {
4748 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4751 - (void) _setToken:(NSString *)token {
4755 [Metadata_ removeObjectForKey:@"Token"];
4757 [Metadata_ setObject:Token_ forKey:@"Token"];
4762 - (void) setToken:(NSString *)token {
4763 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4766 - (void) scrollToBottom:(NSNumber *)animated {
4767 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4770 - (void) setViewportWidth:(float)width {
4771 [indirect_ setViewportWidthOnMainThread:width];
4774 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4775 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4776 unsigned count([arguments count]);
4778 for (unsigned i(0); i != count; ++i)
4779 values[i] = [arguments objectAtIndex:i];
4780 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4783 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4784 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4786 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4788 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4794 @interface NSURL (CydiaSecure)
4797 @implementation NSURL (CydiaSecure)
4799 - (bool) isCydiaSecure {
4800 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4803 @synchronized (HostConfig_) {
4804 if ([InsecureHosts_ containsObject:[self host]])
4813 /* Cydia Browser Controller {{{ */
4814 @implementation CydiaWebViewController
4816 - (NSURL *) navigationURL {
4817 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4820 + (void) _initialize {
4821 [super _initialize];
4823 Diversions_ = [NSMutableSet setWithCapacity:0];
4826 + (void) addDiversion:(Diversion *)diversion {
4827 [Diversions_ addObject:diversion];
4830 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4831 [super webView:view didClearWindowObject:window forFrame:frame];
4832 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
4835 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia {
4836 WebDataSource *source([frame dataSource]);
4837 NSURLResponse *response([source response]);
4838 NSURL *url([response URL]);
4839 NSString *scheme([[url scheme] lowercaseString]);
4841 bool bridged(false);
4843 @synchronized (HostConfig_) {
4844 if ([scheme isEqualToString:@"file"])
4846 else if ([scheme isEqualToString:@"https"])
4847 if ([BridgedHosts_ containsObject:[url host]])
4852 [window setValue:cydia forKey:@"cydia"];
4855 - (void) _setupMail:(MFMailComposeViewController *)controller {
4856 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4858 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4859 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4862 - (NSURL *) URLWithURL:(NSURL *)url {
4863 return [Diversion divertURL:url];
4866 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4867 return [CydiaWebViewController requestWithHeaders:[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
4870 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request {
4871 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
4873 NSURL *url([copy URL]);
4874 NSString *href([url absoluteString]);
4875 NSString *host([url host]);
4877 if ([href hasPrefix:@"https://cydia.saurik.com/TSS/"]) {
4878 if (NSString *agent = [copy valueForHTTPHeaderField:@"X-User-Agent"]) {
4879 [copy setValue:agent forHTTPHeaderField:@"User-Agent"];
4880 [copy setValue:nil forHTTPHeaderField:@"X-User-Agent"];
4883 [copy setValue:nil forHTTPHeaderField:@"Referer"];
4884 [copy setValue:nil forHTTPHeaderField:@"Origin"];
4886 [copy setURL:[NSURL URLWithString:[@"http://gs.apple.com/TSS/" stringByAppendingString:[href substringFromIndex:29]]]];
4890 if ([copy valueForHTTPHeaderField:@"X-Cydia-Cf"] == nil)
4891 [copy setValue:[NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber] forHTTPHeaderField:@"X-Cydia-Cf"];
4892 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4893 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4898 @synchronized (HostConfig_) {
4899 bridged = [BridgedHosts_ containsObject:host];
4900 token = [TokenHosts_ containsObject:host];
4903 if ([url isCydiaSecure]) {
4905 if (UniqueID_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Id"] == nil)
4906 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
4908 if (Token_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Token"] == nil)
4909 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4916 - (void) setDelegate:(id)delegate {
4917 [super setDelegate:delegate];
4918 [cydia_ setDelegate:delegate];
4921 - (NSString *) applicationNameForUserAgent {
4926 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4927 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
4933 @interface AppCacheController : CydiaWebViewController {
4938 @implementation AppCacheController
4940 - (void) didReceiveMemoryWarning {
4941 // XXX: this doesn't work
4944 - (bool) retainsNetworkActivityIndicator {
4952 @interface NSObject (CydiaScript)
4953 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4956 @implementation NSObject (CydiaScript)
4958 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4964 @implementation NSArray (CydiaScript)
4966 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4967 WebScriptObject *object([context evaluateWebScript:@"[]"]);
4968 for (size_t i(0), e([self count]); i != e; ++i)
4969 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
4975 @implementation NSDictionary (CydiaScript)
4977 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4978 WebScriptObject *object([context evaluateWebScript:@"({})"]);
4980 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
4987 /* Confirmation Controller {{{ */
4988 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4989 if (!iterator.end())
4990 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4991 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4993 pkgCache::PkgIterator package(dep.TargetPkg());
4996 if (strcmp(package.Name(), "mobilesubstrate") == 0)
5003 @protocol ConfirmationControllerDelegate
5004 - (void) cancelAndClear:(bool)clear;
5005 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
5009 @interface ConfirmationController : CydiaWebViewController {
5010 _transient Database *database_;
5012 _H<UIAlertView> essential_;
5014 _H<NSDictionary> changes_;
5015 _H<NSMutableArray> issues_;
5016 _H<NSDictionary> sizes_;
5021 - (id) initWithDatabase:(Database *)database;
5025 @implementation ConfirmationController
5029 RestartSubstrate_ = true;
5030 [delegate_ confirmWithNavigationController:[self navigationController]];
5033 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
5034 NSString *context([alert context]);
5036 if ([context isEqualToString:@"remove"]) {
5037 if (button == [alert cancelButtonIndex])
5038 [self dismissModalViewControllerAnimated:YES];
5039 else if (button == [alert firstOtherButtonIndex]) {
5040 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
5043 [alert dismissWithClickedButtonIndex:-1 animated:YES];
5044 } else if ([context isEqualToString:@"unable"]) {
5045 [self dismissModalViewControllerAnimated:YES];
5046 [alert dismissWithClickedButtonIndex:-1 animated:YES];
5048 [super alertView:alert clickedButtonAtIndex:button];
5052 - (void) _doContinue {
5053 [delegate_ cancelAndClear:NO];
5054 [self dismissModalViewControllerAnimated:YES];
5057 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
5058 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
5062 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5063 [super webView:view didClearWindowObject:window forFrame:frame];
5065 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
5066 (id) changes_, @"changes",
5067 (id) issues_, @"issues",
5068 (id) sizes_, @"sizes",
5070 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
5073 - (id) initWithDatabase:(Database *)database {
5074 if ((self = [super init]) != nil) {
5075 database_ = database;
5077 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
5078 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
5079 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
5080 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
5081 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
5085 pkgCacheFile &cache([database_ cache]);
5086 NSArray *packages([database_ packages]);
5087 pkgDepCache::Policy *policy([database_ policy]);
5089 issues_ = [NSMutableArray arrayWithCapacity:4];
5091 for (Package *package in packages) {
5092 pkgCache::PkgIterator iterator([package iterator]);
5093 NSString *name([package id]);
5095 if ([package broken]) {
5096 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
5098 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5100 reasons, @"reasons",
5103 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
5107 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
5108 pkgCache::DepIterator start;
5109 pkgCache::DepIterator end;
5110 dep.GlobOr(start, end); // ++dep
5112 if (!cache->IsImportantDep(end))
5114 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
5117 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
5119 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5120 [NSString stringWithUTF8String:start.DepType()], @"relationship",
5121 clauses, @"clauses",
5125 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
5127 pkgCache::PkgIterator target(start.TargetPkg());
5128 if (target->ProvidesList != 0)
5129 reason = @"missing";
5131 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
5133 reason = @"installed";
5134 installed = [NSString stringWithUTF8String:ver.VerStr()];
5135 } else if (!cache[target].CandidateVerIter(cache).end())
5136 reason = @"uninstalled";
5137 else if (target->ProvidesList == 0)
5138 reason = @"uninstallable";
5140 reason = @"virtual";
5143 NSDictionary *version(start.TargetVer() == 0 ? (NSDictionary *) [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
5144 [NSString stringWithUTF8String:start.CompType()], @"operator",
5145 [NSString stringWithUTF8String:start.TargetVer()], @"value",
5148 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5149 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
5150 version, @"version",
5152 installed, @"installed",
5155 // yes, seriously. (wtf?)
5163 pkgDepCache::StateCache &state(cache[iterator]);
5165 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
5167 if (state.NewInstall())
5168 [installs addObject:name];
5169 // XXX: else if (state.Install())
5170 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
5171 [reinstalls addObject:name];
5172 // XXX: move before previous if
5173 else if (state.Upgrade())
5174 [upgrades addObject:name];
5175 else if (state.Downgrade())
5176 [downgrades addObject:name];
5177 else if (!state.Delete())
5178 // XXX: _assert(state.Keep());
5180 else if (special_r(name))
5181 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5182 [NSNull null], @"package",
5183 [NSArray arrayWithObjects:
5184 [NSDictionary dictionaryWithObjectsAndKeys:
5185 @"Conflicts", @"relationship",
5186 [NSArray arrayWithObjects:
5187 [NSDictionary dictionaryWithObjectsAndKeys:
5189 [NSNull null], @"version",
5190 @"installed", @"reason",
5197 if ([package essential])
5199 [removes addObject:name];
5202 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
5203 substrate_ |= DepSubstrate(iterator.CurrentVer());
5208 else if (Advanced_) {
5209 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
5211 essential_ = [[[UIAlertView alloc]
5212 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
5213 message:UCLocalize("REMOVING_ESSENTIALS_EX")
5215 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
5217 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
5221 [essential_ setContext:@"remove"];
5222 [essential_ setNumberOfRows:2];
5224 essential_ = [[[UIAlertView alloc]
5225 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
5226 message:UCLocalize("UNABLE_TO_COMPLY_EX")
5228 cancelButtonTitle:UCLocalize("OKAY")
5229 otherButtonTitles:nil
5232 [essential_ setContext:@"unable"];
5235 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5236 installs, @"installs",
5237 reinstalls, @"reinstalls",
5238 upgrades, @"upgrades",
5239 downgrades, @"downgrades",
5240 removes, @"removes",
5243 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5244 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
5245 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
5248 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
5252 - (UIBarButtonItem *) leftButton {
5253 return [[[UIBarButtonItem alloc]
5254 initWithTitle:UCLocalize("CANCEL")
5255 style:UIBarButtonItemStylePlain
5257 action:@selector(cancelButtonClicked)
5262 - (void) applyRightButton {
5263 if ([issues_ count] == 0 && ![self isLoading])
5264 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
5265 initWithTitle:UCLocalize("CONFIRM")
5266 style:UIBarButtonItemStyleDone
5268 action:@selector(confirmButtonClicked)
5271 [[self navigationItem] setRightBarButtonItem:nil];
5275 - (void) cancelButtonClicked {
5276 [delegate_ cancelAndClear:YES];
5277 [self dismissModalViewControllerAnimated:YES];
5281 - (void) confirmButtonClicked {
5282 if (essential_ != nil)
5292 /* Progress Data {{{ */
5293 @interface CydiaProgressData : NSObject {
5294 _transient id delegate_;
5303 _H<NSMutableArray> events_;
5304 _H<NSString> title_;
5306 _H<NSString> status_;
5307 _H<NSString> finish_;
5312 @implementation CydiaProgressData
5314 + (NSArray *) _attributeKeys {
5315 return [NSArray arrayWithObjects:
5327 - (NSArray *) attributeKeys {
5328 return [[self class] _attributeKeys];
5331 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5332 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5336 if ((self = [super init]) != nil) {
5337 events_ = [NSMutableArray arrayWithCapacity:32];
5345 - (void) setDelegate:(id)delegate {
5346 delegate_ = delegate;
5349 - (void) setPercent:(float)value {
5353 - (NSNumber *) percent {
5354 return [NSNumber numberWithFloat:percent_];
5357 - (void) setCurrent:(float)value {
5361 - (NSNumber *) current {
5362 return [NSNumber numberWithFloat:current_];
5365 - (void) setTotal:(float)value {
5369 - (NSNumber *) total {
5370 return [NSNumber numberWithFloat:total_];
5373 - (void) setSpeed:(float)value {
5377 - (NSNumber *) speed {
5378 return [NSNumber numberWithFloat:speed_];
5381 - (NSArray *) events {
5385 - (void) removeAllEvents {
5386 [events_ removeAllObjects];
5389 - (void) addEvent:(CydiaProgressEvent *)event {
5390 [events_ addObject:event];
5393 - (void) setTitle:(NSString *)text {
5397 - (NSString *) title {
5401 - (void) setFinish:(NSString *)text {
5405 - (NSString *) finish {
5406 return (id) finish_ ?: [NSNull null];
5409 - (void) setRunning:(bool)running {
5413 - (NSNumber *) running {
5414 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5419 /* Progress Controller {{{ */
5420 @interface ProgressController : CydiaWebViewController <
5423 _transient Database *database_;
5424 _H<CydiaProgressData, 1> progress_;
5428 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5430 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5432 - (void) setTitle:(NSString *)title;
5433 - (void) setCancellable:(bool)cancellable;
5437 @implementation ProgressController
5440 [database_ setProgressDelegate:nil];
5444 - (UIBarButtonItem *) leftButton {
5445 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5446 initWithTitle:UCLocalize("CANCEL")
5447 style:UIBarButtonItemStylePlain
5449 action:@selector(cancel)
5450 ] autorelease] : nil;
5453 - (void) updateCancel {
5454 [super applyLeftButton];
5457 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5458 if ((self = [super init]) != nil) {
5459 database_ = database;
5460 delegate_ = delegate;
5462 [database_ setProgressDelegate:self];
5464 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5465 [progress_ setDelegate:self];
5467 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5469 [scroller_ setBackgroundColor:[UIColor blackColor]];
5471 [[self navigationItem] setHidesBackButton:YES];
5473 [self updateCancel];
5477 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5478 [super webView:view didClearWindowObject:window forFrame:frame];
5479 [window setValue:progress_ forKey:@"cydiaProgress"];
5482 - (void) updateProgress {
5483 [self dispatchEvent:@"CydiaProgressUpdate"];
5486 - (void) viewWillAppear:(BOOL)animated {
5487 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5488 [super viewWillAppear:animated];
5491 - (void) reloadSpringBoard {
5492 if (kCFCoreFoundationVersionNumber > 700) { // XXX: iOS 6.x
5493 system("/bin/launchctl stop com.apple.backboardd");
5495 system("/usr/bin/killall backboardd SpringBoard sbreload");
5499 pid_t pid(ExecFork());
5504 pid_t pid(ExecFork());
5506 execl("/usr/bin/sbreload", "sbreload", NULL);
5516 system("/usr/bin/killall backboardd SpringBoard sbreload");
5520 UpdateExternalStatus(0);
5523 [delegate_ saveState];
5527 [delegate_ returnToCydia];
5531 [delegate_ terminateWithSuccess];
5532 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5533 [delegate_ suspendWithAnimation:YES];
5535 [delegate_ suspend];*/
5547 UIProgressHUD *hud([delegate_ addProgressHUD]);
5548 [hud setText:UCLocalize("LOADING")];
5549 [self performSelector:@selector(reloadSpringBoard) withObject:nil afterDelay:0.5];
5555 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5556 SBReboot(SBSSpringBoardServerPort());
5558 reboot2(RB_AUTOBOOT);
5565 - (void) setTitle:(NSString *)title {
5566 [progress_ setTitle:title];
5567 [self updateProgress];
5570 - (UIBarButtonItem *) rightButton {
5571 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5572 initWithTitle:UCLocalize("CLOSE")
5573 style:UIBarButtonItemStylePlain
5575 action:@selector(close)
5579 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5580 UpdateExternalStatus(1);
5582 [progress_ setRunning:true];
5583 [self setTitle:title];
5584 // implicit updateProgress
5586 SHA1SumValue notifyconf; {
5588 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5591 MMap mmap(file, MMap::ReadOnly);
5593 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5594 notifyconf = sha1.Result();
5598 SHA1SumValue springlist; {
5600 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5603 MMap mmap(file, MMap::ReadOnly);
5605 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5606 springlist = sha1.Result();
5610 if (invocation != nil) {
5611 [invocation yieldToSelector:@selector(invoke)];
5612 [self setTitle:@"COMPLETE"];
5617 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5620 MMap mmap(file, MMap::ReadOnly);
5622 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5623 if (!(notifyconf == sha1.Result()))
5630 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5633 MMap mmap(file, MMap::ReadOnly);
5635 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5636 if (!(springlist == sha1.Result()))
5642 if (RestartSubstrate_)
5646 RestartSubstrate_ = false;
5649 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5650 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5651 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5652 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5653 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5656 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5658 [progress_ setRunning:false];
5659 [self updateProgress];
5661 [self applyRightButton];
5664 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5665 [progress_ addEvent:event];
5666 [self updateProgress];
5669 - (bool) isProgressCancelled {
5670 return cancel_ == 2;
5675 [self updateCancel];
5678 - (void) setCancellable:(bool)cancellable {
5679 unsigned cancel(cancel_);
5683 else if (cancel_ == 0)
5686 if (cancel != cancel_)
5687 [self updateCancel];
5690 - (void) setProgressCancellable:(NSNumber *)cancellable {
5691 [self setCancellable:[cancellable boolValue]];
5694 - (void) setProgressPercent:(NSNumber *)percent {
5695 [progress_ setPercent:[percent floatValue]];
5696 [self updateProgress];
5699 - (void) setProgressStatus:(NSDictionary *)status {
5700 if (status == nil) {
5701 [progress_ setCurrent:0];
5702 [progress_ setTotal:0];
5703 [progress_ setSpeed:0];
5705 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5707 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5708 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5709 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5712 [self updateProgress];
5718 /* Package Cell {{{ */
5719 @interface PackageCell : CyteTableViewCell <
5720 CyteTableViewCellDelegate
5724 _H<NSString> description_;
5726 _H<NSString> source_;
5728 _H<UIImage> placard_;
5732 - (PackageCell *) init;
5733 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5735 - (void) drawContentRect:(CGRect)rect;
5739 @implementation PackageCell
5741 - (PackageCell *) init {
5742 CGRect frame(CGRectMake(0, 0, 320, 74));
5743 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5744 UIView *content([self contentView]);
5745 CGRect bounds([content bounds]);
5747 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5748 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5749 [content addSubview:content_];
5751 [content_ setDelegate:self];
5752 [content_ setOpaque:YES];
5756 - (NSString *) accessibilityLabel {
5760 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5761 summarized_ = summary;
5771 [content_ setBackgroundColor:[UIColor whiteColor]];
5775 Source *source = [package source];
5777 icon_ = [package icon];
5779 if (NSString *name = [package name])
5780 name_ = [NSString stringWithString:name];
5782 if (NSString *description = [package shortDescription])
5783 description_ = [NSString stringWithString:description];
5785 commercial_ = [package isCommercial];
5787 NSString *label = nil;
5788 bool trusted = false;
5790 if (source != nil) {
5791 label = [source label];
5792 trusted = [source trusted];
5793 } else if ([[package id] isEqualToString:@"firmware"])
5794 label = UCLocalize("APPLE");
5796 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5798 NSString *from(label);
5800 NSString *section = [package simpleSection];
5801 if (section != nil && ![section isEqualToString:label]) {
5802 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5803 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5806 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5808 if (NSString *purpose = [package primaryPurpose])
5809 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5814 if (NSString *mode = [package mode]) {
5815 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5816 color = RemovingColor_;
5817 placard = @"removing";
5819 color = InstallingColor_;
5820 placard = @"installing";
5823 color = [UIColor whiteColor];
5825 if ([package installed] != nil)
5826 placard = @"installed";
5831 [content_ setBackgroundColor:color];
5834 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5837 [self setNeedsDisplay];
5838 [content_ setNeedsDisplay];
5841 - (void) drawSummaryContentRect:(CGRect)rect {
5842 bool highlighted(highlighted_);
5843 float width([self bounds].size.width);
5847 rect.size = [(UIImage *) icon_ size];
5849 while (rect.size.width > 16 || rect.size.height > 16) {
5850 rect.size.width /= 2;
5851 rect.size.height /= 2;
5854 rect.origin.x = 19 - rect.size.width / 2;
5855 rect.origin.y = 19 - rect.size.height / 2;
5857 [icon_ drawInRect:Retina(rect)];
5860 if (badge_ != nil) {
5862 rect.size = [(UIImage *) badge_ size];
5864 rect.size.width /= 4;
5865 rect.size.height /= 4;
5867 rect.origin.x = 25 - rect.size.width / 2;
5868 rect.origin.y = 25 - rect.size.height / 2;
5870 [badge_ drawInRect:Retina(rect)];
5873 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5877 UISetColor(commercial_ ? Purple_ : Black_);
5878 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
5880 if (placard_ != nil)
5881 [placard_ drawAtPoint:CGPointMake(width - 52, 11)];
5884 - (void) drawNormalContentRect:(CGRect)rect {
5885 bool highlighted(highlighted_);
5886 float width([self bounds].size.width);
5890 rect.size = [(UIImage *) icon_ size];
5892 while (rect.size.width > 32 || rect.size.height > 32) {
5893 rect.size.width /= 2;
5894 rect.size.height /= 2;
5897 rect.origin.x = 25 - rect.size.width / 2;
5898 rect.origin.y = 25 - rect.size.height / 2;
5900 [icon_ drawInRect:Retina(rect)];
5903 if (badge_ != nil) {
5905 rect.size = [(UIImage *) badge_ size];
5907 rect.size.width /= 2;
5908 rect.size.height /= 2;
5910 rect.origin.x = 36 - rect.size.width / 2;
5911 rect.origin.y = 36 - rect.size.height / 2;
5913 [badge_ drawInRect:Retina(rect)];
5916 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5920 UISetColor(commercial_ ? Purple_ : Black_);
5921 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
5922 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
5925 UISetColor(commercial_ ? Purplish_ : Gray_);
5926 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:NSLineBreakByTruncatingTail];
5928 if (placard_ != nil)
5929 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5932 - (void) drawContentRect:(CGRect)rect {
5934 [self drawSummaryContentRect:rect];
5936 [self drawNormalContentRect:rect];
5941 /* Section Cell {{{ */
5942 @interface SectionCell : CyteTableViewCell <
5943 CyteTableViewCellDelegate
5945 _H<NSString> basic_;
5946 _H<NSString> section_;
5948 _H<NSString> count_;
5950 _H<UISwitch> switch_;
5954 - (void) setSection:(Section *)section editing:(BOOL)editing;
5958 @implementation SectionCell
5960 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5961 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5962 icon_ = [UIImage applicationImageNamed:@"folder.png"];
5963 // XXX: this initial frame is wrong, but is fixed later
5964 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5965 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5967 UIView *content([self contentView]);
5968 CGRect bounds([content bounds]);
5970 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5971 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5972 [content addSubview:content_];
5973 [content_ setBackgroundColor:[UIColor whiteColor]];
5975 [content_ setDelegate:self];
5979 - (void) onSwitch:(id)sender {
5980 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5981 if (metadata == nil) {
5982 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5983 [Sections_ setObject:metadata forKey:basic_];
5986 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5990 - (void) setSection:(Section *)section editing:(BOOL)editing {
5991 if (editing != editing_) {
5993 [switch_ removeFromSuperview];
5995 [self addSubview:switch_];
6004 if (section == nil) {
6005 name_ = UCLocalize("ALL_PACKAGES");
6008 basic_ = [section name];
6009 section_ = [section localized];
6011 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
6012 count_ = [NSString stringWithFormat:@"%zd", [section count]];
6015 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
6018 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
6019 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
6021 [content_ setNeedsDisplay];
6024 - (void) setFrame:(CGRect)frame {
6025 [super setFrame:frame];
6027 CGRect rect([switch_ frame]);
6028 [switch_ setFrame:CGRectMake(frame.size.width - rect.size.width - 9, 9, rect.size.width, rect.size.height)];
6031 - (NSString *) accessibilityLabel {
6035 - (void) drawContentRect:(CGRect)rect {
6036 bool highlighted(highlighted_ && !editing_);
6038 [icon_ drawInRect:CGRectMake(7, 7, 32, 32)];
6040 if (highlighted && kCFCoreFoundationVersionNumber < 800)
6043 float width(rect.size.width);
6045 width -= 9 + [switch_ frame].size.width;
6049 [name_ drawAtPoint:CGPointMake(48, 12) forWidth:(width - 58) withFont:Font18_ lineBreakMode:NSLineBreakByTruncatingTail];
6051 CGSize size = [count_ sizeWithFont:Font14_];
6053 UISetColor(Folder_);
6055 [count_ drawAtPoint:CGPointMake(Retina(10 + (30 - size.width) / 2), 18) withFont:Font12Bold_];
6061 /* File Table {{{ */
6062 @interface FileTable : CyteViewController <
6063 UITableViewDataSource,
6066 _transient Database *database_;
6067 _H<Package> package_;
6069 _H<NSMutableArray> files_;
6070 _H<UITableView, 2> list_;
6073 - (id) initWithDatabase:(Database *)database;
6074 - (void) setPackage:(Package *)package;
6078 @implementation FileTable
6080 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6081 return files_ == nil ? 0 : [files_ count];
6084 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6088 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6089 static NSString *reuseIdentifier = @"Cell";
6091 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6093 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6094 [cell setFont:[UIFont systemFontOfSize:16]];
6096 [cell setText:[files_ objectAtIndex:indexPath.row]];
6097 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
6102 - (NSURL *) navigationURL {
6103 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
6107 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
6108 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6109 [list_ setRowHeight:24.0f];
6110 [(UITableView *) list_ setDataSource:self];
6111 [list_ setDelegate:self];
6112 [self setView:list_];
6115 - (void) viewDidLoad {
6116 [super viewDidLoad];
6118 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
6121 - (void) releaseSubviews {
6127 [super releaseSubviews];
6130 - (id) initWithDatabase:(Database *)database {
6131 if ((self = [super init]) != nil) {
6132 database_ = database;
6136 - (void) setPackage:(Package *)package {
6140 files_ = [NSMutableArray arrayWithCapacity:32];
6142 if (package != nil) {
6144 name_ = [package id];
6146 if (NSArray *files = [package files])
6147 [files_ addObjectsFromArray:files];
6149 if ([files_ count] != 0) {
6150 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
6151 [files_ removeObjectAtIndex:0];
6152 [files_ sortUsingSelector:@selector(compareByPath:)];
6154 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
6155 [stack addObject:@"/"];
6157 for (int i(0), e([files_ count]); i != e; ++i) {
6158 NSString *file = [files_ objectAtIndex:i];
6159 while (![file hasPrefix:[stack lastObject]])
6160 [stack removeLastObject];
6161 NSString *directory = [stack lastObject];
6162 [stack addObject:[file stringByAppendingString:@"/"]];
6163 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
6164 ([stack count] - 2) * 3, "",
6165 [file substringFromIndex:[directory length]]
6174 - (void) reloadData {
6177 [self setPackage:[database_ packageWithName:name_]];
6182 /* Package Controller {{{ */
6183 @interface CYPackageController : CydiaWebViewController <
6184 UIActionSheetDelegate
6186 _transient Database *database_;
6187 _H<Package> package_;
6190 _H<NSMutableArray> buttons_;
6191 _H<UIBarButtonItem> button_;
6194 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer;
6198 @implementation CYPackageController
6200 - (NSURL *) navigationURL {
6201 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
6204 /* XXX: this is not safe at all... localization of /fail/ */
6205 - (void) _clickButtonWithName:(NSString *)name {
6206 if ([name isEqualToString:UCLocalize("CLEAR")])
6207 [delegate_ clearPackage:package_];
6208 else if ([name isEqualToString:UCLocalize("INSTALL")])
6209 [delegate_ installPackage:package_];
6210 else if ([name isEqualToString:UCLocalize("REINSTALL")])
6211 [delegate_ installPackage:package_];
6212 else if ([name isEqualToString:UCLocalize("REMOVE")])
6213 [delegate_ removePackage:package_];
6214 else if ([name isEqualToString:UCLocalize("UPGRADE")])
6215 [delegate_ installPackage:package_];
6216 else _assert(false);
6219 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
6220 NSString *context([sheet context]);
6222 if ([context isEqualToString:@"modify"]) {
6223 if (button != [sheet cancelButtonIndex]) {
6224 NSString *buttonName = [buttons_ objectAtIndex:button];
6225 [self _clickButtonWithName:buttonName];
6228 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
6232 - (bool) _allowJavaScriptPanel {
6237 - (void) _customButtonClicked {
6238 int count([buttons_ count]);
6243 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
6245 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
6246 [buttons addObjectsFromArray:buttons_];
6248 UIActionSheet *sheet = [[[UIActionSheet alloc]
6251 cancelButtonTitle:nil
6252 destructiveButtonTitle:nil
6253 otherButtonTitles:nil
6256 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
6258 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
6259 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
6261 [sheet setContext:@"modify"];
6263 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
6267 - (void) reloadButtonClicked {
6268 if (commercial_ && function_ == nil && [package_ uninstalled])
6270 [self customButtonClicked];
6273 - (void) applyLoadingTitle {
6274 // Don't show "Loading" as the title. Ever.
6277 - (UIBarButtonItem *) rightButton {
6282 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer {
6283 if ((self = [super init]) != nil) {
6284 database_ = database;
6285 buttons_ = [NSMutableArray arrayWithCapacity:4];
6286 name_ = name == nil ? @"" : [NSString stringWithString:name];
6287 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]] withReferrer:referrer];
6291 - (void) reloadData {
6294 package_ = [database_ packageWithName:name_];
6296 [buttons_ removeAllObjects];
6298 if (package_ != nil) {
6299 [(Package *) package_ parse];
6301 commercial_ = [package_ isCommercial];
6303 if ([package_ mode] != nil)
6304 [buttons_ addObject:UCLocalize("CLEAR")];
6305 if ([package_ source] == nil);
6306 else if ([package_ upgradableAndEssential:NO])
6307 [buttons_ addObject:UCLocalize("UPGRADE")];
6308 else if ([package_ uninstalled])
6309 [buttons_ addObject:UCLocalize("INSTALL")];
6311 [buttons_ addObject:UCLocalize("REINSTALL")];
6312 if (![package_ uninstalled])
6313 [buttons_ addObject:UCLocalize("REMOVE")];
6317 switch ([buttons_ count]) {
6318 case 0: title = nil; break;
6319 case 1: title = [buttons_ objectAtIndex:0]; break;
6320 default: title = UCLocalize("MODIFY"); break;
6323 button_ = [[[UIBarButtonItem alloc]
6325 style:UIBarButtonItemStylePlain
6327 action:@selector(customButtonClicked)
6331 - (bool) isLoading {
6332 return commercial_ ? [super isLoading] : false;
6338 /* Package List Controller {{{ */
6339 @interface PackageListController : CyteViewController <
6340 UITableViewDataSource,
6343 _transient Database *database_;
6345 _H<NSArray> packages_;
6346 _H<NSArray> sections_;
6347 _H<UITableView, 2> list_;
6349 _H<NSArray> thumbs_;
6350 std::vector<NSInteger> offset_;
6352 _H<NSString> title_;
6353 unsigned reloading_;
6356 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6357 - (void) setDelegate:(id)delegate;
6358 - (void) resetCursor;
6361 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages;
6365 @implementation PackageListController
6367 - (NSURL *) referrerURL {
6368 return [self navigationURL];
6371 - (bool) isSummarized {
6375 - (bool) showsSections {
6379 - (void) deselectWithAnimation:(BOOL)animated {
6380 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6383 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6384 CGRect base = [[self view] bounds];
6385 base.size.height -= bounds.size.height;
6386 base.origin = [list_ frame].origin;
6388 [UIView beginAnimations:nil context:NULL];
6389 [UIView setAnimationBeginsFromCurrentState:YES];
6390 [UIView setAnimationCurve:curve];
6391 [UIView setAnimationDuration:duration];
6392 [list_ setFrame:base];
6393 [UIView commitAnimations];
6396 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6397 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6400 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6401 [self resizeForKeyboardBounds:bounds duration:0];
6404 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6405 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6406 *curve = UIViewAnimationCurveEaseInOut;
6408 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6410 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6413 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6416 - (void) keyboardWillShow:(NSNotification *)notification {
6419 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6420 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6422 NSTimeInterval duration;
6423 UIViewAnimationCurve curve;
6424 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6426 CGRect kbframe = CGRectMake(Retina(center.x - bounds.size.width / 2), Retina(center.y - bounds.size.height / 2), bounds.size.width, bounds.size.height);
6427 UIViewController *base = self;
6428 while ([base parentOrPresentingViewController] != nil)
6429 base = [base parentOrPresentingViewController];
6430 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6431 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6433 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6434 intersection.size.height += CYStatusBarHeight();
6436 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6439 - (void) keyboardWillHide:(NSNotification *)notification {
6440 NSTimeInterval duration;
6441 UIViewAnimationCurve curve;
6442 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6444 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6447 - (void) viewWillAppear:(BOOL)animated {
6448 [super viewWillAppear:animated];
6450 [self resizeForKeyboardBounds:CGRectZero];
6451 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6452 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6455 - (void) viewWillDisappear:(BOOL)animated {
6456 [super viewWillDisappear:animated];
6458 [self resizeForKeyboardBounds:CGRectZero];
6459 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6460 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6463 - (void) viewDidAppear:(BOOL)animated {
6464 [super viewDidAppear:animated];
6465 [self deselectWithAnimation:animated];
6468 - (void) didSelectPackage:(Package *)package {
6469 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[[self referrerURL] absoluteString]] autorelease]);
6470 [view setDelegate:delegate_];
6471 [[self navigationController] pushViewController:view animated:YES];
6474 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6475 NSInteger count([sections_ count]);
6476 return count == 0 ? 1 : count;
6479 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6480 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6482 return [[sections_ objectAtIndex:section] name];
6485 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6486 if ([sections_ count] == 0)
6488 return [[sections_ objectAtIndex:section] count];
6491 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6492 @synchronized (database_) {
6493 if ([database_ era] != era_)
6496 Section *section([sections_ objectAtIndex:[path section]]);
6497 NSInteger row([path row]);
6498 Package *package([packages_ objectAtIndex:([section row] + row)]);
6499 return [[package retain] autorelease];
6502 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6503 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6505 cell = [[[PackageCell alloc] init] autorelease];
6507 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6508 [cell setPackage:package asSummary:[self isSummarized]];
6512 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6513 Package *package([self packageAtIndexPath:path]);
6514 package = [database_ packageWithName:[package id]];
6515 [self didSelectPackage:package];
6518 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6522 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6523 return offset_[index];
6526 - (void) updateHeight {
6527 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6530 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6531 if ((self = [super init]) != nil) {
6532 database_ = database;
6533 title_ = [title copy];
6534 [[self navigationItem] setTitle:title_];
6539 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
6540 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
6541 [self setView:view];
6543 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6544 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6545 [view addSubview:list_];
6547 // XXX: is 20 the most optimal number here?
6548 [list_ setSectionIndexMinimumDisplayRowCount:20];
6550 [(UITableView *) list_ setDataSource:self];
6551 [list_ setDelegate:self];
6553 [self updateHeight];
6556 - (void) releaseSubviews {
6565 [super releaseSubviews];
6568 - (void) setDelegate:(id)delegate {
6569 delegate_ = delegate;
6572 - (bool) shouldYield {
6576 - (bool) shouldBlock {
6580 - (NSMutableArray *) _reloadPackages {
6581 @synchronized (database_) {
6582 era_ = [database_ era];
6583 NSArray *packages([database_ packages]);
6585 return [NSMutableArray arrayWithArray:packages];
6588 - (void) _reloadData {
6589 if (reloading_ != 0) {
6594 NSMutableArray *packages;
6597 if ([self shouldYield]) {
6601 if (![self shouldBlock])
6604 hud = [delegate_ addProgressHUD];
6605 [hud setText:UCLocalize("LOADING")];
6609 packages = [self yieldToSelector:@selector(_reloadPackages)];
6612 [delegate_ removeProgressHUD:hud];
6613 } while (reloading_ == 2);
6615 packages = [self _reloadPackages];
6618 @synchronized (database_) {
6619 if (era_ != [database_ era])
6626 packages_ = packages;
6628 if ([self showsSections])
6629 sections_ = [self sectionsForPackages:packages];
6631 Section *section([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6632 [section setCount:[packages_ count]];
6633 sections_ = [NSArray arrayWithObject:section];
6636 [self updateHeight];
6638 _profile(PackageTable$reloadData$List)
6639 [(UITableView *) list_ setDataSource:self];
6647 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
6648 Section *prefix([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6649 size_t end([packages count]);
6651 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
6652 Section *section(prefix);
6654 thumbs_ = CollationThumbs_;
6655 offset_ = CollationOffset_;
6658 size_t offsets([CollationStarts_ count]);
6660 NSString *start([CollationStarts_ objectAtIndex:offset]);
6661 size_t length([start length]);
6663 for (size_t index(0); index != end; ++index) {
6665 Package *package([packages objectAtIndex:index]);
6666 NSString *name(PackageName(package, @selector(cyname)));
6668 //while ([start compare:name options:NSNumericSearch range:NSMakeRange(0, length) locale:CollationLocale_] != NSOrderedDescending) {
6669 while (StringNameCompare(start, name, length) != kCFCompareGreaterThan) {
6670 NSString *title([CollationTitles_ objectAtIndex:offset]);
6671 section = [[[Section alloc] initWithName:title row:index localize:NO] autorelease];
6672 [sections addObject:section];
6674 start = ++offset == offsets ? nil : [CollationStarts_ objectAtIndex:offset];
6677 length = [start length];
6681 [section addToCount];
6684 for (; offset != offsets; ++offset) {
6685 NSString *title([CollationTitles_ objectAtIndex:offset]);
6686 Section *section([[[Section alloc] initWithName:title row:end localize:NO] autorelease]);
6687 [sections addObject:section];
6690 if ([prefix count] != 0) {
6691 Section *suffix([sections lastObject]);
6692 [prefix setName:[suffix name]];
6693 [suffix setName:nil];
6694 [sections insertObject:prefix atIndex:(offsets - 1)];
6700 - (void) reloadData {
6703 if ([self shouldYield])
6704 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6709 - (void) resetCursor {
6710 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6713 - (void) clearData {
6714 [self updateHeight];
6716 [list_ setDataSource:nil];
6724 /* Filtered Package List Controller {{{ */
6725 typedef Function<bool, Package *> PackageFilter;
6726 typedef Function<void, NSMutableArray *> PackageSorter;
6727 @interface FilteredPackageListController : PackageListController {
6728 PackageFilter filter_;
6729 PackageSorter sorter_;
6732 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter;
6734 - (void) setFilter:(PackageFilter)filter;
6735 - (void) setSorter:(PackageSorter)sorter;
6739 @implementation FilteredPackageListController
6741 - (void) setFilter:(PackageFilter)filter {
6742 @synchronized (self) {
6746 - (void) setSorter:(PackageSorter)sorter {
6747 @synchronized (self) {
6751 - (NSMutableArray *) _reloadPackages {
6752 @synchronized (database_) {
6753 era_ = [database_ era];
6755 NSArray *packages([database_ packages]);
6756 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6758 PackageFilter filter;
6759 PackageSorter sorter;
6761 @synchronized (self) {
6766 _profile(PackageTable$reloadData$Filter)
6767 for (Package *package in packages)
6768 if ([package valid] && filter(package))
6769 [filtered addObject:package];
6777 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter {
6778 if ((self = [super initWithDatabase:database title:title]) != nil) {
6779 [self setFilter:filter];
6786 /* Home Controller {{{ */
6787 @interface HomeController : CydiaWebViewController {
6788 CFRunLoopRef runloop_;
6789 SCNetworkReachabilityRef reachability_;
6794 @implementation HomeController
6796 static void HomeControllerReachabilityCallback(SCNetworkReachabilityRef reachability, SCNetworkReachabilityFlags flags, void *info) {
6797 [(HomeController *) info dispatchEvent:@"CydiaReachabilityCallback"];
6801 if ((self = [super init]) != nil) {
6802 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6805 reachability_ = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "cydia.saurik.com");
6806 if (reachability_ != NULL) {
6807 SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
6808 SCNetworkReachabilitySetCallback(reachability_, HomeControllerReachabilityCallback, &context);
6810 CFRunLoopRef runloop(CFRunLoopGetCurrent());
6811 if (SCNetworkReachabilityScheduleWithRunLoop(reachability_, runloop, kCFRunLoopDefaultMode))
6818 if (reachability_ != NULL && runloop_ != NULL)
6819 SCNetworkReachabilityUnscheduleFromRunLoop(reachability_, runloop_, kCFRunLoopDefaultMode);
6823 - (NSURL *) navigationURL {
6824 return [NSURL URLWithString:@"cydia://home"];
6827 - (void) aboutButtonClicked {
6828 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6830 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6831 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6832 [alert setCancelButtonIndex:0];
6835 @"Copyright \u00a9 2008-2014\n"
6838 "Jay Freeman (saurik)\n"
6839 "saurik@saurik.com\n"
6840 "http://www.saurik.com/"
6846 - (UIBarButtonItem *) leftButton {
6847 return [[[UIBarButtonItem alloc]
6848 initWithTitle:UCLocalize("ABOUT")
6849 style:UIBarButtonItemStylePlain
6851 action:@selector(aboutButtonClicked)
6858 /* Cydia Navigation Controller Interface {{{ */
6859 @interface UINavigationController (Cydia)
6861 - (NSArray *) navigationURLCollection;
6862 - (void) unloadData;
6867 /* Cydia Tab Bar Controller {{{ */
6868 @interface CydiaTabBarController : CyteTabBarController <
6869 UITabBarControllerDelegate,
6872 _transient Database *database_;
6874 _H<UIActivityIndicatorView> indicator_;
6877 // XXX: ok, "updatedelegate_"?...
6878 _transient NSObject<CydiaDelegate> *updatedelegate_;
6881 - (NSArray *) navigationURLCollection;
6882 - (void) beginUpdate;
6887 @implementation CydiaTabBarController
6889 - (NSArray *) navigationURLCollection {
6890 NSMutableArray *items([NSMutableArray array]);
6892 // XXX: Should this deal with transient view controllers?
6893 for (id navigation in [self viewControllers]) {
6894 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6896 [items addObject:stack];
6902 - (id) initWithDatabase:(Database *)database {
6903 if ((self = [super init]) != nil) {
6904 database_ = database;
6905 [self setDelegate:self];
6907 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteTiny] autorelease];
6908 [indicator_ setOrigin:CGPointMake(kCFCoreFoundationVersionNumber >= 800 ? 2 : 4, 2)];
6910 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6914 - (void) setUpdate:(NSDate *)date {
6918 - (void) beginUpdate {
6922 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
6923 UITabBarItem *item([controller tabBarItem]);
6925 [item setBadgeValue:@""];
6926 UIView *badge(MSHookIvar<UIView *>([item view], "_badge"));
6928 [indicator_ startAnimating];
6929 [badge addSubview:indicator_];
6931 [updatedelegate_ retainNetworkActivityIndicator];
6935 detachNewThreadSelector:@selector(performUpdate)
6941 - (void) performUpdate {
6942 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
6944 SourceStatus status(self, database_);
6945 [database_ updateWithStatus:status];
6948 performSelectorOnMainThread:@selector(completeUpdate)
6956 - (void) stopUpdateWithSelector:(SEL)selector {
6958 [updatedelegate_ releaseNetworkActivityIndicator];
6960 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
6961 [[controller tabBarItem] setBadgeValue:nil];
6963 [indicator_ removeFromSuperview];
6964 [indicator_ stopAnimating];
6966 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6969 - (void) completeUpdate {
6972 [self stopUpdateWithSelector:@selector(reloadData)];
6975 - (void) cancelUpdate {
6976 [self stopUpdateWithSelector:@selector(updateDataAndLoad)];
6979 - (void) cancelPressed {
6980 [self cancelUpdate];
6987 - (bool) isSourceCancelled {
6991 - (void) startSourceFetch:(NSString *)uri {
6994 - (void) stopSourceFetch:(NSString *)uri {
6997 - (void) setUpdateDelegate:(id)delegate {
6998 updatedelegate_ = delegate;
7004 /* Cydia Navigation Controller Implementation {{{ */
7005 @implementation UINavigationController (Cydia)
7007 - (NSArray *) navigationURLCollection {
7008 NSMutableArray *stack([NSMutableArray array]);
7010 for (CyteViewController *controller in [self viewControllers]) {
7011 NSString *url = [[controller navigationURL] absoluteString];
7013 [stack addObject:url];
7019 - (void) reloadData {
7022 UIViewController *visible([self visibleViewController]);
7024 [visible reloadData];
7026 // on the iPad, this view controller is ALSO visible. :(
7028 if (UIViewController *top = [self topViewController])
7033 - (void) unloadData {
7034 for (CyteViewController *page in [self viewControllers])
7043 /* Cydia:// Protocol {{{ */
7044 @interface CydiaURLProtocol : NSURLProtocol {
7049 @implementation CydiaURLProtocol
7051 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7052 NSURL *url([request URL]);
7056 NSString *scheme([[url scheme] lowercaseString]);
7057 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7059 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7065 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7069 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7070 id<NSURLProtocolClient> client([self client]);
7072 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7074 NSData *data(UIImagePNGRepresentation(icon));
7076 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7077 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7078 [client URLProtocol:self didLoadData:data];
7079 [client URLProtocolDidFinishLoading:self];
7083 - (void) startLoading {
7084 id<NSURLProtocolClient> client([self client]);
7085 NSURLRequest *request([self request]);
7087 NSURL *url([request URL]);
7088 NSString *href([url absoluteString]);
7089 NSString *scheme([[url scheme] lowercaseString]);
7093 if ([scheme isEqualToString:@"cydia"])
7094 path = [href substringFromIndex:8];
7095 else if ([scheme isEqualToString:@"about"])
7096 path = [href substringFromIndex:12];
7097 else _assert(false);
7099 NSRange slash([path rangeOfString:@"/"]);
7102 if (slash.location == NSNotFound) {
7106 command = [path substringToIndex:slash.location];
7107 path = [path substringFromIndex:(slash.location + 1)];
7110 Database *database([Database sharedInstance]);
7112 if ([command isEqualToString:@"package-icon"]) {
7115 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7116 Package *package([database packageWithName:path]);
7120 UIImage *icon([package icon]);
7121 [self _returnPNGWithImage:icon forRequest:request];
7122 } else if ([command isEqualToString:@"uikit-image"]) {
7125 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7126 UIImage *icon(_UIImageWithName(path));
7127 [self _returnPNGWithImage:icon forRequest:request];
7128 } else if ([command isEqualToString:@"section-icon"]) {
7131 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7132 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7134 icon = [UIImage applicationImageNamed:@"unknown.png"];
7135 [self _returnPNGWithImage:icon forRequest:request];
7137 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7141 - (void) stopLoading {
7147 /* Section Controller {{{ */
7148 @interface SectionController : FilteredPackageListController {
7150 _H<NSString> section_;
7153 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section;
7157 @implementation SectionController
7159 - (NSURL *) referrerURL {
7160 NSString *name(section_);
7161 name = name ?: @"*";
7162 NSString *key(key_);
7164 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sections/%@/%@", UI_, [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7167 - (NSURL *) navigationURL {
7168 NSString *name(section_);
7169 name = name ?: @"*";
7170 NSString *key(key_);
7172 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@/%@", [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7175 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section {
7178 title = UCLocalize("ALL_PACKAGES");
7179 else if (![section isEqual:@""])
7180 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(section) value:nil table:@"Sections"];
7182 title = UCLocalize("NO_SECTION");
7184 if ((self = [super initWithDatabase:database title:title]) != nil) {
7185 key_ = [source key];
7190 - (void) reloadData {
7191 Source *source([database_ sourceWithKey:key_]);
7192 _H<NSString> name(section_);
7194 [self setFilter:[=](Package *package) {
7195 NSString *section([package section]);
7199 section == nil && [name length] == 0 ||
7200 [name isEqualToString:section]
7203 [package source] == source
7204 ) && [package visible];
7212 /* Sections Controller {{{ */
7213 @interface SectionsController : CyteViewController <
7214 UITableViewDataSource,
7217 _transient Database *database_;
7219 _H<NSMutableArray> sections_;
7220 _H<NSMutableArray> filtered_;
7221 _H<UITableView, 2> list_;
7224 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7225 - (void) editButtonClicked;
7229 @implementation SectionsController
7231 - (NSURL *) navigationURL {
7232 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
7235 - (Source *) source {
7238 return [database_ sourceWithKey:key_];
7241 - (void) updateNavigationItem {
7242 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7243 if ([sections_ count] == 0) {
7244 [[self navigationItem] setRightBarButtonItem:nil];
7246 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7247 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7249 action:@selector(editButtonClicked)
7250 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7254 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7255 [super setEditing:editing animated:animated];
7260 [delegate_ updateData];
7262 [self updateNavigationItem];
7265 - (void) viewDidAppear:(BOOL)animated {
7266 [super viewDidAppear:animated];
7267 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7270 - (void) viewWillDisappear:(BOOL)animated {
7271 [super viewWillDisappear:animated];
7272 [self setEditing:NO];
7275 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7276 Section *section = nil;
7277 int index = [indexPath row];
7278 if (![self isEditing]) {
7281 section = [filtered_ objectAtIndex:index];
7283 section = [sections_ objectAtIndex:index];
7288 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7289 if ([self isEditing])
7290 return [sections_ count];
7292 return [filtered_ count] + 1;
7295 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7299 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7300 static NSString *reuseIdentifier = @"SectionCell";
7302 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7304 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7306 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7311 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7312 if ([self isEditing])
7315 Section *section = [self sectionAtIndexPath:indexPath];
7317 SectionController *controller = [[[SectionController alloc]
7318 initWithDatabase:database_
7319 source:[self source]
7320 section:[section name]
7322 [controller setDelegate:delegate_];
7324 [[self navigationController] pushViewController:controller animated:YES];
7328 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
7329 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7330 [list_ setRowHeight:46];
7331 [(UITableView *) list_ setDataSource:self];
7332 [list_ setDelegate:self];
7333 [self setView:list_];
7336 - (void) viewDidLoad {
7337 [super viewDidLoad];
7339 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7342 - (void) releaseSubviews {
7348 [super releaseSubviews];
7351 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7352 if ((self = [super init]) != nil) {
7353 database_ = database;
7354 key_ = [source key];
7358 - (void) reloadData {
7361 NSArray *packages = [database_ packages];
7363 sections_ = [NSMutableArray arrayWithCapacity:16];
7364 filtered_ = [NSMutableArray arrayWithCapacity:16];
7366 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7368 Source *source([self source]);
7371 for (Package *package in packages) {
7372 if (source != nil && [package source] != source)
7375 NSString *name([package section]);
7376 NSString *key(name == nil ? @"" : name);
7380 _profile(SectionsView$reloadData$Section)
7381 section = [sections objectForKey:key];
7382 if (section == nil) {
7383 _profile(SectionsView$reloadData$Section$Allocate)
7384 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7385 [sections setObject:section forKey:key];
7390 [section addToCount];
7392 _profile(SectionsView$reloadData$Filter)
7393 if (![package valid] || ![package visible])
7401 [sections_ addObjectsFromArray:[sections allValues]];
7403 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7405 for (Section *section in (id) sections_) {
7406 size_t count([section row]);
7410 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7411 [section setCount:count];
7412 [filtered_ addObject:section];
7415 [self updateNavigationItem];
7420 - (void) editButtonClicked {
7421 [self setEditing:![self isEditing] animated:YES];
7427 /* Changes Controller {{{ */
7428 @interface ChangesController : FilteredPackageListController {
7432 - (id) initWithDatabase:(Database *)database;
7436 @implementation ChangesController
7438 - (NSURL *) referrerURL {
7439 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/changes/", UI_]];
7442 - (NSURL *) navigationURL {
7443 return [NSURL URLWithString:@"cydia://changes"];
7446 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7447 @synchronized (database_) {
7448 if ([database_ era] != era_)
7451 NSUInteger sectionIndex([path section]);
7452 if (sectionIndex >= [sections_ count])
7454 Section *section([sections_ objectAtIndex:sectionIndex]);
7455 NSInteger row([path row]);
7456 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7459 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7460 NSString *context([alert context]);
7462 if ([context isEqualToString:@"norefresh"])
7463 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7466 - (void) setLeftBarButtonItem {
7467 if ([delegate_ updating])
7468 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7469 initWithTitle:UCLocalize("CANCEL")
7470 style:UIBarButtonItemStyleDone
7472 action:@selector(cancelButtonClicked)
7473 ] autorelease] animated:YES];
7475 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7476 initWithTitle:UCLocalize("REFRESH")
7477 style:UIBarButtonItemStylePlain
7479 action:@selector(refreshButtonClicked)
7480 ] autorelease] animated:YES];
7483 - (void) refreshButtonClicked {
7484 if ([delegate_ requestUpdate])
7485 [self setLeftBarButtonItem];
7488 - (void) cancelButtonClicked {
7489 [delegate_ cancelUpdate];
7492 - (void) upgradeButtonClicked {
7493 [delegate_ distUpgrade];
7494 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7497 - (bool) shouldYield {
7501 - (bool) shouldBlock {
7505 - (void) useFilter {
7506 @synchronized (self) {
7507 [self setFilter:[](Package *package) {
7508 return [package upgradableAndEssential:YES] || [package visible];
7511 [self setSorter:[](NSMutableArray *packages) {
7512 [packages radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7516 - (id) initWithDatabase:(Database *)database {
7517 if ((self = [super initWithDatabase:database title:UCLocalize("CHANGES")]) != nil) {
7522 - (void) viewDidLoad {
7523 [super viewDidLoad];
7524 [self setLeftBarButtonItem];
7527 - (void) viewWillAppear:(BOOL)animated {
7528 [super viewWillAppear:animated];
7529 [self setLeftBarButtonItem];
7532 - (void) reloadData {
7533 [self setLeftBarButtonItem];
7537 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
7538 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
7540 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7541 Section *ignored = nil;
7542 Section *section = nil;
7546 bool unseens = false;
7548 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7550 for (size_t offset = 0, count = [packages count]; offset != count; ++offset) {
7551 Package *package = [packages objectAtIndex:offset];
7553 BOOL uae = [package upgradableAndEssential:YES];
7557 time_t seen([package seen]);
7559 if (section == nil || last != seen) {
7563 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7566 _profile(ChangesController$reloadData$Allocate)
7567 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7568 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7569 [sections addObject:section];
7573 [section addToCount];
7574 } else if ([package ignored]) {
7575 if (ignored == nil) {
7576 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7578 [ignored addToCount];
7581 [upgradable addToCount];
7586 CFRelease(formatter);
7589 Section *last = [sections lastObject];
7590 size_t count = [last count];
7591 [packages removeObjectsInRange:NSMakeRange([packages count] - count, count)];
7592 [sections removeLastObject];
7595 if ([ignored count] != 0)
7596 [sections insertObject:ignored atIndex:0];
7598 [sections insertObject:upgradable atIndex:0];
7602 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7603 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7604 style:UIBarButtonItemStylePlain
7606 action:@selector(upgradeButtonClicked)
7607 ] autorelease]) animated:YES];
7614 /* Search Controller {{{ */
7615 @interface SearchController : FilteredPackageListController <
7618 _H<UISearchBar, 1> search_;
7623 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7624 - (void) reloadData;
7628 @implementation SearchController
7630 - (NSURL *) referrerURL {
7631 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/search?q=%@", UI_, [([search_ text] ?: @"") stringByAddingPercentEscapesIncludingReserved]]];
7634 - (NSURL *) navigationURL {
7635 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7636 return [NSURL URLWithString:@"cydia://search"];
7638 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [[search_ text] stringByAddingPercentEscapesIncludingReserved]]];
7641 - (NSArray *) termsForQuery:(NSString *)query {
7642 NSMutableArray *terms([NSMutableArray arrayWithCapacity:2]);
7643 for (NSString *component in [query componentsSeparatedByString:@" "])
7644 if ([component length] != 0)
7645 [terms addObject:component];
7650 - (void) useSearch {
7651 _H<NSArray> query([self termsForQuery:[search_ text]]);
7654 @synchronized (self) {
7655 [self setFilter:[=](Package *package) {
7656 if (![package unfiltered])
7658 if (![package matches:query])
7663 [self setSorter:[](NSMutableArray *packages) {
7664 [packages radixSortUsingSelector:@selector(rank)];
7672 - (void) usePrefix:(NSString *)prefix {
7673 _H<NSString> query(prefix);
7676 @synchronized (self) {
7677 [self setFilter:[=](Package *package) {
7678 if ([query length] == 0)
7680 if (![package unfiltered])
7682 if ([[package name] compare:query options:MatchCompareOptions_ range:NSMakeRange(0, [query length])] != NSOrderedSame)
7687 [self setSorter:nullptr];
7693 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7695 [self usePrefix:[search_ text]];
7698 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7699 [search_ resignFirstResponder];
7703 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7704 [search_ setText:@""];
7705 [self searchBarButtonClicked:searchBar];
7708 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7709 [self searchBarButtonClicked:searchBar];
7712 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7713 [self usePrefix:text];
7716 - (bool) shouldYield {
7720 - (bool) shouldBlock {
7724 - (bool) isSummarized {
7728 - (bool) showsSections {
7732 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7733 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH")])) {
7734 search_ = [[[UISearchBar alloc] init] autorelease];
7735 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7736 [search_ setDelegate:self];
7738 UITextField *textField;
7739 if ([search_ respondsToSelector:@selector(searchField)])
7740 textField = [search_ searchField];
7742 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7744 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7745 [textField setEnablesReturnKeyAutomatically:NO];
7746 [[self navigationItem] setTitleView:textField];
7749 [search_ setText:query];
7754 - (void) viewDidAppear:(BOOL)animated {
7755 [super viewDidAppear:animated];
7757 if (!searchloaded_) {
7758 searchloaded_ = YES;
7759 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7760 [search_ layoutSubviews];
7763 if ([self isSummarized])
7764 [search_ becomeFirstResponder];
7767 - (void) reloadData {
7772 - (void) didSelectPackage:(Package *)package {
7773 [search_ resignFirstResponder];
7774 [super didSelectPackage:package];
7779 /* Package Settings Controller {{{ */
7780 @interface PackageSettingsController : CyteViewController <
7781 UITableViewDataSource,
7784 _transient Database *database_;
7786 _H<Package> package_;
7787 _H<UITableView, 2> table_;
7788 _H<UISwitch> subscribedSwitch_;
7789 _H<UISwitch> ignoredSwitch_;
7790 _H<UITableViewCell> subscribedCell_;
7791 _H<UITableViewCell> ignoredCell_;
7794 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7798 @implementation PackageSettingsController
7800 - (NSURL *) navigationURL {
7801 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
7804 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7805 if (package_ == nil)
7808 if ([package_ installed] == nil)
7814 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7815 if (package_ == nil)
7818 // both sections contain just one item right now.
7822 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7826 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7828 return UCLocalize("SHOW_ALL_CHANGES_EX");
7830 return UCLocalize("IGNORE_UPGRADES_EX");
7833 - (void) onSubscribed:(id)control {
7834 bool value([control isOn]);
7835 if (package_ == nil)
7837 if ([package_ setSubscribed:value])
7838 [delegate_ updateData];
7841 - (void) _updateIgnored {
7842 const char *package([name_ UTF8String]);
7843 bool on([ignoredSwitch_ isOn]);
7845 pid_t pid(ExecFork());
7847 FILE *dpkg(popen("dpkg --set-selections", "w"));
7848 fwrite(package, strlen(package), 1, dpkg);
7851 fwrite(" hold\n", 6, 1, dpkg);
7853 fwrite(" install\n", 9, 1, dpkg);
7861 - (void) onIgnored:(id)control {
7862 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7863 [invocation setTarget:self];
7864 [invocation setSelector:@selector(_updateIgnored)];
7866 [delegate_ reloadDataWithInvocation:invocation];
7869 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7870 if (package_ == nil)
7873 switch ([indexPath section]) {
7874 case 0: return subscribedCell_;
7875 case 1: return ignoredCell_;
7884 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
7885 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
7886 [self setView:view];
7888 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7889 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7890 [(UITableView *) table_ setDataSource:self];
7891 [table_ setDelegate:self];
7892 [view addSubview:table_];
7894 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7895 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7896 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7898 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7899 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7900 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7902 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7903 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7904 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7905 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7907 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7908 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7909 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7910 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7913 - (void) viewDidLoad {
7914 [super viewDidLoad];
7916 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7919 - (void) releaseSubviews {
7921 subscribedCell_ = nil;
7923 ignoredSwitch_ = nil;
7924 subscribedSwitch_ = nil;
7926 [super releaseSubviews];
7929 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7930 if ((self = [super init]) != nil) {
7931 database_ = database;
7936 - (void) reloadData {
7939 package_ = [database_ packageWithName:name_];
7941 if (package_ != nil) {
7942 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7943 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7944 } // XXX: what now, G?
7946 [table_ reloadData];
7952 /* Installed Controller {{{ */
7953 @interface InstalledController : FilteredPackageListController {
7957 - (id) initWithDatabase:(Database *)database;
7958 - (void) queueStatusDidChange;
7962 @implementation InstalledController
7964 - (NSURL *) referrerURL {
7965 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/installed/", UI_]];
7968 - (NSURL *) navigationURL {
7969 return [NSURL URLWithString:@"cydia://installed"];
7972 - (void) useRecent {
7975 @synchronized (self) {
7976 [self setFilter:[](Package *package) {
7977 return ![package uninstalled] && package->role_ < 7;
7980 [self setSorter:[](NSMutableArray *packages) {
7981 [packages radixSortUsingSelector:@selector(recent)];
7985 - (void) useFilter:(UISegmentedControl *)segmented {
7986 NSInteger selected([segmented selectedSegmentIndex]);
7988 return [self useRecent];
7989 bool simple(selected == 0);
7992 @synchronized (self) {
7993 [self setFilter:[=](Package *package) {
7994 return ![package uninstalled] && package->role_ <= (simple ? 1 : 3);
7997 [self setSorter:nullptr];
8000 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
8002 return [super sectionsForPackages:packages];
8004 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterLongStyle, kCFDateFormatterNoStyle));
8006 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
8007 Section *section(nil);
8010 for (size_t offset(0), count([packages count]); offset != count; ++offset) {
8011 Package *package([packages objectAtIndex:offset]);
8013 time_t upgraded([package upgraded]);
8014 if (upgraded < 1168364520)
8017 upgraded -= upgraded % (60 * 60 * 24);
8019 if (section == nil || upgraded != last) {
8024 continue; // XXX: name = UCLocalize("...");
8026 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:upgraded]);
8030 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
8031 [sections addObject:section];
8034 [section addToCount];
8037 CFRelease(formatter);
8041 - (id) initWithDatabase:(Database *)database {
8042 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED")]) != nil) {
8043 UISegmentedControl *segmented([[[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:UCLocalize("USER"), UCLocalize("EXPERT"), UCLocalize("RECENT"), nil]] autorelease]);
8044 [segmented setSelectedSegmentIndex:0];
8045 [segmented setSegmentedControlStyle:UISegmentedControlStyleBar];
8046 [[self navigationItem] setTitleView:segmented];
8048 [segmented addTarget:self action:@selector(modeChanged:) forEvents:UIControlEventValueChanged];
8049 [self useFilter:segmented];
8051 [self queueStatusDidChange];
8056 - (void) queueButtonClicked {
8061 - (void) queueStatusDidChange {
8064 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8065 initWithTitle:UCLocalize("QUEUE")
8066 style:UIBarButtonItemStyleDone
8068 action:@selector(queueButtonClicked)
8071 [[self navigationItem] setLeftBarButtonItem:nil];
8076 - (void) modeChanged:(UISegmentedControl *)segmented {
8077 [self useFilter:segmented];
8084 /* Source Cell {{{ */
8085 @interface SourceCell : CyteTableViewCell <
8086 CyteTableViewCellDelegate,
8089 _H<Source, 1> source_;
8092 _H<NSString> origin_;
8093 _H<NSString> label_;
8094 _H<UIActivityIndicatorView> indicator_;
8097 - (void) setSource:(Source *)source;
8098 - (void) setFetch:(NSNumber *)fetch;
8102 @implementation SourceCell
8104 - (void) _setImage:(NSArray *)data {
8105 if ([url_ isEqual:[data objectAtIndex:0]]) {
8106 icon_ = [data objectAtIndex:1];
8107 [content_ setNeedsDisplay];
8111 - (void) _setSource:(NSURL *) url {
8112 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8114 if (NSData *data = [NSURLConnection
8115 sendSynchronousRequest:[NSURLRequest
8117 cachePolicy:NSURLRequestUseProtocolCachePolicy
8121 returningResponse:NULL
8124 if (UIImage *image = [UIImage imageWithData:data])
8125 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
8130 - (void) setSource:(Source *)source {
8132 [source_ setDelegate:self];
8134 [self setFetch:[NSNumber numberWithBool:[source_ fetch]]];
8136 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
8138 origin_ = [source name];
8139 label_ = [source rooturi];
8141 [content_ setNeedsDisplay];
8143 url_ = [source iconURL];
8144 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
8147 - (void) setAllSource {
8149 [indicator_ stopAnimating];
8151 icon_ = [UIImage applicationImageNamed:@"folder.png"];
8152 origin_ = UCLocalize("ALL_SOURCES");
8153 label_ = UCLocalize("ALL_SOURCES_EX");
8154 [content_ setNeedsDisplay];
8157 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8158 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8159 UIView *content([self contentView]);
8160 CGRect bounds([content bounds]);
8162 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8163 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8164 [content_ setBackgroundColor:[UIColor whiteColor]];
8165 [content addSubview:content_];
8167 [content_ setDelegate:self];
8168 [content_ setOpaque:YES];
8170 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGraySmall] autorelease];
8171 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin];// | UIViewAutoresizingFlexibleBottomMargin];
8172 [content addSubview:indicator_];
8174 [[content_ layer] setContentsGravity:kCAGravityTopLeft];
8178 - (void) layoutSubviews {
8179 [super layoutSubviews];
8181 UIView *content([self contentView]);
8182 CGRect bounds([content bounds]);
8184 CGRect frame([indicator_ frame]);
8185 frame.origin.x = bounds.size.width - frame.size.width;
8186 frame.origin.y = Retina((bounds.size.height - frame.size.height) / 2);
8188 if (kCFCoreFoundationVersionNumber < 800)
8189 frame.origin.x -= 8;
8190 [indicator_ setFrame:frame];
8193 - (NSString *) accessibilityLabel {
8197 - (void) drawContentRect:(CGRect)rect {
8198 bool highlighted(highlighted_);
8199 float width(rect.size.width);
8203 rect.size = [(UIImage *) icon_ size];
8205 while (rect.size.width > 32 || rect.size.height > 32) {
8206 rect.size.width /= 2;
8207 rect.size.height /= 2;
8210 rect.origin.x = 26 - rect.size.width / 2;
8211 rect.origin.y = 26 - rect.size.height / 2;
8213 [icon_ drawInRect:Retina(rect)];
8216 if (highlighted && kCFCoreFoundationVersionNumber < 800)
8221 [origin_ drawAtPoint:CGPointMake(52, 8) forWidth:(width - 61) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
8225 [label_ drawAtPoint:CGPointMake(52, 29) forWidth:(width - 61) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
8228 - (void) setFetch:(NSNumber *)fetch {
8229 if ([fetch boolValue])
8230 [indicator_ startAnimating];
8232 [indicator_ stopAnimating];
8237 /* Sources Controller {{{ */
8238 @interface SourcesController : CyteViewController <
8239 UITableViewDataSource,
8242 _transient Database *database_;
8245 _H<UITableView, 2> list_;
8246 _H<NSMutableArray> sources_;
8250 _H<UIProgressHUD> hud_;
8253 NSURLConnection *trivial_bz2_;
8254 NSURLConnection *trivial_gz_;
8259 - (id) initWithDatabase:(Database *)database;
8260 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated;
8264 @implementation SourcesController
8266 - (void) _releaseConnection:(NSURLConnection *)connection {
8267 if (connection != nil) {
8268 [connection cancel];
8269 //[connection setDelegate:nil];
8270 [connection release];
8275 [self _releaseConnection:trivial_gz_];
8276 [self _releaseConnection:trivial_bz2_];
8281 - (NSURL *) navigationURL {
8282 return [NSURL URLWithString:@"cydia://sources"];
8285 - (void) viewDidAppear:(BOOL)animated {
8286 [super viewDidAppear:animated];
8287 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8290 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8294 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8296 return UCLocalize("INDIVIDUAL_SOURCES");
8300 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8303 case 1: return [sources_ count];
8308 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8309 @synchronized (database_) {
8310 if ([database_ era] != era_)
8312 if ([indexPath section] != 1)
8314 NSUInteger index([indexPath row]);
8315 if (index >= [sources_ count])
8317 return [sources_ objectAtIndex:index];
8320 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8321 static NSString *cellIdentifier = @"SourceCell";
8323 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8324 if (cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8325 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8327 Source *source([self sourceAtIndexPath:indexPath]);
8329 [cell setAllSource];
8331 [cell setSource:source];
8336 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8337 SectionsController *controller([[[SectionsController alloc]
8338 initWithDatabase:database_
8339 source:[self sourceAtIndexPath:indexPath]
8342 [controller setDelegate:delegate_];
8343 [[self navigationController] pushViewController:controller animated:YES];
8346 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8347 if ([indexPath section] != 1)
8349 Source *source = [self sourceAtIndexPath:indexPath];
8350 return [source record] != nil;
8353 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8354 _assert([indexPath section] == 1);
8355 if (editingStyle == UITableViewCellEditingStyleDelete) {
8356 Source *source = [self sourceAtIndexPath:indexPath];
8357 if (source == nil) return;
8359 [Sources_ removeObjectForKey:[source key]];
8362 [delegate_ _saveConfig];
8363 [delegate_ reloadDataWithInvocation:nil];
8367 - (void) tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath {
8368 [self updateButtonsForEditingStatusAnimated:YES];
8372 [delegate_ addTrivialSource:href_];
8375 [delegate_ syncData];
8378 - (NSString *) getWarning {
8379 NSString *href(href_);
8380 NSRange colon([href rangeOfString:@"://"]);
8381 if (colon.location != NSNotFound)
8382 href = [href substringFromIndex:(colon.location + 3)];
8383 href = [href stringByAddingPercentEscapes];
8384 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8386 NSURL *url([NSURL URLWithString:href]);
8388 NSStringEncoding encoding;
8389 NSError *error(nil);
8391 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8392 return [warning length] == 0 ? nil : warning;
8396 - (void) _endConnection:(NSURLConnection *)connection {
8397 // XXX: the memory management in this method is horribly awkward
8399 NSURLConnection **field = NULL;
8400 if (connection == trivial_bz2_)
8401 field = &trivial_bz2_;
8402 else if (connection == trivial_gz_)
8403 field = &trivial_gz_;
8404 _assert(field != NULL);
8405 [connection release];
8409 trivial_bz2_ == nil &&
8412 NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil);
8414 [delegate_ releaseNetworkActivityIndicator];
8416 [delegate_ removeProgressHUD:hud_];
8420 if (warning != nil) {
8421 UIAlertView *alert = [[[UIAlertView alloc]
8422 initWithTitle:UCLocalize("SOURCE_WARNING")
8425 cancelButtonTitle:UCLocalize("CANCEL")
8427 UCLocalize("ADD_ANYWAY"),
8431 [alert setContext:@"warning"];
8432 [alert setNumberOfRows:1];
8435 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
8441 } else if (error_ != nil) {
8442 UIAlertView *alert = [[[UIAlertView alloc]
8443 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8444 message:[error_ localizedDescription]
8446 cancelButtonTitle:UCLocalize("OK")
8447 otherButtonTitles:nil
8450 [alert setContext:@"urlerror"];
8455 UIAlertView *alert = [[[UIAlertView alloc]
8456 initWithTitle:UCLocalize("NOT_REPOSITORY")
8457 message:UCLocalize("NOT_REPOSITORY_EX")
8459 cancelButtonTitle:UCLocalize("OK")
8460 otherButtonTitles:nil
8463 [alert setContext:@"trivial"];
8473 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8474 switch ([response statusCode]) {
8480 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8481 lprintf("connection:\"%s\" didFailWithError:\"%s\"\n", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8483 [self _endConnection:connection];
8486 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8487 [self _endConnection:connection];
8490 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8491 NSURL *url([NSURL URLWithString:href]);
8493 NSMutableURLRequest *request = [NSMutableURLRequest
8495 cachePolicy:NSURLRequestUseProtocolCachePolicy
8499 [request setHTTPMethod:method];
8501 if (Machine_ != NULL)
8502 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8504 if (UniqueID_ != nil)
8505 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8507 if ([url isCydiaSecure]) {
8508 if (UniqueID_ != nil)
8509 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
8512 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8515 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8516 NSString *context([alert context]);
8518 if ([context isEqualToString:@"source"]) {
8521 NSString *href = [[alert textField] text];
8523 static Pcre href_r("^http(s?)://[^# ]*$");
8524 if (!href_r(href)) {
8525 UIAlertView *alert = [[[UIAlertView alloc]
8526 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("INVALID_URL")]
8527 message:UCLocalize("INVALID_URL_EX")
8529 cancelButtonTitle:UCLocalize("OK")
8530 otherButtonTitles:nil
8533 [alert setContext:@"badurl"];
8539 if (![href hasSuffix:@"/"])
8540 href_ = [href stringByAppendingString:@"/"];
8544 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8545 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8549 // XXX: this is stupid
8550 hud_ = [delegate_ addProgressHUD];
8551 [hud_ setText:UCLocalize("VERIFYING_URL")];
8552 [delegate_ retainNetworkActivityIndicator];
8561 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8562 } else if ([context isEqualToString:@"trivial"])
8563 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8564 else if ([context isEqualToString:@"urlerror"])
8565 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8566 else if ([context isEqualToString:@"warning"]) {
8569 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
8578 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8582 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated {
8583 BOOL editing([list_ isEditing]);
8586 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8587 initWithTitle:UCLocalize("ADD")
8588 style:UIBarButtonItemStylePlain
8590 action:@selector(addButtonClicked)
8591 ] autorelease] animated:animated];
8592 else if ([delegate_ updating])
8593 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8594 initWithTitle:UCLocalize("CANCEL")
8595 style:UIBarButtonItemStyleDone
8597 action:@selector(cancelButtonClicked)
8598 ] autorelease] animated:animated];
8600 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8601 initWithTitle:UCLocalize("REFRESH")
8602 style:UIBarButtonItemStylePlain
8604 action:@selector(refreshButtonClicked)
8605 ] autorelease] animated:animated];
8607 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8608 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8609 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8611 action:@selector(editButtonClicked)
8612 ] autorelease] animated:animated];
8616 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease];
8617 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8618 [list_ setRowHeight:53];
8619 [(UITableView *) list_ setDataSource:self];
8620 [list_ setDelegate:self];
8621 [self setView:list_];
8624 - (void) viewDidLoad {
8625 [super viewDidLoad];
8627 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8628 [self updateButtonsForEditingStatusAnimated:NO];
8631 - (void) viewWillAppear:(BOOL)animated {
8632 [super viewWillAppear:animated];
8634 [list_ setEditing:NO];
8635 [self updateButtonsForEditingStatusAnimated:NO];
8638 - (void) releaseSubviews {
8643 [super releaseSubviews];
8646 - (id) initWithDatabase:(Database *)database {
8647 if ((self = [super init]) != nil) {
8648 database_ = database;
8652 - (void) reloadData {
8654 [self updateButtonsForEditingStatusAnimated:YES];
8656 @synchronized (database_) {
8657 era_ = [database_ era];
8659 sources_ = [NSMutableArray arrayWithCapacity:16];
8660 [sources_ addObjectsFromArray:[database_ sources]];
8662 [sources_ sortUsingSelector:@selector(compareByName:)];
8665 int count([sources_ count]);
8667 for (int i = 0; i != count; i++) {
8668 if ([[sources_ objectAtIndex:i] record] == nil)
8676 - (void) showAddSourcePrompt {
8677 UIAlertView *alert = [[[UIAlertView alloc]
8678 initWithTitle:UCLocalize("ENTER_APT_URL")
8681 cancelButtonTitle:UCLocalize("CANCEL")
8683 UCLocalize("ADD_SOURCE"),
8687 [alert setContext:@"source"];
8689 [alert setNumberOfRows:1];
8690 [alert addTextFieldWithValue:@"http://" label:@""];
8692 UITextInputTraits *traits = [[alert textField] textInputTraits];
8693 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8694 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8695 [traits setKeyboardType:UIKeyboardTypeURL];
8696 // XXX: UIReturnKeyDone
8697 [traits setReturnKeyType:UIReturnKeyNext];
8702 - (void) addButtonClicked {
8703 [self showAddSourcePrompt];
8706 - (void) refreshButtonClicked {
8707 if ([delegate_ requestUpdate])
8708 [self updateButtonsForEditingStatusAnimated:YES];
8711 - (void) cancelButtonClicked {
8712 [delegate_ cancelUpdate];
8715 - (void) editButtonClicked {
8716 [list_ setEditing:![list_ isEditing] animated:YES];
8717 [self updateButtonsForEditingStatusAnimated:YES];
8723 /* Stash Controller {{{ */
8724 @interface StashController : CyteViewController {
8725 _H<UIActivityIndicatorView> spinner_;
8726 _H<UILabel> status_;
8727 _H<UILabel> caption_;
8732 @implementation StashController
8735 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8736 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8737 [self setView:view];
8739 [view setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8741 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8742 CGRect spinrect = [spinner_ frame];
8743 spinrect.origin.x = Retina([[self view] frame].size.width / 2 - spinrect.size.width / 2);
8744 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8745 [spinner_ setFrame:spinrect];
8746 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8747 [view addSubview:spinner_];
8748 [spinner_ startAnimating];
8751 captrect.size.width = [[self view] frame].size.width;
8752 captrect.size.height = 40.0f;
8753 captrect.origin.x = 0;
8754 captrect.origin.y = Retina([[self view] frame].size.height / 2 - captrect.size.height * 2);
8755 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8756 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8757 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8758 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8759 [caption_ setTextColor:[UIColor whiteColor]];
8760 [caption_ setBackgroundColor:[UIColor clearColor]];
8761 [caption_ setShadowColor:[UIColor blackColor]];
8762 [caption_ setTextAlignment:NSTextAlignmentCenter];
8763 [view addSubview:caption_];
8766 statusrect.size.width = [[self view] frame].size.width;
8767 statusrect.size.height = 30.0f;
8768 statusrect.origin.x = 0;
8769 statusrect.origin.y = Retina([[self view] frame].size.height / 2 - statusrect.size.height);
8770 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8771 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8772 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8773 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8774 [status_ setTextColor:[UIColor whiteColor]];
8775 [status_ setBackgroundColor:[UIColor clearColor]];
8776 [status_ setShadowColor:[UIColor blackColor]];
8777 [status_ setTextAlignment:NSTextAlignmentCenter];
8778 [view addSubview:status_];
8781 - (void) releaseSubviews {
8786 [super releaseSubviews];
8792 @interface CYURLCache : SDURLCache {
8797 @implementation CYURLCache
8799 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8802 else if ([event isEqualToString:@"no-cache"])
8804 else if ([event isEqualToString:@"store"])
8806 else if ([event isEqualToString:@"invalid"])
8808 else if ([event isEqualToString:@"memory"])
8810 else if ([event isEqualToString:@"disk"])
8812 else if ([event isEqualToString:@"miss"])
8815 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8819 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
8820 if (NSURLResponse *response = [cached response])
8821 if (NSString *mime = [response MIMEType])
8822 if ([mime isEqualToString:@"text/cache-manifest"]) {
8823 NSURL *url([response URL]);
8826 NSLog(@"###: %@", [url absoluteString]);
8829 @synchronized (HostConfig_) {
8830 [CachedURLs_ addObject:url];
8834 [super storeCachedResponse:cached forRequest:request];
8839 @interface Cydia : UIApplication <
8840 ConfirmationControllerDelegate,
8844 _H<UIWindow> window_;
8845 _H<CydiaTabBarController> tabbar_;
8846 _H<CyteTabBarController> emulated_;
8848 _H<NSMutableArray> essential_;
8849 _H<NSMutableArray> broken_;
8851 Database *database_;
8853 _H<NSURL> starturl_;
8858 _H<StashController> stash_;
8867 @implementation Cydia
8869 - (void) lockSuspend {
8870 if (locked_++ == 0) {
8871 if ($SBSSetInterceptsMenuButtonForever != NULL)
8872 (*$SBSSetInterceptsMenuButtonForever)(true);
8874 [self setIdleTimerDisabled:YES];
8878 - (void) unlockSuspend {
8879 if (--locked_ == 0) {
8880 [self setIdleTimerDisabled:NO];
8882 if ($SBSSetInterceptsMenuButtonForever != NULL)
8883 (*$SBSSetInterceptsMenuButtonForever)(false);
8887 - (void) beginUpdate {
8888 [tabbar_ beginUpdate];
8891 - (void) cancelUpdate {
8892 [tabbar_ cancelUpdate];
8895 - (bool) requestUpdate {
8896 if (IsReachable("cydia.saurik.com")) {
8900 UIAlertView *alert = [[[UIAlertView alloc]
8901 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("REFRESH")]
8902 message:@"Host Unreachable" // XXX: Localize
8904 cancelButtonTitle:UCLocalize("OK")
8905 otherButtonTitles:nil
8908 [alert setContext:@"norefresh"];
8916 return [tabbar_ updating];
8920 if ([broken_ count] != 0) {
8921 int count = [broken_ count];
8923 UIAlertView *alert = [[[UIAlertView alloc]
8924 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8925 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8927 cancelButtonTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("FORCIBLY_CLEAR"), UCLocalize("UNSAFE")]
8929 UCLocalize("TEMPORARY_IGNORE"),
8933 [alert setContext:@"fixhalf"];
8934 [alert setNumberOfRows:2];
8936 } else if (!Ignored_ && [essential_ count] != 0) {
8937 int count = [essential_ count];
8939 UIAlertView *alert = [[[UIAlertView alloc]
8940 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8941 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8943 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8945 UCLocalize("UPGRADE_ESSENTIAL"),
8946 UCLocalize("COMPLETE_UPGRADE"),
8950 [alert setContext:@"upgrade"];
8955 - (void) returnToCydia {
8959 - (void) _saveConfig {
8960 @synchronized (database_) {
8967 NSString *error(nil);
8969 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8971 NSError *error(nil);
8972 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8973 NSLog(@"failure to save metadata data: %@", error);
8978 NSLog(@"failure to serialize metadata: %@", error);
8982 CydiaWriteSources();
8985 // Navigation controller for the queuing badge.
8986 - (UINavigationController *) queueNavigationController {
8987 NSArray *controllers = [tabbar_ viewControllers];
8988 return [controllers objectAtIndex:3];
8991 - (void) unloadData {
8992 [tabbar_ unloadData];
8995 - (void) _updateData {
8999 UINavigationController *navigation = [self queueNavigationController];
9001 id queuedelegate = nil;
9002 if ([[navigation viewControllers] count] > 0)
9003 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9005 [queuedelegate queueStatusDidChange];
9006 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9009 - (void) _refreshIfPossible:(NSDate *)update {
9010 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9012 bool recently = false;
9013 if (update != nil) {
9014 NSTimeInterval interval([update timeIntervalSinceNow]);
9015 if (interval <= 0 && interval > -(15*60))
9019 // Don't automatic refresh if:
9020 // - We already refreshed recently.
9021 // - We already auto-refreshed this launch.
9022 // - Auto-refresh is disabled.
9023 // - Cydia's server is not reachable
9024 if (recently || loaded_ || ManualRefresh || !IsReachable("cydia.saurik.com")) {
9025 // If we are cancelling, we need to make sure it knows it's already loaded.
9028 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9030 // We are going to load, so remember that.
9033 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
9039 - (void) refreshIfPossible {
9040 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
9043 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9044 _profile(reloadDataWithInvocation)
9045 @synchronized (self) {
9046 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9048 [hud setText:UCLocalize("RELOADING_DATA")];
9050 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9054 [essential_ removeAllObjects];
9055 [broken_ removeAllObjects];
9057 _profile(reloadDataWithInvocation$Essential)
9058 NSArray *packages([database_ packages]);
9059 for (Package *package in packages) {
9061 [broken_ addObject:package];
9062 if ([package upgradableAndEssential:YES] && ![package ignored]) {
9063 if ([package essential] && [package installed] != nil)
9064 [essential_ addObject:package];
9070 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9073 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9074 [changesItem setBadgeValue:badge];
9075 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9076 [self setApplicationIconBadgeNumber:changes];
9079 [changesItem setBadgeValue:nil];
9080 [changesItem setAnimatedBadge:NO];
9081 [self setApplicationIconBadgeNumber:0];
9087 [self removeProgressHUD:hud];
9094 - (void) updateData {
9098 - (void) updateDataAndLoad {
9100 if ([database_ progressDelegate] == nil)
9106 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9109 - (void) disemulate {
9110 if (emulated_ == nil)
9113 if ([window_ respondsToSelector:@selector(setRootViewController:)])
9114 [window_ setRootViewController:tabbar_];
9116 [window_ addSubview:[tabbar_ view]];
9117 [[emulated_ view] removeFromSuperview];
9121 [window_ setUserInteractionEnabled:YES];
9124 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9125 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9127 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9129 UIViewController *parent;
9130 if (emulated_ == nil)
9139 [parent presentModalViewController:navigation animated:YES];
9142 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9143 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9145 if (navigation != nil)
9146 [navigation pushViewController:progress animated:YES];
9148 [self presentModalViewController:progress force:YES];
9150 [progress invoke:invocation withTitle:title];
9154 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9155 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9158 - (void) repairWithInvocation:(NSInvocation *)invocation {
9160 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9164 - (void) repairWithSelector:(SEL)selector {
9165 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9168 - (void) reloadData {
9169 [self reloadDataWithInvocation:nil];
9170 if ([database_ progressDelegate] == nil)
9176 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9179 - (void) addSource:(NSDictionary *) source {
9180 CydiaAddSource(source);
9183 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9184 CydiaAddSource(href, distribution, sections);
9187 - (void) addTrivialSource:(NSString *)href {
9188 CydiaAddSource(href, @"./");
9191 - (void) updateValues {
9196 pkgProblemResolver *resolver = [database_ resolver];
9198 resolver->InstallProtect();
9199 if (!resolver->Resolve(true))
9204 // XXX: this is a really crappy way of doing this.
9205 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9206 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9207 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9208 if ([tabbar_ updating])
9209 [tabbar_ cancelUpdate];
9211 if (![database_ prepare])
9214 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9215 [page setDelegate:self];
9216 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9219 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9220 [tabbar_ presentModalViewController:confirm_ animated:YES];
9226 @synchronized (self) {
9231 - (void) clearPackage:(Package *)package {
9232 @synchronized (self) {
9239 - (void) installPackages:(NSArray *)packages {
9240 @synchronized (self) {
9241 for (Package *package in packages)
9248 - (void) installPackage:(Package *)package {
9249 @synchronized (self) {
9256 - (void) removePackage:(Package *)package {
9257 @synchronized (self) {
9264 - (void) distUpgrade {
9265 @synchronized (self) {
9266 if (![database_ upgrade])
9274 system("su -c /usr/bin/uicache mobile");
9279 UIProgressHUD *hud([self addProgressHUD]);
9280 [hud setText:UCLocalize("LOADING")];
9281 [self yieldToSelector:@selector(_uicache)];
9282 [self removeProgressHUD:hud];
9286 [database_ perform];
9287 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9288 [self performSelectorOnMainThread:@selector(uicache) withObject:nil waitUntilDone:YES];
9291 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9294 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9295 [self unlockSuspend];
9298 - (void) retainNetworkActivityIndicator {
9299 if (activity_++ == 0)
9300 [self setNetworkActivityIndicatorVisible:YES];
9303 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9307 - (void) releaseNetworkActivityIndicator {
9308 if (--activity_ == 0)
9309 [self setNetworkActivityIndicatorVisible:NO];
9312 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9317 - (void) cancelAndClear:(bool)clear {
9318 @synchronized (self) {
9330 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9331 NSString *context([alert context]);
9333 if ([context isEqualToString:@"conffile"]) {
9334 FILE *input = [database_ input];
9335 if (button == [alert cancelButtonIndex])
9336 fprintf(input, "N\n");
9337 else if (button == [alert firstOtherButtonIndex])
9338 fprintf(input, "Y\n");
9341 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9342 } else if ([context isEqualToString:@"fixhalf"]) {
9343 if (button == [alert cancelButtonIndex]) {
9344 @synchronized (self) {
9345 for (Package *broken in (id) broken_) {
9348 NSString *id = [broken id];
9349 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9350 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9351 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9352 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9358 } else if (button == [alert firstOtherButtonIndex]) {
9359 [broken_ removeAllObjects];
9363 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9364 } else if ([context isEqualToString:@"upgrade"]) {
9365 if (button == [alert firstOtherButtonIndex]) {
9366 @synchronized (self) {
9367 for (Package *essential in (id) essential_)
9368 [essential install];
9373 } else if (button == [alert firstOtherButtonIndex] + 1) {
9375 } else if (button == [alert cancelButtonIndex]) {
9379 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9383 - (void) system:(NSString *)command {
9384 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9387 system([command UTF8String]);
9393 - (void) applicationWillSuspend {
9395 [super applicationWillSuspend];
9398 - (BOOL) isSafeToSuspend {
9401 NSLog(@"isSafeToSuspend: locked_ != 0");
9406 if ([tabbar_ modalViewController] != nil)
9409 // Use external process status API internally.
9410 // This is probably a really bad idea.
9411 // XXX: what is the point of this? does this solve anything at all?
9412 uint64_t status = 0;
9414 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9415 notify_get_state(notify_token, &status);
9416 notify_cancel(notify_token);
9421 NSLog(@"isSafeToSuspend: status != 0");
9427 NSLog(@"isSafeToSuspend: -> true");
9432 - (void) applicationSuspend:(__GSEvent *)event {
9433 if ([self isSafeToSuspend])
9434 [super applicationSuspend:event];
9437 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9438 if ([self isSafeToSuspend])
9439 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9442 - (void) _setSuspended:(BOOL)value {
9443 if ([self isSafeToSuspend])
9444 [super _setSuspended:value];
9447 - (UIProgressHUD *) addProgressHUD {
9448 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9449 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9451 [window_ setUserInteractionEnabled:NO];
9453 UIViewController *target(tabbar_);
9454 if (UIViewController *modal = [target modalViewController])
9457 [hud showInView:[target view]];
9463 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9464 [self unlockSuspend];
9466 [hud removeFromSuperview];
9467 [window_ setUserInteractionEnabled:YES];
9470 - (CyteViewController *) pageForPackage:(NSString *)name withReferrer:(NSString *)referrer {
9471 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name withReferrer:referrer] autorelease];
9474 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external withReferrer:(NSString *)referrer {
9475 NSString *scheme([[url scheme] lowercaseString]);
9476 if ([[url absoluteString] length] <= [scheme length] + 3)
9478 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9479 NSArray *components([path componentsSeparatedByString:@"/"]);
9481 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"]) {
9482 CyteViewController *controller([self pageForPackage:[components objectAtIndex:1] withReferrer:referrer]);
9483 if (controller != nil)
9484 [controller setDelegate:self];
9488 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9491 NSString *base([components objectAtIndex:0]);
9493 CyteViewController *controller = nil;
9495 if ([base isEqualToString:@"url"]) {
9496 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9497 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9498 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9499 } else if (!external && [components count] == 1) {
9500 if ([base isEqualToString:@"sources"]) {
9501 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9504 if ([base isEqualToString:@"home"]) {
9505 controller = [[[HomeController alloc] init] autorelease];
9508 if ([base isEqualToString:@"sections"]) {
9509 controller = [[[SectionsController alloc] initWithDatabase:database_ source:nil] autorelease];
9512 if ([base isEqualToString:@"search"]) {
9513 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9516 if ([base isEqualToString:@"changes"]) {
9517 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9520 if ([base isEqualToString:@"installed"]) {
9521 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9523 } else if ([components count] == 2) {
9524 NSString *argument = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9526 if ([base isEqualToString:@"package"]) {
9527 controller = [self pageForPackage:argument withReferrer:referrer];
9530 if (!external && [base isEqualToString:@"search"]) {
9531 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9534 if (!external && [base isEqualToString:@"sections"]) {
9535 if ([argument isEqualToString:@"all"] || [argument isEqualToString:@"*"])
9537 controller = [[[SectionController alloc] initWithDatabase:database_ source:nil section:argument] autorelease];
9540 if (!external && [base isEqualToString:@"sources"]) {
9541 if ([argument isEqualToString:@"add"]) {
9542 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9543 [(SourcesController *)controller showAddSourcePrompt];
9545 Source *source([database_ sourceWithKey:argument]);
9546 controller = [[[SectionsController alloc] initWithDatabase:database_ source:source] autorelease];
9550 if (!external && [base isEqualToString:@"launch"]) {
9551 [self launchApplicationWithIdentifier:argument suspended:NO];
9554 } else if (!external && [components count] == 3) {
9555 NSString *arg1 = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9556 NSString *arg2 = [[components objectAtIndex:2] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9558 if ([base isEqualToString:@"package"]) {
9559 if ([arg2 isEqualToString:@"settings"]) {
9560 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9561 } else if ([arg2 isEqualToString:@"files"]) {
9562 if (Package *package = [database_ packageWithName:arg1]) {
9563 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9564 [(FileTable *)controller setPackage:package];
9569 if ([base isEqualToString:@"sections"]) {
9570 Source *source([arg1 isEqualToString:@"*"] ? nil : [database_ sourceWithKey:arg1]);
9571 NSString *section([arg2 isEqualToString:@"*"] ? nil : arg2);
9572 controller = [[[SectionController alloc] initWithDatabase:database_ source:source section:section] autorelease];
9576 [controller setDelegate:self];
9580 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9581 CyteViewController *page([self pageForURL:url forExternal:external withReferrer:nil]);
9584 [tabbar_ setUnselectedViewController:page];
9589 - (void) applicationOpenURL:(NSURL *)url {
9590 [super applicationOpenURL:url];
9595 [self openCydiaURL:url forExternal:YES];
9598 - (void) applicationWillResignActive:(UIApplication *)application {
9599 // Stop refreshing if you get a phone call or lock the device.
9600 if ([tabbar_ updating])
9601 [tabbar_ cancelUpdate];
9603 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9604 [super applicationWillResignActive:application];
9607 - (void) saveState {
9608 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9609 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9610 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9616 - (void) applicationWillTerminate:(UIApplication *)application {
9620 - (void) setConfigurationData:(NSString *)data {
9621 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9623 if (!conffile_r(data)) {
9624 lprintf("E:invalid conffile\n");
9628 NSString *ofile = conffile_r[1];
9629 //NSString *nfile = conffile_r[2];
9631 UIAlertView *alert = [[[UIAlertView alloc]
9632 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9633 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9635 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9637 UCLocalize("ACCEPT_NEW_COPY"),
9638 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9642 [alert setContext:@"conffile"];
9643 [alert setNumberOfRows:2];
9647 - (void) addStashController {
9649 stash_ = [[[StashController alloc] init] autorelease];
9650 [window_ addSubview:[stash_ view]];
9653 - (void) removeStashController {
9654 [[stash_ view] removeFromSuperview];
9656 [self unlockSuspend];
9660 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9661 UpdateExternalStatus(1);
9662 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9663 UpdateExternalStatus(0);
9665 [self removeStashController];
9667 pid_t pid(ExecFork());
9669 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9670 perror("launchctl stop");
9676 - (void) setupViewControllers {
9677 tabbar_ = [[[CydiaTabBarController alloc] initWithDatabase:database_] autorelease];
9679 NSMutableArray *items;
9680 if (kCFCoreFoundationVersionNumber < 800) {
9681 items = [NSMutableArray arrayWithObjects:
9682 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9683 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9684 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9685 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease],
9686 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9689 items = [NSMutableArray arrayWithObjects:
9690 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home7.png"] selectedImage:[UIImage applicationImageNamed:@"home7s.png"]] autorelease],
9691 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"install7.png"] selectedImage:[UIImage applicationImageNamed:@"install7s.png"]] autorelease],
9692 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes7.png"] selectedImage:[UIImage applicationImageNamed:@"changes7s.png"]] autorelease],
9693 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage7.png"] selectedImage:[UIImage applicationImageNamed:@"manage7s.png"]] autorelease],
9694 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search7.png"] selectedImage:[UIImage applicationImageNamed:@"search7s.png"]] autorelease],
9698 NSMutableArray *controllers([NSMutableArray array]);
9699 for (UITabBarItem *item in items) {
9700 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9701 [controller setTabBarItem:item];
9702 [controllers addObject:controller];
9704 [tabbar_ setViewControllers:controllers];
9706 [tabbar_ setUpdateDelegate:self];
9709 - (void) _sendMemoryWarningNotification {
9710 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: maybe 4_0?
9711 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationMemoryWarningNotification" object:[UIApplication sharedApplication]];
9713 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
9716 - (void) _sendMemoryWarningNotifications {
9718 [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO];
9724 - (void) applicationDidReceiveMemoryWarning:(UIApplication *)application {
9726 [[NSURLCache sharedURLCache] removeAllCachedResponses];
9729 - (void) applicationDidFinishLaunching:(id)unused {
9730 //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil];
9733 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9734 [self setApplicationSupportsShakeToEdit:NO];
9736 @synchronized (HostConfig_) {
9737 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9740 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9741 initWithMemoryCapacity:524288
9742 diskCapacity:10485760
9743 diskPath:[NSString stringWithFormat:@"%@/SDURLCache", Cache_]
9746 [CydiaWebViewController _initialize];
9748 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9750 // this would disallow http{,s} URLs from accessing this data
9751 //[WebView registerURLSchemeAsLocal:@"cydia"];
9753 Font12_ = [UIFont systemFontOfSize:12];
9754 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9755 Font14_ = [UIFont systemFontOfSize:14];
9756 Font18_ = [UIFont systemFontOfSize:18];
9757 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9758 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9760 essential_ = [NSMutableArray arrayWithCapacity:4];
9761 broken_ = [NSMutableArray arrayWithCapacity:4];
9763 // XXX: I really need this thing... like, seriously... I'm sorry
9764 [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
9766 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9767 [window_ orderFront:self];
9768 [window_ makeKey:self];
9769 [window_ setHidden:NO];
9772 [self addStashController];
9773 // XXX: this would be much cleaner as a yieldToSelector:
9774 // that way the removeStashController could happen right here inline
9775 // we also could no longer require the useless stash_ field anymore
9776 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9781 int error(stat("/", &root));
9782 _assert(error != -1);
9784 #define Stash_(path) do { \
9785 struct stat folder; \
9786 int error(lstat((path), &folder)); \
9787 if (error != -1 && ( \
9788 folder.st_dev == root.st_dev && \
9789 S_ISDIR(folder.st_mode) \
9790 ) || error == -1 && ( \
9791 errno == ENOENT || \
9796 Stash_("/Applications");
9797 Stash_("/Library/Ringtones");
9798 Stash_("/Library/Wallpaper");
9799 //Stash_("/usr/bin");
9800 Stash_("/usr/include");
9801 Stash_("/usr/lib/pam");
9802 Stash_("/usr/share");
9803 //Stash_("/var/lib");
9805 database_ = [Database sharedInstance];
9806 [database_ setDelegate:self];
9808 [window_ setUserInteractionEnabled:NO];
9809 [self setupViewControllers];
9811 CydiaLoadingViewController *loading([[[CydiaLoadingViewController alloc] init] autorelease]);
9812 UINavigationController *navigation([[[UINavigationController alloc] init] autorelease]);
9813 [navigation setViewControllers:[NSArray arrayWithObject:loading]];
9815 emulated_ = [[[CyteTabBarController alloc] init] autorelease];
9816 [emulated_ setViewControllers:[NSArray arrayWithObject:navigation]];
9817 [emulated_ setSelectedIndex:0];
9818 [emulated_ concealTabBarSelection];
9820 if ([window_ respondsToSelector:@selector(setRootViewController:)])
9821 [window_ setRootViewController:emulated_];
9823 [window_ addSubview:[emulated_ view]];
9825 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9829 - (NSArray *) defaultStartPages {
9830 NSMutableArray *standard = [NSMutableArray array];
9831 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9832 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9833 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9834 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9835 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9841 if ([emulated_ modalViewController] != nil)
9842 [emulated_ dismissModalViewControllerAnimated:YES];
9843 [window_ setUserInteractionEnabled:NO];
9845 [self reloadDataWithInvocation:nil];
9846 [self refreshIfPossible];
9849 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9850 NSArray *saved = [[[Metadata_ objectForKey:@"InterfaceState"] mutableCopy] autorelease];
9851 int standardIndex = 0;
9852 NSArray *standard = [self defaultStartPages];
9859 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9860 if (valid && closed != nil) {
9861 NSTimeInterval interval([closed timeIntervalSinceNow]);
9862 // XXX: Is 30 minutes the optimal time here?
9863 if (interval <= -(30*60))
9867 if (valid && [saved count] != [standard count])
9871 for (unsigned int i = 0; i < [standard count]; i++) {
9872 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9873 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9874 // but it's good enough for now.
9875 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9882 NSArray *items = nil;
9884 [tabbar_ setSelectedIndex:savedIndex];
9887 [tabbar_ setSelectedIndex:standardIndex];
9891 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9892 NSArray *stack = [items objectAtIndex:tab];
9893 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9894 NSMutableArray *current = [NSMutableArray array];
9896 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9897 NSString *addr = [stack objectAtIndex:nav];
9898 NSURL *url = [NSURL URLWithString:addr];
9899 CyteViewController *page = [self pageForURL:url forExternal:NO withReferrer:nil];
9901 [current addObject:page];
9904 [navigation setViewControllers:current];
9907 // (Try to) show the startup URL.
9908 if (starturl_ != nil) {
9909 [self openCydiaURL:starturl_ forExternal:YES];
9914 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9915 if (item != nil && IsWildcat_) {
9916 [sheet showFromBarButtonItem:item animated:YES];
9918 [sheet showInView:window_];
9922 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9923 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9924 [progress setTitle:task];
9925 [progress addProgressEvent:event];
9928 - (void) addProgressEventForTask:(NSArray *)data {
9929 CydiaProgressEvent *event([data objectAtIndex:0]);
9930 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9931 [self addProgressEvent:event forTask:task];
9934 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9935 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9941 id Alloc_(id self, SEL selector) {
9942 id object = alloc_(self, selector);
9943 lprintf("[%s]A-%p\n", self->isa->name, object);
9948 id Dealloc_(id self, SEL selector) {
9949 id object = dealloc_(self, selector);
9950 lprintf("[%s]D-%p\n", self->isa->name, object);
9954 static NSSet *MobilizedFiles_;
9956 static NSURL *MobilizeURL(NSURL *url) {
9957 NSString *path([url path]);
9958 if ([path hasPrefix:@"/var/root/"]) {
9959 NSString *file([path substringFromIndex:10]);
9960 if ([MobilizedFiles_ containsObject:file])
9961 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
9967 Class $CFXPreferencesPropertyListSource;
9968 @class CFXPreferencesPropertyListSource;
9970 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9971 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9972 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9974 url = MobilizeURL(url);
9976 value = _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd);
9977 //NSLog(@"CFX %@ %s", [url absoluteString], value ? "YES" : "NO");
9986 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9987 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9988 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9990 url = MobilizeURL(url);
9992 value = _CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd);
9993 //NSLog(@"CFX %@ %@", [url absoluteString], value);
10002 Class $NSURLConnection;
10004 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
10005 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
10007 NSURL *url([copy URL]);
10009 NSString *host([url host]);
10010 NSString *scheme([[url scheme] lowercaseString]);
10012 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
10014 @synchronized (HostConfig_) {
10015 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
10016 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
10017 [copy setHTTPShouldUsePipelining:YES];
10019 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
10020 if ([control isEqualToString:@"max-age=0"])
10021 if ([CachedURLs_ containsObject:url]) {
10023 NSLog(@"~~~: %@", url);
10026 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
10028 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
10029 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
10030 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
10034 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
10040 static CGSize $WAKWindow$screenSize(WAKWindow *self, SEL _cmd) {
10041 CGSize size([[UIScreen mainScreen] bounds].size);
10042 /*if ([$WAKWindow respondsToSelector:@selector(hasLandscapeOrientation)])
10043 if ([$WAKWindow hasLandscapeOrientation])
10044 std::swap(size.width, size.height);*/
10048 Class $NSUserDefaults;
10050 MSHook(id, NSUserDefaults$objectForKey$, NSUserDefaults *self, SEL _cmd, NSString *key) {
10051 if ([key respondsToSelector:@selector(isEqualToString:)] && [key isEqualToString:@"WebKitLocalStorageDatabasePathPreferenceKey"])
10052 return [NSString stringWithFormat:@"%@/LocalStorage", Cache_];
10053 return _NSUserDefaults$objectForKey$(self, _cmd, key);
10056 int main(int argc, char *argv[]) {
10057 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10061 UpdateExternalStatus(0);
10063 UIScreen *screen([UIScreen mainScreen]);
10064 if ([screen respondsToSelector:@selector(scale)])
10065 ScreenScale_ = [screen scale];
10069 UIDevice *device([UIDevice currentDevice]);
10070 if ([device respondsToSelector:@selector(userInterfaceIdiom)]) {
10071 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10072 if (idiom == UIUserInterfaceIdiomPad)
10076 Idiom_ = IsWildcat_ ? @"ipad" : @"iphone";
10078 Pcre pattern("^([0-9]+\\.[0-9]+)");
10080 if (pattern([device systemVersion]))
10081 Firmware_ = pattern[1];
10082 if (pattern(Cydia_))
10083 Major_ = pattern[1];
10085 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
10087 HostConfig_ = [[[NSObject alloc] init] autorelease];
10088 @synchronized (HostConfig_) {
10089 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10090 TokenHosts_ = [NSMutableSet setWithCapacity:4];
10091 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
10092 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
10093 CachedURLs_ = [NSMutableSet setWithCapacity:32];
10096 NSString *ui(@"ui/ios");
10098 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
10099 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"/%@", Major_]];
10100 UI_ = CydiaURL(ui);
10102 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10104 MobilizedFiles_ = [NSMutableSet setWithObjects:
10105 @"Library/Preferences/.GlobalPreferences.plist",
10106 @"Library/Preferences/com.apple.Accessibility.plist",
10107 @"Library/Preferences/com.apple.preferences.sounds.plist",
10110 /* Library Hacks {{{ */
10111 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10113 $WAKWindow = objc_getClass("WAKWindow");
10114 if ($WAKWindow != NULL)
10115 if (Method method = class_getInstanceMethod($WAKWindow, @selector(screenSize)))
10116 method_setImplementation(method, (IMP) &$WAKWindow$screenSize);
10118 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSourceSynchronizer");
10119 if ($CFXPreferencesPropertyListSource == Nil)
10120 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
10122 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
10123 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
10124 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10125 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10128 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
10129 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
10130 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
10131 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
10134 $NSURLConnection = objc_getClass("NSURLConnection");
10135 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10136 if (NSURLConnection$init$ != NULL) {
10137 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10138 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10141 $NSUserDefaults = objc_getClass("NSUserDefaults");
10142 Method NSUserDefaults$objectForKey$(class_getInstanceMethod($NSUserDefaults, @selector(objectForKey:)));
10143 if (NSUserDefaults$objectForKey$ != NULL) {
10144 _NSUserDefaults$objectForKey$ = reinterpret_cast<id (*)(NSUserDefaults *, SEL, NSString *)>(method_getImplementation(NSUserDefaults$objectForKey$));
10145 method_setImplementation(NSUserDefaults$objectForKey$, reinterpret_cast<IMP>(&$NSUserDefaults$objectForKey$));
10148 /* Set Locale {{{ */
10149 Locale_ = CFLocaleCopyCurrent();
10150 Languages_ = [NSLocale preferredLanguages];
10152 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10153 //NSLog(@"%@", [Languages_ description]);
10156 if (Locale_ != NULL)
10157 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10158 else if (Languages_ != nil && [Languages_ count] != 0)
10159 lang = [[Languages_ objectAtIndex:0] UTF8String];
10161 // XXX: consider just setting to C and then falling through?
10164 if (lang != NULL) {
10165 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
10166 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10169 NSLog(@"Setting Language: %s", lang);
10171 if (lang != NULL) {
10172 setenv("LANG", lang, true);
10173 std::setlocale(LC_ALL, lang);
10176 /* Index Collation {{{ */
10177 if (Class $UILocalizedIndexedCollation = objc_getClass("UILocalizedIndexedCollation")) {
10178 NSBundle *bundle([NSBundle bundleForClass:$UILocalizedIndexedCollation]);
10179 NSString *path([bundle pathForResource:@"UITableViewLocalizedSectionIndex" ofType:@"plist"]);
10180 //path = @"/System/Library/Frameworks/UIKit.framework/.lproj/UITableViewLocalizedSectionIndex.plist";
10181 NSDictionary *dictionary([NSDictionary dictionaryWithContentsOfFile:path]);
10182 _H<UILocalizedIndexedCollation> collation([[[UILocalizedIndexedCollation alloc] initWithDictionary:dictionary] autorelease]);
10184 CollationLocale_ = MSHookIvar<NSLocale *>(collation, "_locale");
10186 CollationThumbs_ = [collation sectionIndexTitles];
10187 for (size_t index(0), end([CollationThumbs_ count]); index != end; ++index)
10188 CollationOffset_.push_back([collation sectionForSectionIndexTitleAtIndex:index]);
10190 CollationTitles_ = [collation sectionTitles];
10191 CollationStarts_ = MSHookIvar<NSArray *>(collation, "_sectionStartStrings");
10193 NSString *&transform(MSHookIvar<NSString *>(collation, "_transform"));
10194 if (&transform != NULL && transform != nil) {
10195 /*if ([collation respondsToSelector:@selector(transformedCollationStringForString:)])
10196 CollationModify_ = [=](NSString *value) { return [collation transformedCollationStringForString:value]; };*/
10197 const UChar *uid(reinterpret_cast<const UChar *>([transform cStringUsingEncoding:NSUnicodeStringEncoding]));
10198 UErrorCode code(U_ZERO_ERROR);
10199 CollationTransl_ = utrans_openU(uid, -1, UTRANS_FORWARD, NULL, 0, NULL, &code);
10200 if (!U_SUCCESS(code))
10201 NSLog(@"%s", u_errorName(code));
10204 CollationLocale_ = [[[NSLocale alloc] initWithLocaleIdentifier:@"en@collation=dictionary"] autorelease];
10206 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];
10207 for (NSInteger offset(0); offset != 28; ++offset)
10208 CollationOffset_.push_back(offset);
10210 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];
10211 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];
10215 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
10217 /* Parse Arguments {{{ */
10218 bool substrate(false);
10224 for (int argi(1); argi != argc; ++argi)
10225 if (strcmp(argv[argi], "--") == 0) {
10227 argv[argi] = argv[0];
10233 for (int argi(1); argi != arge; ++argi)
10234 if (strcmp(args[argi], "--substrate") == 0)
10237 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10241 App_ = [[NSBundle mainBundle] bundlePath];
10247 if (access("/var/mobile/Library/Keyboard/UserDictionary.sqlite", F_OK) == 0)
10248 system("mkdir -p /var/root/Library/Keyboard; cp -af /var/mobile/Library/Keyboard/UserDictionary.sqlite /var/root/Library/Keyboard/");
10250 Cache_ = [[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia", @"/var/root"] retain];
10252 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10253 alloc_ = alloc->method_imp;
10254 alloc->method_imp = (IMP) &Alloc_;*/
10256 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10257 dealloc_ = dealloc->method_imp;
10258 dealloc->method_imp = (IMP) &Dealloc_;*/
10260 void *gestalt(dlopen("/usr/lib/libMobileGestalt.dylib", RTLD_GLOBAL | RTLD_LAZY));
10261 $MGCopyAnswer = reinterpret_cast<CFStringRef (*)(CFStringRef)>(dlsym(gestalt, "MGCopyAnswer"));
10263 /* System Information {{{ */
10267 size = sizeof(maxproc);
10268 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10269 perror("sysctlbyname(\"kern.maxproc\", ?)");
10270 else if (maxproc < 64) {
10272 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10273 perror("sysctlbyname(\"kern.maxproc\", #)");
10276 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10277 char *osversion = new char[size];
10278 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10279 perror("sysctlbyname(\"kern.osversion\", ?)");
10281 System_ = [NSString stringWithUTF8String:osversion];
10283 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10284 char *machine = new char[size];
10285 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10286 perror("sysctlbyname(\"hw.machine\", ?)");
10288 Machine_ = machine;
10290 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10291 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10292 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10294 UniqueID_ = UniqueIdentifier(device);
10296 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10297 Product_ = [info objectForKey:@"SafariProductVersion"];
10298 Safari_ = [info objectForKey:@"CFBundleVersion"];
10301 NSString *agent([NSString stringWithFormat:@"Cydia/%@ CyF/%.2f", Cydia_, kCFCoreFoundationVersionNumber]);
10303 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Safari_))
10304 agent = [NSString stringWithFormat:@"Safari/%@ %@", match[0], agent];
10305 if (Pcre match = Pcre("^[0-9]+[A-Z][0-9]+[a-z]?", System_))
10306 agent = [NSString stringWithFormat:@"Mobile/%@ %@", match[0], agent];
10307 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Product_))
10308 agent = [NSString stringWithFormat:@"Version/%@ %@", match[0], agent];
10310 UserAgent_ = agent;
10312 /* Load Database {{{ */
10314 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10316 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10318 if (Metadata_ == NULL)
10319 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10321 Settings_ = [Metadata_ objectForKey:@"Settings"];
10323 Packages_ = [Metadata_ objectForKey:@"Packages"];
10325 Values_ = [Metadata_ objectForKey:@"Values"];
10326 Sections_ = [Metadata_ objectForKey:@"Sections"];
10327 Sources_ = [Metadata_ objectForKey:@"Sources"];
10329 Token_ = [Metadata_ objectForKey:@"Token"];
10331 Version_ = [Metadata_ objectForKey:@"Version"];
10334 if (Values_ == nil) {
10335 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10336 [Metadata_ setObject:Values_ forKey:@"Values"];
10339 if (Sections_ == nil) {
10340 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10341 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10344 if (Sources_ == nil) {
10345 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10346 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10349 if (Version_ == nil) {
10350 Version_ = [NSNumber numberWithUnsignedInt:0];
10351 [Metadata_ setObject:Version_ forKey:@"Version"];
10354 if ([Version_ unsignedIntValue] == 0) {
10355 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10356 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10357 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10358 CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./");
10360 Version_ = [NSNumber numberWithUnsignedInt:1];
10361 [Metadata_ setObject:Version_ forKey:@"Version"];
10363 [Metadata_ removeObjectForKey:@"LastUpdate"];
10368 _H<NSMutableArray> broken([NSMutableArray array]);
10369 for (NSString *key in (id) Sources_)
10370 if ([key rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"# "]].location != NSNotFound)
10371 [broken addObject:key];
10372 if ([broken count] != 0) {
10373 for (NSString *key in (id) broken)
10374 [Sources_ removeObjectForKey:key];
10379 CydiaWriteSources();
10382 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10385 if (Packages_ != nil) {
10387 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10391 [Metadata_ removeObjectForKey:@"Packages"];
10397 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10399 #define MobileSubstrate_(name) \
10400 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10401 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10402 if (handle == NULL) \
10403 NSLog(@"%s", dlerror()); \
10406 MobileSubstrate_(Activator)
10407 MobileSubstrate_(libstatusbar)
10408 MobileSubstrate_(SimulatedKeyEvents)
10409 MobileSubstrate_(WinterBoard)
10411 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10412 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10414 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10416 if (access("/User", F_OK) != 0 || version != 6) {
10418 system("/usr/libexec/cydia/firmware.sh");
10422 _assert([[NSFileManager defaultManager]
10423 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10424 withIntermediateDirectories:YES
10429 if (access("/tmp/cydia.chk", F_OK) == 0) {
10430 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10431 _assert(errno == ENOENT);
10432 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10433 _assert(errno == ENOENT);
10436 /* APT Initialization {{{ */
10437 _assert(pkgInitConfig(*_config));
10438 _assert(pkgInitSystem(*_config, _system));
10441 _config->Set("APT::Acquire::Translation", lang);
10443 // XXX: this timeout might be important :(
10444 //_config->Set("Acquire::http::Timeout", 15);
10446 _config->Set("Acquire::http::MaxParallel", 3);
10448 /* Color Choices {{{ */
10449 space_ = CGColorSpaceCreateDeviceRGB();
10451 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10452 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10453 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10454 Folder_.Set(space_, 0x8e/255.f, 0x8e/255.f, 0x93/255.f, 1.0);
10455 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10456 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10457 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10458 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10459 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10460 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10462 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10463 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10465 /* UIKit Configuration {{{ */
10466 // XXX: I have a feeling this was important
10467 //UIKeyboardDisableAutomaticAppearance();
10470 $SBSSetInterceptsMenuButtonForever = reinterpret_cast<void (*)(bool)>(dlsym(RTLD_DEFAULT, "SBSSetInterceptsMenuButtonForever"));
10472 const char *symbol(kCFCoreFoundationVersionNumber >= 800 ? "MGGetBoolAnswer" : "GSSystemHasCapability");
10473 BOOL (*GSSystemHasCapability)(CFStringRef) = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, symbol));
10474 bool fast = GSSystemHasCapability != NULL && GSSystemHasCapability(CFSTR("armv7"));
10476 PulseInterval_ = fast ? 50000 : 500000;
10478 Colon_ = UCLocalize("COLON_DELIMITED");
10479 Elision_ = UCLocalize("ELISION");
10480 Error_ = UCLocalize("ERROR");
10481 Warning_ = UCLocalize("WARNING");
10484 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10486 CGColorSpaceRelease(space_);
10487 CFRelease(Locale_);