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 - (void) setPageColor:(UIColor *)color {
6283 return [super setPageColor:nil];
6286 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer {
6287 if ((self = [super init]) != nil) {
6288 database_ = database;
6289 buttons_ = [NSMutableArray arrayWithCapacity:4];
6290 name_ = name == nil ? @"" : [NSString stringWithString:name];
6291 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]] withReferrer:referrer];
6295 - (void) reloadData {
6298 package_ = [database_ packageWithName:name_];
6300 [buttons_ removeAllObjects];
6302 if (package_ != nil) {
6303 [(Package *) package_ parse];
6305 commercial_ = [package_ isCommercial];
6307 if ([package_ mode] != nil)
6308 [buttons_ addObject:UCLocalize("CLEAR")];
6309 if ([package_ source] == nil);
6310 else if ([package_ upgradableAndEssential:NO])
6311 [buttons_ addObject:UCLocalize("UPGRADE")];
6312 else if ([package_ uninstalled])
6313 [buttons_ addObject:UCLocalize("INSTALL")];
6315 [buttons_ addObject:UCLocalize("REINSTALL")];
6316 if (![package_ uninstalled])
6317 [buttons_ addObject:UCLocalize("REMOVE")];
6321 switch ([buttons_ count]) {
6322 case 0: title = nil; break;
6323 case 1: title = [buttons_ objectAtIndex:0]; break;
6324 default: title = UCLocalize("MODIFY"); break;
6327 button_ = [[[UIBarButtonItem alloc]
6329 style:UIBarButtonItemStylePlain
6331 action:@selector(customButtonClicked)
6335 - (bool) isLoading {
6336 return commercial_ ? [super isLoading] : false;
6342 /* Package List Controller {{{ */
6343 @interface PackageListController : CyteViewController <
6344 UITableViewDataSource,
6347 _transient Database *database_;
6349 _H<NSArray> packages_;
6350 _H<NSArray> sections_;
6351 _H<UITableView, 2> list_;
6353 _H<NSArray> thumbs_;
6354 std::vector<NSInteger> offset_;
6356 _H<NSString> title_;
6357 unsigned reloading_;
6360 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6361 - (void) setDelegate:(id)delegate;
6362 - (void) resetCursor;
6365 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages;
6369 @implementation PackageListController
6371 - (NSURL *) referrerURL {
6372 return [self navigationURL];
6375 - (bool) isSummarized {
6379 - (bool) showsSections {
6383 - (void) deselectWithAnimation:(BOOL)animated {
6384 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6387 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6388 CGRect base = [[self view] bounds];
6389 base.size.height -= bounds.size.height;
6390 base.origin = [list_ frame].origin;
6392 [UIView beginAnimations:nil context:NULL];
6393 [UIView setAnimationBeginsFromCurrentState:YES];
6394 [UIView setAnimationCurve:curve];
6395 [UIView setAnimationDuration:duration];
6396 [list_ setFrame:base];
6397 [UIView commitAnimations];
6400 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6401 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6404 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6405 [self resizeForKeyboardBounds:bounds duration:0];
6408 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6409 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6410 *curve = UIViewAnimationCurveEaseInOut;
6412 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6414 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6417 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6420 - (void) keyboardWillShow:(NSNotification *)notification {
6423 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6424 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6426 NSTimeInterval duration;
6427 UIViewAnimationCurve curve;
6428 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6430 CGRect kbframe = CGRectMake(Retina(center.x - bounds.size.width / 2), Retina(center.y - bounds.size.height / 2), bounds.size.width, bounds.size.height);
6431 UIViewController *base = self;
6432 while ([base parentOrPresentingViewController] != nil)
6433 base = [base parentOrPresentingViewController];
6434 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6435 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6437 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6438 intersection.size.height += CYStatusBarHeight();
6440 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6443 - (void) keyboardWillHide:(NSNotification *)notification {
6444 NSTimeInterval duration;
6445 UIViewAnimationCurve curve;
6446 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6448 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6451 - (void) viewWillAppear:(BOOL)animated {
6452 [super viewWillAppear:animated];
6454 [self resizeForKeyboardBounds:CGRectZero];
6455 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6456 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6459 - (void) viewWillDisappear:(BOOL)animated {
6460 [super viewWillDisappear:animated];
6462 [self resizeForKeyboardBounds:CGRectZero];
6463 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6464 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6467 - (void) viewDidAppear:(BOOL)animated {
6468 [super viewDidAppear:animated];
6469 [self deselectWithAnimation:animated];
6472 - (void) didSelectPackage:(Package *)package {
6473 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[[self referrerURL] absoluteString]] autorelease]);
6474 [view setDelegate:delegate_];
6475 [[self navigationController] pushViewController:view animated:YES];
6478 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6479 NSInteger count([sections_ count]);
6480 return count == 0 ? 1 : count;
6483 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6484 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6486 return [[sections_ objectAtIndex:section] name];
6489 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6490 if ([sections_ count] == 0)
6492 return [[sections_ objectAtIndex:section] count];
6495 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6496 @synchronized (database_) {
6497 if ([database_ era] != era_)
6500 Section *section([sections_ objectAtIndex:[path section]]);
6501 NSInteger row([path row]);
6502 Package *package([packages_ objectAtIndex:([section row] + row)]);
6503 return [[package retain] autorelease];
6506 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6507 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6509 cell = [[[PackageCell alloc] init] autorelease];
6511 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6512 [cell setPackage:package asSummary:[self isSummarized]];
6516 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6517 Package *package([self packageAtIndexPath:path]);
6518 package = [database_ packageWithName:[package id]];
6519 [self didSelectPackage:package];
6522 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6526 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6527 return offset_[index];
6530 - (void) updateHeight {
6531 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6534 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6535 if ((self = [super init]) != nil) {
6536 database_ = database;
6537 title_ = [title copy];
6538 [[self navigationItem] setTitle:title_];
6543 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
6544 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
6545 [self setView:view];
6547 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6548 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6549 [view addSubview:list_];
6551 // XXX: is 20 the most optimal number here?
6552 [list_ setSectionIndexMinimumDisplayRowCount:20];
6554 [(UITableView *) list_ setDataSource:self];
6555 [list_ setDelegate:self];
6557 [self updateHeight];
6560 - (void) releaseSubviews {
6569 [super releaseSubviews];
6572 - (void) setDelegate:(id)delegate {
6573 delegate_ = delegate;
6576 - (bool) shouldYield {
6580 - (bool) shouldBlock {
6584 - (NSMutableArray *) _reloadPackages {
6585 @synchronized (database_) {
6586 era_ = [database_ era];
6587 NSArray *packages([database_ packages]);
6589 return [NSMutableArray arrayWithArray:packages];
6592 - (void) _reloadData {
6593 if (reloading_ != 0) {
6598 NSMutableArray *packages;
6601 if ([self shouldYield]) {
6605 if (![self shouldBlock])
6608 hud = [delegate_ addProgressHUD];
6609 [hud setText:UCLocalize("LOADING")];
6613 packages = [self yieldToSelector:@selector(_reloadPackages)];
6616 [delegate_ removeProgressHUD:hud];
6617 } while (reloading_ == 2);
6619 packages = [self _reloadPackages];
6622 @synchronized (database_) {
6623 if (era_ != [database_ era])
6630 packages_ = packages;
6632 if ([self showsSections])
6633 sections_ = [self sectionsForPackages:packages];
6635 Section *section([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6636 [section setCount:[packages_ count]];
6637 sections_ = [NSArray arrayWithObject:section];
6640 [self updateHeight];
6642 _profile(PackageTable$reloadData$List)
6643 [(UITableView *) list_ setDataSource:self];
6651 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
6652 Section *prefix([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6653 size_t end([packages count]);
6655 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
6656 Section *section(prefix);
6658 thumbs_ = CollationThumbs_;
6659 offset_ = CollationOffset_;
6662 size_t offsets([CollationStarts_ count]);
6664 NSString *start([CollationStarts_ objectAtIndex:offset]);
6665 size_t length([start length]);
6667 for (size_t index(0); index != end; ++index) {
6669 Package *package([packages objectAtIndex:index]);
6670 NSString *name(PackageName(package, @selector(cyname)));
6672 //while ([start compare:name options:NSNumericSearch range:NSMakeRange(0, length) locale:CollationLocale_] != NSOrderedDescending) {
6673 while (StringNameCompare(start, name, length) != kCFCompareGreaterThan) {
6674 NSString *title([CollationTitles_ objectAtIndex:offset]);
6675 section = [[[Section alloc] initWithName:title row:index localize:NO] autorelease];
6676 [sections addObject:section];
6678 start = ++offset == offsets ? nil : [CollationStarts_ objectAtIndex:offset];
6681 length = [start length];
6685 [section addToCount];
6688 for (; offset != offsets; ++offset) {
6689 NSString *title([CollationTitles_ objectAtIndex:offset]);
6690 Section *section([[[Section alloc] initWithName:title row:end localize:NO] autorelease]);
6691 [sections addObject:section];
6694 if ([prefix count] != 0) {
6695 Section *suffix([sections lastObject]);
6696 [prefix setName:[suffix name]];
6697 [suffix setName:nil];
6698 [sections insertObject:prefix atIndex:(offsets - 1)];
6704 - (void) reloadData {
6707 if ([self shouldYield])
6708 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6713 - (void) resetCursor {
6714 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6717 - (void) clearData {
6718 [self updateHeight];
6720 [list_ setDataSource:nil];
6728 /* Filtered Package List Controller {{{ */
6729 typedef Function<bool, Package *> PackageFilter;
6730 typedef Function<void, NSMutableArray *> PackageSorter;
6731 @interface FilteredPackageListController : PackageListController {
6732 PackageFilter filter_;
6733 PackageSorter sorter_;
6736 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter;
6738 - (void) setFilter:(PackageFilter)filter;
6739 - (void) setSorter:(PackageSorter)sorter;
6743 @implementation FilteredPackageListController
6745 - (void) setFilter:(PackageFilter)filter {
6746 @synchronized (self) {
6750 - (void) setSorter:(PackageSorter)sorter {
6751 @synchronized (self) {
6755 - (NSMutableArray *) _reloadPackages {
6756 @synchronized (database_) {
6757 era_ = [database_ era];
6759 NSArray *packages([database_ packages]);
6760 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6762 PackageFilter filter;
6763 PackageSorter sorter;
6765 @synchronized (self) {
6770 _profile(PackageTable$reloadData$Filter)
6771 for (Package *package in packages)
6772 if ([package valid] && filter(package))
6773 [filtered addObject:package];
6781 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter {
6782 if ((self = [super initWithDatabase:database title:title]) != nil) {
6783 [self setFilter:filter];
6790 /* Home Controller {{{ */
6791 @interface HomeController : CydiaWebViewController {
6792 CFRunLoopRef runloop_;
6793 SCNetworkReachabilityRef reachability_;
6798 @implementation HomeController
6800 static void HomeControllerReachabilityCallback(SCNetworkReachabilityRef reachability, SCNetworkReachabilityFlags flags, void *info) {
6801 [(HomeController *) info dispatchEvent:@"CydiaReachabilityCallback"];
6805 if ((self = [super init]) != nil) {
6806 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6809 reachability_ = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "cydia.saurik.com");
6810 if (reachability_ != NULL) {
6811 SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
6812 SCNetworkReachabilitySetCallback(reachability_, HomeControllerReachabilityCallback, &context);
6814 CFRunLoopRef runloop(CFRunLoopGetCurrent());
6815 if (SCNetworkReachabilityScheduleWithRunLoop(reachability_, runloop, kCFRunLoopDefaultMode))
6822 if (reachability_ != NULL && runloop_ != NULL)
6823 SCNetworkReachabilityUnscheduleFromRunLoop(reachability_, runloop_, kCFRunLoopDefaultMode);
6827 - (NSURL *) navigationURL {
6828 return [NSURL URLWithString:@"cydia://home"];
6831 - (void) aboutButtonClicked {
6832 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6834 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6835 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6836 [alert setCancelButtonIndex:0];
6839 @"Copyright \u00a9 2008-2014\n"
6842 "Jay Freeman (saurik)\n"
6843 "saurik@saurik.com\n"
6844 "http://www.saurik.com/"
6850 - (UIBarButtonItem *) leftButton {
6851 return [[[UIBarButtonItem alloc]
6852 initWithTitle:UCLocalize("ABOUT")
6853 style:UIBarButtonItemStylePlain
6855 action:@selector(aboutButtonClicked)
6862 /* Cydia Navigation Controller Interface {{{ */
6863 @interface UINavigationController (Cydia)
6865 - (NSArray *) navigationURLCollection;
6866 - (void) unloadData;
6871 /* Cydia Tab Bar Controller {{{ */
6872 @interface CydiaTabBarController : CyteTabBarController <
6873 UITabBarControllerDelegate,
6876 _transient Database *database_;
6878 _H<UIActivityIndicatorView> indicator_;
6881 // XXX: ok, "updatedelegate_"?...
6882 _transient NSObject<CydiaDelegate> *updatedelegate_;
6885 - (NSArray *) navigationURLCollection;
6886 - (void) beginUpdate;
6891 @implementation CydiaTabBarController
6893 - (NSArray *) navigationURLCollection {
6894 NSMutableArray *items([NSMutableArray array]);
6896 // XXX: Should this deal with transient view controllers?
6897 for (id navigation in [self viewControllers]) {
6898 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6900 [items addObject:stack];
6906 - (id) initWithDatabase:(Database *)database {
6907 if ((self = [super init]) != nil) {
6908 database_ = database;
6909 [self setDelegate:self];
6911 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteTiny] autorelease];
6912 [indicator_ setOrigin:CGPointMake(kCFCoreFoundationVersionNumber >= 800 ? 2 : 4, 2)];
6914 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6918 - (void) setUpdate:(NSDate *)date {
6922 - (void) beginUpdate {
6926 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
6927 UITabBarItem *item([controller tabBarItem]);
6929 [item setBadgeValue:@""];
6930 UIView *badge(MSHookIvar<UIView *>([item view], "_badge"));
6932 [indicator_ startAnimating];
6933 [badge addSubview:indicator_];
6935 [updatedelegate_ retainNetworkActivityIndicator];
6939 detachNewThreadSelector:@selector(performUpdate)
6945 - (void) performUpdate {
6946 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
6948 SourceStatus status(self, database_);
6949 [database_ updateWithStatus:status];
6952 performSelectorOnMainThread:@selector(completeUpdate)
6960 - (void) stopUpdateWithSelector:(SEL)selector {
6962 [updatedelegate_ releaseNetworkActivityIndicator];
6964 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
6965 [[controller tabBarItem] setBadgeValue:nil];
6967 [indicator_ removeFromSuperview];
6968 [indicator_ stopAnimating];
6970 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6973 - (void) completeUpdate {
6976 [self stopUpdateWithSelector:@selector(reloadData)];
6979 - (void) cancelUpdate {
6980 [self stopUpdateWithSelector:@selector(updateDataAndLoad)];
6983 - (void) cancelPressed {
6984 [self cancelUpdate];
6991 - (bool) isSourceCancelled {
6995 - (void) startSourceFetch:(NSString *)uri {
6998 - (void) stopSourceFetch:(NSString *)uri {
7001 - (void) setUpdateDelegate:(id)delegate {
7002 updatedelegate_ = delegate;
7008 /* Cydia Navigation Controller Implementation {{{ */
7009 @implementation UINavigationController (Cydia)
7011 - (NSArray *) navigationURLCollection {
7012 NSMutableArray *stack([NSMutableArray array]);
7014 for (CyteViewController *controller in [self viewControllers]) {
7015 NSString *url = [[controller navigationURL] absoluteString];
7017 [stack addObject:url];
7023 - (void) reloadData {
7026 UIViewController *visible([self visibleViewController]);
7028 [visible reloadData];
7030 // on the iPad, this view controller is ALSO visible. :(
7032 if (UIViewController *top = [self topViewController])
7037 - (void) unloadData {
7038 for (CyteViewController *page in [self viewControllers])
7047 /* Cydia:// Protocol {{{ */
7048 @interface CydiaURLProtocol : NSURLProtocol {
7053 @implementation CydiaURLProtocol
7055 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7056 NSURL *url([request URL]);
7060 NSString *scheme([[url scheme] lowercaseString]);
7061 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7063 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7069 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7073 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7074 id<NSURLProtocolClient> client([self client]);
7076 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7078 NSData *data(UIImagePNGRepresentation(icon));
7080 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7081 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7082 [client URLProtocol:self didLoadData:data];
7083 [client URLProtocolDidFinishLoading:self];
7087 - (void) startLoading {
7088 id<NSURLProtocolClient> client([self client]);
7089 NSURLRequest *request([self request]);
7091 NSURL *url([request URL]);
7092 NSString *href([url absoluteString]);
7093 NSString *scheme([[url scheme] lowercaseString]);
7097 if ([scheme isEqualToString:@"cydia"])
7098 path = [href substringFromIndex:8];
7099 else if ([scheme isEqualToString:@"about"])
7100 path = [href substringFromIndex:12];
7101 else _assert(false);
7103 NSRange slash([path rangeOfString:@"/"]);
7106 if (slash.location == NSNotFound) {
7110 command = [path substringToIndex:slash.location];
7111 path = [path substringFromIndex:(slash.location + 1)];
7114 Database *database([Database sharedInstance]);
7116 if ([command isEqualToString:@"package-icon"]) {
7119 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7120 Package *package([database packageWithName:path]);
7124 UIImage *icon([package icon]);
7125 [self _returnPNGWithImage:icon forRequest:request];
7126 } else if ([command isEqualToString:@"uikit-image"]) {
7129 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7130 UIImage *icon(_UIImageWithName(path));
7131 [self _returnPNGWithImage:icon forRequest:request];
7132 } else if ([command isEqualToString:@"section-icon"]) {
7135 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7136 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7138 icon = [UIImage applicationImageNamed:@"unknown.png"];
7139 [self _returnPNGWithImage:icon forRequest:request];
7141 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7145 - (void) stopLoading {
7151 /* Section Controller {{{ */
7152 @interface SectionController : FilteredPackageListController {
7154 _H<NSString> section_;
7157 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section;
7161 @implementation SectionController
7163 - (NSURL *) referrerURL {
7164 NSString *name(section_);
7165 name = name ?: @"*";
7166 NSString *key(key_);
7168 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sections/%@/%@", UI_, [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7171 - (NSURL *) navigationURL {
7172 NSString *name(section_);
7173 name = name ?: @"*";
7174 NSString *key(key_);
7176 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@/%@", [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7179 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section {
7182 title = UCLocalize("ALL_PACKAGES");
7183 else if (![section isEqual:@""])
7184 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(section) value:nil table:@"Sections"];
7186 title = UCLocalize("NO_SECTION");
7188 if ((self = [super initWithDatabase:database title:title]) != nil) {
7189 key_ = [source key];
7194 - (void) reloadData {
7195 Source *source([database_ sourceWithKey:key_]);
7196 _H<NSString> name(section_);
7198 [self setFilter:[=](Package *package) {
7199 NSString *section([package section]);
7203 section == nil && [name length] == 0 ||
7204 [name isEqualToString:section]
7207 [package source] == source
7208 ) && [package visible];
7216 /* Sections Controller {{{ */
7217 @interface SectionsController : CyteViewController <
7218 UITableViewDataSource,
7221 _transient Database *database_;
7223 _H<NSMutableArray> sections_;
7224 _H<NSMutableArray> filtered_;
7225 _H<UITableView, 2> list_;
7228 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7229 - (void) editButtonClicked;
7233 @implementation SectionsController
7235 - (NSURL *) navigationURL {
7236 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
7239 - (Source *) source {
7242 return [database_ sourceWithKey:key_];
7245 - (void) updateNavigationItem {
7246 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7247 if ([sections_ count] == 0) {
7248 [[self navigationItem] setRightBarButtonItem:nil];
7250 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7251 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7253 action:@selector(editButtonClicked)
7254 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7258 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7259 [super setEditing:editing animated:animated];
7264 [delegate_ updateData];
7266 [self updateNavigationItem];
7269 - (void) viewDidAppear:(BOOL)animated {
7270 [super viewDidAppear:animated];
7271 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7274 - (void) viewWillDisappear:(BOOL)animated {
7275 [super viewWillDisappear:animated];
7276 [self setEditing:NO];
7279 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7280 Section *section = nil;
7281 int index = [indexPath row];
7282 if (![self isEditing]) {
7285 section = [filtered_ objectAtIndex:index];
7287 section = [sections_ objectAtIndex:index];
7292 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7293 if ([self isEditing])
7294 return [sections_ count];
7296 return [filtered_ count] + 1;
7299 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7303 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7304 static NSString *reuseIdentifier = @"SectionCell";
7306 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7308 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7310 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7315 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7316 if ([self isEditing])
7319 Section *section = [self sectionAtIndexPath:indexPath];
7321 SectionController *controller = [[[SectionController alloc]
7322 initWithDatabase:database_
7323 source:[self source]
7324 section:[section name]
7326 [controller setDelegate:delegate_];
7328 [[self navigationController] pushViewController:controller animated:YES];
7332 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
7333 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7334 [list_ setRowHeight:46];
7335 [(UITableView *) list_ setDataSource:self];
7336 [list_ setDelegate:self];
7337 [self setView:list_];
7340 - (void) viewDidLoad {
7341 [super viewDidLoad];
7343 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7346 - (void) releaseSubviews {
7352 [super releaseSubviews];
7355 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7356 if ((self = [super init]) != nil) {
7357 database_ = database;
7358 key_ = [source key];
7362 - (void) reloadData {
7365 NSArray *packages = [database_ packages];
7367 sections_ = [NSMutableArray arrayWithCapacity:16];
7368 filtered_ = [NSMutableArray arrayWithCapacity:16];
7370 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7372 Source *source([self source]);
7375 for (Package *package in packages) {
7376 if (source != nil && [package source] != source)
7379 NSString *name([package section]);
7380 NSString *key(name == nil ? @"" : name);
7384 _profile(SectionsView$reloadData$Section)
7385 section = [sections objectForKey:key];
7386 if (section == nil) {
7387 _profile(SectionsView$reloadData$Section$Allocate)
7388 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7389 [sections setObject:section forKey:key];
7394 [section addToCount];
7396 _profile(SectionsView$reloadData$Filter)
7397 if (![package valid] || ![package visible])
7405 [sections_ addObjectsFromArray:[sections allValues]];
7407 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7409 for (Section *section in (id) sections_) {
7410 size_t count([section row]);
7414 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7415 [section setCount:count];
7416 [filtered_ addObject:section];
7419 [self updateNavigationItem];
7424 - (void) editButtonClicked {
7425 [self setEditing:![self isEditing] animated:YES];
7431 /* Changes Controller {{{ */
7432 @interface ChangesController : FilteredPackageListController {
7436 - (id) initWithDatabase:(Database *)database;
7440 @implementation ChangesController
7442 - (NSURL *) referrerURL {
7443 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/changes/", UI_]];
7446 - (NSURL *) navigationURL {
7447 return [NSURL URLWithString:@"cydia://changes"];
7450 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7451 @synchronized (database_) {
7452 if ([database_ era] != era_)
7455 NSUInteger sectionIndex([path section]);
7456 if (sectionIndex >= [sections_ count])
7458 Section *section([sections_ objectAtIndex:sectionIndex]);
7459 NSInteger row([path row]);
7460 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7463 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7464 NSString *context([alert context]);
7466 if ([context isEqualToString:@"norefresh"])
7467 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7470 - (void) setLeftBarButtonItem {
7471 if ([delegate_ updating])
7472 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7473 initWithTitle:UCLocalize("CANCEL")
7474 style:UIBarButtonItemStyleDone
7476 action:@selector(cancelButtonClicked)
7477 ] autorelease] animated:YES];
7479 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7480 initWithTitle:UCLocalize("REFRESH")
7481 style:UIBarButtonItemStylePlain
7483 action:@selector(refreshButtonClicked)
7484 ] autorelease] animated:YES];
7487 - (void) refreshButtonClicked {
7488 if ([delegate_ requestUpdate])
7489 [self setLeftBarButtonItem];
7492 - (void) cancelButtonClicked {
7493 [delegate_ cancelUpdate];
7496 - (void) upgradeButtonClicked {
7497 [delegate_ distUpgrade];
7498 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7501 - (bool) shouldYield {
7505 - (bool) shouldBlock {
7509 - (void) useFilter {
7510 @synchronized (self) {
7511 [self setFilter:[](Package *package) {
7512 return [package upgradableAndEssential:YES] || [package visible];
7515 [self setSorter:[](NSMutableArray *packages) {
7516 [packages radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7520 - (id) initWithDatabase:(Database *)database {
7521 if ((self = [super initWithDatabase:database title:UCLocalize("CHANGES")]) != nil) {
7526 - (void) viewDidLoad {
7527 [super viewDidLoad];
7528 [self setLeftBarButtonItem];
7531 - (void) viewWillAppear:(BOOL)animated {
7532 [super viewWillAppear:animated];
7533 [self setLeftBarButtonItem];
7536 - (void) reloadData {
7537 [self setLeftBarButtonItem];
7541 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
7542 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
7544 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7545 Section *ignored = nil;
7546 Section *section = nil;
7550 bool unseens = false;
7552 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7554 for (size_t offset = 0, count = [packages count]; offset != count; ++offset) {
7555 Package *package = [packages objectAtIndex:offset];
7557 BOOL uae = [package upgradableAndEssential:YES];
7561 time_t seen([package seen]);
7563 if (section == nil || last != seen) {
7567 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7570 _profile(ChangesController$reloadData$Allocate)
7571 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7572 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7573 [sections addObject:section];
7577 [section addToCount];
7578 } else if ([package ignored]) {
7579 if (ignored == nil) {
7580 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7582 [ignored addToCount];
7585 [upgradable addToCount];
7590 CFRelease(formatter);
7593 Section *last = [sections lastObject];
7594 size_t count = [last count];
7595 [packages removeObjectsInRange:NSMakeRange([packages count] - count, count)];
7596 [sections removeLastObject];
7599 if ([ignored count] != 0)
7600 [sections insertObject:ignored atIndex:0];
7602 [sections insertObject:upgradable atIndex:0];
7606 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7607 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7608 style:UIBarButtonItemStylePlain
7610 action:@selector(upgradeButtonClicked)
7611 ] autorelease]) animated:YES];
7618 /* Search Controller {{{ */
7619 @interface SearchController : FilteredPackageListController <
7622 _H<UISearchBar, 1> search_;
7627 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7628 - (void) reloadData;
7632 @implementation SearchController
7634 - (NSURL *) referrerURL {
7635 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/search?q=%@", UI_, [([search_ text] ?: @"") stringByAddingPercentEscapesIncludingReserved]]];
7638 - (NSURL *) navigationURL {
7639 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7640 return [NSURL URLWithString:@"cydia://search"];
7642 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [[search_ text] stringByAddingPercentEscapesIncludingReserved]]];
7645 - (NSArray *) termsForQuery:(NSString *)query {
7646 NSMutableArray *terms([NSMutableArray arrayWithCapacity:2]);
7647 for (NSString *component in [query componentsSeparatedByString:@" "])
7648 if ([component length] != 0)
7649 [terms addObject:component];
7654 - (void) useSearch {
7655 _H<NSArray> query([self termsForQuery:[search_ text]]);
7658 @synchronized (self) {
7659 [self setFilter:[=](Package *package) {
7660 if (![package unfiltered])
7662 if (![package matches:query])
7667 [self setSorter:[](NSMutableArray *packages) {
7668 [packages radixSortUsingSelector:@selector(rank)];
7676 - (void) usePrefix:(NSString *)prefix {
7677 _H<NSString> query(prefix);
7680 @synchronized (self) {
7681 [self setFilter:[=](Package *package) {
7682 if ([query length] == 0)
7684 if (![package unfiltered])
7686 if ([[package name] compare:query options:MatchCompareOptions_ range:NSMakeRange(0, [query length])] != NSOrderedSame)
7691 [self setSorter:nullptr];
7697 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7699 [self usePrefix:[search_ text]];
7702 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7703 [search_ resignFirstResponder];
7707 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7708 [search_ setText:@""];
7709 [self searchBarButtonClicked:searchBar];
7712 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7713 [self searchBarButtonClicked:searchBar];
7716 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7717 [self usePrefix:text];
7720 - (bool) shouldYield {
7724 - (bool) shouldBlock {
7728 - (bool) isSummarized {
7732 - (bool) showsSections {
7736 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7737 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH")])) {
7738 search_ = [[[UISearchBar alloc] init] autorelease];
7739 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7740 [search_ setDelegate:self];
7742 UITextField *textField;
7743 if ([search_ respondsToSelector:@selector(searchField)])
7744 textField = [search_ searchField];
7746 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7748 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7749 [textField setEnablesReturnKeyAutomatically:NO];
7750 [[self navigationItem] setTitleView:textField];
7753 [search_ setText:query];
7758 - (void) viewDidAppear:(BOOL)animated {
7759 [super viewDidAppear:animated];
7761 if (!searchloaded_) {
7762 searchloaded_ = YES;
7763 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7764 [search_ layoutSubviews];
7767 if ([self isSummarized])
7768 [search_ becomeFirstResponder];
7771 - (void) reloadData {
7776 - (void) didSelectPackage:(Package *)package {
7777 [search_ resignFirstResponder];
7778 [super didSelectPackage:package];
7783 /* Package Settings Controller {{{ */
7784 @interface PackageSettingsController : CyteViewController <
7785 UITableViewDataSource,
7788 _transient Database *database_;
7790 _H<Package> package_;
7791 _H<UITableView, 2> table_;
7792 _H<UISwitch> subscribedSwitch_;
7793 _H<UISwitch> ignoredSwitch_;
7794 _H<UITableViewCell> subscribedCell_;
7795 _H<UITableViewCell> ignoredCell_;
7798 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7802 @implementation PackageSettingsController
7804 - (NSURL *) navigationURL {
7805 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
7808 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7809 if (package_ == nil)
7812 if ([package_ installed] == nil)
7818 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7819 if (package_ == nil)
7822 // both sections contain just one item right now.
7826 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7830 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7832 return UCLocalize("SHOW_ALL_CHANGES_EX");
7834 return UCLocalize("IGNORE_UPGRADES_EX");
7837 - (void) onSubscribed:(id)control {
7838 bool value([control isOn]);
7839 if (package_ == nil)
7841 if ([package_ setSubscribed:value])
7842 [delegate_ updateData];
7845 - (void) _updateIgnored {
7846 const char *package([name_ UTF8String]);
7847 bool on([ignoredSwitch_ isOn]);
7849 pid_t pid(ExecFork());
7851 FILE *dpkg(popen("dpkg --set-selections", "w"));
7852 fwrite(package, strlen(package), 1, dpkg);
7855 fwrite(" hold\n", 6, 1, dpkg);
7857 fwrite(" install\n", 9, 1, dpkg);
7865 - (void) onIgnored:(id)control {
7866 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7867 [invocation setTarget:self];
7868 [invocation setSelector:@selector(_updateIgnored)];
7870 [delegate_ reloadDataWithInvocation:invocation];
7873 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7874 if (package_ == nil)
7877 switch ([indexPath section]) {
7878 case 0: return subscribedCell_;
7879 case 1: return ignoredCell_;
7888 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
7889 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
7890 [self setView:view];
7892 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7893 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7894 [(UITableView *) table_ setDataSource:self];
7895 [table_ setDelegate:self];
7896 [view addSubview:table_];
7898 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7899 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7900 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7902 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7903 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7904 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7906 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7907 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7908 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7909 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7911 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7912 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7913 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7914 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7917 - (void) viewDidLoad {
7918 [super viewDidLoad];
7920 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7923 - (void) releaseSubviews {
7925 subscribedCell_ = nil;
7927 ignoredSwitch_ = nil;
7928 subscribedSwitch_ = nil;
7930 [super releaseSubviews];
7933 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7934 if ((self = [super init]) != nil) {
7935 database_ = database;
7940 - (void) reloadData {
7943 package_ = [database_ packageWithName:name_];
7945 if (package_ != nil) {
7946 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7947 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7948 } // XXX: what now, G?
7950 [table_ reloadData];
7956 /* Installed Controller {{{ */
7957 @interface InstalledController : FilteredPackageListController {
7961 - (id) initWithDatabase:(Database *)database;
7962 - (void) queueStatusDidChange;
7966 @implementation InstalledController
7968 - (NSURL *) referrerURL {
7969 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/installed/", UI_]];
7972 - (NSURL *) navigationURL {
7973 return [NSURL URLWithString:@"cydia://installed"];
7976 - (void) useRecent {
7979 @synchronized (self) {
7980 [self setFilter:[](Package *package) {
7981 return ![package uninstalled] && package->role_ < 7;
7984 [self setSorter:[](NSMutableArray *packages) {
7985 [packages radixSortUsingSelector:@selector(recent)];
7989 - (void) useFilter:(UISegmentedControl *)segmented {
7990 NSInteger selected([segmented selectedSegmentIndex]);
7992 return [self useRecent];
7993 bool simple(selected == 0);
7996 @synchronized (self) {
7997 [self setFilter:[=](Package *package) {
7998 return ![package uninstalled] && package->role_ <= (simple ? 1 : 3);
8001 [self setSorter:nullptr];
8004 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
8006 return [super sectionsForPackages:packages];
8008 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterLongStyle, kCFDateFormatterNoStyle));
8010 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
8011 Section *section(nil);
8014 for (size_t offset(0), count([packages count]); offset != count; ++offset) {
8015 Package *package([packages objectAtIndex:offset]);
8017 time_t upgraded([package upgraded]);
8018 if (upgraded < 1168364520)
8021 upgraded -= upgraded % (60 * 60 * 24);
8023 if (section == nil || upgraded != last) {
8028 continue; // XXX: name = UCLocalize("...");
8030 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:upgraded]);
8034 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
8035 [sections addObject:section];
8038 [section addToCount];
8041 CFRelease(formatter);
8045 - (id) initWithDatabase:(Database *)database {
8046 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED")]) != nil) {
8047 UISegmentedControl *segmented([[[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:UCLocalize("USER"), UCLocalize("EXPERT"), UCLocalize("RECENT"), nil]] autorelease]);
8048 [segmented setSelectedSegmentIndex:0];
8049 [segmented setSegmentedControlStyle:UISegmentedControlStyleBar];
8050 [[self navigationItem] setTitleView:segmented];
8052 [segmented addTarget:self action:@selector(modeChanged:) forEvents:UIControlEventValueChanged];
8053 [self useFilter:segmented];
8055 [self queueStatusDidChange];
8060 - (void) queueButtonClicked {
8065 - (void) queueStatusDidChange {
8068 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8069 initWithTitle:UCLocalize("QUEUE")
8070 style:UIBarButtonItemStyleDone
8072 action:@selector(queueButtonClicked)
8075 [[self navigationItem] setLeftBarButtonItem:nil];
8080 - (void) modeChanged:(UISegmentedControl *)segmented {
8081 [self useFilter:segmented];
8088 /* Source Cell {{{ */
8089 @interface SourceCell : CyteTableViewCell <
8090 CyteTableViewCellDelegate,
8093 _H<Source, 1> source_;
8096 _H<NSString> origin_;
8097 _H<NSString> label_;
8098 _H<UIActivityIndicatorView> indicator_;
8101 - (void) setSource:(Source *)source;
8102 - (void) setFetch:(NSNumber *)fetch;
8106 @implementation SourceCell
8108 - (void) _setImage:(NSArray *)data {
8109 if ([url_ isEqual:[data objectAtIndex:0]]) {
8110 icon_ = [data objectAtIndex:1];
8111 [content_ setNeedsDisplay];
8115 - (void) _setSource:(NSURL *) url {
8116 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8118 if (NSData *data = [NSURLConnection
8119 sendSynchronousRequest:[NSURLRequest
8121 cachePolicy:NSURLRequestUseProtocolCachePolicy
8125 returningResponse:NULL
8128 if (UIImage *image = [UIImage imageWithData:data])
8129 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
8134 - (void) setSource:(Source *)source {
8136 [source_ setDelegate:self];
8138 [self setFetch:[NSNumber numberWithBool:[source_ fetch]]];
8140 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
8142 origin_ = [source name];
8143 label_ = [source rooturi];
8145 [content_ setNeedsDisplay];
8147 url_ = [source iconURL];
8148 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
8151 - (void) setAllSource {
8153 [indicator_ stopAnimating];
8155 icon_ = [UIImage applicationImageNamed:@"folder.png"];
8156 origin_ = UCLocalize("ALL_SOURCES");
8157 label_ = UCLocalize("ALL_SOURCES_EX");
8158 [content_ setNeedsDisplay];
8161 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8162 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8163 UIView *content([self contentView]);
8164 CGRect bounds([content bounds]);
8166 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8167 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8168 [content_ setBackgroundColor:[UIColor whiteColor]];
8169 [content addSubview:content_];
8171 [content_ setDelegate:self];
8172 [content_ setOpaque:YES];
8174 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGraySmall] autorelease];
8175 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin];// | UIViewAutoresizingFlexibleBottomMargin];
8176 [content addSubview:indicator_];
8178 [[content_ layer] setContentsGravity:kCAGravityTopLeft];
8182 - (void) layoutSubviews {
8183 [super layoutSubviews];
8185 UIView *content([self contentView]);
8186 CGRect bounds([content bounds]);
8188 CGRect frame([indicator_ frame]);
8189 frame.origin.x = bounds.size.width - frame.size.width;
8190 frame.origin.y = Retina((bounds.size.height - frame.size.height) / 2);
8192 if (kCFCoreFoundationVersionNumber < 800)
8193 frame.origin.x -= 8;
8194 [indicator_ setFrame:frame];
8197 - (NSString *) accessibilityLabel {
8201 - (void) drawContentRect:(CGRect)rect {
8202 bool highlighted(highlighted_);
8203 float width(rect.size.width);
8207 rect.size = [(UIImage *) icon_ size];
8209 while (rect.size.width > 32 || rect.size.height > 32) {
8210 rect.size.width /= 2;
8211 rect.size.height /= 2;
8214 rect.origin.x = 26 - rect.size.width / 2;
8215 rect.origin.y = 26 - rect.size.height / 2;
8217 [icon_ drawInRect:Retina(rect)];
8220 if (highlighted && kCFCoreFoundationVersionNumber < 800)
8225 [origin_ drawAtPoint:CGPointMake(52, 8) forWidth:(width - 61) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
8229 [label_ drawAtPoint:CGPointMake(52, 29) forWidth:(width - 61) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
8232 - (void) setFetch:(NSNumber *)fetch {
8233 if ([fetch boolValue])
8234 [indicator_ startAnimating];
8236 [indicator_ stopAnimating];
8241 /* Sources Controller {{{ */
8242 @interface SourcesController : CyteViewController <
8243 UITableViewDataSource,
8246 _transient Database *database_;
8249 _H<UITableView, 2> list_;
8250 _H<NSMutableArray> sources_;
8254 _H<UIProgressHUD> hud_;
8257 NSURLConnection *trivial_bz2_;
8258 NSURLConnection *trivial_gz_;
8263 - (id) initWithDatabase:(Database *)database;
8264 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated;
8268 @implementation SourcesController
8270 - (void) _releaseConnection:(NSURLConnection *)connection {
8271 if (connection != nil) {
8272 [connection cancel];
8273 //[connection setDelegate:nil];
8274 [connection release];
8279 [self _releaseConnection:trivial_gz_];
8280 [self _releaseConnection:trivial_bz2_];
8285 - (NSURL *) navigationURL {
8286 return [NSURL URLWithString:@"cydia://sources"];
8289 - (void) viewDidAppear:(BOOL)animated {
8290 [super viewDidAppear:animated];
8291 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8294 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8298 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8300 return UCLocalize("INDIVIDUAL_SOURCES");
8304 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8307 case 1: return [sources_ count];
8312 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8313 @synchronized (database_) {
8314 if ([database_ era] != era_)
8316 if ([indexPath section] != 1)
8318 NSUInteger index([indexPath row]);
8319 if (index >= [sources_ count])
8321 return [sources_ objectAtIndex:index];
8324 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8325 static NSString *cellIdentifier = @"SourceCell";
8327 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8328 if (cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8329 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8331 Source *source([self sourceAtIndexPath:indexPath]);
8333 [cell setAllSource];
8335 [cell setSource:source];
8340 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8341 SectionsController *controller([[[SectionsController alloc]
8342 initWithDatabase:database_
8343 source:[self sourceAtIndexPath:indexPath]
8346 [controller setDelegate:delegate_];
8347 [[self navigationController] pushViewController:controller animated:YES];
8350 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8351 if ([indexPath section] != 1)
8353 Source *source = [self sourceAtIndexPath:indexPath];
8354 return [source record] != nil;
8357 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8358 _assert([indexPath section] == 1);
8359 if (editingStyle == UITableViewCellEditingStyleDelete) {
8360 Source *source = [self sourceAtIndexPath:indexPath];
8361 if (source == nil) return;
8363 [Sources_ removeObjectForKey:[source key]];
8366 [delegate_ _saveConfig];
8367 [delegate_ reloadDataWithInvocation:nil];
8371 - (void) tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath {
8372 [self updateButtonsForEditingStatusAnimated:YES];
8376 [delegate_ addTrivialSource:href_];
8379 [delegate_ syncData];
8382 - (NSString *) getWarning {
8383 NSString *href(href_);
8384 NSRange colon([href rangeOfString:@"://"]);
8385 if (colon.location != NSNotFound)
8386 href = [href substringFromIndex:(colon.location + 3)];
8387 href = [href stringByAddingPercentEscapes];
8388 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8390 NSURL *url([NSURL URLWithString:href]);
8392 NSStringEncoding encoding;
8393 NSError *error(nil);
8395 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8396 return [warning length] == 0 ? nil : warning;
8400 - (void) _endConnection:(NSURLConnection *)connection {
8401 // XXX: the memory management in this method is horribly awkward
8403 NSURLConnection **field = NULL;
8404 if (connection == trivial_bz2_)
8405 field = &trivial_bz2_;
8406 else if (connection == trivial_gz_)
8407 field = &trivial_gz_;
8408 _assert(field != NULL);
8409 [connection release];
8413 trivial_bz2_ == nil &&
8416 NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil);
8418 [delegate_ releaseNetworkActivityIndicator];
8420 [delegate_ removeProgressHUD:hud_];
8424 if (warning != nil) {
8425 UIAlertView *alert = [[[UIAlertView alloc]
8426 initWithTitle:UCLocalize("SOURCE_WARNING")
8429 cancelButtonTitle:UCLocalize("CANCEL")
8431 UCLocalize("ADD_ANYWAY"),
8435 [alert setContext:@"warning"];
8436 [alert setNumberOfRows:1];
8439 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
8445 } else if (error_ != nil) {
8446 UIAlertView *alert = [[[UIAlertView alloc]
8447 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8448 message:[error_ localizedDescription]
8450 cancelButtonTitle:UCLocalize("OK")
8451 otherButtonTitles:nil
8454 [alert setContext:@"urlerror"];
8459 UIAlertView *alert = [[[UIAlertView alloc]
8460 initWithTitle:UCLocalize("NOT_REPOSITORY")
8461 message:UCLocalize("NOT_REPOSITORY_EX")
8463 cancelButtonTitle:UCLocalize("OK")
8464 otherButtonTitles:nil
8467 [alert setContext:@"trivial"];
8477 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8478 switch ([response statusCode]) {
8484 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8485 lprintf("connection:\"%s\" didFailWithError:\"%s\"\n", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8487 [self _endConnection:connection];
8490 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8491 [self _endConnection:connection];
8494 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8495 NSURL *url([NSURL URLWithString:href]);
8497 NSMutableURLRequest *request = [NSMutableURLRequest
8499 cachePolicy:NSURLRequestUseProtocolCachePolicy
8503 [request setHTTPMethod:method];
8505 if (Machine_ != NULL)
8506 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8508 if (UniqueID_ != nil)
8509 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8511 if ([url isCydiaSecure]) {
8512 if (UniqueID_ != nil)
8513 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
8516 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8519 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8520 NSString *context([alert context]);
8522 if ([context isEqualToString:@"source"]) {
8525 NSString *href = [[alert textField] text];
8527 static Pcre href_r("^http(s?)://[^# ]*$");
8528 if (!href_r(href)) {
8529 UIAlertView *alert = [[[UIAlertView alloc]
8530 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("INVALID_URL")]
8531 message:UCLocalize("INVALID_URL_EX")
8533 cancelButtonTitle:UCLocalize("OK")
8534 otherButtonTitles:nil
8537 [alert setContext:@"badurl"];
8543 if (![href hasSuffix:@"/"])
8544 href_ = [href stringByAppendingString:@"/"];
8548 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8549 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8553 // XXX: this is stupid
8554 hud_ = [delegate_ addProgressHUD];
8555 [hud_ setText:UCLocalize("VERIFYING_URL")];
8556 [delegate_ retainNetworkActivityIndicator];
8565 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8566 } else if ([context isEqualToString:@"trivial"])
8567 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8568 else if ([context isEqualToString:@"urlerror"])
8569 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8570 else if ([context isEqualToString:@"warning"]) {
8573 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
8582 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8586 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated {
8587 BOOL editing([list_ isEditing]);
8590 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8591 initWithTitle:UCLocalize("ADD")
8592 style:UIBarButtonItemStylePlain
8594 action:@selector(addButtonClicked)
8595 ] autorelease] animated:animated];
8596 else if ([delegate_ updating])
8597 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8598 initWithTitle:UCLocalize("CANCEL")
8599 style:UIBarButtonItemStyleDone
8601 action:@selector(cancelButtonClicked)
8602 ] autorelease] animated:animated];
8604 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8605 initWithTitle:UCLocalize("REFRESH")
8606 style:UIBarButtonItemStylePlain
8608 action:@selector(refreshButtonClicked)
8609 ] autorelease] animated:animated];
8611 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8612 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8613 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8615 action:@selector(editButtonClicked)
8616 ] autorelease] animated:animated];
8620 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease];
8621 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8622 [list_ setRowHeight:53];
8623 [(UITableView *) list_ setDataSource:self];
8624 [list_ setDelegate:self];
8625 [self setView:list_];
8628 - (void) viewDidLoad {
8629 [super viewDidLoad];
8631 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8632 [self updateButtonsForEditingStatusAnimated:NO];
8635 - (void) viewWillAppear:(BOOL)animated {
8636 [super viewWillAppear:animated];
8638 [list_ setEditing:NO];
8639 [self updateButtonsForEditingStatusAnimated:NO];
8642 - (void) releaseSubviews {
8647 [super releaseSubviews];
8650 - (id) initWithDatabase:(Database *)database {
8651 if ((self = [super init]) != nil) {
8652 database_ = database;
8656 - (void) reloadData {
8658 [self updateButtonsForEditingStatusAnimated:YES];
8660 @synchronized (database_) {
8661 era_ = [database_ era];
8663 sources_ = [NSMutableArray arrayWithCapacity:16];
8664 [sources_ addObjectsFromArray:[database_ sources]];
8666 [sources_ sortUsingSelector:@selector(compareByName:)];
8669 int count([sources_ count]);
8671 for (int i = 0; i != count; i++) {
8672 if ([[sources_ objectAtIndex:i] record] == nil)
8680 - (void) showAddSourcePrompt {
8681 UIAlertView *alert = [[[UIAlertView alloc]
8682 initWithTitle:UCLocalize("ENTER_APT_URL")
8685 cancelButtonTitle:UCLocalize("CANCEL")
8687 UCLocalize("ADD_SOURCE"),
8691 [alert setContext:@"source"];
8693 [alert setNumberOfRows:1];
8694 [alert addTextFieldWithValue:@"http://" label:@""];
8696 UITextInputTraits *traits = [[alert textField] textInputTraits];
8697 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8698 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8699 [traits setKeyboardType:UIKeyboardTypeURL];
8700 // XXX: UIReturnKeyDone
8701 [traits setReturnKeyType:UIReturnKeyNext];
8706 - (void) addButtonClicked {
8707 [self showAddSourcePrompt];
8710 - (void) refreshButtonClicked {
8711 if ([delegate_ requestUpdate])
8712 [self updateButtonsForEditingStatusAnimated:YES];
8715 - (void) cancelButtonClicked {
8716 [delegate_ cancelUpdate];
8719 - (void) editButtonClicked {
8720 [list_ setEditing:![list_ isEditing] animated:YES];
8721 [self updateButtonsForEditingStatusAnimated:YES];
8727 /* Stash Controller {{{ */
8728 @interface StashController : CyteViewController {
8729 _H<UIActivityIndicatorView> spinner_;
8730 _H<UILabel> status_;
8731 _H<UILabel> caption_;
8736 @implementation StashController
8739 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8740 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8741 [self setView:view];
8743 [view setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8745 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8746 CGRect spinrect = [spinner_ frame];
8747 spinrect.origin.x = Retina([[self view] frame].size.width / 2 - spinrect.size.width / 2);
8748 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8749 [spinner_ setFrame:spinrect];
8750 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8751 [view addSubview:spinner_];
8752 [spinner_ startAnimating];
8755 captrect.size.width = [[self view] frame].size.width;
8756 captrect.size.height = 40.0f;
8757 captrect.origin.x = 0;
8758 captrect.origin.y = Retina([[self view] frame].size.height / 2 - captrect.size.height * 2);
8759 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8760 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8761 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8762 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8763 [caption_ setTextColor:[UIColor whiteColor]];
8764 [caption_ setBackgroundColor:[UIColor clearColor]];
8765 [caption_ setShadowColor:[UIColor blackColor]];
8766 [caption_ setTextAlignment:NSTextAlignmentCenter];
8767 [view addSubview:caption_];
8770 statusrect.size.width = [[self view] frame].size.width;
8771 statusrect.size.height = 30.0f;
8772 statusrect.origin.x = 0;
8773 statusrect.origin.y = Retina([[self view] frame].size.height / 2 - statusrect.size.height);
8774 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8775 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8776 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8777 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8778 [status_ setTextColor:[UIColor whiteColor]];
8779 [status_ setBackgroundColor:[UIColor clearColor]];
8780 [status_ setShadowColor:[UIColor blackColor]];
8781 [status_ setTextAlignment:NSTextAlignmentCenter];
8782 [view addSubview:status_];
8785 - (void) releaseSubviews {
8790 [super releaseSubviews];
8796 @interface CYURLCache : SDURLCache {
8801 @implementation CYURLCache
8803 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8806 else if ([event isEqualToString:@"no-cache"])
8808 else if ([event isEqualToString:@"store"])
8810 else if ([event isEqualToString:@"invalid"])
8812 else if ([event isEqualToString:@"memory"])
8814 else if ([event isEqualToString:@"disk"])
8816 else if ([event isEqualToString:@"miss"])
8819 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8823 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
8824 if (NSURLResponse *response = [cached response])
8825 if (NSString *mime = [response MIMEType])
8826 if ([mime isEqualToString:@"text/cache-manifest"]) {
8827 NSURL *url([response URL]);
8830 NSLog(@"###: %@", [url absoluteString]);
8833 @synchronized (HostConfig_) {
8834 [CachedURLs_ addObject:url];
8838 [super storeCachedResponse:cached forRequest:request];
8843 @interface Cydia : UIApplication <
8844 ConfirmationControllerDelegate,
8848 _H<UIWindow> window_;
8849 _H<CydiaTabBarController> tabbar_;
8850 _H<CyteTabBarController> emulated_;
8852 _H<NSMutableArray> essential_;
8853 _H<NSMutableArray> broken_;
8855 Database *database_;
8857 _H<NSURL> starturl_;
8862 _H<StashController> stash_;
8871 @implementation Cydia
8873 - (void) lockSuspend {
8874 if (locked_++ == 0) {
8875 if ($SBSSetInterceptsMenuButtonForever != NULL)
8876 (*$SBSSetInterceptsMenuButtonForever)(true);
8878 [self setIdleTimerDisabled:YES];
8882 - (void) unlockSuspend {
8883 if (--locked_ == 0) {
8884 [self setIdleTimerDisabled:NO];
8886 if ($SBSSetInterceptsMenuButtonForever != NULL)
8887 (*$SBSSetInterceptsMenuButtonForever)(false);
8891 - (void) beginUpdate {
8892 [tabbar_ beginUpdate];
8895 - (void) cancelUpdate {
8896 [tabbar_ cancelUpdate];
8899 - (bool) requestUpdate {
8900 if (IsReachable("cydia.saurik.com")) {
8904 UIAlertView *alert = [[[UIAlertView alloc]
8905 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("REFRESH")]
8906 message:@"Host Unreachable" // XXX: Localize
8908 cancelButtonTitle:UCLocalize("OK")
8909 otherButtonTitles:nil
8912 [alert setContext:@"norefresh"];
8920 return [tabbar_ updating];
8924 if ([broken_ count] != 0) {
8925 int count = [broken_ count];
8927 UIAlertView *alert = [[[UIAlertView alloc]
8928 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8929 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8931 cancelButtonTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("FORCIBLY_CLEAR"), UCLocalize("UNSAFE")]
8933 UCLocalize("TEMPORARY_IGNORE"),
8937 [alert setContext:@"fixhalf"];
8938 [alert setNumberOfRows:2];
8940 } else if (!Ignored_ && [essential_ count] != 0) {
8941 int count = [essential_ count];
8943 UIAlertView *alert = [[[UIAlertView alloc]
8944 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8945 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8947 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8949 UCLocalize("UPGRADE_ESSENTIAL"),
8950 UCLocalize("COMPLETE_UPGRADE"),
8954 [alert setContext:@"upgrade"];
8959 - (void) returnToCydia {
8963 - (void) _saveConfig {
8964 @synchronized (database_) {
8971 NSString *error(nil);
8973 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8975 NSError *error(nil);
8976 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8977 NSLog(@"failure to save metadata data: %@", error);
8982 NSLog(@"failure to serialize metadata: %@", error);
8986 CydiaWriteSources();
8989 // Navigation controller for the queuing badge.
8990 - (UINavigationController *) queueNavigationController {
8991 NSArray *controllers = [tabbar_ viewControllers];
8992 return [controllers objectAtIndex:3];
8995 - (void) unloadData {
8996 [tabbar_ unloadData];
8999 - (void) _updateData {
9003 UINavigationController *navigation = [self queueNavigationController];
9005 id queuedelegate = nil;
9006 if ([[navigation viewControllers] count] > 0)
9007 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9009 [queuedelegate queueStatusDidChange];
9010 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9013 - (void) _refreshIfPossible:(NSDate *)update {
9014 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9016 bool recently = false;
9017 if (update != nil) {
9018 NSTimeInterval interval([update timeIntervalSinceNow]);
9019 if (interval <= 0 && interval > -(15*60))
9023 // Don't automatic refresh if:
9024 // - We already refreshed recently.
9025 // - We already auto-refreshed this launch.
9026 // - Auto-refresh is disabled.
9027 // - Cydia's server is not reachable
9028 if (recently || loaded_ || ManualRefresh || !IsReachable("cydia.saurik.com")) {
9029 // If we are cancelling, we need to make sure it knows it's already loaded.
9032 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9034 // We are going to load, so remember that.
9037 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
9043 - (void) refreshIfPossible {
9044 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
9047 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9048 _profile(reloadDataWithInvocation)
9049 @synchronized (self) {
9050 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9052 [hud setText:UCLocalize("RELOADING_DATA")];
9054 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9058 [essential_ removeAllObjects];
9059 [broken_ removeAllObjects];
9061 _profile(reloadDataWithInvocation$Essential)
9062 NSArray *packages([database_ packages]);
9063 for (Package *package in packages) {
9065 [broken_ addObject:package];
9066 if ([package upgradableAndEssential:YES] && ![package ignored]) {
9067 if ([package essential] && [package installed] != nil)
9068 [essential_ addObject:package];
9074 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9077 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9078 [changesItem setBadgeValue:badge];
9079 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9080 [self setApplicationIconBadgeNumber:changes];
9083 [changesItem setBadgeValue:nil];
9084 [changesItem setAnimatedBadge:NO];
9085 [self setApplicationIconBadgeNumber:0];
9091 [self removeProgressHUD:hud];
9098 - (void) updateData {
9102 - (void) updateDataAndLoad {
9104 if ([database_ progressDelegate] == nil)
9110 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9113 - (void) disemulate {
9114 if (emulated_ == nil)
9117 if ([window_ respondsToSelector:@selector(setRootViewController:)])
9118 [window_ setRootViewController:tabbar_];
9120 [window_ addSubview:[tabbar_ view]];
9121 [[emulated_ view] removeFromSuperview];
9125 [window_ setUserInteractionEnabled:YES];
9128 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9129 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9131 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9133 UIViewController *parent;
9134 if (emulated_ == nil)
9143 [parent presentModalViewController:navigation animated:YES];
9146 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9147 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9149 if (navigation != nil)
9150 [navigation pushViewController:progress animated:YES];
9152 [self presentModalViewController:progress force:YES];
9154 [progress invoke:invocation withTitle:title];
9158 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9159 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9162 - (void) repairWithInvocation:(NSInvocation *)invocation {
9164 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9168 - (void) repairWithSelector:(SEL)selector {
9169 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9172 - (void) reloadData {
9173 [self reloadDataWithInvocation:nil];
9174 if ([database_ progressDelegate] == nil)
9180 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9183 - (void) addSource:(NSDictionary *) source {
9184 CydiaAddSource(source);
9187 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9188 CydiaAddSource(href, distribution, sections);
9191 - (void) addTrivialSource:(NSString *)href {
9192 CydiaAddSource(href, @"./");
9195 - (void) updateValues {
9200 pkgProblemResolver *resolver = [database_ resolver];
9202 resolver->InstallProtect();
9203 if (!resolver->Resolve(true))
9208 // XXX: this is a really crappy way of doing this.
9209 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9210 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9211 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9212 if ([tabbar_ updating])
9213 [tabbar_ cancelUpdate];
9215 if (![database_ prepare])
9218 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9219 [page setDelegate:self];
9220 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9223 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9224 [tabbar_ presentModalViewController:confirm_ animated:YES];
9230 @synchronized (self) {
9235 - (void) clearPackage:(Package *)package {
9236 @synchronized (self) {
9243 - (void) installPackages:(NSArray *)packages {
9244 @synchronized (self) {
9245 for (Package *package in packages)
9252 - (void) installPackage:(Package *)package {
9253 @synchronized (self) {
9260 - (void) removePackage:(Package *)package {
9261 @synchronized (self) {
9268 - (void) distUpgrade {
9269 @synchronized (self) {
9270 if (![database_ upgrade])
9278 system("su -c /usr/bin/uicache mobile");
9283 UIProgressHUD *hud([self addProgressHUD]);
9284 [hud setText:UCLocalize("LOADING")];
9285 [self yieldToSelector:@selector(_uicache)];
9286 [self removeProgressHUD:hud];
9290 [database_ perform];
9291 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9292 [self performSelectorOnMainThread:@selector(uicache) withObject:nil waitUntilDone:YES];
9295 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9298 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9299 [self unlockSuspend];
9302 - (void) retainNetworkActivityIndicator {
9303 if (activity_++ == 0)
9304 [self setNetworkActivityIndicatorVisible:YES];
9307 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9311 - (void) releaseNetworkActivityIndicator {
9312 if (--activity_ == 0)
9313 [self setNetworkActivityIndicatorVisible:NO];
9316 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9321 - (void) cancelAndClear:(bool)clear {
9322 @synchronized (self) {
9334 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9335 NSString *context([alert context]);
9337 if ([context isEqualToString:@"conffile"]) {
9338 FILE *input = [database_ input];
9339 if (button == [alert cancelButtonIndex])
9340 fprintf(input, "N\n");
9341 else if (button == [alert firstOtherButtonIndex])
9342 fprintf(input, "Y\n");
9345 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9346 } else if ([context isEqualToString:@"fixhalf"]) {
9347 if (button == [alert cancelButtonIndex]) {
9348 @synchronized (self) {
9349 for (Package *broken in (id) broken_) {
9352 NSString *id = [broken id];
9353 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9354 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9355 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9356 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9362 } else if (button == [alert firstOtherButtonIndex]) {
9363 [broken_ removeAllObjects];
9367 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9368 } else if ([context isEqualToString:@"upgrade"]) {
9369 if (button == [alert firstOtherButtonIndex]) {
9370 @synchronized (self) {
9371 for (Package *essential in (id) essential_)
9372 [essential install];
9377 } else if (button == [alert firstOtherButtonIndex] + 1) {
9379 } else if (button == [alert cancelButtonIndex]) {
9383 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9387 - (void) system:(NSString *)command {
9388 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9391 system([command UTF8String]);
9397 - (void) applicationWillSuspend {
9399 [super applicationWillSuspend];
9402 - (BOOL) isSafeToSuspend {
9405 NSLog(@"isSafeToSuspend: locked_ != 0");
9410 if ([tabbar_ modalViewController] != nil)
9413 // Use external process status API internally.
9414 // This is probably a really bad idea.
9415 // XXX: what is the point of this? does this solve anything at all?
9416 uint64_t status = 0;
9418 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9419 notify_get_state(notify_token, &status);
9420 notify_cancel(notify_token);
9425 NSLog(@"isSafeToSuspend: status != 0");
9431 NSLog(@"isSafeToSuspend: -> true");
9436 - (void) applicationSuspend:(__GSEvent *)event {
9437 if ([self isSafeToSuspend])
9438 [super applicationSuspend:event];
9441 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9442 if ([self isSafeToSuspend])
9443 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9446 - (void) _setSuspended:(BOOL)value {
9447 if ([self isSafeToSuspend])
9448 [super _setSuspended:value];
9451 - (UIProgressHUD *) addProgressHUD {
9452 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9453 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9455 [window_ setUserInteractionEnabled:NO];
9457 UIViewController *target(tabbar_);
9458 if (UIViewController *modal = [target modalViewController])
9461 [hud showInView:[target view]];
9467 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9468 [self unlockSuspend];
9470 [hud removeFromSuperview];
9471 [window_ setUserInteractionEnabled:YES];
9474 - (CyteViewController *) pageForPackage:(NSString *)name withReferrer:(NSString *)referrer {
9475 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name withReferrer:referrer] autorelease];
9478 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external withReferrer:(NSString *)referrer {
9479 NSString *scheme([[url scheme] lowercaseString]);
9480 if ([[url absoluteString] length] <= [scheme length] + 3)
9482 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9483 NSArray *components([path componentsSeparatedByString:@"/"]);
9485 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"]) {
9486 CyteViewController *controller([self pageForPackage:[components objectAtIndex:1] withReferrer:referrer]);
9487 if (controller != nil)
9488 [controller setDelegate:self];
9492 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9495 NSString *base([components objectAtIndex:0]);
9497 CyteViewController *controller = nil;
9499 if ([base isEqualToString:@"url"]) {
9500 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9501 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9502 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9503 } else if (!external && [components count] == 1) {
9504 if ([base isEqualToString:@"sources"]) {
9505 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9508 if ([base isEqualToString:@"home"]) {
9509 controller = [[[HomeController alloc] init] autorelease];
9512 if ([base isEqualToString:@"sections"]) {
9513 controller = [[[SectionsController alloc] initWithDatabase:database_ source:nil] autorelease];
9516 if ([base isEqualToString:@"search"]) {
9517 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9520 if ([base isEqualToString:@"changes"]) {
9521 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9524 if ([base isEqualToString:@"installed"]) {
9525 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9527 } else if ([components count] == 2) {
9528 NSString *argument = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9530 if ([base isEqualToString:@"package"]) {
9531 controller = [self pageForPackage:argument withReferrer:referrer];
9534 if (!external && [base isEqualToString:@"search"]) {
9535 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9538 if (!external && [base isEqualToString:@"sections"]) {
9539 if ([argument isEqualToString:@"all"] || [argument isEqualToString:@"*"])
9541 controller = [[[SectionController alloc] initWithDatabase:database_ source:nil section:argument] autorelease];
9544 if (!external && [base isEqualToString:@"sources"]) {
9545 if ([argument isEqualToString:@"add"]) {
9546 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9547 [(SourcesController *)controller showAddSourcePrompt];
9549 Source *source([database_ sourceWithKey:argument]);
9550 controller = [[[SectionsController alloc] initWithDatabase:database_ source:source] autorelease];
9554 if (!external && [base isEqualToString:@"launch"]) {
9555 [self launchApplicationWithIdentifier:argument suspended:NO];
9558 } else if (!external && [components count] == 3) {
9559 NSString *arg1 = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9560 NSString *arg2 = [[components objectAtIndex:2] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9562 if ([base isEqualToString:@"package"]) {
9563 if ([arg2 isEqualToString:@"settings"]) {
9564 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9565 } else if ([arg2 isEqualToString:@"files"]) {
9566 if (Package *package = [database_ packageWithName:arg1]) {
9567 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9568 [(FileTable *)controller setPackage:package];
9573 if ([base isEqualToString:@"sections"]) {
9574 Source *source([arg1 isEqualToString:@"*"] ? nil : [database_ sourceWithKey:arg1]);
9575 NSString *section([arg2 isEqualToString:@"*"] ? nil : arg2);
9576 controller = [[[SectionController alloc] initWithDatabase:database_ source:source section:section] autorelease];
9580 [controller setDelegate:self];
9584 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9585 CyteViewController *page([self pageForURL:url forExternal:external withReferrer:nil]);
9588 [tabbar_ setUnselectedViewController:page];
9593 - (void) applicationOpenURL:(NSURL *)url {
9594 [super applicationOpenURL:url];
9599 [self openCydiaURL:url forExternal:YES];
9602 - (void) applicationWillResignActive:(UIApplication *)application {
9603 // Stop refreshing if you get a phone call or lock the device.
9604 if ([tabbar_ updating])
9605 [tabbar_ cancelUpdate];
9607 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9608 [super applicationWillResignActive:application];
9611 - (void) saveState {
9612 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9613 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9614 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9620 - (void) applicationWillTerminate:(UIApplication *)application {
9624 - (void) setConfigurationData:(NSString *)data {
9625 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9627 if (!conffile_r(data)) {
9628 lprintf("E:invalid conffile\n");
9632 NSString *ofile = conffile_r[1];
9633 //NSString *nfile = conffile_r[2];
9635 UIAlertView *alert = [[[UIAlertView alloc]
9636 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9637 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9639 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9641 UCLocalize("ACCEPT_NEW_COPY"),
9642 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9646 [alert setContext:@"conffile"];
9647 [alert setNumberOfRows:2];
9651 - (void) addStashController {
9653 stash_ = [[[StashController alloc] init] autorelease];
9654 [window_ addSubview:[stash_ view]];
9657 - (void) removeStashController {
9658 [[stash_ view] removeFromSuperview];
9660 [self unlockSuspend];
9664 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9665 UpdateExternalStatus(1);
9666 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9667 UpdateExternalStatus(0);
9669 [self removeStashController];
9671 pid_t pid(ExecFork());
9673 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9674 perror("launchctl stop");
9680 - (void) setupViewControllers {
9681 tabbar_ = [[[CydiaTabBarController alloc] initWithDatabase:database_] autorelease];
9683 NSMutableArray *items;
9684 if (kCFCoreFoundationVersionNumber < 800) {
9685 items = [NSMutableArray arrayWithObjects:
9686 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9687 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9688 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9689 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease],
9690 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9693 items = [NSMutableArray arrayWithObjects:
9694 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home7.png"] selectedImage:[UIImage applicationImageNamed:@"home7s.png"]] autorelease],
9695 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"install7.png"] selectedImage:[UIImage applicationImageNamed:@"install7s.png"]] autorelease],
9696 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes7.png"] selectedImage:[UIImage applicationImageNamed:@"changes7s.png"]] autorelease],
9697 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage7.png"] selectedImage:[UIImage applicationImageNamed:@"manage7s.png"]] autorelease],
9698 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search7.png"] selectedImage:[UIImage applicationImageNamed:@"search7s.png"]] autorelease],
9702 NSMutableArray *controllers([NSMutableArray array]);
9703 for (UITabBarItem *item in items) {
9704 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9705 [controller setTabBarItem:item];
9706 [controllers addObject:controller];
9708 [tabbar_ setViewControllers:controllers];
9710 [tabbar_ setUpdateDelegate:self];
9713 - (void) _sendMemoryWarningNotification {
9714 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: maybe 4_0?
9715 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationMemoryWarningNotification" object:[UIApplication sharedApplication]];
9717 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
9720 - (void) _sendMemoryWarningNotifications {
9722 [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO];
9728 - (void) applicationDidReceiveMemoryWarning:(UIApplication *)application {
9730 [[NSURLCache sharedURLCache] removeAllCachedResponses];
9733 - (void) applicationDidFinishLaunching:(id)unused {
9734 //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil];
9737 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9738 [self setApplicationSupportsShakeToEdit:NO];
9740 @synchronized (HostConfig_) {
9741 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9744 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9745 initWithMemoryCapacity:524288
9746 diskCapacity:10485760
9747 diskPath:[NSString stringWithFormat:@"%@/SDURLCache", Cache_]
9750 [CydiaWebViewController _initialize];
9752 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9754 // this would disallow http{,s} URLs from accessing this data
9755 //[WebView registerURLSchemeAsLocal:@"cydia"];
9757 Font12_ = [UIFont systemFontOfSize:12];
9758 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9759 Font14_ = [UIFont systemFontOfSize:14];
9760 Font18_ = [UIFont systemFontOfSize:18];
9761 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9762 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9764 essential_ = [NSMutableArray arrayWithCapacity:4];
9765 broken_ = [NSMutableArray arrayWithCapacity:4];
9767 // XXX: I really need this thing... like, seriously... I'm sorry
9768 [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
9770 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9771 [window_ orderFront:self];
9772 [window_ makeKey:self];
9773 [window_ setHidden:NO];
9776 [self addStashController];
9777 // XXX: this would be much cleaner as a yieldToSelector:
9778 // that way the removeStashController could happen right here inline
9779 // we also could no longer require the useless stash_ field anymore
9780 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9785 int error(stat("/", &root));
9786 _assert(error != -1);
9788 #define Stash_(path) do { \
9789 struct stat folder; \
9790 int error(lstat((path), &folder)); \
9791 if (error != -1 && ( \
9792 folder.st_dev == root.st_dev && \
9793 S_ISDIR(folder.st_mode) \
9794 ) || error == -1 && ( \
9795 errno == ENOENT || \
9800 Stash_("/Applications");
9801 Stash_("/Library/Ringtones");
9802 Stash_("/Library/Wallpaper");
9803 //Stash_("/usr/bin");
9804 Stash_("/usr/include");
9805 Stash_("/usr/lib/pam");
9806 Stash_("/usr/share");
9807 //Stash_("/var/lib");
9809 database_ = [Database sharedInstance];
9810 [database_ setDelegate:self];
9812 [window_ setUserInteractionEnabled:NO];
9813 [self setupViewControllers];
9815 CydiaLoadingViewController *loading([[[CydiaLoadingViewController alloc] init] autorelease]);
9816 UINavigationController *navigation([[[UINavigationController alloc] init] autorelease]);
9817 [navigation setViewControllers:[NSArray arrayWithObject:loading]];
9819 emulated_ = [[[CyteTabBarController alloc] init] autorelease];
9820 [emulated_ setViewControllers:[NSArray arrayWithObject:navigation]];
9821 [emulated_ setSelectedIndex:0];
9822 [emulated_ concealTabBarSelection];
9824 if ([window_ respondsToSelector:@selector(setRootViewController:)])
9825 [window_ setRootViewController:emulated_];
9827 [window_ addSubview:[emulated_ view]];
9829 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9833 - (NSArray *) defaultStartPages {
9834 NSMutableArray *standard = [NSMutableArray array];
9835 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9836 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9837 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9838 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9839 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9845 if ([emulated_ modalViewController] != nil)
9846 [emulated_ dismissModalViewControllerAnimated:YES];
9847 [window_ setUserInteractionEnabled:NO];
9849 [self reloadDataWithInvocation:nil];
9850 [self refreshIfPossible];
9853 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9854 NSArray *saved = [[[Metadata_ objectForKey:@"InterfaceState"] mutableCopy] autorelease];
9855 int standardIndex = 0;
9856 NSArray *standard = [self defaultStartPages];
9863 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9864 if (valid && closed != nil) {
9865 NSTimeInterval interval([closed timeIntervalSinceNow]);
9866 // XXX: Is 30 minutes the optimal time here?
9867 if (interval <= -(30*60))
9871 if (valid && [saved count] != [standard count])
9875 for (unsigned int i = 0; i < [standard count]; i++) {
9876 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9877 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9878 // but it's good enough for now.
9879 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9886 NSArray *items = nil;
9888 [tabbar_ setSelectedIndex:savedIndex];
9891 [tabbar_ setSelectedIndex:standardIndex];
9895 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9896 NSArray *stack = [items objectAtIndex:tab];
9897 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9898 NSMutableArray *current = [NSMutableArray array];
9900 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9901 NSString *addr = [stack objectAtIndex:nav];
9902 NSURL *url = [NSURL URLWithString:addr];
9903 CyteViewController *page = [self pageForURL:url forExternal:NO withReferrer:nil];
9905 [current addObject:page];
9908 [navigation setViewControllers:current];
9911 // (Try to) show the startup URL.
9912 if (starturl_ != nil) {
9913 [self openCydiaURL:starturl_ forExternal:YES];
9918 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9919 if (item != nil && IsWildcat_) {
9920 [sheet showFromBarButtonItem:item animated:YES];
9922 [sheet showInView:window_];
9926 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9927 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9928 [progress setTitle:task];
9929 [progress addProgressEvent:event];
9932 - (void) addProgressEventForTask:(NSArray *)data {
9933 CydiaProgressEvent *event([data objectAtIndex:0]);
9934 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9935 [self addProgressEvent:event forTask:task];
9938 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9939 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9945 id Alloc_(id self, SEL selector) {
9946 id object = alloc_(self, selector);
9947 lprintf("[%s]A-%p\n", self->isa->name, object);
9952 id Dealloc_(id self, SEL selector) {
9953 id object = dealloc_(self, selector);
9954 lprintf("[%s]D-%p\n", self->isa->name, object);
9958 static NSSet *MobilizedFiles_;
9960 static NSURL *MobilizeURL(NSURL *url) {
9961 NSString *path([url path]);
9962 if ([path hasPrefix:@"/var/root/"]) {
9963 NSString *file([path substringFromIndex:10]);
9964 if ([MobilizedFiles_ containsObject:file])
9965 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
9971 Class $CFXPreferencesPropertyListSource;
9972 @class CFXPreferencesPropertyListSource;
9974 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9975 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9976 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9978 url = MobilizeURL(url);
9980 value = _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd);
9981 //NSLog(@"CFX %@ %s", [url absoluteString], value ? "YES" : "NO");
9990 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
9991 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
9992 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9994 url = MobilizeURL(url);
9996 value = _CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd);
9997 //NSLog(@"CFX %@ %@", [url absoluteString], value);
10006 Class $NSURLConnection;
10008 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
10009 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
10011 NSURL *url([copy URL]);
10013 NSString *host([url host]);
10014 NSString *scheme([[url scheme] lowercaseString]);
10016 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
10018 @synchronized (HostConfig_) {
10019 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
10020 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
10021 [copy setHTTPShouldUsePipelining:YES];
10023 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
10024 if ([control isEqualToString:@"max-age=0"])
10025 if ([CachedURLs_ containsObject:url]) {
10027 NSLog(@"~~~: %@", url);
10030 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
10032 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
10033 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
10034 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
10038 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
10044 static CGSize $WAKWindow$screenSize(WAKWindow *self, SEL _cmd) {
10045 CGSize size([[UIScreen mainScreen] bounds].size);
10046 /*if ([$WAKWindow respondsToSelector:@selector(hasLandscapeOrientation)])
10047 if ([$WAKWindow hasLandscapeOrientation])
10048 std::swap(size.width, size.height);*/
10052 Class $NSUserDefaults;
10054 MSHook(id, NSUserDefaults$objectForKey$, NSUserDefaults *self, SEL _cmd, NSString *key) {
10055 if ([key respondsToSelector:@selector(isEqualToString:)] && [key isEqualToString:@"WebKitLocalStorageDatabasePathPreferenceKey"])
10056 return [NSString stringWithFormat:@"%@/LocalStorage", Cache_];
10057 return _NSUserDefaults$objectForKey$(self, _cmd, key);
10060 int main(int argc, char *argv[]) {
10061 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10065 UpdateExternalStatus(0);
10067 UIScreen *screen([UIScreen mainScreen]);
10068 if ([screen respondsToSelector:@selector(scale)])
10069 ScreenScale_ = [screen scale];
10073 UIDevice *device([UIDevice currentDevice]);
10074 if ([device respondsToSelector:@selector(userInterfaceIdiom)]) {
10075 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10076 if (idiom == UIUserInterfaceIdiomPad)
10080 Idiom_ = IsWildcat_ ? @"ipad" : @"iphone";
10082 Pcre pattern("^([0-9]+\\.[0-9]+)");
10084 if (pattern([device systemVersion]))
10085 Firmware_ = pattern[1];
10086 if (pattern(Cydia_))
10087 Major_ = pattern[1];
10089 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
10091 HostConfig_ = [[[NSObject alloc] init] autorelease];
10092 @synchronized (HostConfig_) {
10093 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10094 TokenHosts_ = [NSMutableSet setWithCapacity:4];
10095 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
10096 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
10097 CachedURLs_ = [NSMutableSet setWithCapacity:32];
10100 NSString *ui(@"ui/ios");
10102 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
10103 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"/%@", Major_]];
10104 UI_ = CydiaURL(ui);
10106 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10108 MobilizedFiles_ = [NSMutableSet setWithObjects:
10109 @"Library/Preferences/.GlobalPreferences.plist",
10110 @"Library/Preferences/com.apple.Accessibility.plist",
10111 @"Library/Preferences/com.apple.preferences.sounds.plist",
10114 /* Library Hacks {{{ */
10115 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10117 $WAKWindow = objc_getClass("WAKWindow");
10118 if ($WAKWindow != NULL)
10119 if (Method method = class_getInstanceMethod($WAKWindow, @selector(screenSize)))
10120 method_setImplementation(method, (IMP) &$WAKWindow$screenSize);
10122 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSourceSynchronizer");
10123 if ($CFXPreferencesPropertyListSource == Nil)
10124 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
10126 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
10127 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
10128 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10129 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10132 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
10133 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
10134 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
10135 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
10138 $NSURLConnection = objc_getClass("NSURLConnection");
10139 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10140 if (NSURLConnection$init$ != NULL) {
10141 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10142 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10145 $NSUserDefaults = objc_getClass("NSUserDefaults");
10146 Method NSUserDefaults$objectForKey$(class_getInstanceMethod($NSUserDefaults, @selector(objectForKey:)));
10147 if (NSUserDefaults$objectForKey$ != NULL) {
10148 _NSUserDefaults$objectForKey$ = reinterpret_cast<id (*)(NSUserDefaults *, SEL, NSString *)>(method_getImplementation(NSUserDefaults$objectForKey$));
10149 method_setImplementation(NSUserDefaults$objectForKey$, reinterpret_cast<IMP>(&$NSUserDefaults$objectForKey$));
10152 /* Set Locale {{{ */
10153 Locale_ = CFLocaleCopyCurrent();
10154 Languages_ = [NSLocale preferredLanguages];
10156 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10157 //NSLog(@"%@", [Languages_ description]);
10160 if (Locale_ != NULL)
10161 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10162 else if (Languages_ != nil && [Languages_ count] != 0)
10163 lang = [[Languages_ objectAtIndex:0] UTF8String];
10165 // XXX: consider just setting to C and then falling through?
10168 if (lang != NULL) {
10169 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
10170 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10173 NSLog(@"Setting Language: %s", lang);
10175 if (lang != NULL) {
10176 setenv("LANG", lang, true);
10177 std::setlocale(LC_ALL, lang);
10180 /* Index Collation {{{ */
10181 if (Class $UILocalizedIndexedCollation = objc_getClass("UILocalizedIndexedCollation")) {
10182 NSBundle *bundle([NSBundle bundleForClass:$UILocalizedIndexedCollation]);
10183 NSString *path([bundle pathForResource:@"UITableViewLocalizedSectionIndex" ofType:@"plist"]);
10184 //path = @"/System/Library/Frameworks/UIKit.framework/.lproj/UITableViewLocalizedSectionIndex.plist";
10185 NSDictionary *dictionary([NSDictionary dictionaryWithContentsOfFile:path]);
10186 _H<UILocalizedIndexedCollation> collation([[[UILocalizedIndexedCollation alloc] initWithDictionary:dictionary] autorelease]);
10188 CollationLocale_ = MSHookIvar<NSLocale *>(collation, "_locale");
10190 CollationThumbs_ = [collation sectionIndexTitles];
10191 for (size_t index(0), end([CollationThumbs_ count]); index != end; ++index)
10192 CollationOffset_.push_back([collation sectionForSectionIndexTitleAtIndex:index]);
10194 CollationTitles_ = [collation sectionTitles];
10195 CollationStarts_ = MSHookIvar<NSArray *>(collation, "_sectionStartStrings");
10197 NSString *&transform(MSHookIvar<NSString *>(collation, "_transform"));
10198 if (&transform != NULL && transform != nil) {
10199 /*if ([collation respondsToSelector:@selector(transformedCollationStringForString:)])
10200 CollationModify_ = [=](NSString *value) { return [collation transformedCollationStringForString:value]; };*/
10201 const UChar *uid(reinterpret_cast<const UChar *>([transform cStringUsingEncoding:NSUnicodeStringEncoding]));
10202 UErrorCode code(U_ZERO_ERROR);
10203 CollationTransl_ = utrans_openU(uid, -1, UTRANS_FORWARD, NULL, 0, NULL, &code);
10204 if (!U_SUCCESS(code))
10205 NSLog(@"%s", u_errorName(code));
10208 CollationLocale_ = [[[NSLocale alloc] initWithLocaleIdentifier:@"en@collation=dictionary"] autorelease];
10210 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];
10211 for (NSInteger offset(0); offset != 28; ++offset)
10212 CollationOffset_.push_back(offset);
10214 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];
10215 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];
10219 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
10221 /* Parse Arguments {{{ */
10222 bool substrate(false);
10228 for (int argi(1); argi != argc; ++argi)
10229 if (strcmp(argv[argi], "--") == 0) {
10231 argv[argi] = argv[0];
10237 for (int argi(1); argi != arge; ++argi)
10238 if (strcmp(args[argi], "--substrate") == 0)
10241 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10245 App_ = [[NSBundle mainBundle] bundlePath];
10251 if (access("/var/mobile/Library/Keyboard/UserDictionary.sqlite", F_OK) == 0)
10252 system("mkdir -p /var/root/Library/Keyboard; cp -af /var/mobile/Library/Keyboard/UserDictionary.sqlite /var/root/Library/Keyboard/");
10254 Cache_ = [[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia", @"/var/root"] retain];
10256 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10257 alloc_ = alloc->method_imp;
10258 alloc->method_imp = (IMP) &Alloc_;*/
10260 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10261 dealloc_ = dealloc->method_imp;
10262 dealloc->method_imp = (IMP) &Dealloc_;*/
10264 void *gestalt(dlopen("/usr/lib/libMobileGestalt.dylib", RTLD_GLOBAL | RTLD_LAZY));
10265 $MGCopyAnswer = reinterpret_cast<CFStringRef (*)(CFStringRef)>(dlsym(gestalt, "MGCopyAnswer"));
10267 /* System Information {{{ */
10271 size = sizeof(maxproc);
10272 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10273 perror("sysctlbyname(\"kern.maxproc\", ?)");
10274 else if (maxproc < 64) {
10276 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10277 perror("sysctlbyname(\"kern.maxproc\", #)");
10280 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10281 char *osversion = new char[size];
10282 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10283 perror("sysctlbyname(\"kern.osversion\", ?)");
10285 System_ = [NSString stringWithUTF8String:osversion];
10287 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10288 char *machine = new char[size];
10289 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10290 perror("sysctlbyname(\"hw.machine\", ?)");
10292 Machine_ = machine;
10294 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10295 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10296 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10298 UniqueID_ = UniqueIdentifier(device);
10300 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10301 Product_ = [info objectForKey:@"SafariProductVersion"];
10302 Safari_ = [info objectForKey:@"CFBundleVersion"];
10305 NSString *agent([NSString stringWithFormat:@"Cydia/%@ CyF/%.2f", Cydia_, kCFCoreFoundationVersionNumber]);
10307 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Safari_))
10308 agent = [NSString stringWithFormat:@"Safari/%@ %@", match[0], agent];
10309 if (Pcre match = Pcre("^[0-9]+[A-Z][0-9]+[a-z]?", System_))
10310 agent = [NSString stringWithFormat:@"Mobile/%@ %@", match[0], agent];
10311 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Product_))
10312 agent = [NSString stringWithFormat:@"Version/%@ %@", match[0], agent];
10314 UserAgent_ = agent;
10316 /* Load Database {{{ */
10318 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10320 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10322 if (Metadata_ == NULL)
10323 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10325 Settings_ = [Metadata_ objectForKey:@"Settings"];
10327 Packages_ = [Metadata_ objectForKey:@"Packages"];
10329 Values_ = [Metadata_ objectForKey:@"Values"];
10330 Sections_ = [Metadata_ objectForKey:@"Sections"];
10331 Sources_ = [Metadata_ objectForKey:@"Sources"];
10333 Token_ = [Metadata_ objectForKey:@"Token"];
10335 Version_ = [Metadata_ objectForKey:@"Version"];
10338 if (Values_ == nil) {
10339 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10340 [Metadata_ setObject:Values_ forKey:@"Values"];
10343 if (Sections_ == nil) {
10344 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10345 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10348 if (Sources_ == nil) {
10349 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10350 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10353 if (Version_ == nil) {
10354 Version_ = [NSNumber numberWithUnsignedInt:0];
10355 [Metadata_ setObject:Version_ forKey:@"Version"];
10358 if ([Version_ unsignedIntValue] == 0) {
10359 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10360 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10361 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10362 CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./");
10364 Version_ = [NSNumber numberWithUnsignedInt:1];
10365 [Metadata_ setObject:Version_ forKey:@"Version"];
10367 [Metadata_ removeObjectForKey:@"LastUpdate"];
10372 _H<NSMutableArray> broken([NSMutableArray array]);
10373 for (NSString *key in (id) Sources_)
10374 if ([key rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"# "]].location != NSNotFound)
10375 [broken addObject:key];
10376 if ([broken count] != 0) {
10377 for (NSString *key in (id) broken)
10378 [Sources_ removeObjectForKey:key];
10383 CydiaWriteSources();
10386 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10389 if (Packages_ != nil) {
10391 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10395 [Metadata_ removeObjectForKey:@"Packages"];
10401 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10403 #define MobileSubstrate_(name) \
10404 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10405 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10406 if (handle == NULL) \
10407 NSLog(@"%s", dlerror()); \
10410 MobileSubstrate_(Activator)
10411 MobileSubstrate_(libstatusbar)
10412 MobileSubstrate_(SimulatedKeyEvents)
10413 MobileSubstrate_(WinterBoard)
10415 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10416 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10418 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10420 if (access("/User", F_OK) != 0 || version != 6) {
10422 system("/usr/libexec/cydia/firmware.sh");
10426 _assert([[NSFileManager defaultManager]
10427 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10428 withIntermediateDirectories:YES
10433 if (access("/tmp/cydia.chk", F_OK) == 0) {
10434 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10435 _assert(errno == ENOENT);
10436 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10437 _assert(errno == ENOENT);
10440 /* APT Initialization {{{ */
10441 _assert(pkgInitConfig(*_config));
10442 _assert(pkgInitSystem(*_config, _system));
10445 _config->Set("APT::Acquire::Translation", lang);
10447 // XXX: this timeout might be important :(
10448 //_config->Set("Acquire::http::Timeout", 15);
10450 _config->Set("Acquire::http::MaxParallel", 3);
10452 /* Color Choices {{{ */
10453 space_ = CGColorSpaceCreateDeviceRGB();
10455 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10456 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10457 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10458 Folder_.Set(space_, 0x8e/255.f, 0x8e/255.f, 0x93/255.f, 1.0);
10459 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10460 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10461 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10462 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10463 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10464 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10466 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10467 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10469 /* UIKit Configuration {{{ */
10470 // XXX: I have a feeling this was important
10471 //UIKeyboardDisableAutomaticAppearance();
10474 $SBSSetInterceptsMenuButtonForever = reinterpret_cast<void (*)(bool)>(dlsym(RTLD_DEFAULT, "SBSSetInterceptsMenuButtonForever"));
10476 const char *symbol(kCFCoreFoundationVersionNumber >= 800 ? "MGGetBoolAnswer" : "GSSystemHasCapability");
10477 BOOL (*GSSystemHasCapability)(CFStringRef) = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, symbol));
10478 bool fast = GSSystemHasCapability != NULL && GSSystemHasCapability(CFSTR("armv7"));
10480 PulseInterval_ = fast ? 50000 : 500000;
10482 Colon_ = UCLocalize("COLON_DELIMITED");
10483 Elision_ = UCLocalize("ELISION");
10484 Error_ = UCLocalize("ERROR");
10485 Warning_ = UCLocalize("WARNING");
10488 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10490 CGColorSpaceRelease(space_);
10491 CFRelease(Locale_);