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 &desc) {
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 &desc) {
1029 NSString *name([NSString stringWithUTF8String:desc.ShortDesc.c_str()]);
1030 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItemDesc:desc]);
1031 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1034 virtual void Done(pkgAcquire::ItemDesc &desc) {
1035 NSString *name([NSString stringWithUTF8String:desc.ShortDesc.c_str()]);
1036 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:Colon_, UCLocalize("DONE"), name] ofType:kCydiaProgressEventTypeStatus forItemDesc:desc]);
1037 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1040 virtual void Fail(pkgAcquire::ItemDesc &desc) {
1042 desc.Owner->Status == pkgAcquire::Item::StatIdle ||
1043 desc.Owner->Status == pkgAcquire::Item::StatDone
1047 std::string &error(desc.Owner->ErrorText);
1051 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItemDesc:desc]);
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_;
1169 std::set<std::string> fetches_;
1172 SourceStatus(NSObject<FetchDelegate> *delegate, Database *database) :
1173 delegate_(delegate),
1178 void Set(bool fetch, const std::string &uri) {
1180 if (!fetches_.insert(uri).second)
1183 if (fetches_.erase(uri) == 0)
1187 //printf("Set(%s, %s)\n", fetch ? "true" : "false", uri.c_str());
1188 [database_ setFetch:fetch forURI:uri.c_str()];
1191 _finline void Set(bool fetch, pkgAcquire::Item *item) {
1192 /*unsigned long ID(fetch ? 1 : 0);
1196 Set(fetch, item->DescURI());
1199 void Log(const char *tag, pkgAcquire::Item *item) {
1200 //printf("%s(%s) S:%u Q:%u\n", tag, item->DescURI().c_str(), item->Status, item->QueueCounter);
1203 virtual void Fetch(pkgAcquire::ItemDesc &desc) {
1204 Log("Fetch", desc.Owner);
1205 Set(true, desc.Owner);
1208 virtual void Done(pkgAcquire::ItemDesc &desc) {
1209 Log("Done", desc.Owner);
1210 Set(false, desc.Owner);
1213 virtual void Fail(pkgAcquire::ItemDesc &desc) {
1214 Log("Fail", desc.Owner);
1215 Set(false, desc.Owner);
1218 virtual bool Pulse_(pkgAcquire *Owner) {
1219 std::set<std::string> fetches;
1220 for (pkgAcquire::ItemCIterator item(Owner->ItemsBegin()); item != Owner->ItemsEnd(); ++item) {
1222 if ((*item)->QueueCounter == 0)
1224 else switch ((*item)->Status) {
1225 case pkgAcquire::Item::StatFetching:
1226 fetches.insert((*item)->DescURI());
1235 Log(fetch ? "Pulse<true>" : "Pulse<false>", *item);
1239 std::vector<std::string> stops;
1240 std::set_difference(fetches_.begin(), fetches_.end(), fetches.begin(), fetches.end(), std::back_insert_iterator<std::vector<std::string>>(stops));
1241 for (std::vector<std::string>::const_iterator stop(stops.begin()); stop != stops.end(); ++stop) {
1242 //printf("Stop(%s)\n", stop->c_str());
1246 return ![delegate_ isSourceCancelled];
1249 virtual void Stop() {
1250 pkgAcquireStatus::Stop();
1251 [database_ resetFetch];
1255 /* ProgressEvent Implementation {{{ */
1256 @implementation CydiaProgressEvent
1258 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1259 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1262 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1263 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1264 [event setPackage:package];
1268 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItemDesc:(pkgAcquire::ItemDesc &)desc {
1269 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1271 NSString *description([NSString stringWithUTF8String:desc.Description.c_str()]);
1272 NSArray *fields([description componentsSeparatedByString:@" "]);
1273 [event setItem:fields];
1275 if ([fields count] > 3) {
1276 [event setPackage:[fields objectAtIndex:2]];
1277 [event setVersion:[fields objectAtIndex:3]];
1280 [event setURL:[NSString stringWithUTF8String:desc.URI.c_str()]];
1285 + (NSArray *) _attributeKeys {
1286 return [NSArray arrayWithObjects:
1296 - (NSArray *) attributeKeys {
1297 return [[self class] _attributeKeys];
1300 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1301 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1304 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1305 if ((self = [super init]) != nil) {
1311 - (NSString *) message {
1315 - (NSString *) type {
1319 - (NSArray *) item {
1320 return (id) item_ ?: [NSNull null];
1323 - (void) setItem:(NSArray *)item {
1327 - (NSString *) package {
1328 return (id) package_ ?: [NSNull null];
1331 - (void) setPackage:(NSString *)package {
1335 - (NSString *) url {
1336 return (id) url_ ?: [NSNull null];
1339 - (void) setURL:(NSString *)url {
1343 - (void) setVersion:(NSString *)version {
1347 - (NSString *) version {
1348 return (id) version_ ?: [NSNull null];
1351 - (NSString *) compound:(NSString *)value {
1353 NSString *mode(nil); {
1354 NSString *type([self type]);
1355 if ([type isEqualToString:kCydiaProgressEventTypeError])
1356 mode = UCLocalize("ERROR");
1357 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1358 mode = UCLocalize("WARNING");
1362 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1368 - (NSString *) compoundMessage {
1369 return [self compound:[self message]];
1372 - (NSString *) compoundTitle {
1375 if (package_ == nil)
1377 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1378 title = [package name];
1382 return [self compound:title];
1388 // Cytore Definitions {{{
1389 struct PackageValue :
1392 Cytore::Offset<PackageValue> next_;
1394 uint32_t index_ : 23;
1395 uint32_t subscribed_ : 1;
1412 Cytore::Offset<PackageValue> packages_[1 << 16];
1415 static Cytore::File<MetaValue> MetaFile_;
1417 // Cytore Helper Functions {{{
1418 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1419 SplitHash nhash = { hashlittle(name, length) };
1421 PackageValue *metadata;
1423 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1424 for (;; offset = &metadata->next_) { if (offset->IsNull()) {
1425 *offset = MetaFile_.New<PackageValue>(length + 1);
1426 metadata = &MetaFile_.Get(*offset);
1428 if (metadata == NULL) {
1432 metadata = new PackageValue();
1433 memset(metadata, 0, sizeof(*metadata));
1436 memcpy(metadata->name_, name, length);
1437 metadata->name_[length] = '\0';
1438 metadata->nhash_ = nhash.u16[1];
1440 metadata = &MetaFile_.Get(*offset);
1441 if (metadata->nhash_ != nhash.u16[1])
1443 if (strncmp(metadata->name_, name, length) != 0)
1445 if (metadata->name_[length] != '\0')
1452 static void PackageImport(const void *key, const void *value, void *context) {
1453 bool &fail(*reinterpret_cast<bool *>(context));
1456 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1457 NSLog(@"failed to import package %@", key);
1461 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1462 NSDictionary *package((NSDictionary *) value);
1464 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1465 if ([subscribed boolValue] && !metadata->subscribed_)
1466 metadata->subscribed_ = true;
1468 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1469 time_t time([date timeIntervalSince1970]);
1470 if (metadata->first_ > time || metadata->first_ == 0)
1471 metadata->first_ = time;
1474 NSDate *date([package objectForKey:@"LastSeen"]);
1475 NSString *version([package objectForKey:@"LastVersion"]);
1477 if (date != nil && version != nil) {
1478 time_t time([date timeIntervalSince1970]);
1479 if (metadata->last_ < time || metadata->last_ == 0)
1480 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1481 size_t length(strlen(buffer));
1482 uint16_t vhash(hashlittle(buffer, length));
1484 size_t capped(std::min<size_t>(8, length));
1485 char *latest(buffer + length - capped);
1487 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1488 metadata->vhash_ = vhash;
1490 metadata->last_ = time;
1496 /* Source Class {{{ */
1497 @interface Source : NSObject {
1499 Database *database_;
1502 CYString depiction_;
1503 CYString description_;
1509 CYString distribution_;
1515 _H<NSString> authority_;
1517 CYString defaultIcon_;
1519 _H<NSMutableDictionary> record_;
1522 std::set<std::string> fetches_;
1523 std::set<std::string> files_;
1524 _transient NSObject<SourceDelegate> *delegate_;
1527 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool;
1529 - (NSComparisonResult) compareByName:(Source *)source;
1531 - (NSString *) depictionForPackage:(NSString *)package;
1532 - (NSString *) supportForPackage:(NSString *)package;
1534 - (metaIndex *) metaIndex;
1535 - (NSDictionary *) record;
1538 - (NSString *) rooturi;
1539 - (NSString *) distribution;
1540 - (NSString *) type;
1543 - (NSString *) host;
1545 - (NSString *) name;
1546 - (NSString *) shortDescription;
1547 - (NSString *) label;
1548 - (NSString *) origin;
1549 - (NSString *) version;
1551 - (NSString *) defaultIcon;
1552 - (NSURL *) iconURL;
1554 - (void) setFetch:(bool)fetch forURI:(const char *)uri;
1555 - (void) resetFetch;
1559 @implementation Source
1561 + (NSString *) webScriptNameForSelector:(SEL)selector {
1563 else if (selector == @selector(addSection:))
1564 return @"addSection";
1565 else if (selector == @selector(getField:))
1567 else if (selector == @selector(removeSection:))
1568 return @"removeSection";
1569 else if (selector == @selector(remove))
1575 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1576 return [self webScriptNameForSelector:selector] == nil;
1579 + (NSArray *) _attributeKeys {
1580 return [NSArray arrayWithObjects:
1591 @"shortDescription",
1598 - (NSArray *) attributeKeys {
1599 return [[self class] _attributeKeys];
1602 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1603 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1606 - (metaIndex *) metaIndex {
1610 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1611 trusted_ = index->IsTrusted();
1613 uri_.set(pool, index->GetURI());
1614 distribution_.set(pool, index->GetDist());
1615 type_.set(pool, index->GetType());
1617 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1618 if (dindex != NULL) {
1619 std::string file(dindex->MetaIndexURI(""));
1620 base_.set(pool, file);
1623 _profile(Source$setMetaIndex$GetIndexes)
1624 dindex->GetIndexes(&acquire, true);
1626 _profile(Source$setMetaIndex$DescURI)
1627 for (pkgAcquire::ItemIterator item(acquire.ItemsBegin()); item != acquire.ItemsEnd(); item++) {
1628 std::string file((*item)->DescURI());
1629 files_.insert(file);
1630 if (file.length() < sizeof("Packages.bz2") || file.substr(file.length() - sizeof("Packages.bz2")) != "/Packages.bz2")
1632 file = file.substr(0, file.length() - 4);
1633 files_.insert(file);
1634 files_.insert(file + ".gz");
1635 files_.insert(file + "Index");
1640 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1643 pkgTagFile tags(&fd);
1645 pkgTagSection section;
1652 {"default-icon", &defaultIcon_},
1653 {"depiction", &depiction_},
1654 {"description", &description_},
1656 {"origin", &origin_},
1657 {"support", &support_},
1658 {"version", &version_},
1661 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1662 const char *start, *end;
1664 if (section.Find(names[i].name_, start, end)) {
1665 CYString &value(*names[i].value_);
1666 value.set(pool, start, end - start);
1672 record_ = [Sources_ objectForKey:[self key]];
1674 NSURL *url([NSURL URLWithString:uri_]);
1678 host_ = [host_ lowercaseString];
1683 authority_ = [url path];
1686 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(apr_pool_t *)pool {
1687 if ((self = [super init]) != nil) {
1688 era_ = [database era];
1689 database_ = database;
1692 _profile(Source$initWithMetaIndex$setMetaIndex)
1693 [self setMetaIndex:index inPool:pool];
1698 - (NSString *) getField:(NSString *)name {
1699 @synchronized (database_) {
1700 if ([database_ era] != era_ || index_ == NULL)
1703 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index_));
1708 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly)) {
1713 pkgTagFile tags(&fd);
1715 pkgTagSection section;
1718 const char *start, *end;
1719 if (!section.Find([name UTF8String], start, end))
1720 return (NSString *) [NSNull null];
1722 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
1725 - (NSComparisonResult) compareByName:(Source *)source {
1726 NSString *lhs = [self name];
1727 NSString *rhs = [source name];
1729 if ([lhs length] != 0 && [rhs length] != 0) {
1730 unichar lhc = [lhs characterAtIndex:0];
1731 unichar rhc = [rhs characterAtIndex:0];
1733 if (isalpha(lhc) && !isalpha(rhc))
1734 return NSOrderedAscending;
1735 else if (!isalpha(lhc) && isalpha(rhc))
1736 return NSOrderedDescending;
1739 return [lhs compare:rhs options:LaxCompareOptions_];
1742 - (NSString *) depictionForPackage:(NSString *)package {
1743 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1746 - (NSString *) supportForPackage:(NSString *)package {
1747 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1750 - (NSArray *) sections {
1751 return record_ == nil ? (id) [NSNull null] : [record_ objectForKey:@"Sections"] ?: [NSArray array];
1754 - (void) _addSection:(NSString *)section {
1757 else if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) {
1758 if (![sections containsObject:section]) {
1759 [sections addObject:section];
1763 [record_ setObject:[NSMutableArray arrayWithObject:section] forKey:@"Sections"];
1768 - (bool) addSection:(NSString *)section {
1772 [self performSelectorOnMainThread:@selector(_addSection:) withObject:section waitUntilDone:NO];
1776 - (void) _removeSection:(NSString *)section {
1780 if (NSMutableArray *sections = [record_ objectForKey:@"Sections"])
1781 if ([sections containsObject:section]) {
1782 [sections removeObject:section];
1787 - (bool) removeSection:(NSString *)section {
1791 [self performSelectorOnMainThread:@selector(_removeSection:) withObject:section waitUntilDone:NO];
1796 [Sources_ removeObjectForKey:[self key]];
1801 bool value(record_ != nil);
1802 [self performSelectorOnMainThread:@selector(_remove) withObject:nil waitUntilDone:NO];
1806 - (NSDictionary *) record {
1814 - (NSString *) rooturi {
1818 - (NSString *) distribution {
1819 return distribution_;
1822 - (NSString *) type {
1826 - (NSString *) baseuri {
1827 return base_.empty() ? nil : (id) base_;
1830 - (NSString *) iconuri {
1831 if (NSString *base = [self baseuri])
1832 return [base stringByAppendingString:@"CydiaIcon.png"];
1837 - (NSURL *) iconURL {
1838 if (NSString *uri = [self iconuri])
1839 return [NSURL URLWithString:uri];
1843 - (NSString *) key {
1844 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1847 - (NSString *) host {
1851 - (NSString *) name {
1852 return origin_.empty() ? (id) authority_ : origin_;
1855 - (NSString *) shortDescription {
1856 return description_;
1859 - (NSString *) label {
1860 return label_.empty() ? (id) authority_ : label_;
1863 - (NSString *) origin {
1867 - (NSString *) version {
1871 - (NSString *) defaultIcon {
1872 return defaultIcon_;
1875 - (void) setDelegate:(NSObject<SourceDelegate> *)delegate {
1876 delegate_ = delegate;
1880 return !fetches_.empty();
1883 - (void) setFetch:(bool)fetch forURI:(const char *)uri {
1885 if (fetches_.erase(uri) == 0)
1887 } else if (files_.find(uri) == files_.end())
1889 else if (!fetches_.insert(uri).second)
1892 [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:[self fetch]] waitUntilDone:NO];
1895 - (void) resetFetch {
1897 [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:NO];
1902 /* CydiaOperation Class {{{ */
1903 @interface CydiaOperation : NSObject {
1904 _H<NSString> operator_;
1905 _H<NSString> value_;
1908 - (NSString *) operator;
1909 - (NSString *) value;
1913 @implementation CydiaOperation
1915 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1916 if ((self = [super init]) != nil) {
1917 operator_ = [NSString stringWithUTF8String:_operator];
1918 value_ = [NSString stringWithUTF8String:value];
1922 + (NSArray *) _attributeKeys {
1923 return [NSArray arrayWithObjects:
1929 - (NSArray *) attributeKeys {
1930 return [[self class] _attributeKeys];
1933 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1934 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1937 - (NSString *) operator {
1941 - (NSString *) value {
1947 /* CydiaClause Class {{{ */
1948 @interface CydiaClause : NSObject {
1949 _H<NSString> package_;
1950 _H<CydiaOperation> version_;
1953 - (NSString *) package;
1954 - (CydiaOperation *) version;
1958 @implementation CydiaClause
1960 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1961 if ((self = [super init]) != nil) {
1962 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1964 if (const char *version = dep.TargetVer())
1965 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1967 version_ = (id) [NSNull null];
1971 + (NSArray *) _attributeKeys {
1972 return [NSArray arrayWithObjects:
1978 - (NSArray *) attributeKeys {
1979 return [[self class] _attributeKeys];
1982 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1983 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1986 - (NSString *) package {
1990 - (CydiaOperation *) version {
1996 /* CydiaRelation Class {{{ */
1997 @interface CydiaRelation : NSObject {
1998 _H<NSString> relationship_;
1999 _H<NSMutableArray> clauses_;
2002 - (NSString *) relationship;
2003 - (NSArray *) clauses;
2007 @implementation CydiaRelation
2009 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
2010 if ((self = [super init]) != nil) {
2011 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
2012 clauses_ = [NSMutableArray arrayWithCapacity:8];
2014 pkgCache::DepIterator start;
2015 pkgCache::DepIterator end;
2016 dep.GlobOr(start, end); // ++dep
2019 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
2021 // yes, seriously. (wtf?)
2029 + (NSArray *) _attributeKeys {
2030 return [NSArray arrayWithObjects:
2036 - (NSArray *) attributeKeys {
2037 return [[self class] _attributeKeys];
2040 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2041 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2044 - (NSString *) relationship {
2045 return relationship_;
2048 - (NSArray *) clauses {
2052 - (void) addClause:(CydiaClause *)clause {
2053 [clauses_ addObject:clause];
2058 /* Package Class {{{ */
2059 struct ParsedPackage {
2063 CYString architecture_;
2066 CYString depiction_;
2073 @interface Package : NSObject {
2075 @public uint32_t role_ : 3;
2076 uint32_t essential_ : 1;
2077 uint32_t obsolete_ : 1;
2078 uint32_t ignored_ : 1;
2079 uint32_t pooled_ : 1;
2085 _transient Database *database_;
2087 pkgCache::VerIterator version_;
2088 pkgCache::PkgIterator iterator_;
2089 pkgCache::VerFileIterator file_;
2093 CYString transform_;
2096 CYString installed_;
2099 const char *section_;
2100 _transient NSString *section$_;
2104 PackageValue *metadata_;
2105 ParsedPackage *parsed_;
2107 _H<NSMutableArray> tags_;
2110 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
2111 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
2113 - (pkgCache::PkgIterator) iterator;
2116 - (NSString *) section;
2117 - (NSString *) simpleSection;
2119 - (NSString *) longSection;
2120 - (NSString *) shortSection;
2124 - (MIMEAddress *) maintainer;
2126 - (NSString *) longDescription;
2127 - (NSString *) shortDescription;
2130 - (PackageValue *) metadata;
2133 - (bool) subscribed;
2134 - (bool) setSubscribed:(bool)subscribed;
2138 - (NSString *) latest;
2139 - (NSString *) installed;
2140 - (BOOL) uninstalled;
2143 - (BOOL) upgradableAndEssential:(BOOL)essential;
2146 - (BOOL) unfiltered;
2150 - (BOOL) halfConfigured;
2151 - (BOOL) halfInstalled;
2153 - (NSString *) mode;
2156 - (NSString *) name;
2158 - (NSString *) homepage;
2159 - (NSString *) depiction;
2160 - (MIMEAddress *) author;
2162 - (NSString *) support;
2164 - (NSArray *) files;
2165 - (NSArray *) warnings;
2166 - (NSArray *) applications;
2168 - (Source *) source;
2171 - (BOOL) matches:(NSArray *)query;
2173 - (BOOL) hasTag:(NSString *)tag;
2174 - (NSString *) primaryPurpose;
2175 - (NSArray *) purposes;
2176 - (bool) isCommercial;
2178 - (void) setIndex:(size_t)index;
2180 - (CYString &) cyname;
2182 - (uint32_t) compareBySection:(NSArray *)sections;
2189 uint32_t PackageChangesRadix(Package *self, void *) {
2194 uint32_t timestamp : 30;
2195 uint32_t ignored : 1;
2196 uint32_t upgradable : 1;
2200 bool upgradable([self upgradableAndEssential:YES]);
2201 value.bits.upgradable = upgradable ? 1 : 0;
2204 value.bits.timestamp = 0;
2205 value.bits.ignored = [self ignored] ? 0 : 1;
2206 value.bits.upgradable = 1;
2208 value.bits.timestamp = [self seen] >> 2;
2209 value.bits.ignored = 0;
2210 value.bits.upgradable = 0;
2213 return _not(uint32_t) - value.key;
2216 CYString &(*PackageName)(Package *self, SEL sel);
2218 uint32_t PackagePrefixRadix(Package *self, void *context) {
2219 size_t offset(reinterpret_cast<size_t>(context));
2220 CYString &name(PackageName(self, @selector(cyname)));
2222 size_t size(name.size());
2225 char *text(name.data());
2228 if (!isdigit(text[0]))
2232 while (size != digits && isdigit(text[digits]))
2240 if (offset == 0 && zeros != 0) {
2241 memset(data, '0', zeros);
2242 memcpy(data + zeros, text, 4 - zeros);
2244 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2245 if (size <= offset - zeros)
2248 text += offset - zeros;
2249 size -= offset - zeros;
2252 memcpy(data, text, 4);
2254 memcpy(data, text, size);
2255 memset(data + size, 0, 4 - size);
2258 for (size_t i(0); i != 4; ++i)
2259 if (isalpha(data[i]))
2267 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2269 /* XXX: ntohl may be more honest */
2270 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2273 CFComparisonResult StringNameCompare(CFStringRef lhn, CFStringRef rhn, size_t length) {
2274 _profile(PackageNameCompare)
2276 return rhn == NULL ? kCFCompareEqualTo : kCFCompareLessThan;
2277 else if (rhn == NULL)
2278 return kCFCompareGreaterThan;
2280 CFIndex length(CFStringGetLength(lhn));
2282 _profile(PackageNameCompare$NumbersLast)
2283 if (length != 0 && CFStringGetLength(rhn) != 0) {
2284 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2285 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2286 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2287 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2288 return lha ? kCFCompareLessThan : kCFCompareGreaterThan;
2292 _profile(PackageNameCompare$Compare)
2293 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, (CFLocaleRef) (id) CollationLocale_);
2298 _finline CFComparisonResult StringNameCompare(NSString *lhn, NSString*rhn, size_t length) {
2299 return StringNameCompare((CFStringRef) lhn, (CFStringRef) rhn, length);
2302 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2303 CYString &lhn(PackageName(lhs, @selector(cyname)));
2304 NSString *rhn(PackageName(rhs, @selector(cyname)));
2305 return StringNameCompare(lhn, rhn, lhn.size());
2308 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *arg) {
2309 return PackageNameCompare(*lhs, *rhs, arg);
2312 struct PackageNameOrdering :
2313 std::binary_function<Package *, Package *, bool>
2315 _finline bool operator ()(Package *lhs, Package *rhs) const {
2316 return PackageNameCompare(lhs, rhs, NULL) == kCFCompareLessThan;
2320 @implementation Package
2322 - (NSString *) description {
2323 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2328 apr_pool_destroy(pool_);
2329 if (parsed_ != NULL)
2334 + (NSString *) webScriptNameForSelector:(SEL)selector {
2336 else if (selector == @selector(clear))
2338 else if (selector == @selector(getField:))
2340 else if (selector == @selector(getRecord))
2341 return @"getRecord";
2342 else if (selector == @selector(hasTag:))
2344 else if (selector == @selector(install))
2346 else if (selector == @selector(remove))
2352 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2353 return [self webScriptNameForSelector:selector] == nil;
2356 + (NSArray *) _attributeKeys {
2357 return [NSArray arrayWithObjects:
2378 @"shortDescription",
2391 - (NSArray *) attributeKeys {
2392 return [[self class] _attributeKeys];
2395 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2396 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2399 - (NSArray *) relations {
2400 @synchronized (database_) {
2401 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2402 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2403 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2407 - (NSString *) architecture {
2409 @synchronized (database_) {
2410 return parsed_->architecture_.empty() ? [NSNull null] : (id) parsed_->architecture_;
2413 - (NSString *) getField:(NSString *)name {
2414 @synchronized (database_) {
2415 if ([database_ era] != era_ || file_.end())
2418 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2420 const char *start, *end;
2421 if (!parser.Find([name UTF8String], start, end))
2422 return (NSString *) [NSNull null];
2424 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2427 - (NSString *) getRecord {
2428 @synchronized (database_) {
2429 if ([database_ era] != era_ || file_.end())
2432 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2434 const char *start, *end;
2435 parser.GetRec(start, end);
2437 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2441 if (parsed_ != NULL)
2443 @synchronized (database_) {
2444 if ([database_ era] != era_ || file_.end())
2447 ParsedPackage *parsed(new ParsedPackage);
2450 _profile(Package$parse)
2451 pkgRecords::Parser *parser;
2453 _profile(Package$parse$Lookup)
2454 parser = &[database_ records]->Lookup(file_);
2460 _profile(Package$parse$Find)
2465 {"architecture", &parsed->architecture_},
2466 {"icon", &parsed->icon_},
2467 {"depiction", &parsed->depiction_},
2468 {"homepage", &parsed->homepage_},
2469 {"website", &website},
2471 {"support", &parsed->support_},
2472 {"author", &parsed->author_},
2473 {"md5sum", &parsed->md5sum_},
2476 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2477 const char *start, *end;
2479 if (parser->Find(names[i].name_, start, end)) {
2480 CYString &value(*names[i].value_);
2481 _profile(Package$parse$Value)
2482 value.set(pool_, start, end - start);
2488 _profile(Package$parse$Tagline)
2489 const char *start, *end;
2490 if (parser->ShortDesc(start, end)) {
2491 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2494 while (stop != start && stop[-1] == '\r')
2496 parsed->tagline_.set(pool_, start, stop - start);
2500 _profile(Package$parse$Retain)
2501 if (parsed->homepage_.empty())
2502 parsed->homepage_ = website;
2503 if (parsed->homepage_ == parsed->depiction_)
2504 parsed->homepage_.clear();
2505 if (parsed->support_.empty())
2506 parsed->support_ = bugs;
2511 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2512 if ((self = [super init]) != nil) {
2513 _profile(Package$initWithVersion)
2515 apr_pool_create(&pool_, NULL);
2521 database_ = database;
2522 era_ = [database era];
2526 pkgCache::PkgIterator iterator(version.ParentPkg());
2527 iterator_ = iterator;
2529 _profile(Package$initWithVersion$Version)
2530 if (!version_.end())
2531 file_ = version_.FileList();
2533 pkgCache &cache([database_ cache]);
2534 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2538 _profile(Package$initWithVersion$Cache)
2539 name_.set(NULL, iterator.Display());
2541 latest_.set(NULL, StripVersion_(version_.VerStr()));
2543 pkgCache::VerIterator current(iterator.CurrentVer());
2545 installed_.set(NULL, StripVersion_(current.VerStr()));
2548 _profile(Package$initWithVersion$Transliterate) do {
2549 if (CollationTransl_ == NULL)
2554 _profile(Package$initWithVersion$Transliterate$utf8)
2555 const uint8_t *data(reinterpret_cast<const uint8_t *>(name_.data()));
2556 for (size_t i(0), e(name_.size()); i != e; ++i)
2557 if (data[i] >= 0x80)
2562 UErrorCode code(U_ZERO_ERROR);
2565 _profile(Package$initWithVersion$Transliterate$u_strFromUTF8WithSub)
2566 CollationString_.resize(name_.size());
2567 u_strFromUTF8WithSub(&CollationString_[0], CollationString_.size(), &length, name_.data(), name_.size(), 0xfffd, NULL, &code);
2568 if (!U_SUCCESS(code))
2570 CollationString_.resize(length);
2573 _profile(Package$initWithVersion$Transliterate$utrans_trans)
2574 length = CollationString_.size();
2575 utrans_trans(CollationTransl_, reinterpret_cast<UReplaceable *>(&CollationString_), &CollationUCalls_, 0, &length, &code);
2576 if (!U_SUCCESS(code))
2578 _assert(CollationString_.size() == length);
2581 _profile(Package$initWithVersion$Transliterate$u_strToUTF8WithSub$preflight)
2582 u_strToUTF8WithSub(NULL, 0, &length, CollationString_.data(), CollationString_.size(), 0xfffd, NULL, &code);
2583 if (code == U_BUFFER_OVERFLOW_ERROR)
2584 code = U_ZERO_ERROR;
2585 else if (!U_SUCCESS(code))
2590 _profile(Package$initWithVersion$Transliterate$apr_palloc)
2591 transform = static_cast<char *>(apr_palloc(pool_, length));
2593 _profile(Package$initWithVersion$Transliterate$u_strToUTF8WithSub$transform)
2594 u_strToUTF8WithSub(transform, length, NULL, CollationString_.data(), CollationString_.size(), 0xfffd, NULL, &code);
2595 if (!U_SUCCESS(code))
2599 transform_.set(NULL, transform, length);
2600 } while (false); _end
2602 _profile(Package$initWithVersion$Tags)
2603 pkgCache::TagIterator tag(iterator.TagList());
2605 tags_ = [NSMutableArray arrayWithCapacity:8];
2607 goto tag; for (; !tag.end(); ++tag) tag: {
2608 const char *name(tag.Name());
2609 NSString *string((NSString *) CYStringCreate(name));
2613 [tags_ addObject:[string autorelease]];
2615 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2616 if (strcmp(name + 6, "enduser") == 0)
2618 else if (strcmp(name + 6, "hacker") == 0)
2620 else if (strcmp(name + 6, "developer") == 0)
2622 else if (strcmp(name + 6, "cydia") == 0)
2628 if (strncmp(name, "cydia::", 7) == 0) {
2629 if (strcmp(name + 7, "essential") == 0)
2631 else if (strcmp(name + 7, "obsolete") == 0)
2638 _profile(Package$initWithVersion$Metadata)
2639 const char *mixed(iterator.Name());
2640 size_t size(strlen(mixed));
2641 static const size_t prefix(sizeof("/var/lib/dpkg/info/") - 1);
2642 char lower[prefix + size + 5 + 1];
2644 for (size_t i(0); i != size; ++i)
2645 lower[prefix + i] = mixed[i] | 0x20;
2647 if (!installed_.empty()) {
2648 memcpy(lower, "/var/lib/dpkg/info/", prefix);
2649 memcpy(lower + prefix + size, ".list", 6);
2651 if (stat(lower, &info) != -1)
2652 upgraded_ = info.st_birthtime;
2655 PackageValue *metadata(PackageFind(lower + prefix, size));
2656 metadata_ = metadata;
2658 id_.set(NULL, metadata->name_, size);
2660 const char *latest(version_.VerStr());
2661 size_t length(strlen(latest));
2663 uint16_t vhash(hashlittle(latest, length));
2665 size_t capped(std::min<size_t>(8, length));
2666 latest = latest + length - capped;
2668 if (metadata->first_ == 0)
2669 metadata->first_ = now_;
2671 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2672 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2673 metadata->vhash_ = vhash;
2674 metadata->last_ = now_;
2675 } else if (metadata->last_ == 0)
2676 metadata->last_ = metadata->first_;
2679 _profile(Package$initWithVersion$Section)
2680 section_ = version_.Section();
2683 _profile(Package$initWithVersion$Flags)
2684 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2685 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2690 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2691 pkgCache::VerIterator version;
2693 _profile(Package$packageWithIterator$GetCandidateVer)
2694 version = [database policy]->GetCandidateVer(iterator);
2702 _profile(Package$packageWithIterator$Allocate)
2703 package = [Package allocWithZone:zone];
2706 _profile(Package$packageWithIterator$Initialize)
2708 initWithVersion:version
2715 _profile(Package$packageWithIterator$Autorelease)
2716 package = [package autorelease];
2722 - (pkgCache::PkgIterator) iterator {
2726 - (NSString *) section {
2727 if (section$_ == nil) {
2728 if (section_ == NULL)
2731 _profile(Package$section$mappedSectionForPointer)
2732 section$_ = [database_ mappedSectionForPointer:section_];
2737 - (NSString *) simpleSection {
2738 if (NSString *section = [self section])
2739 return Simplify(section);
2744 - (NSString *) longSection {
2745 return LocalizeSection([self section]);
2748 - (NSString *) shortSection {
2749 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2752 - (NSString *) uri {
2755 pkgIndexFile *index;
2756 pkgCache::PkgFileIterator file(file_.File());
2757 if (![database_ list].FindIndex(file, index))
2759 return [NSString stringWithUTF8String:iterator_->Path];
2760 //return [NSString stringWithUTF8String:file.Site()];
2761 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2765 - (MIMEAddress *) maintainer {
2766 @synchronized (database_) {
2767 if ([database_ era] != era_ || file_.end())
2770 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2771 const std::string &maintainer(parser->Maintainer());
2772 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2775 - (NSString *) md5sum {
2776 return parsed_ == NULL ? nil : (id) parsed_->md5sum_;
2780 @synchronized (database_) {
2781 if ([database_ era] != era_ || version_.end())
2784 return version_->InstalledSize;
2787 - (NSString *) longDescription {
2788 @synchronized (database_) {
2789 if ([database_ era] != era_ || file_.end())
2792 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2793 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2795 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2796 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2797 if ([lines count] < 2)
2800 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2801 for (size_t i(1), e([lines count]); i != e; ++i) {
2802 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2803 [trimmed addObject:trim];
2806 return [trimmed componentsJoinedByString:@"\n"];
2809 - (NSString *) shortDescription {
2810 if (parsed_ != NULL)
2811 return static_cast<NSString *>(parsed_->tagline_);
2813 @synchronized (database_) {
2814 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2816 const char *start, *end;
2817 if (!parser.ShortDesc(start, end))
2820 if (end - start > 200)
2824 if (const char *stop = reinterpret_cast<const char *>(memchr(start, '\n', end - start)))
2827 while (end != start && end[-1] == '\r')
2831 return [(id) CYStringCreate(start, end - start) autorelease];
2835 _profile(Package$index)
2836 CFStringRef name((CFStringRef) [self name]);
2837 if (CFStringGetLength(name) == 0)
2839 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2840 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2842 return toupper(character);
2846 - (PackageValue *) metadata {
2851 PackageValue *metadata([self metadata]);
2852 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2855 - (bool) subscribed {
2856 return [self metadata]->subscribed_;
2859 - (bool) setSubscribed:(bool)subscribed {
2860 PackageValue *metadata([self metadata]);
2861 if (metadata->subscribed_ == subscribed)
2863 metadata->subscribed_ = subscribed;
2871 - (NSString *) latest {
2875 - (NSString *) installed {
2879 - (BOOL) uninstalled {
2880 return installed_.empty();
2884 return !version_.end();
2887 - (BOOL) upgradableAndEssential:(BOOL)essential {
2888 _profile(Package$upgradableAndEssential)
2889 pkgCache::VerIterator current(iterator_.CurrentVer());
2891 return essential && essential_;
2893 return !version_.end() && version_ != current;
2897 - (BOOL) essential {
2902 return [database_ cache][iterator_].InstBroken();
2905 - (BOOL) unfiltered {
2906 _profile(Package$unfiltered$obsolete)
2907 if (_unlikely(obsolete_))
2911 _profile(Package$unfiltered$role)
2912 if (_unlikely(role_ > 3))
2920 if (![self unfiltered])
2925 _profile(Package$visible$section)
2926 section = [self section];
2929 _profile(Package$visible$isSectionVisible)
2930 if (!isSectionVisible(section))
2938 unsigned char current(iterator_->CurrentState);
2939 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2942 - (BOOL) halfConfigured {
2943 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2946 - (BOOL) halfInstalled {
2947 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2951 @synchronized (database_) {
2952 if ([database_ era] != era_ || iterator_.end())
2955 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2956 return state.Mode != pkgDepCache::ModeKeep;
2959 - (NSString *) mode {
2960 @synchronized (database_) {
2961 if ([database_ era] != era_ || iterator_.end())
2964 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2966 switch (state.Mode) {
2967 case pkgDepCache::ModeDelete:
2968 if ((state.iFlags & pkgDepCache::Purge) != 0)
2972 case pkgDepCache::ModeKeep:
2973 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2974 return @"REINSTALL";
2975 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2979 case pkgDepCache::ModeInstall:
2980 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2981 return @"REINSTALL";
2982 else*/ switch (state.Status) {
2984 return @"DOWNGRADE";
2990 return @"NEW_INSTALL";
3001 - (NSString *) name {
3002 return name_.empty() ? id_ : name_;
3005 - (UIImage *) icon {
3006 NSString *section = [self simpleSection];
3009 if (parsed_ != NULL)
3010 if (NSString *href = parsed_->icon_)
3011 if ([href hasPrefix:@"file:///"])
3012 icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
3013 if (icon == nil) if (section != nil)
3014 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]];
3015 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
3016 if ([dicon hasPrefix:@"file:///"])
3017 icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
3019 icon = [UIImage applicationImageNamed:@"unknown.png"];
3023 - (NSString *) homepage {
3024 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
3027 - (NSString *) depiction {
3028 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
3031 - (MIMEAddress *) author {
3032 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
3035 - (NSString *) support {
3036 return parsed_ != NULL && !parsed_->support_.empty() ? parsed_->support_ : [[self source] supportForPackage:id_];
3039 - (NSArray *) files {
3040 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
3041 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
3044 fin.open([path UTF8String]);
3049 while (std::getline(fin, line))
3050 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
3055 - (NSString *) state {
3056 @synchronized (database_) {
3057 if ([database_ era] != era_ || file_.end())
3060 switch (iterator_->CurrentState) {
3061 case pkgCache::State::NotInstalled:
3062 return @"NotInstalled";
3063 case pkgCache::State::UnPacked:
3065 case pkgCache::State::HalfConfigured:
3066 return @"HalfConfigured";
3067 case pkgCache::State::HalfInstalled:
3068 return @"HalfInstalled";
3069 case pkgCache::State::ConfigFiles:
3070 return @"ConfigFiles";
3071 case pkgCache::State::Installed:
3072 return @"Installed";
3073 case pkgCache::State::TriggersAwaited:
3074 return @"TriggersAwaited";
3075 case pkgCache::State::TriggersPending:
3076 return @"TriggersPending";
3079 return (NSString *) [NSNull null];
3082 - (NSString *) selection {
3083 @synchronized (database_) {
3084 if ([database_ era] != era_ || file_.end())
3087 switch (iterator_->SelectedState) {
3088 case pkgCache::State::Unknown:
3090 case pkgCache::State::Install:
3092 case pkgCache::State::Hold:
3094 case pkgCache::State::DeInstall:
3095 return @"DeInstall";
3096 case pkgCache::State::Purge:
3100 return (NSString *) [NSNull null];
3103 - (NSArray *) warnings {
3104 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
3105 const char *name(iterator_.Name());
3107 size_t length(strlen(name));
3108 if (length < 2) invalid:
3109 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
3110 else for (size_t i(0); i != length; ++i)
3112 /* XXX: technically this is not allowed */
3113 (name[i] < 'A' || name[i] > 'Z') &&
3114 (name[i] < 'a' || name[i] > 'z') &&
3115 (name[i] < '0' || name[i] > '9') &&
3116 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
3119 if (strcmp(name, "cydia") != 0) {
3122 bool _private = false;
3124 bool dsstore = false;
3126 bool repository = [[self section] isEqualToString:@"Repositories"];
3128 if (NSArray *files = [self files])
3129 for (NSString *file in files)
3130 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
3132 else if (!user && [file isEqualToString:@"/User"])
3134 else if (!_private && [file isEqualToString:@"/private"])
3136 else if (!stash && [file isEqualToString:@"/var/stash"])
3138 else if (!dsstore && [file hasSuffix:@"/.DS_Store"])
3141 /* XXX: this is not sensitive enough. only some folders are valid. */
3142 if (cydia && !repository)
3143 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
3145 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
3147 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
3149 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
3151 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @".DS_Store"]];
3154 return [warnings count] == 0 ? nil : warnings;
3157 - (NSArray *) applications {
3158 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
3160 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
3162 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
3163 if (NSArray *files = [self files])
3164 for (NSString *file in files)
3165 if (application_r(file)) {
3166 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
3167 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
3168 if ([id isEqualToString:me])
3171 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
3173 display = application_r[1];
3175 NSString *bundle([file stringByDeletingLastPathComponent]);
3176 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
3177 // XXX: maybe this should check if this is really a string, not just for length
3178 if (icon == nil || ![icon respondsToSelector:@selector(length)] || [icon length] == 0)
3180 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
3182 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
3183 [applications addObject:application];
3185 [application addObject:id];
3186 [application addObject:display];
3187 [application addObject:url];
3190 return [applications count] == 0 ? nil : applications;
3193 - (Source *) source {
3194 if (source_ == nil) {
3195 @synchronized (database_) {
3196 if ([database_ era] != era_ || file_.end())
3197 source_ = (Source *) [NSNull null];
3199 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
3203 return source_ == (Source *) [NSNull null] ? nil : source_;
3206 - (time_t) upgraded {
3210 - (uint32_t) recent {
3211 return std::numeric_limits<uint32_t>::max() - upgraded_;
3218 - (BOOL) matches:(NSArray *)query {
3219 if (query == nil || [query count] == 0)
3228 string = [self name];
3229 length = [string length];
3232 for (NSString *term in query) {
3233 range = [string rangeOfString:term options:MatchCompareOptions_];
3234 if (range.location != NSNotFound)
3235 rank_ -= 6 * 1000000 / length;
3240 length = [string length];
3243 for (NSString *term in query) {
3244 range = [string rangeOfString:term options:MatchCompareOptions_];
3245 if (range.location != NSNotFound)
3246 rank_ -= 6 * 1000000 / length;
3250 string = [self shortDescription];
3251 length = [string length];
3252 NSUInteger stop(std::min<NSUInteger>(length, 200));
3255 for (NSString *term in query) {
3256 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
3257 if (range.location != NSNotFound)
3258 rank_ -= 2 * 100000;
3264 - (NSArray *) tags {
3268 - (BOOL) hasTag:(NSString *)tag {
3269 return tags_ == nil ? NO : [tags_ containsObject:tag];
3272 - (NSString *) primaryPurpose {
3273 for (NSString *tag in (NSArray *) tags_)
3274 if ([tag hasPrefix:@"purpose::"])
3275 return [tag substringFromIndex:9];
3279 - (NSArray *) purposes {
3280 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
3281 for (NSString *tag in (NSArray *) tags_)
3282 if ([tag hasPrefix:@"purpose::"])
3283 [purposes addObject:[tag substringFromIndex:9]];
3284 return [purposes count] == 0 ? nil : purposes;
3287 - (bool) isCommercial {
3288 return [self hasTag:@"cydia::commercial"];
3291 - (void) setIndex:(size_t)index {
3292 if (metadata_->index_ != index)
3293 metadata_->index_ = index;
3296 - (CYString &) cyname {
3297 return !transform_.empty() ? transform_ : !name_.empty() ? name_ : id_;
3300 - (uint32_t) compareBySection:(NSArray *)sections {
3301 NSString *section([self section]);
3302 for (size_t i(0), e([sections count]); i != e; ++i) {
3303 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3307 return _not(uint32_t);
3311 @synchronized (database_) {
3312 pkgProblemResolver *resolver = [database_ resolver];
3313 resolver->Clear(iterator_);
3315 pkgCacheFile &cache([database_ cache]);
3316 cache->SetReInstall(iterator_, false);
3317 cache->MarkKeep(iterator_, false);
3321 @synchronized (database_) {
3322 pkgProblemResolver *resolver = [database_ resolver];
3323 resolver->Clear(iterator_);
3324 resolver->Protect(iterator_);
3326 pkgCacheFile &cache([database_ cache]);
3327 cache->SetReInstall(iterator_, false);
3328 cache->MarkInstall(iterator_, false);
3330 pkgDepCache::StateCache &state((*cache)[iterator_]);
3331 if (!state.Install())
3332 cache->SetReInstall(iterator_, true);
3336 @synchronized (database_) {
3337 pkgProblemResolver *resolver = [database_ resolver];
3338 resolver->Clear(iterator_);
3339 resolver->Remove(iterator_);
3340 resolver->Protect(iterator_);
3342 pkgCacheFile &cache([database_ cache]);
3343 cache->SetReInstall(iterator_, false);
3344 cache->MarkDelete(iterator_, true);
3349 /* Section Class {{{ */
3350 @interface Section : NSObject {
3354 _H<NSString> localized_;
3357 - (NSComparisonResult) compareByLocalized:(Section *)section;
3358 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3359 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3360 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3362 - (NSString *) name;
3363 - (void) setName:(NSString *)name;
3369 - (void) addToCount;
3371 - (void) setCount:(size_t)count;
3372 - (NSString *) localized;
3376 @implementation Section
3378 - (NSComparisonResult) compareByLocalized:(Section *)section {
3379 NSString *lhs(localized_);
3380 NSString *rhs([section localized]);
3382 /*if ([lhs length] != 0 && [rhs length] != 0) {
3383 unichar lhc = [lhs characterAtIndex:0];
3384 unichar rhc = [rhs characterAtIndex:0];
3386 if (isalpha(lhc) && !isalpha(rhc))
3387 return NSOrderedAscending;
3388 else if (!isalpha(lhc) && isalpha(rhc))
3389 return NSOrderedDescending;
3392 return [lhs compare:rhs options:LaxCompareOptions_];
3395 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3396 if ((self = [self initWithName:name localize:NO]) != nil) {
3397 if (localized != nil)
3398 localized_ = localized;
3402 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3403 return [self initWithName:name row:0 localize:localize];
3406 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3407 if ((self = [super init]) != nil) {
3411 localized_ = LocalizeSection(name_);
3415 - (NSString *) name {
3419 - (void) setName:(NSString *)name {
3435 - (void) addToCount {
3439 - (void) setCount:(size_t)count {
3443 - (NSString *) localized {
3450 class CydiaLogCleaner :
3451 public pkgArchiveCleaner
3454 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3459 /* Database Implementation {{{ */
3460 @implementation Database
3462 + (Database *) sharedInstance {
3463 static _H<Database> instance;
3464 if (instance == nil)
3465 instance = [[[Database alloc] init] autorelease];
3473 - (void) releasePackages {
3474 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3475 CFArrayRemoveAllValues(packages_);
3479 // XXX: actually implement this thing
3481 [self releasePackages];
3482 apr_pool_destroy(pool_);
3483 NSRecycleZone(zone_);
3487 - (void) _readCydia:(NSNumber *)fd {
3488 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3489 std::istream is(&ib);
3492 static Pcre finish_r("^finish:([^:]*)$");
3494 while (std::getline(is, line)) {
3495 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3497 const char *data(line.c_str());
3498 size_t size = line.size();
3499 lprintf("C:%s\n", data);
3501 if (finish_r(data, size)) {
3502 NSString *finish = finish_r[1];
3503 int index = [Finishes_ indexOfObject:finish];
3504 if (index != INT_MAX && index > Finish_)
3514 - (void) _readStatus:(NSNumber *)fd {
3515 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3516 std::istream is(&ib);
3519 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3520 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3522 while (std::getline(is, line)) {
3523 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3525 const char *data(line.c_str());
3526 size_t size(line.size());
3527 lprintf("S:%s\n", data);
3529 if (conffile_r(data, size)) {
3530 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3531 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3532 } else if (strncmp(data, "status: ", 8) == 0) {
3533 // status: <package>: {unpacked,half-configured,installed}
3534 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3535 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3536 } else if (strncmp(data, "processing: ", 12) == 0) {
3537 // processing: configure: config-test
3538 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3539 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3540 } else if (pmstatus_r(data, size)) {
3541 std::string type([pmstatus_r[1] UTF8String]);
3543 NSString *package = pmstatus_r[2];
3544 if ([package isEqualToString:@"dpkg-exec"])
3547 float percent([pmstatus_r[3] floatValue]);
3548 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3550 NSString *string = pmstatus_r[4];
3552 if (type == "pmerror") {
3553 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3554 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3555 } else if (type == "pmstatus") {
3556 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3557 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3558 } else if (type == "pmconffile")
3559 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3561 lprintf("E:unknown pmstatus\n");
3563 lprintf("E:unknown status\n");
3571 - (void) _readOutput:(NSNumber *)fd {
3572 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3573 std::istream is(&ib);
3576 while (std::getline(is, line)) {
3577 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3579 lprintf("O:%s\n", line.c_str());
3581 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3582 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3594 - (Package *) packageWithName:(NSString *)name {
3597 @synchronized (self) {
3598 if (static_cast<pkgDepCache *>(cache_) == NULL)
3600 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3601 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:NULL database:self];
3605 if ((self = [super init]) != nil) {
3612 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3613 apr_pool_create(&pool_, NULL);
3615 size_t capacity(MetaFile_->active_);
3621 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3622 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3626 _assert(pipe(fds) != -1);
3629 _config->Set("APT::Keep-Fds::", cydiafd_);
3630 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3633 detachNewThreadSelector:@selector(_readCydia:)
3635 withObject:[NSNumber numberWithInt:fds[0]]
3638 _assert(pipe(fds) != -1);
3642 detachNewThreadSelector:@selector(_readStatus:)
3644 withObject:[NSNumber numberWithInt:fds[0]]
3647 _assert(pipe(fds) != -1);
3648 _assert(dup2(fds[0], 0) != -1);
3649 _assert(close(fds[0]) != -1);
3651 input_ = fdopen(fds[1], "a");
3653 _assert(pipe(fds) != -1);
3654 _assert(dup2(fds[1], 1) != -1);
3655 _assert(close(fds[1]) != -1);
3658 detachNewThreadSelector:@selector(_readOutput:)
3660 withObject:[NSNumber numberWithInt:fds[0]]
3665 - (pkgCacheFile &) cache {
3669 - (pkgDepCache::Policy *) policy {
3673 - (pkgRecords *) records {
3677 - (pkgProblemResolver *) resolver {
3681 - (pkgAcquire &) fetcher {
3685 - (pkgSourceList &) list {
3689 - (NSArray *) packages {
3690 return (NSArray *) packages_;
3693 - (NSArray *) sources {
3697 - (Source *) sourceWithKey:(NSString *)key {
3698 for (Source *source in [self sources]) {
3699 if ([[source key] isEqualToString:key])
3704 - (bool) popErrorWithTitle:(NSString *)title {
3707 while (!_error->empty()) {
3709 bool warning(!_error->PopMessage(error));
3714 size_t size(error.size());
3715 if (size == 0 || error[size - 1] != '\n')
3717 error.resize(size - 1);
3720 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3722 static Pcre no_pubkey("^GPG error:.* NO_PUBKEY .*$");
3723 if (warning && no_pubkey(error.c_str()))
3726 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3732 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3733 return [self popErrorWithTitle:title] || !success;
3736 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3737 @synchronized (self) {
3740 [self releasePackages];
3743 [sourceList_ removeAllObjects];
3763 apr_pool_clear(pool_);
3765 NSRecycleZone(zone_);
3766 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3768 int chk(creat("/tmp/cydia.chk", 0644));
3772 if (invocation != nil)
3773 [invocation invoke];
3775 NSString *title(UCLocalize("DATABASE"));
3777 list_ = new pkgSourceList();
3778 _profile(reloadDataWithInvocation$ReadMainList)
3779 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3783 _profile(reloadDataWithInvocation$Source$initWithMetaIndex)
3784 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3785 Source *object([[[Source alloc] initWithMetaIndex:*source forDatabase:self inPool:pool_] autorelease]);
3786 [sourceList_ addObject:object];
3791 OpProgress progress;
3794 _profile(reloadDataWithInvocation$pkgCacheFile)
3795 opened = cache_.Open(progress, true);
3798 // XXX: what if there are errors, but Open() == true? this should be merged with popError:
3799 while (!_error->empty()) {
3801 bool warning(!_error->PopMessage(error));
3803 lprintf("cache_.Open():[%s]\n", error.c_str());
3805 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3809 else if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3810 repair = @selector(configure);
3811 //else if (error == "The package lists or status file could not be parsed or opened.")
3812 // repair = @selector(update);
3813 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3814 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3815 // else if (error == "Malformed Status line")
3816 // else if (error == "The list of sources could not be read.")
3818 if (repair != NULL) {
3820 [delegate_ repairWithSelector:repair];
3829 unlink("/tmp/cydia.chk");
3831 now_ = [[NSDate date] timeIntervalSince1970];
3833 policy_ = new pkgDepCache::Policy();
3834 records_ = new pkgRecords(cache_);
3835 resolver_ = new pkgProblemResolver(cache_);
3836 fetcher_ = new pkgAcquire(&status_);
3839 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3840 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3844 _profile(reloadDataWithInvocation$pkgApplyStatus)
3845 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3849 if (cache_->BrokenCount() != 0) {
3850 _profile(pkgApplyStatus$pkgFixBroken)
3851 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3855 if (cache_->BrokenCount() != 0) {
3856 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3860 _profile(pkgApplyStatus$pkgMinimizeUpgrade)
3861 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3866 for (Source *object in (id) sourceList_) {
3867 metaIndex *source([object metaIndex]);
3868 std::vector<pkgIndexFile *> *indices = source->GetIndexFiles();
3869 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3870 // XXX: this could be more intelligent
3871 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3872 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3874 sourceMap_[cached->ID] = object;
3879 /*std::vector<Package *> packages;
3880 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3883 _profile(reloadDataWithInvocation$packageWithIterator)
3884 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3885 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3886 //packages.push_back(package);
3887 CFArrayAppendValue(packages_, CFRetain(package));
3891 /*if (packages.empty())
3892 packages_ = [[NSArray alloc] init];
3894 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3897 _profile(reloadDataWithInvocation$radix$8)
3898 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(8)];
3901 _profile(reloadDataWithInvocation$radix$4)
3902 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3905 _profile(reloadDataWithInvocation$radix$0)
3906 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3909 _profile(reloadDataWithInvocation$insertion)
3910 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3913 /*_profile(reloadDataWithInvocation$CFQSortArray)
3914 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);
3917 /*_profile(reloadDataWithInvocation$stdsort)
3918 std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3921 /*_profile(reloadDataWithInvocation$CFArraySortValues)
3922 CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3925 /*_profile(reloadDataWithInvocation$sortUsingFunction)
3926 [packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3930 size_t count(CFArrayGetCount(packages_));
3931 MetaFile_->active_ = count;
3932 for (size_t index(0); index != count; ++index)
3933 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3938 @synchronized (self) {
3940 resolver_ = new pkgProblemResolver(cache_);
3942 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3943 if (!cache_[iterator].Keep())
3944 cache_->MarkKeep(iterator, false);
3945 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3946 cache_->SetReInstall(iterator, false);
3949 - (void) configure {
3950 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3952 system([dpkg UTF8String]);
3957 @synchronized (self) {
3958 // XXX: I don't remember this condition
3963 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3965 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3967 if ([self popErrorWithTitle:title])
3971 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3973 CydiaLogCleaner cleaner;
3974 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3981 fetcher_->Shutdown();
3983 pkgRecords records(cache_);
3985 lock_ = new FileFd();
3986 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3988 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3990 if ([self popErrorWithTitle:title])
3994 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3997 manager_ = (_system->CreatePM(cache_));
3998 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
4005 bool substrate(RestartSubstrate_);
4006 RestartSubstrate_ = false;
4008 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
4010 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
4012 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
4014 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
4015 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
4018 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4020 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
4022 [self popErrorWithTitle:title];
4026 bool failed = false;
4027 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
4028 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
4030 if ((*item)->Status == pkgAcquire::Item::StatIdle)
4033 std::string uri = (*item)->DescURI();
4034 std::string error = (*item)->ErrorText;
4036 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
4039 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError]);
4040 [delegate_ addProgressEventOnMainThread:event forTask:title];
4043 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4051 RestartSubstrate_ = true;
4054 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
4055 if ([self popErrorWithTitle:title])
4058 if (result == pkgPackageManager::Failed) {
4063 if (result != pkgPackageManager::Completed) {
4068 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
4070 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
4072 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
4073 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
4076 if (![before isEqualToArray:after])
4081 NSString *title(UCLocalize("UPGRADE"));
4082 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
4088 [self updateWithStatus:status_];
4091 - (void) updateWithStatus:(CancelStatus &)status {
4092 NSString *title(UCLocalize("REFRESHING_DATA"));
4095 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
4099 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
4100 if ([self popErrorWithTitle:title])
4103 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4105 bool success(ListUpdate(status, list, PulseInterval_));
4106 if (status.WasCancelled())
4109 [self popErrorWithTitle:title forOperation:success];
4110 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
4114 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4117 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
4118 delegate_ = delegate;
4121 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
4122 progress_ = delegate;
4123 status_.setDelegate(delegate);
4126 - (NSObject<ProgressDelegate> *) progressDelegate {
4130 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
4131 SourceMap::const_iterator i(sourceMap_.find(file->ID));
4132 return i == sourceMap_.end() ? nil : i->second;
4135 - (void) setFetch:(bool)fetch forURI:(const char *)uri {
4136 for (Source *source in (id) sourceList_)
4137 [source setFetch:fetch forURI:uri];
4140 - (void) resetFetch {
4141 for (Source *source in (id) sourceList_)
4142 [source resetFetch];
4145 - (NSString *) mappedSectionForPointer:(const char *)section {
4146 _H<NSString> *mapped;
4148 _profile(Database$mappedSectionForPointer$Cache)
4149 mapped = §ions_[section];
4152 if (*mapped == NULL) {
4153 size_t length(strlen(section));
4154 char spaced[length + 1];
4156 _profile(Database$mappedSectionForPointer$Replace)
4157 for (size_t index(0); index != length; ++index)
4158 spaced[index] = section[index] == '_' ? ' ' : section[index];
4159 spaced[length] = '\0';
4164 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
4165 string = [NSString stringWithUTF8String:spaced];
4168 _profile(Database$mappedSectionForPointer$Map)
4169 string = [SectionMap_ objectForKey:string] ?: string;
4179 static _H<NSMutableSet> Diversions_;
4181 @interface Diversion : NSObject {
4184 _H<NSString> format_;
4189 @implementation Diversion
4191 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
4192 if ((self = [super init]) != nil) {
4193 pattern_ = [from UTF8String];
4199 - (NSString *) divert:(NSString *)url {
4200 return !pattern_(url) ? nil : pattern_->*format_;
4203 + (NSURL *) divertURL:(NSURL *)url {
4205 NSString *href([url absoluteString]);
4207 for (Diversion *diversion in (id) Diversions_)
4208 if (NSString *diverted = [diversion divert:href]) {
4210 NSLog(@"div: %@", diverted);
4212 url = [NSURL URLWithString:diverted];
4219 - (NSString *) key {
4223 - (NSUInteger) hash {
4227 - (BOOL) isEqual:(Diversion *)object {
4228 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
4233 @interface CydiaObject : NSObject {
4234 _H<CyteWebViewController> indirect_;
4235 _transient id delegate_;
4238 - (id) initWithDelegate:(IndirectDelegate *)indirect;
4244 @interface CydiaWebViewController : CyteWebViewController {
4245 _H<CydiaObject> cydia_;
4248 + (void) addDiversion:(Diversion *)diversion;
4249 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request;
4250 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia;
4251 - (void) setDelegate:(id)delegate;
4255 /* Web Scripting {{{ */
4256 @implementation CydiaObject
4258 - (id) initWithDelegate:(IndirectDelegate *)indirect {
4259 if ((self = [super init]) != nil) {
4260 indirect_ = (CyteWebViewController *) indirect;
4264 - (void) setDelegate:(id)delegate {
4265 delegate_ = delegate;
4268 + (NSArray *) _attributeKeys {
4269 return [NSArray arrayWithObjects:
4272 @"coreFoundationVersionNumber",
4289 - (NSArray *) attributeKeys {
4290 return [[self class] _attributeKeys];
4293 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4294 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4297 - (NSString *) version {
4301 - (NSString *) build {
4305 - (NSString *) coreFoundationVersionNumber {
4306 return [NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber];
4309 - (NSString *) device {
4310 return UniqueIdentifier();
4313 - (NSString *) firmware {
4314 return [[UIDevice currentDevice] systemVersion];
4317 - (NSString *) hostname {
4318 return [[UIDevice currentDevice] name];
4321 - (NSString *) idiom {
4322 return (id) Idiom_ ?: [NSNull null];
4325 - (NSString *) mcc {
4326 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode")))
4327 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault) autorelease];
4331 - (NSString *) mnc {
4332 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberNetworkCode")))
4333 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault) autorelease];
4337 - (NSString *) operator {
4338 if (CFStringRef (*$CTRegistrationCopyOperatorName)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTRegistrationCopyOperatorName")))
4339 return [(NSString *) (*$CTRegistrationCopyOperatorName)(kCFAllocatorDefault) autorelease];
4343 - (NSString *) bbsnum {
4344 return (id) BBSNum_ ?: [NSNull null];
4347 - (NSString *) ecid {
4348 return (id) ChipID_ ?: [NSNull null];
4351 - (NSString *) serial {
4352 return SerialNumber_;
4355 - (NSString *) role {
4356 return (id) [NSNull null];
4359 - (NSString *) model {
4360 return [NSString stringWithUTF8String:Machine_];
4363 - (NSString *) token {
4364 return (id) Token_ ?: [NSNull null];
4367 + (NSString *) webScriptNameForSelector:(SEL)selector {
4369 else if (selector == @selector(addBridgedHost:))
4370 return @"addBridgedHost";
4371 else if (selector == @selector(addInsecureHost:))
4372 return @"addInsecureHost";
4373 else if (selector == @selector(addInternalRedirect::))
4374 return @"addInternalRedirect";
4375 else if (selector == @selector(addPipelinedHost:scheme:))
4376 return @"addPipelinedHost";
4377 else if (selector == @selector(addSource:::))
4378 return @"addSource";
4379 else if (selector == @selector(addTokenHost:))
4380 return @"addTokenHost";
4381 else if (selector == @selector(addTrivialSource:))
4382 return @"addTrivialSource";
4383 else if (selector == @selector(close))
4385 else if (selector == @selector(du:))
4387 else if (selector == @selector(stringWithFormat:arguments:))
4389 else if (selector == @selector(getAllSources))
4390 return @"getAllSources";
4391 else if (selector == @selector(getApplicationInfo:value:))
4392 return @"getApplicationInfoValue";
4393 else if (selector == @selector(getKernelNumber:))
4394 return @"getKernelNumber";
4395 else if (selector == @selector(getKernelString:))
4396 return @"getKernelString";
4397 else if (selector == @selector(getInstalledPackages))
4398 return @"getInstalledPackages";
4399 else if (selector == @selector(getIORegistryEntry::))
4400 return @"getIORegistryEntry";
4401 else if (selector == @selector(getLocaleIdentifier))
4402 return @"getLocaleIdentifier";
4403 else if (selector == @selector(getPreferredLanguages))
4404 return @"getPreferredLanguages";
4405 else if (selector == @selector(getPackageById:))
4406 return @"getPackageById";
4407 else if (selector == @selector(getMetadataKeys))
4408 return @"getMetadataKeys";
4409 else if (selector == @selector(getMetadataValue:))
4410 return @"getMetadataValue";
4411 else if (selector == @selector(getSessionValue:))
4412 return @"getSessionValue";
4413 else if (selector == @selector(installPackages:))
4414 return @"installPackages";
4415 else if (selector == @selector(isReachable:))
4416 return @"isReachable";
4417 else if (selector == @selector(localizedStringForKey:value:table:))
4419 else if (selector == @selector(popViewController:))
4420 return @"popViewController";
4421 else if (selector == @selector(refreshSources))
4422 return @"refreshSources";
4423 else if (selector == @selector(registerFrame:))
4424 return @"registerFrame";
4425 else if (selector == @selector(removeButton))
4426 return @"removeButton";
4427 else if (selector == @selector(saveConfig))
4428 return @"saveConfig";
4429 else if (selector == @selector(setMetadataValue::))
4430 return @"setMetadataValue";
4431 else if (selector == @selector(setSessionValue::))
4432 return @"setSessionValue";
4433 else if (selector == @selector(substitutePackageNames:))
4434 return @"substitutePackageNames";
4435 else if (selector == @selector(scrollToBottom:))
4436 return @"scrollToBottom";
4437 else if (selector == @selector(setAllowsNavigationAction:))
4438 return @"setAllowsNavigationAction";
4439 else if (selector == @selector(setBadgeValue:))
4440 return @"setBadgeValue";
4441 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4442 return @"setButtonImage";
4443 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4444 return @"setButtonTitle";
4445 else if (selector == @selector(setHidesBackButton:))
4446 return @"setHidesBackButton";
4447 else if (selector == @selector(setHidesNavigationBar:))
4448 return @"setHidesNavigationBar";
4449 else if (selector == @selector(setNavigationBarStyle:))
4450 return @"setNavigationBarStyle";
4451 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4452 return @"setNavigationBarTintColor";
4453 else if (selector == @selector(setPasteboardString:))
4454 return @"setPasteboardString";
4455 else if (selector == @selector(setPasteboardURL:))
4456 return @"setPasteboardURL";
4457 else if (selector == @selector(setScrollAlwaysBounceVertical:))
4458 return @"setScrollAlwaysBounceVertical";
4459 else if (selector == @selector(setScrollIndicatorStyle:))
4460 return @"setScrollIndicatorStyle";
4461 else if (selector == @selector(setToken:))
4463 else if (selector == @selector(setViewportWidth:))
4464 return @"setViewportWidth";
4465 else if (selector == @selector(statfs:))
4467 else if (selector == @selector(supports:))
4469 else if (selector == @selector(unload))
4475 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4476 return [self webScriptNameForSelector:selector] == nil;
4479 - (BOOL) supports:(NSString *)feature {
4480 return [feature isEqualToString:@"window.open"];
4484 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4487 - (void) setScrollAlwaysBounceVertical:(NSNumber *)value {
4488 [indirect_ performSelectorOnMainThread:@selector(setScrollAlwaysBounceVerticalNumber:) withObject:value waitUntilDone:NO];
4491 - (void) setScrollIndicatorStyle:(NSString *)style {
4492 [indirect_ performSelectorOnMainThread:@selector(setScrollIndicatorStyleWithName:) withObject:style waitUntilDone:NO];
4495 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4496 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4499 - (NSDictionary *) getApplicationInfo:(NSString *)display value:(NSString *)key {
4501 if (SBBundlePathForDisplayIdentifier(SBSSpringBoardServerPort(), [display UTF8String], path) != 0)
4502 return (id) [NSNull null];
4503 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:[[NSString stringWithUTF8String:path] stringByAppendingString:@"/Info.plist"]]);
4505 return (id) [NSNull null];
4506 return [info objectForKey:key];
4509 - (NSNumber *) getKernelNumber:(NSString *)name {
4510 const char *string([name UTF8String]);
4513 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4514 return (id) [NSNull null];
4516 if (size != sizeof(int))
4517 return (id) [NSNull null];
4520 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4521 return (id) [NSNull null];
4523 return [NSNumber numberWithInt:value];
4526 - (NSString *) getKernelString:(NSString *)name {
4527 const char *string([name UTF8String]);
4530 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4531 return (id) [NSNull null];
4533 char value[size + 1];
4534 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4535 return (id) [NSNull null];
4537 // XXX: just in case you request something ludicrous
4540 return [NSString stringWithCString:value];
4543 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4544 NSObject *value(CYIOGetValue([path UTF8String], entry));
4547 if ([value isKindOfClass:[NSData class]])
4548 value = CYHex((NSData *) value);
4553 - (NSArray *) getMetadataKeys {
4554 @synchronized (Values_) {
4555 return [Values_ allKeys];
4558 - (void) registerFrame:(DOMHTMLIFrameElement *)iframe {
4559 WebFrame *frame([iframe contentFrame]);
4560 [indirect_ registerFrame:frame];
4563 - (id) getMetadataValue:(NSString *)key {
4564 @synchronized (Values_) {
4565 return [Values_ objectForKey:key];
4568 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4569 @synchronized (Values_) {
4570 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4571 [Values_ removeObjectForKey:key];
4573 [Values_ setObject:value forKey:key];
4575 [delegate_ performSelectorOnMainThread:@selector(updateValues) withObject:nil waitUntilDone:YES];
4578 - (id) getSessionValue:(NSString *)key {
4579 @synchronized (SessionData_) {
4580 return [SessionData_ objectForKey:key];
4583 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4584 @synchronized (SessionData_) {
4585 if (value == (id) [WebUndefined undefined])
4586 [SessionData_ removeObjectForKey:key];
4588 [SessionData_ setObject:value forKey:key];
4591 - (void) addBridgedHost:(NSString *)host {
4592 @synchronized (HostConfig_) {
4593 [BridgedHosts_ addObject:host];
4596 - (void) addInsecureHost:(NSString *)host {
4597 @synchronized (HostConfig_) {
4598 [InsecureHosts_ addObject:host];
4601 - (void) addTokenHost:(NSString *)host {
4602 @synchronized (HostConfig_) {
4603 [TokenHosts_ addObject:host];
4606 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4607 @synchronized (HostConfig_) {
4608 if (scheme != (id) [WebUndefined undefined])
4609 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4611 [PipelinedHosts_ addObject:host];
4614 - (void) popViewController:(NSNumber *)value {
4615 if (value == (id) [WebUndefined undefined])
4616 value = [NSNumber numberWithBool:YES];
4617 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4620 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4621 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4623 for (NSString *section in sections)
4624 [array addObject:section];
4626 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4629 distribution, @"Distribution",
4631 nil] waitUntilDone:NO];
4634 - (void) addTrivialSource:(NSString *)href {
4635 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4638 - (void) refreshSources {
4639 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4642 - (void) saveConfig {
4643 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4646 - (NSArray *) getAllSources {
4647 return [[Database sharedInstance] sources];
4650 - (NSArray *) getInstalledPackages {
4651 Database *database([Database sharedInstance]);
4652 @synchronized (database) {
4653 NSArray *packages([database packages]);
4654 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4655 for (Package *package in packages)
4656 if (![package uninstalled])
4657 [installed addObject:package];
4661 - (Package *) getPackageById:(NSString *)id {
4662 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4666 return (Package *) [NSNull null];
4669 - (NSString *) getLocaleIdentifier {
4670 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4673 - (NSArray *) getPreferredLanguages {
4677 - (NSArray *) statfs:(NSString *)path {
4680 if (path == nil || statfs([path UTF8String], &stat) == -1)
4683 return [NSArray arrayWithObjects:
4684 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4685 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4686 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4690 - (NSNumber *) du:(NSString *)path {
4691 NSNumber *value(nil);
4694 _assert(pipe(fds) != -1);
4696 pid_t pid(ExecFork());
4698 _assert(dup2(fds[1], 1) != -1);
4699 _assert(close(fds[0]) != -1);
4700 _assert(close(fds[1]) != -1);
4701 /* XXX: this should probably not use du */
4702 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
4705 _assert(close(fds[1]) != -1);
4707 if (FILE *du = fdopen(fds[0], "r")) {
4709 while (fgets(line, sizeof(line), du) != NULL) {
4710 size_t length(strlen(line));
4711 while (length != 0 && line[length - 1] == '\n')
4712 line[--length] = '\0';
4713 if (char *tab = strchr(line, '\t')) {
4715 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4721 _assert(close(fds[0]) != -1);
4728 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4731 - (NSNumber *) isReachable:(NSString *)name {
4732 return [NSNumber numberWithBool:IsReachable([name UTF8String])];
4735 - (void) installPackages:(NSArray *)packages {
4736 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4739 - (NSString *) substitutePackageNames:(NSString *)message {
4740 NSMutableArray *words([[[message componentsSeparatedByString:@" "] mutableCopy] autorelease]);
4741 for (size_t i(0), e([words count]); i != e; ++i) {
4742 NSString *word([words objectAtIndex:i]);
4743 if (Package *package = [[Database sharedInstance] packageWithName:word])
4744 [words replaceObjectAtIndex:i withObject:[package name]];
4747 return [words componentsJoinedByString:@" "];
4750 - (void) removeButton {
4751 [indirect_ removeButton];
4754 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4755 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4758 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4759 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4762 - (void) setBadgeValue:(id)value {
4763 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4766 - (void) setAllowsNavigationAction:(NSString *)value {
4767 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4770 - (void) setHidesBackButton:(NSString *)value {
4771 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4774 - (void) setHidesNavigationBar:(NSString *)value {
4775 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4778 - (void) setNavigationBarStyle:(NSString *)value {
4779 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4782 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4783 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4784 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4785 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4788 - (void) setPasteboardString:(NSString *)value {
4789 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4792 - (void) setPasteboardURL:(NSString *)value {
4793 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4796 - (void) _setToken:(NSString *)token {
4800 [Metadata_ removeObjectForKey:@"Token"];
4802 [Metadata_ setObject:Token_ forKey:@"Token"];
4807 - (void) setToken:(NSString *)token {
4808 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4811 - (void) scrollToBottom:(NSNumber *)animated {
4812 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4815 - (void) setViewportWidth:(float)width {
4816 [indirect_ setViewportWidthOnMainThread:width];
4819 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4820 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4821 unsigned count([arguments count]);
4823 for (unsigned i(0); i != count; ++i)
4824 values[i] = [arguments objectAtIndex:i];
4825 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4828 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4829 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4831 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4833 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4839 @interface NSURL (CydiaSecure)
4842 @implementation NSURL (CydiaSecure)
4844 - (bool) isCydiaSecure {
4845 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4848 @synchronized (HostConfig_) {
4849 if ([InsecureHosts_ containsObject:[self host]])
4858 /* Cydia Browser Controller {{{ */
4859 @implementation CydiaWebViewController
4861 - (NSURL *) navigationURL {
4862 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4865 + (void) _initialize {
4866 [super _initialize];
4868 Diversions_ = [NSMutableSet setWithCapacity:0];
4871 + (void) addDiversion:(Diversion *)diversion {
4872 [Diversions_ addObject:diversion];
4875 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4876 [super webView:view didClearWindowObject:window forFrame:frame];
4877 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
4880 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia {
4881 WebDataSource *source([frame dataSource]);
4882 NSURLResponse *response([source response]);
4883 NSURL *url([response URL]);
4884 NSString *scheme([[url scheme] lowercaseString]);
4886 bool bridged(false);
4888 @synchronized (HostConfig_) {
4889 if ([scheme isEqualToString:@"file"])
4891 else if ([scheme isEqualToString:@"https"])
4892 if ([BridgedHosts_ containsObject:[url host]])
4897 [window setValue:cydia forKey:@"cydia"];
4900 - (void) _setupMail:(MFMailComposeViewController *)controller {
4901 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4903 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4904 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4907 - (NSURL *) URLWithURL:(NSURL *)url {
4908 return [Diversion divertURL:url];
4911 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4912 return [CydiaWebViewController requestWithHeaders:[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
4915 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request {
4916 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
4918 NSURL *url([copy URL]);
4919 NSString *href([url absoluteString]);
4920 NSString *host([url host]);
4922 if ([href hasPrefix:@"https://cydia.saurik.com/TSS/"]) {
4923 if (NSString *agent = [copy valueForHTTPHeaderField:@"X-User-Agent"]) {
4924 [copy setValue:agent forHTTPHeaderField:@"User-Agent"];
4925 [copy setValue:nil forHTTPHeaderField:@"X-User-Agent"];
4928 [copy setValue:nil forHTTPHeaderField:@"Referer"];
4929 [copy setValue:nil forHTTPHeaderField:@"Origin"];
4931 [copy setURL:[NSURL URLWithString:[@"http://gs.apple.com/TSS/" stringByAppendingString:[href substringFromIndex:29]]]];
4935 if ([copy valueForHTTPHeaderField:@"X-Cydia-Cf"] == nil)
4936 [copy setValue:[NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber] forHTTPHeaderField:@"X-Cydia-Cf"];
4937 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4938 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4943 @synchronized (HostConfig_) {
4944 bridged = [BridgedHosts_ containsObject:host];
4945 token = [TokenHosts_ containsObject:host];
4948 if ([url isCydiaSecure]) {
4950 if (UniqueID_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Id"] == nil)
4951 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
4953 if (Token_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Token"] == nil)
4954 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4961 - (void) setDelegate:(id)delegate {
4962 [super setDelegate:delegate];
4963 [cydia_ setDelegate:delegate];
4966 - (NSString *) applicationNameForUserAgent {
4971 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4972 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
4978 @interface AppCacheController : CydiaWebViewController {
4983 @implementation AppCacheController
4985 - (void) didReceiveMemoryWarning {
4986 // XXX: this doesn't work
4989 - (bool) retainsNetworkActivityIndicator {
4997 @interface NSObject (CydiaScript)
4998 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
5001 @implementation NSObject (CydiaScript)
5003 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5009 @implementation NSArray (CydiaScript)
5011 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5012 WebScriptObject *object([context evaluateWebScript:@"[]"]);
5013 for (size_t i(0), e([self count]); i != e; ++i)
5014 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
5020 @implementation NSDictionary (CydiaScript)
5022 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5023 WebScriptObject *object([context evaluateWebScript:@"({})"]);
5025 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
5032 /* Confirmation Controller {{{ */
5033 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
5034 if (!iterator.end())
5035 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
5036 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
5038 pkgCache::PkgIterator package(dep.TargetPkg());
5041 if (strcmp(package.Name(), "mobilesubstrate") == 0)
5048 @protocol ConfirmationControllerDelegate
5049 - (void) cancelAndClear:(bool)clear;
5050 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
5054 @interface ConfirmationController : CydiaWebViewController {
5055 _transient Database *database_;
5057 _H<UIAlertView> essential_;
5059 _H<NSDictionary> changes_;
5060 _H<NSMutableArray> issues_;
5061 _H<NSDictionary> sizes_;
5066 - (id) initWithDatabase:(Database *)database;
5070 @implementation ConfirmationController
5074 RestartSubstrate_ = true;
5075 [delegate_ confirmWithNavigationController:[self navigationController]];
5078 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
5079 NSString *context([alert context]);
5081 if ([context isEqualToString:@"remove"]) {
5082 if (button == [alert cancelButtonIndex])
5083 [self dismissModalViewControllerAnimated:YES];
5084 else if (button == [alert firstOtherButtonIndex]) {
5085 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
5088 [alert dismissWithClickedButtonIndex:-1 animated:YES];
5089 } else if ([context isEqualToString:@"unable"]) {
5090 [self dismissModalViewControllerAnimated:YES];
5091 [alert dismissWithClickedButtonIndex:-1 animated:YES];
5093 [super alertView:alert clickedButtonAtIndex:button];
5097 - (void) _doContinue {
5098 [delegate_ cancelAndClear:NO];
5099 [self dismissModalViewControllerAnimated:YES];
5102 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
5103 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
5107 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5108 [super webView:view didClearWindowObject:window forFrame:frame];
5110 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
5111 (id) changes_, @"changes",
5112 (id) issues_, @"issues",
5113 (id) sizes_, @"sizes",
5115 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
5118 - (id) initWithDatabase:(Database *)database {
5119 if ((self = [super init]) != nil) {
5120 database_ = database;
5122 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
5123 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
5124 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
5125 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
5126 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
5130 pkgCacheFile &cache([database_ cache]);
5131 NSArray *packages([database_ packages]);
5132 pkgDepCache::Policy *policy([database_ policy]);
5134 issues_ = [NSMutableArray arrayWithCapacity:4];
5136 for (Package *package in packages) {
5137 pkgCache::PkgIterator iterator([package iterator]);
5138 NSString *name([package id]);
5140 if ([package broken]) {
5141 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
5143 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5145 reasons, @"reasons",
5148 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
5152 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
5153 pkgCache::DepIterator start;
5154 pkgCache::DepIterator end;
5155 dep.GlobOr(start, end); // ++dep
5157 if (!cache->IsImportantDep(end))
5159 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
5162 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
5164 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5165 [NSString stringWithUTF8String:start.DepType()], @"relationship",
5166 clauses, @"clauses",
5170 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
5172 pkgCache::PkgIterator target(start.TargetPkg());
5173 if (target->ProvidesList != 0)
5174 reason = @"missing";
5176 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
5178 reason = @"installed";
5179 installed = [NSString stringWithUTF8String:ver.VerStr()];
5180 } else if (!cache[target].CandidateVerIter(cache).end())
5181 reason = @"uninstalled";
5182 else if (target->ProvidesList == 0)
5183 reason = @"uninstallable";
5185 reason = @"virtual";
5188 NSDictionary *version(start.TargetVer() == 0 ? (NSDictionary *) [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
5189 [NSString stringWithUTF8String:start.CompType()], @"operator",
5190 [NSString stringWithUTF8String:start.TargetVer()], @"value",
5193 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5194 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
5195 version, @"version",
5197 installed, @"installed",
5200 // yes, seriously. (wtf?)
5208 pkgDepCache::StateCache &state(cache[iterator]);
5210 static Pcre special_r("^(firmware$|gsc\\.|cy\\+)");
5212 if (state.NewInstall())
5213 [installs addObject:name];
5214 // XXX: else if (state.Install())
5215 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
5216 [reinstalls addObject:name];
5217 // XXX: move before previous if
5218 else if (state.Upgrade())
5219 [upgrades addObject:name];
5220 else if (state.Downgrade())
5221 [downgrades addObject:name];
5222 else if (!state.Delete())
5223 // XXX: _assert(state.Keep());
5225 else if (special_r(name))
5226 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5227 [NSNull null], @"package",
5228 [NSArray arrayWithObjects:
5229 [NSDictionary dictionaryWithObjectsAndKeys:
5230 @"Conflicts", @"relationship",
5231 [NSArray arrayWithObjects:
5232 [NSDictionary dictionaryWithObjectsAndKeys:
5234 [NSNull null], @"version",
5235 @"installed", @"reason",
5242 if ([package essential])
5244 [removes addObject:name];
5247 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
5248 substrate_ |= DepSubstrate(iterator.CurrentVer());
5253 else if (Advanced_) {
5254 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
5256 essential_ = [[[UIAlertView alloc]
5257 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
5258 message:UCLocalize("REMOVING_ESSENTIALS_EX")
5260 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
5262 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
5266 [essential_ setContext:@"remove"];
5267 [essential_ setNumberOfRows:2];
5269 essential_ = [[[UIAlertView alloc]
5270 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
5271 message:UCLocalize("UNABLE_TO_COMPLY_EX")
5273 cancelButtonTitle:UCLocalize("OKAY")
5274 otherButtonTitles:nil
5277 [essential_ setContext:@"unable"];
5280 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5281 installs, @"installs",
5282 reinstalls, @"reinstalls",
5283 upgrades, @"upgrades",
5284 downgrades, @"downgrades",
5285 removes, @"removes",
5288 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5289 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
5290 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
5293 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
5297 - (UIBarButtonItem *) leftButton {
5298 return [[[UIBarButtonItem alloc]
5299 initWithTitle:UCLocalize("CANCEL")
5300 style:UIBarButtonItemStylePlain
5302 action:@selector(cancelButtonClicked)
5307 - (void) applyRightButton {
5308 if ([issues_ count] == 0 && ![self isLoading])
5309 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
5310 initWithTitle:UCLocalize("CONFIRM")
5311 style:UIBarButtonItemStyleDone
5313 action:@selector(confirmButtonClicked)
5316 [[self navigationItem] setRightBarButtonItem:nil];
5320 - (void) cancelButtonClicked {
5321 [delegate_ cancelAndClear:YES];
5322 [self dismissModalViewControllerAnimated:YES];
5326 - (void) confirmButtonClicked {
5327 if (essential_ != nil)
5337 /* Progress Data {{{ */
5338 @interface CydiaProgressData : NSObject {
5339 _transient id delegate_;
5348 _H<NSMutableArray> events_;
5349 _H<NSString> title_;
5351 _H<NSString> status_;
5352 _H<NSString> finish_;
5357 @implementation CydiaProgressData
5359 + (NSArray *) _attributeKeys {
5360 return [NSArray arrayWithObjects:
5372 - (NSArray *) attributeKeys {
5373 return [[self class] _attributeKeys];
5376 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5377 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5381 if ((self = [super init]) != nil) {
5382 events_ = [NSMutableArray arrayWithCapacity:32];
5390 - (void) setDelegate:(id)delegate {
5391 delegate_ = delegate;
5394 - (void) setPercent:(float)value {
5398 - (NSNumber *) percent {
5399 return [NSNumber numberWithFloat:percent_];
5402 - (void) setCurrent:(float)value {
5406 - (NSNumber *) current {
5407 return [NSNumber numberWithFloat:current_];
5410 - (void) setTotal:(float)value {
5414 - (NSNumber *) total {
5415 return [NSNumber numberWithFloat:total_];
5418 - (void) setSpeed:(float)value {
5422 - (NSNumber *) speed {
5423 return [NSNumber numberWithFloat:speed_];
5426 - (NSArray *) events {
5430 - (void) removeAllEvents {
5431 [events_ removeAllObjects];
5434 - (void) addEvent:(CydiaProgressEvent *)event {
5435 [events_ addObject:event];
5438 - (void) setTitle:(NSString *)text {
5442 - (NSString *) title {
5446 - (void) setFinish:(NSString *)text {
5450 - (NSString *) finish {
5451 return (id) finish_ ?: [NSNull null];
5454 - (void) setRunning:(bool)running {
5458 - (NSNumber *) running {
5459 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5464 /* Progress Controller {{{ */
5465 @interface ProgressController : CydiaWebViewController <
5468 _transient Database *database_;
5469 _H<CydiaProgressData, 1> progress_;
5473 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5475 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5477 - (void) setTitle:(NSString *)title;
5478 - (void) setCancellable:(bool)cancellable;
5482 @implementation ProgressController
5485 [database_ setProgressDelegate:nil];
5489 - (UIBarButtonItem *) leftButton {
5490 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5491 initWithTitle:UCLocalize("CANCEL")
5492 style:UIBarButtonItemStylePlain
5494 action:@selector(cancel)
5495 ] autorelease] : nil;
5498 - (void) updateCancel {
5499 [super applyLeftButton];
5502 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5503 if ((self = [super init]) != nil) {
5504 database_ = database;
5505 delegate_ = delegate;
5507 [database_ setProgressDelegate:self];
5509 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5510 [progress_ setDelegate:self];
5512 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5514 [scroller_ setBackgroundColor:[UIColor blackColor]];
5516 [[self navigationItem] setHidesBackButton:YES];
5518 [self updateCancel];
5522 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5523 [super webView:view didClearWindowObject:window forFrame:frame];
5524 [window setValue:progress_ forKey:@"cydiaProgress"];
5527 - (void) updateProgress {
5528 [self dispatchEvent:@"CydiaProgressUpdate"];
5531 - (void) viewWillAppear:(BOOL)animated {
5532 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5533 [super viewWillAppear:animated];
5536 - (void) reloadSpringBoard {
5537 if (kCFCoreFoundationVersionNumber > 700) { // XXX: iOS 6.x
5538 system("/bin/launchctl stop com.apple.backboardd");
5540 system("/usr/bin/killall backboardd SpringBoard sbreload");
5544 pid_t pid(ExecFork());
5549 pid_t pid(ExecFork());
5551 execl("/usr/bin/sbreload", "sbreload", NULL);
5561 system("/usr/bin/killall backboardd SpringBoard sbreload");
5565 UpdateExternalStatus(0);
5568 [delegate_ saveState];
5572 [delegate_ returnToCydia];
5576 [delegate_ terminateWithSuccess];
5577 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5578 [delegate_ suspendWithAnimation:YES];
5580 [delegate_ suspend];*/
5592 UIProgressHUD *hud([delegate_ addProgressHUD]);
5593 [hud setText:UCLocalize("LOADING")];
5594 [self performSelector:@selector(reloadSpringBoard) withObject:nil afterDelay:0.5];
5600 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5601 SBReboot(SBSSpringBoardServerPort());
5603 reboot2(RB_AUTOBOOT);
5610 - (void) setTitle:(NSString *)title {
5611 [progress_ setTitle:title];
5612 [self updateProgress];
5615 - (UIBarButtonItem *) rightButton {
5616 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5617 initWithTitle:UCLocalize("CLOSE")
5618 style:UIBarButtonItemStylePlain
5620 action:@selector(close)
5624 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5625 UpdateExternalStatus(1);
5627 [progress_ setRunning:true];
5628 [self setTitle:title];
5629 // implicit updateProgress
5631 SHA1SumValue notifyconf; {
5633 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5636 MMap mmap(file, MMap::ReadOnly);
5638 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5639 notifyconf = sha1.Result();
5643 SHA1SumValue springlist; {
5645 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5648 MMap mmap(file, MMap::ReadOnly);
5650 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5651 springlist = sha1.Result();
5655 if (invocation != nil) {
5656 [invocation yieldToSelector:@selector(invoke)];
5657 [self setTitle:@"COMPLETE"];
5662 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5665 MMap mmap(file, MMap::ReadOnly);
5667 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5668 if (!(notifyconf == sha1.Result()))
5675 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5678 MMap mmap(file, MMap::ReadOnly);
5680 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5681 if (!(springlist == sha1.Result()))
5687 if (RestartSubstrate_)
5691 RestartSubstrate_ = false;
5694 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5695 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5696 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5697 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5698 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5701 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5703 [progress_ setRunning:false];
5704 [self updateProgress];
5706 [self applyRightButton];
5709 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5710 [progress_ addEvent:event];
5711 [self updateProgress];
5714 - (bool) isProgressCancelled {
5715 return cancel_ == 2;
5720 [self updateCancel];
5723 - (void) setCancellable:(bool)cancellable {
5724 unsigned cancel(cancel_);
5728 else if (cancel_ == 0)
5731 if (cancel != cancel_)
5732 [self updateCancel];
5735 - (void) setProgressCancellable:(NSNumber *)cancellable {
5736 [self setCancellable:[cancellable boolValue]];
5739 - (void) setProgressPercent:(NSNumber *)percent {
5740 [progress_ setPercent:[percent floatValue]];
5741 [self updateProgress];
5744 - (void) setProgressStatus:(NSDictionary *)status {
5745 if (status == nil) {
5746 [progress_ setCurrent:0];
5747 [progress_ setTotal:0];
5748 [progress_ setSpeed:0];
5750 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5752 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5753 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5754 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5757 [self updateProgress];
5763 /* Package Cell {{{ */
5764 @interface PackageCell : CyteTableViewCell <
5765 CyteTableViewCellDelegate
5769 _H<NSString> description_;
5771 _H<NSString> source_;
5773 _H<UIImage> placard_;
5777 - (PackageCell *) init;
5778 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5780 - (void) drawContentRect:(CGRect)rect;
5784 @implementation PackageCell
5786 - (PackageCell *) init {
5787 CGRect frame(CGRectMake(0, 0, 320, 74));
5788 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5789 UIView *content([self contentView]);
5790 CGRect bounds([content bounds]);
5792 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5793 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5794 [content addSubview:content_];
5796 [content_ setDelegate:self];
5797 [content_ setOpaque:YES];
5801 - (NSString *) accessibilityLabel {
5805 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5806 summarized_ = summary;
5816 [content_ setBackgroundColor:[UIColor whiteColor]];
5820 Source *source = [package source];
5822 icon_ = [package icon];
5824 if (NSString *name = [package name])
5825 name_ = [NSString stringWithString:name];
5827 if (NSString *description = [package shortDescription])
5828 description_ = [NSString stringWithString:description];
5830 commercial_ = [package isCommercial];
5832 NSString *label = nil;
5833 bool trusted = false;
5835 if (source != nil) {
5836 label = [source label];
5837 trusted = [source trusted];
5838 } else if ([[package id] isEqualToString:@"firmware"])
5839 label = UCLocalize("APPLE");
5841 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5843 NSString *from(label);
5845 NSString *section = [package simpleSection];
5846 if (section != nil && ![section isEqualToString:label]) {
5847 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5848 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5851 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5853 if (NSString *purpose = [package primaryPurpose])
5854 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5859 if (NSString *mode = [package mode]) {
5860 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5861 color = RemovingColor_;
5862 placard = @"removing";
5864 color = InstallingColor_;
5865 placard = @"installing";
5868 color = [UIColor whiteColor];
5870 if ([package installed] != nil)
5871 placard = @"installed";
5876 [content_ setBackgroundColor:color];
5879 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5882 [self setNeedsDisplay];
5883 [content_ setNeedsDisplay];
5886 - (void) drawSummaryContentRect:(CGRect)rect {
5887 bool highlighted(highlighted_);
5888 float width([self bounds].size.width);
5892 rect.size = [(UIImage *) icon_ size];
5894 while (rect.size.width > 16 || rect.size.height > 16) {
5895 rect.size.width /= 2;
5896 rect.size.height /= 2;
5899 rect.origin.x = 19 - rect.size.width / 2;
5900 rect.origin.y = 19 - rect.size.height / 2;
5902 [icon_ drawInRect:Retina(rect)];
5905 if (badge_ != nil) {
5907 rect.size = [(UIImage *) badge_ size];
5909 rect.size.width /= 4;
5910 rect.size.height /= 4;
5912 rect.origin.x = 25 - rect.size.width / 2;
5913 rect.origin.y = 25 - rect.size.height / 2;
5915 [badge_ drawInRect:Retina(rect)];
5918 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5922 UISetColor(commercial_ ? Purple_ : Black_);
5923 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
5925 if (placard_ != nil)
5926 [placard_ drawAtPoint:CGPointMake(width - 52, 11)];
5929 - (void) drawNormalContentRect:(CGRect)rect {
5930 bool highlighted(highlighted_);
5931 float width([self bounds].size.width);
5935 rect.size = [(UIImage *) icon_ size];
5937 while (rect.size.width > 32 || rect.size.height > 32) {
5938 rect.size.width /= 2;
5939 rect.size.height /= 2;
5942 rect.origin.x = 25 - rect.size.width / 2;
5943 rect.origin.y = 25 - rect.size.height / 2;
5945 [icon_ drawInRect:Retina(rect)];
5948 if (badge_ != nil) {
5950 rect.size = [(UIImage *) badge_ size];
5952 rect.size.width /= 2;
5953 rect.size.height /= 2;
5955 rect.origin.x = 36 - rect.size.width / 2;
5956 rect.origin.y = 36 - rect.size.height / 2;
5958 [badge_ drawInRect:Retina(rect)];
5961 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5965 UISetColor(commercial_ ? Purple_ : Black_);
5966 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
5967 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
5970 UISetColor(commercial_ ? Purplish_ : Gray_);
5971 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:NSLineBreakByTruncatingTail];
5973 if (placard_ != nil)
5974 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5977 - (void) drawContentRect:(CGRect)rect {
5979 [self drawSummaryContentRect:rect];
5981 [self drawNormalContentRect:rect];
5986 /* Section Cell {{{ */
5987 @interface SectionCell : CyteTableViewCell <
5988 CyteTableViewCellDelegate
5990 _H<NSString> basic_;
5991 _H<NSString> section_;
5993 _H<NSString> count_;
5995 _H<UISwitch> switch_;
5999 - (void) setSection:(Section *)section editing:(BOOL)editing;
6003 @implementation SectionCell
6005 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
6006 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
6007 icon_ = [UIImage applicationImageNamed:@"folder.png"];
6008 // XXX: this initial frame is wrong, but is fixed later
6009 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
6010 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
6012 UIView *content([self contentView]);
6013 CGRect bounds([content bounds]);
6015 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
6016 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6017 [content addSubview:content_];
6018 [content_ setBackgroundColor:[UIColor whiteColor]];
6020 [content_ setDelegate:self];
6024 - (void) onSwitch:(id)sender {
6025 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
6026 if (metadata == nil) {
6027 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
6028 [Sections_ setObject:metadata forKey:basic_];
6031 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
6035 - (void) setSection:(Section *)section editing:(BOOL)editing {
6036 if (editing != editing_) {
6038 [switch_ removeFromSuperview];
6040 [self addSubview:switch_];
6049 if (section == nil) {
6050 name_ = UCLocalize("ALL_PACKAGES");
6053 basic_ = [section name];
6054 section_ = [section localized];
6056 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
6057 count_ = [NSString stringWithFormat:@"%zd", [section count]];
6060 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
6063 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
6064 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
6066 [content_ setNeedsDisplay];
6069 - (void) setFrame:(CGRect)frame {
6070 [super setFrame:frame];
6072 CGRect rect([switch_ frame]);
6073 [switch_ setFrame:CGRectMake(frame.size.width - rect.size.width - 9, 9, rect.size.width, rect.size.height)];
6076 - (NSString *) accessibilityLabel {
6080 - (void) drawContentRect:(CGRect)rect {
6081 bool highlighted(highlighted_ && !editing_);
6083 [icon_ drawInRect:CGRectMake(7, 7, 32, 32)];
6085 if (highlighted && kCFCoreFoundationVersionNumber < 800)
6088 float width(rect.size.width);
6090 width -= 9 + [switch_ frame].size.width;
6094 [name_ drawAtPoint:CGPointMake(48, 12) forWidth:(width - 58) withFont:Font18_ lineBreakMode:NSLineBreakByTruncatingTail];
6096 CGSize size = [count_ sizeWithFont:Font14_];
6098 UISetColor(Folder_);
6100 [count_ drawAtPoint:CGPointMake(Retina(10 + (30 - size.width) / 2), 18) withFont:Font12Bold_];
6106 /* File Table {{{ */
6107 @interface FileTable : CyteViewController <
6108 UITableViewDataSource,
6111 _transient Database *database_;
6112 _H<Package> package_;
6114 _H<NSMutableArray> files_;
6115 _H<UITableView, 2> list_;
6118 - (id) initWithDatabase:(Database *)database;
6119 - (void) setPackage:(Package *)package;
6123 @implementation FileTable
6125 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6126 return files_ == nil ? 0 : [files_ count];
6129 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6133 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6134 static NSString *reuseIdentifier = @"Cell";
6136 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6138 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6139 [cell setFont:[UIFont systemFontOfSize:16]];
6141 [cell setText:[files_ objectAtIndex:indexPath.row]];
6142 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
6147 - (NSURL *) navigationURL {
6148 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
6152 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
6153 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6154 [list_ setRowHeight:24.0f];
6155 [(UITableView *) list_ setDataSource:self];
6156 [list_ setDelegate:self];
6157 [self setView:list_];
6160 - (void) viewDidLoad {
6161 [super viewDidLoad];
6163 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
6166 - (void) releaseSubviews {
6172 [super releaseSubviews];
6175 - (id) initWithDatabase:(Database *)database {
6176 if ((self = [super init]) != nil) {
6177 database_ = database;
6181 - (void) setPackage:(Package *)package {
6185 files_ = [NSMutableArray arrayWithCapacity:32];
6187 if (package != nil) {
6189 name_ = [package id];
6191 if (NSArray *files = [package files])
6192 [files_ addObjectsFromArray:files];
6194 if ([files_ count] != 0) {
6195 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
6196 [files_ removeObjectAtIndex:0];
6197 [files_ sortUsingSelector:@selector(compareByPath:)];
6199 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
6200 [stack addObject:@"/"];
6202 for (int i(0), e([files_ count]); i != e; ++i) {
6203 NSString *file = [files_ objectAtIndex:i];
6204 while (![file hasPrefix:[stack lastObject]])
6205 [stack removeLastObject];
6206 NSString *directory = [stack lastObject];
6207 [stack addObject:[file stringByAppendingString:@"/"]];
6208 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
6209 ([stack count] - 2) * 3, "",
6210 [file substringFromIndex:[directory length]]
6219 - (void) reloadData {
6222 [self setPackage:[database_ packageWithName:name_]];
6227 /* Package Controller {{{ */
6228 @interface CYPackageController : CydiaWebViewController <
6229 UIActionSheetDelegate
6231 _transient Database *database_;
6232 _H<Package> package_;
6235 _H<NSMutableArray> buttons_;
6236 _H<UIBarButtonItem> button_;
6239 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer;
6243 @implementation CYPackageController
6245 - (NSURL *) navigationURL {
6246 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
6249 /* XXX: this is not safe at all... localization of /fail/ */
6250 - (void) _clickButtonWithName:(NSString *)name {
6251 if ([name isEqualToString:UCLocalize("CLEAR")])
6252 [delegate_ clearPackage:package_];
6253 else if ([name isEqualToString:UCLocalize("INSTALL")])
6254 [delegate_ installPackage:package_];
6255 else if ([name isEqualToString:UCLocalize("REINSTALL")])
6256 [delegate_ installPackage:package_];
6257 else if ([name isEqualToString:UCLocalize("REMOVE")])
6258 [delegate_ removePackage:package_];
6259 else if ([name isEqualToString:UCLocalize("UPGRADE")])
6260 [delegate_ installPackage:package_];
6261 else _assert(false);
6264 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
6265 NSString *context([sheet context]);
6267 if ([context isEqualToString:@"modify"]) {
6268 if (button != [sheet cancelButtonIndex]) {
6269 NSString *buttonName = [buttons_ objectAtIndex:button];
6270 [self _clickButtonWithName:buttonName];
6273 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
6277 - (bool) _allowJavaScriptPanel {
6282 - (void) _customButtonClicked {
6283 int count([buttons_ count]);
6288 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
6290 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
6291 [buttons addObjectsFromArray:buttons_];
6293 UIActionSheet *sheet = [[[UIActionSheet alloc]
6296 cancelButtonTitle:nil
6297 destructiveButtonTitle:nil
6298 otherButtonTitles:nil
6301 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
6303 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
6304 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
6306 [sheet setContext:@"modify"];
6308 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
6312 - (void) reloadButtonClicked {
6313 if (commercial_ && function_ == nil && [package_ uninstalled])
6315 [self customButtonClicked];
6318 - (void) applyLoadingTitle {
6319 // Don't show "Loading" as the title. Ever.
6322 - (UIBarButtonItem *) rightButton {
6327 - (void) setPageColor:(UIColor *)color {
6328 return [super setPageColor:nil];
6331 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer {
6332 if ((self = [super init]) != nil) {
6333 database_ = database;
6334 buttons_ = [NSMutableArray arrayWithCapacity:4];
6335 name_ = name == nil ? @"" : [NSString stringWithString:name];
6336 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]] withReferrer:referrer];
6340 - (void) reloadData {
6343 package_ = [database_ packageWithName:name_];
6345 [buttons_ removeAllObjects];
6347 if (package_ != nil) {
6348 [(Package *) package_ parse];
6350 commercial_ = [package_ isCommercial];
6352 if ([package_ mode] != nil)
6353 [buttons_ addObject:UCLocalize("CLEAR")];
6354 if ([package_ source] == nil);
6355 else if ([package_ upgradableAndEssential:NO])
6356 [buttons_ addObject:UCLocalize("UPGRADE")];
6357 else if ([package_ uninstalled])
6358 [buttons_ addObject:UCLocalize("INSTALL")];
6360 [buttons_ addObject:UCLocalize("REINSTALL")];
6361 if (![package_ uninstalled])
6362 [buttons_ addObject:UCLocalize("REMOVE")];
6366 switch ([buttons_ count]) {
6367 case 0: title = nil; break;
6368 case 1: title = [buttons_ objectAtIndex:0]; break;
6369 default: title = UCLocalize("MODIFY"); break;
6372 button_ = [[[UIBarButtonItem alloc]
6374 style:UIBarButtonItemStylePlain
6376 action:@selector(customButtonClicked)
6380 - (bool) isLoading {
6381 return commercial_ ? [super isLoading] : false;
6387 /* Package List Controller {{{ */
6388 @interface PackageListController : CyteViewController <
6389 UITableViewDataSource,
6392 _transient Database *database_;
6394 _H<NSArray> packages_;
6395 _H<NSArray> sections_;
6396 _H<UITableView, 2> list_;
6398 _H<NSArray> thumbs_;
6399 std::vector<NSInteger> offset_;
6401 _H<NSString> title_;
6402 unsigned reloading_;
6405 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6406 - (void) setDelegate:(id)delegate;
6407 - (void) resetCursor;
6410 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages;
6414 @implementation PackageListController
6416 - (NSURL *) referrerURL {
6417 return [self navigationURL];
6420 - (bool) isSummarized {
6424 - (bool) showsSections {
6428 - (void) deselectWithAnimation:(BOOL)animated {
6429 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6432 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6433 CGRect base = [[self view] bounds];
6434 base.size.height -= bounds.size.height;
6435 base.origin = [list_ frame].origin;
6437 [UIView beginAnimations:nil context:NULL];
6438 [UIView setAnimationBeginsFromCurrentState:YES];
6439 [UIView setAnimationCurve:curve];
6440 [UIView setAnimationDuration:duration];
6441 [list_ setFrame:base];
6442 [UIView commitAnimations];
6445 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6446 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6449 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6450 [self resizeForKeyboardBounds:bounds duration:0];
6453 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6454 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6455 *curve = UIViewAnimationCurveEaseInOut;
6457 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6459 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6462 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6465 - (void) keyboardWillShow:(NSNotification *)notification {
6468 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6469 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6471 NSTimeInterval duration;
6472 UIViewAnimationCurve curve;
6473 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6475 CGRect kbframe = CGRectMake(Retina(center.x - bounds.size.width / 2), Retina(center.y - bounds.size.height / 2), bounds.size.width, bounds.size.height);
6476 UIViewController *base = self;
6477 while ([base parentOrPresentingViewController] != nil)
6478 base = [base parentOrPresentingViewController];
6479 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6480 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6482 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6483 intersection.size.height += CYStatusBarHeight();
6485 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6488 - (void) keyboardWillHide:(NSNotification *)notification {
6489 NSTimeInterval duration;
6490 UIViewAnimationCurve curve;
6491 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6493 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6496 - (void) viewWillAppear:(BOOL)animated {
6497 [super viewWillAppear:animated];
6499 [self resizeForKeyboardBounds:CGRectZero];
6500 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6501 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6504 - (void) viewWillDisappear:(BOOL)animated {
6505 [super viewWillDisappear:animated];
6507 [self resizeForKeyboardBounds:CGRectZero];
6508 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6509 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6512 - (void) viewDidAppear:(BOOL)animated {
6513 [super viewDidAppear:animated];
6514 [self deselectWithAnimation:animated];
6517 - (void) didSelectPackage:(Package *)package {
6518 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[[self referrerURL] absoluteString]] autorelease]);
6519 [view setDelegate:delegate_];
6520 [[self navigationController] pushViewController:view animated:YES];
6523 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6524 NSInteger count([sections_ count]);
6525 return count == 0 ? 1 : count;
6528 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6529 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6531 return [[sections_ objectAtIndex:section] name];
6534 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6535 if ([sections_ count] == 0)
6537 return [[sections_ objectAtIndex:section] count];
6540 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6541 @synchronized (database_) {
6542 if ([database_ era] != era_)
6545 Section *section([sections_ objectAtIndex:[path section]]);
6546 NSInteger row([path row]);
6547 Package *package([packages_ objectAtIndex:([section row] + row)]);
6548 return [[package retain] autorelease];
6551 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6552 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6554 cell = [[[PackageCell alloc] init] autorelease];
6556 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6557 [cell setPackage:package asSummary:[self isSummarized]];
6561 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6562 Package *package([self packageAtIndexPath:path]);
6563 package = [database_ packageWithName:[package id]];
6564 [self didSelectPackage:package];
6567 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6571 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6572 return offset_[index];
6575 - (void) updateHeight {
6576 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6579 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6580 if ((self = [super init]) != nil) {
6581 database_ = database;
6582 title_ = [title copy];
6583 [[self navigationItem] setTitle:title_];
6588 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
6589 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
6590 [self setView:view];
6592 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6593 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6594 [view addSubview:list_];
6596 // XXX: is 20 the most optimal number here?
6597 [list_ setSectionIndexMinimumDisplayRowCount:20];
6599 [(UITableView *) list_ setDataSource:self];
6600 [list_ setDelegate:self];
6602 [self updateHeight];
6605 - (void) releaseSubviews {
6614 [super releaseSubviews];
6617 - (void) setDelegate:(id)delegate {
6618 delegate_ = delegate;
6621 - (bool) shouldYield {
6625 - (bool) shouldBlock {
6629 - (NSMutableArray *) _reloadPackages {
6630 @synchronized (database_) {
6631 era_ = [database_ era];
6632 NSArray *packages([database_ packages]);
6634 return [NSMutableArray arrayWithArray:packages];
6637 - (void) _reloadData {
6638 if (reloading_ != 0) {
6643 NSMutableArray *packages;
6646 if ([self shouldYield]) {
6650 if (![self shouldBlock])
6653 hud = [delegate_ addProgressHUD];
6654 [hud setText:UCLocalize("LOADING")];
6658 packages = [self yieldToSelector:@selector(_reloadPackages)];
6661 [delegate_ removeProgressHUD:hud];
6662 } while (reloading_ == 2);
6664 packages = [self _reloadPackages];
6667 @synchronized (database_) {
6668 if (era_ != [database_ era])
6675 packages_ = packages;
6677 if ([self showsSections])
6678 sections_ = [self sectionsForPackages:packages];
6680 Section *section([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6681 [section setCount:[packages_ count]];
6682 sections_ = [NSArray arrayWithObject:section];
6685 [self updateHeight];
6687 _profile(PackageTable$reloadData$List)
6688 [(UITableView *) list_ setDataSource:self];
6696 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
6697 Section *prefix([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6698 size_t end([packages count]);
6700 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
6701 Section *section(prefix);
6703 thumbs_ = CollationThumbs_;
6704 offset_ = CollationOffset_;
6707 size_t offsets([CollationStarts_ count]);
6709 NSString *start([CollationStarts_ objectAtIndex:offset]);
6710 size_t length([start length]);
6712 for (size_t index(0); index != end; ++index) {
6714 Package *package([packages objectAtIndex:index]);
6715 NSString *name(PackageName(package, @selector(cyname)));
6717 //while ([start compare:name options:NSNumericSearch range:NSMakeRange(0, length) locale:CollationLocale_] != NSOrderedDescending) {
6718 while (StringNameCompare(start, name, length) != kCFCompareGreaterThan) {
6719 NSString *title([CollationTitles_ objectAtIndex:offset]);
6720 section = [[[Section alloc] initWithName:title row:index localize:NO] autorelease];
6721 [sections addObject:section];
6723 start = ++offset == offsets ? nil : [CollationStarts_ objectAtIndex:offset];
6726 length = [start length];
6730 [section addToCount];
6733 for (; offset != offsets; ++offset) {
6734 NSString *title([CollationTitles_ objectAtIndex:offset]);
6735 Section *section([[[Section alloc] initWithName:title row:end localize:NO] autorelease]);
6736 [sections addObject:section];
6739 if ([prefix count] != 0) {
6740 Section *suffix([sections lastObject]);
6741 [prefix setName:[suffix name]];
6742 [suffix setName:nil];
6743 [sections insertObject:prefix atIndex:(offsets - 1)];
6749 - (void) reloadData {
6752 if ([self shouldYield])
6753 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6758 - (void) resetCursor {
6759 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6762 - (void) clearData {
6763 [self updateHeight];
6765 [list_ setDataSource:nil];
6773 /* Filtered Package List Controller {{{ */
6774 typedef Function<bool, Package *> PackageFilter;
6775 typedef Function<void, NSMutableArray *> PackageSorter;
6776 @interface FilteredPackageListController : PackageListController {
6777 PackageFilter filter_;
6778 PackageSorter sorter_;
6781 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter;
6783 - (void) setFilter:(PackageFilter)filter;
6784 - (void) setSorter:(PackageSorter)sorter;
6788 @implementation FilteredPackageListController
6790 - (void) setFilter:(PackageFilter)filter {
6791 @synchronized (self) {
6795 - (void) setSorter:(PackageSorter)sorter {
6796 @synchronized (self) {
6800 - (NSMutableArray *) _reloadPackages {
6801 @synchronized (database_) {
6802 era_ = [database_ era];
6804 NSArray *packages([database_ packages]);
6805 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6807 PackageFilter filter;
6808 PackageSorter sorter;
6810 @synchronized (self) {
6815 _profile(PackageTable$reloadData$Filter)
6816 for (Package *package in packages)
6817 if ([package valid] && filter(package))
6818 [filtered addObject:package];
6826 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter {
6827 if ((self = [super initWithDatabase:database title:title]) != nil) {
6828 [self setFilter:filter];
6835 /* Home Controller {{{ */
6836 @interface HomeController : CydiaWebViewController {
6837 CFRunLoopRef runloop_;
6838 SCNetworkReachabilityRef reachability_;
6843 @implementation HomeController
6845 static void HomeControllerReachabilityCallback(SCNetworkReachabilityRef reachability, SCNetworkReachabilityFlags flags, void *info) {
6846 [(HomeController *) info dispatchEvent:@"CydiaReachabilityCallback"];
6850 if ((self = [super init]) != nil) {
6851 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6854 reachability_ = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "cydia.saurik.com");
6855 if (reachability_ != NULL) {
6856 SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
6857 SCNetworkReachabilitySetCallback(reachability_, HomeControllerReachabilityCallback, &context);
6859 CFRunLoopRef runloop(CFRunLoopGetCurrent());
6860 if (SCNetworkReachabilityScheduleWithRunLoop(reachability_, runloop, kCFRunLoopDefaultMode))
6867 if (reachability_ != NULL && runloop_ != NULL)
6868 SCNetworkReachabilityUnscheduleFromRunLoop(reachability_, runloop_, kCFRunLoopDefaultMode);
6872 - (NSURL *) navigationURL {
6873 return [NSURL URLWithString:@"cydia://home"];
6876 - (void) aboutButtonClicked {
6877 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6879 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6880 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6881 [alert setCancelButtonIndex:0];
6884 @"Copyright \u00a9 2008-2014\n"
6887 "Jay Freeman (saurik)\n"
6888 "saurik@saurik.com\n"
6889 "http://www.saurik.com/"
6895 - (UIBarButtonItem *) leftButton {
6896 return [[[UIBarButtonItem alloc]
6897 initWithTitle:UCLocalize("ABOUT")
6898 style:UIBarButtonItemStylePlain
6900 action:@selector(aboutButtonClicked)
6907 /* Cydia Navigation Controller Interface {{{ */
6908 @interface UINavigationController (Cydia)
6910 - (NSArray *) navigationURLCollection;
6911 - (void) unloadData;
6916 /* Cydia Tab Bar Controller {{{ */
6917 @interface CydiaTabBarController : CyteTabBarController <
6918 UITabBarControllerDelegate,
6921 _transient Database *database_;
6923 _H<UIActivityIndicatorView> indicator_;
6926 // XXX: ok, "updatedelegate_"?...
6927 _transient NSObject<CydiaDelegate> *updatedelegate_;
6930 - (NSArray *) navigationURLCollection;
6931 - (void) beginUpdate;
6936 @implementation CydiaTabBarController
6938 - (NSArray *) navigationURLCollection {
6939 NSMutableArray *items([NSMutableArray array]);
6941 // XXX: Should this deal with transient view controllers?
6942 for (id navigation in [self viewControllers]) {
6943 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6945 [items addObject:stack];
6951 - (id) initWithDatabase:(Database *)database {
6952 if ((self = [super init]) != nil) {
6953 database_ = database;
6954 [self setDelegate:self];
6956 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteTiny] autorelease];
6957 [indicator_ setOrigin:CGPointMake(kCFCoreFoundationVersionNumber >= 800 ? 2 : 4, 2)];
6959 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6963 - (void) setUpdate:(NSDate *)date {
6967 - (void) beginUpdate {
6971 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
6972 UITabBarItem *item([controller tabBarItem]);
6974 [item setBadgeValue:@""];
6975 UIView *badge(MSHookIvar<UIView *>([item view], "_badge"));
6977 [indicator_ startAnimating];
6978 [badge addSubview:indicator_];
6980 [updatedelegate_ retainNetworkActivityIndicator];
6984 detachNewThreadSelector:@selector(performUpdate)
6990 - (void) performUpdate {
6991 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
6993 SourceStatus status(self, database_);
6994 [database_ updateWithStatus:status];
6997 performSelectorOnMainThread:@selector(completeUpdate)
7005 - (void) stopUpdateWithSelector:(SEL)selector {
7007 [updatedelegate_ releaseNetworkActivityIndicator];
7009 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
7010 [[controller tabBarItem] setBadgeValue:nil];
7012 [indicator_ removeFromSuperview];
7013 [indicator_ stopAnimating];
7015 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
7018 - (void) completeUpdate {
7021 [self stopUpdateWithSelector:@selector(reloadData)];
7024 - (void) cancelUpdate {
7025 [self stopUpdateWithSelector:@selector(updateDataAndLoad)];
7028 - (void) cancelPressed {
7029 [self cancelUpdate];
7036 - (bool) isSourceCancelled {
7040 - (void) startSourceFetch:(NSString *)uri {
7043 - (void) stopSourceFetch:(NSString *)uri {
7046 - (void) setUpdateDelegate:(id)delegate {
7047 updatedelegate_ = delegate;
7053 /* Cydia Navigation Controller Implementation {{{ */
7054 @implementation UINavigationController (Cydia)
7056 - (NSArray *) navigationURLCollection {
7057 NSMutableArray *stack([NSMutableArray array]);
7059 for (CyteViewController *controller in [self viewControllers]) {
7060 NSString *url = [[controller navigationURL] absoluteString];
7062 [stack addObject:url];
7068 - (void) reloadData {
7071 UIViewController *visible([self visibleViewController]);
7073 [visible reloadData];
7075 // on the iPad, this view controller is ALSO visible. :(
7077 if (UIViewController *top = [self topViewController])
7082 - (void) unloadData {
7083 for (CyteViewController *page in [self viewControllers])
7092 /* Cydia:// Protocol {{{ */
7093 @interface CydiaURLProtocol : NSURLProtocol {
7098 @implementation CydiaURLProtocol
7100 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7101 NSURL *url([request URL]);
7105 NSString *scheme([[url scheme] lowercaseString]);
7106 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7108 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7114 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7118 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7119 id<NSURLProtocolClient> client([self client]);
7121 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7123 NSData *data(UIImagePNGRepresentation(icon));
7125 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7126 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7127 [client URLProtocol:self didLoadData:data];
7128 [client URLProtocolDidFinishLoading:self];
7132 - (void) startLoading {
7133 id<NSURLProtocolClient> client([self client]);
7134 NSURLRequest *request([self request]);
7136 NSURL *url([request URL]);
7137 NSString *href([url absoluteString]);
7138 NSString *scheme([[url scheme] lowercaseString]);
7142 if ([scheme isEqualToString:@"cydia"])
7143 path = [href substringFromIndex:8];
7144 else if ([scheme isEqualToString:@"about"])
7145 path = [href substringFromIndex:12];
7146 else _assert(false);
7148 NSRange slash([path rangeOfString:@"/"]);
7151 if (slash.location == NSNotFound) {
7155 command = [path substringToIndex:slash.location];
7156 path = [path substringFromIndex:(slash.location + 1)];
7159 Database *database([Database sharedInstance]);
7161 if ([command isEqualToString:@"package-icon"]) {
7164 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7165 Package *package([database packageWithName:path]);
7169 UIImage *icon([package icon]);
7170 [self _returnPNGWithImage:icon forRequest:request];
7171 } else if ([command isEqualToString:@"uikit-image"]) {
7174 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7175 UIImage *icon(_UIImageWithName(path));
7176 [self _returnPNGWithImage:icon forRequest:request];
7177 } else if ([command isEqualToString:@"section-icon"]) {
7180 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7181 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7183 icon = [UIImage applicationImageNamed:@"unknown.png"];
7184 [self _returnPNGWithImage:icon forRequest:request];
7186 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7190 - (void) stopLoading {
7196 /* Section Controller {{{ */
7197 @interface SectionController : FilteredPackageListController {
7199 _H<NSString> section_;
7202 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section;
7206 @implementation SectionController
7208 - (NSURL *) referrerURL {
7209 NSString *name(section_);
7210 name = name ?: @"*";
7211 NSString *key(key_);
7213 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sections/%@/%@", UI_, [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7216 - (NSURL *) navigationURL {
7217 NSString *name(section_);
7218 name = name ?: @"*";
7219 NSString *key(key_);
7221 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@/%@", [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7224 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section {
7227 title = UCLocalize("ALL_PACKAGES");
7228 else if (![section isEqual:@""])
7229 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(section) value:nil table:@"Sections"];
7231 title = UCLocalize("NO_SECTION");
7233 if ((self = [super initWithDatabase:database title:title]) != nil) {
7234 key_ = [source key];
7239 - (void) reloadData {
7240 Source *source([database_ sourceWithKey:key_]);
7241 _H<NSString> name(section_);
7243 [self setFilter:[=](Package *package) {
7244 NSString *section([package section]);
7248 section == nil && [name length] == 0 ||
7249 [name isEqualToString:section]
7252 [package source] == source
7253 ) && [package visible];
7261 /* Sections Controller {{{ */
7262 @interface SectionsController : CyteViewController <
7263 UITableViewDataSource,
7266 _transient Database *database_;
7268 _H<NSMutableArray> sections_;
7269 _H<NSMutableArray> filtered_;
7270 _H<UITableView, 2> list_;
7273 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7274 - (void) editButtonClicked;
7278 @implementation SectionsController
7280 - (NSURL *) navigationURL {
7281 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
7284 - (Source *) source {
7287 return [database_ sourceWithKey:key_];
7290 - (void) updateNavigationItem {
7291 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7292 if ([sections_ count] == 0) {
7293 [[self navigationItem] setRightBarButtonItem:nil];
7295 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7296 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7298 action:@selector(editButtonClicked)
7299 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7303 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7304 [super setEditing:editing animated:animated];
7309 [delegate_ updateData];
7311 [self updateNavigationItem];
7314 - (void) viewDidAppear:(BOOL)animated {
7315 [super viewDidAppear:animated];
7316 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7319 - (void) viewWillDisappear:(BOOL)animated {
7320 [super viewWillDisappear:animated];
7321 [self setEditing:NO];
7324 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7325 Section *section = nil;
7326 int index = [indexPath row];
7327 if (![self isEditing]) {
7330 section = [filtered_ objectAtIndex:index];
7332 section = [sections_ objectAtIndex:index];
7337 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7338 if ([self isEditing])
7339 return [sections_ count];
7341 return [filtered_ count] + 1;
7344 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7348 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7349 static NSString *reuseIdentifier = @"SectionCell";
7351 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7353 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7355 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7360 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7361 if ([self isEditing])
7364 Section *section = [self sectionAtIndexPath:indexPath];
7366 SectionController *controller = [[[SectionController alloc]
7367 initWithDatabase:database_
7368 source:[self source]
7369 section:[section name]
7371 [controller setDelegate:delegate_];
7373 [[self navigationController] pushViewController:controller animated:YES];
7377 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
7378 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7379 [list_ setRowHeight:46];
7380 [(UITableView *) list_ setDataSource:self];
7381 [list_ setDelegate:self];
7382 [self setView:list_];
7385 - (void) viewDidLoad {
7386 [super viewDidLoad];
7388 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7391 - (void) releaseSubviews {
7397 [super releaseSubviews];
7400 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7401 if ((self = [super init]) != nil) {
7402 database_ = database;
7403 key_ = [source key];
7407 - (void) reloadData {
7410 NSArray *packages = [database_ packages];
7412 sections_ = [NSMutableArray arrayWithCapacity:16];
7413 filtered_ = [NSMutableArray arrayWithCapacity:16];
7415 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7417 Source *source([self source]);
7420 for (Package *package in packages) {
7421 if (source != nil && [package source] != source)
7424 NSString *name([package section]);
7425 NSString *key(name == nil ? @"" : name);
7429 _profile(SectionsView$reloadData$Section)
7430 section = [sections objectForKey:key];
7431 if (section == nil) {
7432 _profile(SectionsView$reloadData$Section$Allocate)
7433 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7434 [sections setObject:section forKey:key];
7439 [section addToCount];
7441 _profile(SectionsView$reloadData$Filter)
7442 if (![package valid] || ![package visible])
7450 [sections_ addObjectsFromArray:[sections allValues]];
7452 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7454 for (Section *section in (id) sections_) {
7455 size_t count([section row]);
7459 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7460 [section setCount:count];
7461 [filtered_ addObject:section];
7464 [self updateNavigationItem];
7469 - (void) editButtonClicked {
7470 [self setEditing:![self isEditing] animated:YES];
7476 /* Changes Controller {{{ */
7477 @interface ChangesController : FilteredPackageListController {
7481 - (id) initWithDatabase:(Database *)database;
7485 @implementation ChangesController
7487 - (NSURL *) referrerURL {
7488 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/changes/", UI_]];
7491 - (NSURL *) navigationURL {
7492 return [NSURL URLWithString:@"cydia://changes"];
7495 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7496 @synchronized (database_) {
7497 if ([database_ era] != era_)
7500 NSUInteger sectionIndex([path section]);
7501 if (sectionIndex >= [sections_ count])
7503 Section *section([sections_ objectAtIndex:sectionIndex]);
7504 NSInteger row([path row]);
7505 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7508 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7509 NSString *context([alert context]);
7511 if ([context isEqualToString:@"norefresh"])
7512 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7515 - (void) setLeftBarButtonItem {
7516 if ([delegate_ updating])
7517 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7518 initWithTitle:UCLocalize("CANCEL")
7519 style:UIBarButtonItemStyleDone
7521 action:@selector(cancelButtonClicked)
7522 ] autorelease] animated:YES];
7524 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7525 initWithTitle:UCLocalize("REFRESH")
7526 style:UIBarButtonItemStylePlain
7528 action:@selector(refreshButtonClicked)
7529 ] autorelease] animated:YES];
7532 - (void) refreshButtonClicked {
7533 if ([delegate_ requestUpdate])
7534 [self setLeftBarButtonItem];
7537 - (void) cancelButtonClicked {
7538 [delegate_ cancelUpdate];
7541 - (void) upgradeButtonClicked {
7542 [delegate_ distUpgrade];
7543 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7546 - (bool) shouldYield {
7550 - (bool) shouldBlock {
7554 - (void) useFilter {
7555 @synchronized (self) {
7556 [self setFilter:[](Package *package) {
7557 return [package upgradableAndEssential:YES] || [package visible];
7560 [self setSorter:[](NSMutableArray *packages) {
7561 [packages radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7565 - (id) initWithDatabase:(Database *)database {
7566 if ((self = [super initWithDatabase:database title:UCLocalize("CHANGES")]) != nil) {
7571 - (void) viewDidLoad {
7572 [super viewDidLoad];
7573 [self setLeftBarButtonItem];
7576 - (void) viewWillAppear:(BOOL)animated {
7577 [super viewWillAppear:animated];
7578 [self setLeftBarButtonItem];
7581 - (void) reloadData {
7582 [self setLeftBarButtonItem];
7586 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
7587 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
7589 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7590 Section *ignored = nil;
7591 Section *section = nil;
7595 bool unseens = false;
7597 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7599 for (size_t offset = 0, count = [packages count]; offset != count; ++offset) {
7600 Package *package = [packages objectAtIndex:offset];
7602 BOOL uae = [package upgradableAndEssential:YES];
7606 time_t seen([package seen]);
7608 if (section == nil || last != seen) {
7612 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7615 _profile(ChangesController$reloadData$Allocate)
7616 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7617 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7618 [sections addObject:section];
7622 [section addToCount];
7623 } else if ([package ignored]) {
7624 if (ignored == nil) {
7625 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7627 [ignored addToCount];
7630 [upgradable addToCount];
7635 CFRelease(formatter);
7638 Section *last = [sections lastObject];
7639 size_t count = [last count];
7640 [packages removeObjectsInRange:NSMakeRange([packages count] - count, count)];
7641 [sections removeLastObject];
7644 if ([ignored count] != 0)
7645 [sections insertObject:ignored atIndex:0];
7647 [sections insertObject:upgradable atIndex:0];
7651 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7652 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7653 style:UIBarButtonItemStylePlain
7655 action:@selector(upgradeButtonClicked)
7656 ] autorelease]) animated:YES];
7663 /* Search Controller {{{ */
7664 @interface SearchController : FilteredPackageListController <
7667 _H<UISearchBar, 1> search_;
7672 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7673 - (void) reloadData;
7677 @implementation SearchController
7679 - (NSURL *) referrerURL {
7680 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/search?q=%@", UI_, [([search_ text] ?: @"") stringByAddingPercentEscapesIncludingReserved]]];
7683 - (NSURL *) navigationURL {
7684 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7685 return [NSURL URLWithString:@"cydia://search"];
7687 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [[search_ text] stringByAddingPercentEscapesIncludingReserved]]];
7690 - (NSArray *) termsForQuery:(NSString *)query {
7691 NSMutableArray *terms([NSMutableArray arrayWithCapacity:2]);
7692 for (NSString *component in [query componentsSeparatedByString:@" "])
7693 if ([component length] != 0)
7694 [terms addObject:component];
7699 - (void) useSearch {
7700 _H<NSArray> query([self termsForQuery:[search_ text]]);
7703 @synchronized (self) {
7704 [self setFilter:[=](Package *package) {
7705 if (![package unfiltered])
7707 if (![package matches:query])
7712 [self setSorter:[](NSMutableArray *packages) {
7713 [packages radixSortUsingSelector:@selector(rank)];
7721 - (void) usePrefix:(NSString *)prefix {
7722 _H<NSString> query(prefix);
7725 @synchronized (self) {
7726 [self setFilter:[=](Package *package) {
7727 if ([query length] == 0)
7729 if (![package unfiltered])
7731 if ([[package name] compare:query options:MatchCompareOptions_ range:NSMakeRange(0, [query length])] != NSOrderedSame)
7736 [self setSorter:nullptr];
7742 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7744 [self usePrefix:[search_ text]];
7747 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7748 [search_ resignFirstResponder];
7752 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7753 [search_ setText:@""];
7754 [self searchBarButtonClicked:searchBar];
7757 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7758 [self searchBarButtonClicked:searchBar];
7761 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7762 [self usePrefix:text];
7765 - (bool) shouldYield {
7769 - (bool) shouldBlock {
7773 - (bool) isSummarized {
7777 - (bool) showsSections {
7781 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7782 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH")])) {
7783 search_ = [[[UISearchBar alloc] init] autorelease];
7784 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7785 [search_ setDelegate:self];
7787 UITextField *textField;
7788 if ([search_ respondsToSelector:@selector(searchField)])
7789 textField = [search_ searchField];
7791 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7793 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7794 [textField setEnablesReturnKeyAutomatically:NO];
7795 [[self navigationItem] setTitleView:textField];
7798 [search_ setText:query];
7803 - (void) viewDidAppear:(BOOL)animated {
7804 [super viewDidAppear:animated];
7806 if (!searchloaded_) {
7807 searchloaded_ = YES;
7808 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7809 [search_ layoutSubviews];
7812 if ([self isSummarized])
7813 [search_ becomeFirstResponder];
7816 - (void) reloadData {
7821 - (void) didSelectPackage:(Package *)package {
7822 [search_ resignFirstResponder];
7823 [super didSelectPackage:package];
7828 /* Package Settings Controller {{{ */
7829 @interface PackageSettingsController : CyteViewController <
7830 UITableViewDataSource,
7833 _transient Database *database_;
7835 _H<Package> package_;
7836 _H<UITableView, 2> table_;
7837 _H<UISwitch> subscribedSwitch_;
7838 _H<UISwitch> ignoredSwitch_;
7839 _H<UITableViewCell> subscribedCell_;
7840 _H<UITableViewCell> ignoredCell_;
7843 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7847 @implementation PackageSettingsController
7849 - (NSURL *) navigationURL {
7850 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
7853 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7854 if (package_ == nil)
7857 if ([package_ installed] == nil)
7863 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7864 if (package_ == nil)
7867 // both sections contain just one item right now.
7871 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7875 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7877 return UCLocalize("SHOW_ALL_CHANGES_EX");
7879 return UCLocalize("IGNORE_UPGRADES_EX");
7882 - (void) onSubscribed:(id)control {
7883 bool value([control isOn]);
7884 if (package_ == nil)
7886 if ([package_ setSubscribed:value])
7887 [delegate_ updateData];
7890 - (void) _updateIgnored {
7891 const char *package([name_ UTF8String]);
7892 bool on([ignoredSwitch_ isOn]);
7894 pid_t pid(ExecFork());
7896 FILE *dpkg(popen("dpkg --set-selections", "w"));
7897 fwrite(package, strlen(package), 1, dpkg);
7900 fwrite(" hold\n", 6, 1, dpkg);
7902 fwrite(" install\n", 9, 1, dpkg);
7910 - (void) onIgnored:(id)control {
7911 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7912 [invocation setTarget:self];
7913 [invocation setSelector:@selector(_updateIgnored)];
7915 [delegate_ reloadDataWithInvocation:invocation];
7918 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7919 if (package_ == nil)
7922 switch ([indexPath section]) {
7923 case 0: return subscribedCell_;
7924 case 1: return ignoredCell_;
7933 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
7934 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
7935 [self setView:view];
7937 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7938 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7939 [(UITableView *) table_ setDataSource:self];
7940 [table_ setDelegate:self];
7941 [view addSubview:table_];
7943 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7944 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7945 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7947 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7948 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7949 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7951 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7952 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7953 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7954 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7956 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7957 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7958 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7959 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7962 - (void) viewDidLoad {
7963 [super viewDidLoad];
7965 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7968 - (void) releaseSubviews {
7970 subscribedCell_ = nil;
7972 ignoredSwitch_ = nil;
7973 subscribedSwitch_ = nil;
7975 [super releaseSubviews];
7978 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7979 if ((self = [super init]) != nil) {
7980 database_ = database;
7985 - (void) reloadData {
7988 package_ = [database_ packageWithName:name_];
7990 if (package_ != nil) {
7991 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7992 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7993 } // XXX: what now, G?
7995 [table_ reloadData];
8001 /* Installed Controller {{{ */
8002 @interface InstalledController : FilteredPackageListController {
8006 - (id) initWithDatabase:(Database *)database;
8007 - (void) queueStatusDidChange;
8011 @implementation InstalledController
8013 - (NSURL *) referrerURL {
8014 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/installed/", UI_]];
8017 - (NSURL *) navigationURL {
8018 return [NSURL URLWithString:@"cydia://installed"];
8021 - (void) useRecent {
8024 @synchronized (self) {
8025 [self setFilter:[](Package *package) {
8026 return ![package uninstalled] && package->role_ < 7;
8029 [self setSorter:[](NSMutableArray *packages) {
8030 [packages radixSortUsingSelector:@selector(recent)];
8034 - (void) useFilter:(UISegmentedControl *)segmented {
8035 NSInteger selected([segmented selectedSegmentIndex]);
8037 return [self useRecent];
8038 bool simple(selected == 0);
8041 @synchronized (self) {
8042 [self setFilter:[=](Package *package) {
8043 return ![package uninstalled] && package->role_ <= (simple ? 1 : 3);
8046 [self setSorter:nullptr];
8049 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
8051 return [super sectionsForPackages:packages];
8053 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterLongStyle, kCFDateFormatterNoStyle));
8055 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
8056 Section *section(nil);
8059 for (size_t offset(0), count([packages count]); offset != count; ++offset) {
8060 Package *package([packages objectAtIndex:offset]);
8062 time_t upgraded([package upgraded]);
8063 if (upgraded < 1168364520)
8066 upgraded -= upgraded % (60 * 60 * 24);
8068 if (section == nil || upgraded != last) {
8073 continue; // XXX: name = UCLocalize("...");
8075 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:upgraded]);
8079 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
8080 [sections addObject:section];
8083 [section addToCount];
8086 CFRelease(formatter);
8090 - (id) initWithDatabase:(Database *)database {
8091 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED")]) != nil) {
8092 UISegmentedControl *segmented([[[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:UCLocalize("USER"), UCLocalize("EXPERT"), UCLocalize("RECENT"), nil]] autorelease]);
8093 [segmented setSelectedSegmentIndex:0];
8094 [segmented setSegmentedControlStyle:UISegmentedControlStyleBar];
8095 [[self navigationItem] setTitleView:segmented];
8097 [segmented addTarget:self action:@selector(modeChanged:) forEvents:UIControlEventValueChanged];
8098 [self useFilter:segmented];
8100 [self queueStatusDidChange];
8105 - (void) queueButtonClicked {
8110 - (void) queueStatusDidChange {
8113 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8114 initWithTitle:UCLocalize("QUEUE")
8115 style:UIBarButtonItemStyleDone
8117 action:@selector(queueButtonClicked)
8120 [[self navigationItem] setLeftBarButtonItem:nil];
8125 - (void) modeChanged:(UISegmentedControl *)segmented {
8126 [self useFilter:segmented];
8133 /* Source Cell {{{ */
8134 @interface SourceCell : CyteTableViewCell <
8135 CyteTableViewCellDelegate,
8138 _H<Source, 1> source_;
8141 _H<NSString> origin_;
8142 _H<NSString> label_;
8143 _H<UIActivityIndicatorView> indicator_;
8146 - (void) setSource:(Source *)source;
8147 - (void) setFetch:(NSNumber *)fetch;
8151 @implementation SourceCell
8153 - (void) _setImage:(NSArray *)data {
8154 if ([url_ isEqual:[data objectAtIndex:0]]) {
8155 icon_ = [data objectAtIndex:1];
8156 [content_ setNeedsDisplay];
8160 - (void) _setSource:(NSURL *) url {
8161 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8163 if (NSData *data = [NSURLConnection
8164 sendSynchronousRequest:[NSURLRequest
8166 cachePolicy:NSURLRequestUseProtocolCachePolicy
8170 returningResponse:NULL
8173 if (UIImage *image = [UIImage imageWithData:data])
8174 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
8179 - (void) setSource:(Source *)source {
8181 [source_ setDelegate:self];
8183 [self setFetch:[NSNumber numberWithBool:[source_ fetch]]];
8185 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
8187 origin_ = [source name];
8188 label_ = [source rooturi];
8190 [content_ setNeedsDisplay];
8192 url_ = [source iconURL];
8193 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
8196 - (void) setAllSource {
8198 [indicator_ stopAnimating];
8200 icon_ = [UIImage applicationImageNamed:@"folder.png"];
8201 origin_ = UCLocalize("ALL_SOURCES");
8202 label_ = UCLocalize("ALL_SOURCES_EX");
8203 [content_ setNeedsDisplay];
8206 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8207 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8208 UIView *content([self contentView]);
8209 CGRect bounds([content bounds]);
8211 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8212 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8213 [content_ setBackgroundColor:[UIColor whiteColor]];
8214 [content addSubview:content_];
8216 [content_ setDelegate:self];
8217 [content_ setOpaque:YES];
8219 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGraySmall] autorelease];
8220 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin];// | UIViewAutoresizingFlexibleBottomMargin];
8221 [content addSubview:indicator_];
8223 [[content_ layer] setContentsGravity:kCAGravityTopLeft];
8227 - (void) layoutSubviews {
8228 [super layoutSubviews];
8230 UIView *content([self contentView]);
8231 CGRect bounds([content bounds]);
8233 CGRect frame([indicator_ frame]);
8234 frame.origin.x = bounds.size.width - frame.size.width;
8235 frame.origin.y = Retina((bounds.size.height - frame.size.height) / 2);
8237 if (kCFCoreFoundationVersionNumber < 800)
8238 frame.origin.x -= 8;
8239 [indicator_ setFrame:frame];
8242 - (NSString *) accessibilityLabel {
8246 - (void) drawContentRect:(CGRect)rect {
8247 bool highlighted(highlighted_);
8248 float width(rect.size.width);
8252 rect.size = [(UIImage *) icon_ size];
8254 while (rect.size.width > 32 || rect.size.height > 32) {
8255 rect.size.width /= 2;
8256 rect.size.height /= 2;
8259 rect.origin.x = 26 - rect.size.width / 2;
8260 rect.origin.y = 26 - rect.size.height / 2;
8262 [icon_ drawInRect:Retina(rect)];
8265 if (highlighted && kCFCoreFoundationVersionNumber < 800)
8270 [origin_ drawAtPoint:CGPointMake(52, 8) forWidth:(width - 61) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
8274 [label_ drawAtPoint:CGPointMake(52, 29) forWidth:(width - 61) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
8277 - (void) setFetch:(NSNumber *)fetch {
8278 if ([fetch boolValue])
8279 [indicator_ startAnimating];
8281 [indicator_ stopAnimating];
8286 /* Sources Controller {{{ */
8287 @interface SourcesController : CyteViewController <
8288 UITableViewDataSource,
8291 _transient Database *database_;
8294 _H<UITableView, 2> list_;
8295 _H<NSMutableArray> sources_;
8299 _H<UIProgressHUD> hud_;
8302 NSURLConnection *trivial_bz2_;
8303 NSURLConnection *trivial_gz_;
8308 - (id) initWithDatabase:(Database *)database;
8309 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated;
8313 @implementation SourcesController
8315 - (void) _releaseConnection:(NSURLConnection *)connection {
8316 if (connection != nil) {
8317 [connection cancel];
8318 //[connection setDelegate:nil];
8319 [connection release];
8324 [self _releaseConnection:trivial_gz_];
8325 [self _releaseConnection:trivial_bz2_];
8330 - (NSURL *) navigationURL {
8331 return [NSURL URLWithString:@"cydia://sources"];
8334 - (void) viewDidAppear:(BOOL)animated {
8335 [super viewDidAppear:animated];
8336 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8339 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8343 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8345 return UCLocalize("INDIVIDUAL_SOURCES");
8349 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8352 case 1: return [sources_ count];
8357 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8358 @synchronized (database_) {
8359 if ([database_ era] != era_)
8361 if ([indexPath section] != 1)
8363 NSUInteger index([indexPath row]);
8364 if (index >= [sources_ count])
8366 return [sources_ objectAtIndex:index];
8369 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8370 static NSString *cellIdentifier = @"SourceCell";
8372 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8373 if (cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8374 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8376 Source *source([self sourceAtIndexPath:indexPath]);
8378 [cell setAllSource];
8380 [cell setSource:source];
8385 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8386 SectionsController *controller([[[SectionsController alloc]
8387 initWithDatabase:database_
8388 source:[self sourceAtIndexPath:indexPath]
8391 [controller setDelegate:delegate_];
8392 [[self navigationController] pushViewController:controller animated:YES];
8395 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8396 if ([indexPath section] != 1)
8398 Source *source = [self sourceAtIndexPath:indexPath];
8399 return [source record] != nil;
8402 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8403 _assert([indexPath section] == 1);
8404 if (editingStyle == UITableViewCellEditingStyleDelete) {
8405 Source *source = [self sourceAtIndexPath:indexPath];
8406 if (source == nil) return;
8408 [Sources_ removeObjectForKey:[source key]];
8411 [delegate_ _saveConfig];
8412 [delegate_ reloadDataWithInvocation:nil];
8416 - (void) tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath {
8417 [self updateButtonsForEditingStatusAnimated:YES];
8421 [delegate_ addTrivialSource:href_];
8424 [delegate_ syncData];
8427 - (NSString *) getWarning {
8428 NSString *href(href_);
8429 NSRange colon([href rangeOfString:@"://"]);
8430 if (colon.location != NSNotFound)
8431 href = [href substringFromIndex:(colon.location + 3)];
8432 href = [href stringByAddingPercentEscapes];
8433 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8435 NSURL *url([NSURL URLWithString:href]);
8437 NSStringEncoding encoding;
8438 NSError *error(nil);
8440 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8441 return [warning length] == 0 ? nil : warning;
8445 - (void) _endConnection:(NSURLConnection *)connection {
8446 // XXX: the memory management in this method is horribly awkward
8448 NSURLConnection **field = NULL;
8449 if (connection == trivial_bz2_)
8450 field = &trivial_bz2_;
8451 else if (connection == trivial_gz_)
8452 field = &trivial_gz_;
8453 _assert(field != NULL);
8454 [connection release];
8458 trivial_bz2_ == nil &&
8461 NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil);
8463 [delegate_ releaseNetworkActivityIndicator];
8465 [delegate_ removeProgressHUD:hud_];
8469 if (warning != nil) {
8470 UIAlertView *alert = [[[UIAlertView alloc]
8471 initWithTitle:UCLocalize("SOURCE_WARNING")
8474 cancelButtonTitle:UCLocalize("CANCEL")
8476 UCLocalize("ADD_ANYWAY"),
8480 [alert setContext:@"warning"];
8481 [alert setNumberOfRows:1];
8484 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
8490 } else if (error_ != nil) {
8491 UIAlertView *alert = [[[UIAlertView alloc]
8492 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8493 message:[error_ localizedDescription]
8495 cancelButtonTitle:UCLocalize("OK")
8496 otherButtonTitles:nil
8499 [alert setContext:@"urlerror"];
8504 UIAlertView *alert = [[[UIAlertView alloc]
8505 initWithTitle:UCLocalize("NOT_REPOSITORY")
8506 message:UCLocalize("NOT_REPOSITORY_EX")
8508 cancelButtonTitle:UCLocalize("OK")
8509 otherButtonTitles:nil
8512 [alert setContext:@"trivial"];
8522 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8523 switch ([response statusCode]) {
8529 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8530 lprintf("connection:\"%s\" didFailWithError:\"%s\"\n", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8532 [self _endConnection:connection];
8535 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8536 [self _endConnection:connection];
8539 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8540 NSURL *url([NSURL URLWithString:href]);
8542 NSMutableURLRequest *request = [NSMutableURLRequest
8544 cachePolicy:NSURLRequestUseProtocolCachePolicy
8548 [request setHTTPMethod:method];
8550 if (Machine_ != NULL)
8551 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8553 if (UniqueID_ != nil)
8554 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8556 if ([url isCydiaSecure]) {
8557 if (UniqueID_ != nil)
8558 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
8561 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8564 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8565 NSString *context([alert context]);
8567 if ([context isEqualToString:@"source"]) {
8570 NSString *href = [[alert textField] text];
8572 static Pcre href_r("^http(s?)://[^# ]*$");
8573 if (!href_r(href)) {
8574 UIAlertView *alert = [[[UIAlertView alloc]
8575 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("INVALID_URL")]
8576 message:UCLocalize("INVALID_URL_EX")
8578 cancelButtonTitle:UCLocalize("OK")
8579 otherButtonTitles:nil
8582 [alert setContext:@"badurl"];
8588 if (![href hasSuffix:@"/"])
8589 href_ = [href stringByAppendingString:@"/"];
8593 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8594 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8598 // XXX: this is stupid
8599 hud_ = [delegate_ addProgressHUD];
8600 [hud_ setText:UCLocalize("VERIFYING_URL")];
8601 [delegate_ retainNetworkActivityIndicator];
8610 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8611 } else if ([context isEqualToString:@"trivial"])
8612 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8613 else if ([context isEqualToString:@"urlerror"])
8614 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8615 else if ([context isEqualToString:@"warning"]) {
8618 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
8627 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8631 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated {
8632 BOOL editing([list_ isEditing]);
8635 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8636 initWithTitle:UCLocalize("ADD")
8637 style:UIBarButtonItemStylePlain
8639 action:@selector(addButtonClicked)
8640 ] autorelease] animated:animated];
8641 else if ([delegate_ updating])
8642 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8643 initWithTitle:UCLocalize("CANCEL")
8644 style:UIBarButtonItemStyleDone
8646 action:@selector(cancelButtonClicked)
8647 ] autorelease] animated:animated];
8649 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8650 initWithTitle:UCLocalize("REFRESH")
8651 style:UIBarButtonItemStylePlain
8653 action:@selector(refreshButtonClicked)
8654 ] autorelease] animated:animated];
8656 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8657 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8658 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8660 action:@selector(editButtonClicked)
8661 ] autorelease] animated:animated];
8665 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease];
8666 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8667 [list_ setRowHeight:53];
8668 [(UITableView *) list_ setDataSource:self];
8669 [list_ setDelegate:self];
8670 [self setView:list_];
8673 - (void) viewDidLoad {
8674 [super viewDidLoad];
8676 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8677 [self updateButtonsForEditingStatusAnimated:NO];
8680 - (void) viewWillAppear:(BOOL)animated {
8681 [super viewWillAppear:animated];
8683 [list_ setEditing:NO];
8684 [self updateButtonsForEditingStatusAnimated:NO];
8687 - (void) releaseSubviews {
8692 [super releaseSubviews];
8695 - (id) initWithDatabase:(Database *)database {
8696 if ((self = [super init]) != nil) {
8697 database_ = database;
8701 - (void) reloadData {
8703 [self updateButtonsForEditingStatusAnimated:YES];
8705 @synchronized (database_) {
8706 era_ = [database_ era];
8708 sources_ = [NSMutableArray arrayWithCapacity:16];
8709 [sources_ addObjectsFromArray:[database_ sources]];
8711 [sources_ sortUsingSelector:@selector(compareByName:)];
8714 int count([sources_ count]);
8716 for (int i = 0; i != count; i++) {
8717 if ([[sources_ objectAtIndex:i] record] == nil)
8725 - (void) showAddSourcePrompt {
8726 UIAlertView *alert = [[[UIAlertView alloc]
8727 initWithTitle:UCLocalize("ENTER_APT_URL")
8730 cancelButtonTitle:UCLocalize("CANCEL")
8732 UCLocalize("ADD_SOURCE"),
8736 [alert setContext:@"source"];
8738 [alert setNumberOfRows:1];
8739 [alert addTextFieldWithValue:@"http://" label:@""];
8741 UITextInputTraits *traits = [[alert textField] textInputTraits];
8742 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8743 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8744 [traits setKeyboardType:UIKeyboardTypeURL];
8745 // XXX: UIReturnKeyDone
8746 [traits setReturnKeyType:UIReturnKeyNext];
8751 - (void) addButtonClicked {
8752 [self showAddSourcePrompt];
8755 - (void) refreshButtonClicked {
8756 if ([delegate_ requestUpdate])
8757 [self updateButtonsForEditingStatusAnimated:YES];
8760 - (void) cancelButtonClicked {
8761 [delegate_ cancelUpdate];
8764 - (void) editButtonClicked {
8765 [list_ setEditing:![list_ isEditing] animated:YES];
8766 [self updateButtonsForEditingStatusAnimated:YES];
8772 /* Stash Controller {{{ */
8773 @interface StashController : CyteViewController {
8774 _H<UIActivityIndicatorView> spinner_;
8775 _H<UILabel> status_;
8776 _H<UILabel> caption_;
8781 @implementation StashController
8784 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8785 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8786 [self setView:view];
8788 [view setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8790 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8791 CGRect spinrect = [spinner_ frame];
8792 spinrect.origin.x = Retina([[self view] frame].size.width / 2 - spinrect.size.width / 2);
8793 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8794 [spinner_ setFrame:spinrect];
8795 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8796 [view addSubview:spinner_];
8797 [spinner_ startAnimating];
8800 captrect.size.width = [[self view] frame].size.width;
8801 captrect.size.height = 40.0f;
8802 captrect.origin.x = 0;
8803 captrect.origin.y = Retina([[self view] frame].size.height / 2 - captrect.size.height * 2);
8804 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8805 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8806 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8807 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8808 [caption_ setTextColor:[UIColor whiteColor]];
8809 [caption_ setBackgroundColor:[UIColor clearColor]];
8810 [caption_ setShadowColor:[UIColor blackColor]];
8811 [caption_ setTextAlignment:NSTextAlignmentCenter];
8812 [view addSubview:caption_];
8815 statusrect.size.width = [[self view] frame].size.width;
8816 statusrect.size.height = 30.0f;
8817 statusrect.origin.x = 0;
8818 statusrect.origin.y = Retina([[self view] frame].size.height / 2 - statusrect.size.height);
8819 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8820 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8821 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8822 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8823 [status_ setTextColor:[UIColor whiteColor]];
8824 [status_ setBackgroundColor:[UIColor clearColor]];
8825 [status_ setShadowColor:[UIColor blackColor]];
8826 [status_ setTextAlignment:NSTextAlignmentCenter];
8827 [view addSubview:status_];
8830 - (void) releaseSubviews {
8835 [super releaseSubviews];
8841 @interface CYURLCache : SDURLCache {
8846 @implementation CYURLCache
8848 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8851 else if ([event isEqualToString:@"no-cache"])
8853 else if ([event isEqualToString:@"store"])
8855 else if ([event isEqualToString:@"invalid"])
8857 else if ([event isEqualToString:@"memory"])
8859 else if ([event isEqualToString:@"disk"])
8861 else if ([event isEqualToString:@"miss"])
8864 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8868 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
8869 if (NSURLResponse *response = [cached response])
8870 if (NSString *mime = [response MIMEType])
8871 if ([mime isEqualToString:@"text/cache-manifest"]) {
8872 NSURL *url([response URL]);
8875 NSLog(@"###: %@", [url absoluteString]);
8878 @synchronized (HostConfig_) {
8879 [CachedURLs_ addObject:url];
8883 [super storeCachedResponse:cached forRequest:request];
8888 @interface Cydia : UIApplication <
8889 ConfirmationControllerDelegate,
8893 _H<UIWindow> window_;
8894 _H<CydiaTabBarController> tabbar_;
8895 _H<CyteTabBarController> emulated_;
8897 _H<NSMutableArray> essential_;
8898 _H<NSMutableArray> broken_;
8900 Database *database_;
8902 _H<NSURL> starturl_;
8907 _H<StashController> stash_;
8916 @implementation Cydia
8918 - (void) lockSuspend {
8919 if (locked_++ == 0) {
8920 if ($SBSSetInterceptsMenuButtonForever != NULL)
8921 (*$SBSSetInterceptsMenuButtonForever)(true);
8923 [self setIdleTimerDisabled:YES];
8927 - (void) unlockSuspend {
8928 if (--locked_ == 0) {
8929 [self setIdleTimerDisabled:NO];
8931 if ($SBSSetInterceptsMenuButtonForever != NULL)
8932 (*$SBSSetInterceptsMenuButtonForever)(false);
8936 - (void) beginUpdate {
8937 [tabbar_ beginUpdate];
8940 - (void) cancelUpdate {
8941 [tabbar_ cancelUpdate];
8944 - (bool) requestUpdate {
8945 if (IsReachable("cydia.saurik.com")) {
8949 UIAlertView *alert = [[[UIAlertView alloc]
8950 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("REFRESH")]
8951 message:@"Host Unreachable" // XXX: Localize
8953 cancelButtonTitle:UCLocalize("OK")
8954 otherButtonTitles:nil
8957 [alert setContext:@"norefresh"];
8965 return [tabbar_ updating];
8969 if ([broken_ count] != 0) {
8970 int count = [broken_ count];
8972 UIAlertView *alert = [[[UIAlertView alloc]
8973 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8974 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8976 cancelButtonTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("FORCIBLY_CLEAR"), UCLocalize("UNSAFE")]
8978 UCLocalize("TEMPORARY_IGNORE"),
8982 [alert setContext:@"fixhalf"];
8983 [alert setNumberOfRows:2];
8985 } else if (!Ignored_ && [essential_ count] != 0) {
8986 int count = [essential_ count];
8988 UIAlertView *alert = [[[UIAlertView alloc]
8989 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8990 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8992 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8994 UCLocalize("UPGRADE_ESSENTIAL"),
8995 UCLocalize("COMPLETE_UPGRADE"),
8999 [alert setContext:@"upgrade"];
9004 - (void) returnToCydia {
9008 - (void) _saveConfig {
9009 @synchronized (database_) {
9016 NSString *error(nil);
9018 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
9020 NSError *error(nil);
9021 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
9022 NSLog(@"failure to save metadata data: %@", error);
9027 NSLog(@"failure to serialize metadata: %@", error);
9031 CydiaWriteSources();
9034 // Navigation controller for the queuing badge.
9035 - (UINavigationController *) queueNavigationController {
9036 NSArray *controllers = [tabbar_ viewControllers];
9037 return [controllers objectAtIndex:3];
9040 - (void) unloadData {
9041 [tabbar_ unloadData];
9044 - (void) _updateData {
9048 UINavigationController *navigation = [self queueNavigationController];
9050 id queuedelegate = nil;
9051 if ([[navigation viewControllers] count] > 0)
9052 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9054 [queuedelegate queueStatusDidChange];
9055 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9058 - (void) _refreshIfPossible:(NSDate *)update {
9059 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9061 bool recently = false;
9062 if (update != nil) {
9063 NSTimeInterval interval([update timeIntervalSinceNow]);
9064 if (interval <= 0 && interval > -(15*60))
9068 // Don't automatic refresh if:
9069 // - We already refreshed recently.
9070 // - We already auto-refreshed this launch.
9071 // - Auto-refresh is disabled.
9072 // - Cydia's server is not reachable
9073 if (recently || loaded_ || ManualRefresh || !IsReachable("cydia.saurik.com")) {
9074 // If we are cancelling, we need to make sure it knows it's already loaded.
9077 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9079 // We are going to load, so remember that.
9082 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
9088 - (void) refreshIfPossible {
9089 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
9092 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9093 _profile(reloadDataWithInvocation)
9094 @synchronized (self) {
9095 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9097 [hud setText:UCLocalize("RELOADING_DATA")];
9099 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9103 [essential_ removeAllObjects];
9104 [broken_ removeAllObjects];
9106 _profile(reloadDataWithInvocation$Essential)
9107 NSArray *packages([database_ packages]);
9108 for (Package *package in packages) {
9110 [broken_ addObject:package];
9111 if ([package upgradableAndEssential:YES] && ![package ignored]) {
9112 if ([package essential] && [package installed] != nil)
9113 [essential_ addObject:package];
9119 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9122 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9123 [changesItem setBadgeValue:badge];
9124 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9125 [self setApplicationIconBadgeNumber:changes];
9128 [changesItem setBadgeValue:nil];
9129 [changesItem setAnimatedBadge:NO];
9130 [self setApplicationIconBadgeNumber:0];
9136 [self removeProgressHUD:hud];
9143 - (void) updateData {
9147 - (void) updateDataAndLoad {
9149 if ([database_ progressDelegate] == nil)
9155 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9158 - (void) disemulate {
9159 if (emulated_ == nil)
9162 if ([window_ respondsToSelector:@selector(setRootViewController:)])
9163 [window_ setRootViewController:tabbar_];
9165 [window_ addSubview:[tabbar_ view]];
9166 [[emulated_ view] removeFromSuperview];
9170 [window_ setUserInteractionEnabled:YES];
9173 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9174 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9176 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9178 UIViewController *parent;
9179 if (emulated_ == nil)
9188 [parent presentModalViewController:navigation animated:YES];
9191 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9192 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9194 if (navigation != nil)
9195 [navigation pushViewController:progress animated:YES];
9197 [self presentModalViewController:progress force:YES];
9199 [progress invoke:invocation withTitle:title];
9203 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9204 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9207 - (void) repairWithInvocation:(NSInvocation *)invocation {
9209 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9213 - (void) repairWithSelector:(SEL)selector {
9214 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9217 - (void) reloadData {
9218 [self reloadDataWithInvocation:nil];
9219 if ([database_ progressDelegate] == nil)
9225 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9228 - (void) addSource:(NSDictionary *) source {
9229 CydiaAddSource(source);
9232 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9233 CydiaAddSource(href, distribution, sections);
9236 - (void) addTrivialSource:(NSString *)href {
9237 CydiaAddSource(href, @"./");
9240 - (void) updateValues {
9245 pkgProblemResolver *resolver = [database_ resolver];
9247 resolver->InstallProtect();
9248 if (!resolver->Resolve(true))
9253 // XXX: this is a really crappy way of doing this.
9254 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9255 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9256 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9257 if ([tabbar_ updating])
9258 [tabbar_ cancelUpdate];
9260 if (![database_ prepare])
9263 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9264 [page setDelegate:self];
9265 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9268 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9269 [tabbar_ presentModalViewController:confirm_ animated:YES];
9275 @synchronized (self) {
9280 - (void) clearPackage:(Package *)package {
9281 @synchronized (self) {
9288 - (void) installPackages:(NSArray *)packages {
9289 @synchronized (self) {
9290 for (Package *package in packages)
9297 - (void) installPackage:(Package *)package {
9298 @synchronized (self) {
9305 - (void) removePackage:(Package *)package {
9306 @synchronized (self) {
9313 - (void) distUpgrade {
9314 @synchronized (self) {
9315 if (![database_ upgrade])
9323 system("su -c /usr/bin/uicache mobile");
9328 UIProgressHUD *hud([self addProgressHUD]);
9329 [hud setText:UCLocalize("LOADING")];
9330 [self yieldToSelector:@selector(_uicache)];
9331 [self removeProgressHUD:hud];
9335 [database_ perform];
9336 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9337 [self performSelectorOnMainThread:@selector(uicache) withObject:nil waitUntilDone:YES];
9340 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9343 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9344 [self unlockSuspend];
9347 - (void) retainNetworkActivityIndicator {
9348 if (activity_++ == 0)
9349 [self setNetworkActivityIndicatorVisible:YES];
9352 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9356 - (void) releaseNetworkActivityIndicator {
9357 if (--activity_ == 0)
9358 [self setNetworkActivityIndicatorVisible:NO];
9361 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9366 - (void) cancelAndClear:(bool)clear {
9367 @synchronized (self) {
9379 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9380 NSString *context([alert context]);
9382 if ([context isEqualToString:@"conffile"]) {
9383 FILE *input = [database_ input];
9384 if (button == [alert cancelButtonIndex])
9385 fprintf(input, "N\n");
9386 else if (button == [alert firstOtherButtonIndex])
9387 fprintf(input, "Y\n");
9390 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9391 } else if ([context isEqualToString:@"fixhalf"]) {
9392 if (button == [alert cancelButtonIndex]) {
9393 @synchronized (self) {
9394 for (Package *broken in (id) broken_) {
9397 NSString *id = [broken id];
9398 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9399 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9400 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9401 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9407 } else if (button == [alert firstOtherButtonIndex]) {
9408 [broken_ removeAllObjects];
9412 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9413 } else if ([context isEqualToString:@"upgrade"]) {
9414 if (button == [alert firstOtherButtonIndex]) {
9415 @synchronized (self) {
9416 for (Package *essential in (id) essential_)
9417 [essential install];
9422 } else if (button == [alert firstOtherButtonIndex] + 1) {
9424 } else if (button == [alert cancelButtonIndex]) {
9428 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9432 - (void) system:(NSString *)command {
9433 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9436 system([command UTF8String]);
9442 - (void) applicationWillSuspend {
9444 [super applicationWillSuspend];
9447 - (BOOL) isSafeToSuspend {
9450 NSLog(@"isSafeToSuspend: locked_ != 0");
9455 if ([tabbar_ modalViewController] != nil)
9458 // Use external process status API internally.
9459 // This is probably a really bad idea.
9460 // XXX: what is the point of this? does this solve anything at all?
9461 uint64_t status = 0;
9463 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9464 notify_get_state(notify_token, &status);
9465 notify_cancel(notify_token);
9470 NSLog(@"isSafeToSuspend: status != 0");
9476 NSLog(@"isSafeToSuspend: -> true");
9481 - (void) applicationSuspend:(__GSEvent *)event {
9482 if ([self isSafeToSuspend])
9483 [super applicationSuspend:event];
9486 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9487 if ([self isSafeToSuspend])
9488 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9491 - (void) _setSuspended:(BOOL)value {
9492 if ([self isSafeToSuspend])
9493 [super _setSuspended:value];
9496 - (UIProgressHUD *) addProgressHUD {
9497 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9498 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9500 [window_ setUserInteractionEnabled:NO];
9502 UIViewController *target(tabbar_);
9503 if (UIViewController *modal = [target modalViewController])
9506 [hud showInView:[target view]];
9512 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9513 [self unlockSuspend];
9515 [hud removeFromSuperview];
9516 [window_ setUserInteractionEnabled:YES];
9519 - (CyteViewController *) pageForPackage:(NSString *)name withReferrer:(NSString *)referrer {
9520 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name withReferrer:referrer] autorelease];
9523 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external withReferrer:(NSString *)referrer {
9524 NSString *scheme([[url scheme] lowercaseString]);
9525 if ([[url absoluteString] length] <= [scheme length] + 3)
9527 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9528 NSArray *components([path componentsSeparatedByString:@"/"]);
9530 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"]) {
9531 CyteViewController *controller([self pageForPackage:[components objectAtIndex:1] withReferrer:referrer]);
9532 if (controller != nil)
9533 [controller setDelegate:self];
9537 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9540 NSString *base([components objectAtIndex:0]);
9542 CyteViewController *controller = nil;
9544 if ([base isEqualToString:@"url"]) {
9545 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9546 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9547 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9548 } else if (!external && [components count] == 1) {
9549 if ([base isEqualToString:@"sources"]) {
9550 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9553 if ([base isEqualToString:@"home"]) {
9554 controller = [[[HomeController alloc] init] autorelease];
9557 if ([base isEqualToString:@"sections"]) {
9558 controller = [[[SectionsController alloc] initWithDatabase:database_ source:nil] autorelease];
9561 if ([base isEqualToString:@"search"]) {
9562 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9565 if ([base isEqualToString:@"changes"]) {
9566 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9569 if ([base isEqualToString:@"installed"]) {
9570 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9572 } else if ([components count] == 2) {
9573 NSString *argument = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9575 if ([base isEqualToString:@"package"]) {
9576 controller = [self pageForPackage:argument withReferrer:referrer];
9579 if (!external && [base isEqualToString:@"search"]) {
9580 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9583 if (!external && [base isEqualToString:@"sections"]) {
9584 if ([argument isEqualToString:@"all"] || [argument isEqualToString:@"*"])
9586 controller = [[[SectionController alloc] initWithDatabase:database_ source:nil section:argument] autorelease];
9589 if (!external && [base isEqualToString:@"sources"]) {
9590 if ([argument isEqualToString:@"add"]) {
9591 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9592 [(SourcesController *)controller showAddSourcePrompt];
9594 Source *source([database_ sourceWithKey:argument]);
9595 controller = [[[SectionsController alloc] initWithDatabase:database_ source:source] autorelease];
9599 if (!external && [base isEqualToString:@"launch"]) {
9600 [self launchApplicationWithIdentifier:argument suspended:NO];
9603 } else if (!external && [components count] == 3) {
9604 NSString *arg1 = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9605 NSString *arg2 = [[components objectAtIndex:2] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9607 if ([base isEqualToString:@"package"]) {
9608 if ([arg2 isEqualToString:@"settings"]) {
9609 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9610 } else if ([arg2 isEqualToString:@"files"]) {
9611 if (Package *package = [database_ packageWithName:arg1]) {
9612 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9613 [(FileTable *)controller setPackage:package];
9618 if ([base isEqualToString:@"sections"]) {
9619 Source *source([arg1 isEqualToString:@"*"] ? nil : [database_ sourceWithKey:arg1]);
9620 NSString *section([arg2 isEqualToString:@"*"] ? nil : arg2);
9621 controller = [[[SectionController alloc] initWithDatabase:database_ source:source section:section] autorelease];
9625 [controller setDelegate:self];
9629 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9630 CyteViewController *page([self pageForURL:url forExternal:external withReferrer:nil]);
9633 [tabbar_ setUnselectedViewController:page];
9638 - (void) applicationOpenURL:(NSURL *)url {
9639 [super applicationOpenURL:url];
9644 [self openCydiaURL:url forExternal:YES];
9647 - (void) applicationWillResignActive:(UIApplication *)application {
9648 // Stop refreshing if you get a phone call or lock the device.
9649 if ([tabbar_ updating])
9650 [tabbar_ cancelUpdate];
9652 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9653 [super applicationWillResignActive:application];
9656 - (void) saveState {
9657 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9658 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9659 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9665 - (void) applicationWillTerminate:(UIApplication *)application {
9669 - (void) setConfigurationData:(NSString *)data {
9670 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
9672 if (!conffile_r(data)) {
9673 lprintf("E:invalid conffile\n");
9677 NSString *ofile = conffile_r[1];
9678 //NSString *nfile = conffile_r[2];
9680 UIAlertView *alert = [[[UIAlertView alloc]
9681 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9682 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9684 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9686 UCLocalize("ACCEPT_NEW_COPY"),
9687 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9691 [alert setContext:@"conffile"];
9692 [alert setNumberOfRows:2];
9696 - (void) addStashController {
9698 stash_ = [[[StashController alloc] init] autorelease];
9699 [window_ addSubview:[stash_ view]];
9702 - (void) removeStashController {
9703 [[stash_ view] removeFromSuperview];
9705 [self unlockSuspend];
9709 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9710 UpdateExternalStatus(1);
9711 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
9712 UpdateExternalStatus(0);
9714 [self removeStashController];
9716 pid_t pid(ExecFork());
9718 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9719 perror("launchctl stop");
9725 - (void) setupViewControllers {
9726 tabbar_ = [[[CydiaTabBarController alloc] initWithDatabase:database_] autorelease];
9728 NSMutableArray *items;
9729 if (kCFCoreFoundationVersionNumber < 800) {
9730 items = [NSMutableArray arrayWithObjects:
9731 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
9732 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
9733 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
9734 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease],
9735 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
9738 items = [NSMutableArray arrayWithObjects:
9739 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home7.png"] selectedImage:[UIImage applicationImageNamed:@"home7s.png"]] autorelease],
9740 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"install7.png"] selectedImage:[UIImage applicationImageNamed:@"install7s.png"]] autorelease],
9741 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes7.png"] selectedImage:[UIImage applicationImageNamed:@"changes7s.png"]] autorelease],
9742 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage7.png"] selectedImage:[UIImage applicationImageNamed:@"manage7s.png"]] autorelease],
9743 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search7.png"] selectedImage:[UIImage applicationImageNamed:@"search7s.png"]] autorelease],
9747 NSMutableArray *controllers([NSMutableArray array]);
9748 for (UITabBarItem *item in items) {
9749 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9750 [controller setTabBarItem:item];
9751 [controllers addObject:controller];
9753 [tabbar_ setViewControllers:controllers];
9755 [tabbar_ setUpdateDelegate:self];
9758 - (void) _sendMemoryWarningNotification {
9759 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: maybe 4_0?
9760 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationMemoryWarningNotification" object:[UIApplication sharedApplication]];
9762 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
9765 - (void) _sendMemoryWarningNotifications {
9767 [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO];
9773 - (void) applicationDidReceiveMemoryWarning:(UIApplication *)application {
9775 [[NSURLCache sharedURLCache] removeAllCachedResponses];
9778 - (void) applicationDidFinishLaunching:(id)unused {
9779 //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil];
9782 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9783 [self setApplicationSupportsShakeToEdit:NO];
9785 @synchronized (HostConfig_) {
9786 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9789 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9790 initWithMemoryCapacity:524288
9791 diskCapacity:10485760
9792 diskPath:[NSString stringWithFormat:@"%@/SDURLCache", Cache_]
9795 [CydiaWebViewController _initialize];
9797 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9799 // this would disallow http{,s} URLs from accessing this data
9800 //[WebView registerURLSchemeAsLocal:@"cydia"];
9802 Font12_ = [UIFont systemFontOfSize:12];
9803 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9804 Font14_ = [UIFont systemFontOfSize:14];
9805 Font18_ = [UIFont systemFontOfSize:18];
9806 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9807 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9809 essential_ = [NSMutableArray arrayWithCapacity:4];
9810 broken_ = [NSMutableArray arrayWithCapacity:4];
9812 // XXX: I really need this thing... like, seriously... I'm sorry
9813 [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] reloadData];
9815 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9816 [window_ orderFront:self];
9817 [window_ makeKey:self];
9818 [window_ setHidden:NO];
9821 [self addStashController];
9822 // XXX: this would be much cleaner as a yieldToSelector:
9823 // that way the removeStashController could happen right here inline
9824 // we also could no longer require the useless stash_ field anymore
9825 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9830 int error(stat("/", &root));
9831 _assert(error != -1);
9833 #define Stash_(path) do { \
9834 struct stat folder; \
9835 int error(lstat((path), &folder)); \
9836 if (error != -1 && ( \
9837 folder.st_dev == root.st_dev && \
9838 S_ISDIR(folder.st_mode) \
9839 ) || error == -1 && ( \
9840 errno == ENOENT || \
9845 Stash_("/Applications");
9846 Stash_("/Library/Ringtones");
9847 Stash_("/Library/Wallpaper");
9848 //Stash_("/usr/bin");
9849 Stash_("/usr/include");
9850 Stash_("/usr/lib/pam");
9851 Stash_("/usr/share");
9852 //Stash_("/var/lib");
9854 database_ = [Database sharedInstance];
9855 [database_ setDelegate:self];
9857 [window_ setUserInteractionEnabled:NO];
9858 [self setupViewControllers];
9860 CydiaLoadingViewController *loading([[[CydiaLoadingViewController alloc] init] autorelease]);
9861 UINavigationController *navigation([[[UINavigationController alloc] init] autorelease]);
9862 [navigation setViewControllers:[NSArray arrayWithObject:loading]];
9864 emulated_ = [[[CyteTabBarController alloc] init] autorelease];
9865 [emulated_ setViewControllers:[NSArray arrayWithObject:navigation]];
9866 [emulated_ setSelectedIndex:0];
9867 [emulated_ concealTabBarSelection];
9869 if ([window_ respondsToSelector:@selector(setRootViewController:)])
9870 [window_ setRootViewController:emulated_];
9872 [window_ addSubview:[emulated_ view]];
9874 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9878 - (NSArray *) defaultStartPages {
9879 NSMutableArray *standard = [NSMutableArray array];
9880 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9881 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9882 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9883 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9884 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9890 if ([emulated_ modalViewController] != nil)
9891 [emulated_ dismissModalViewControllerAnimated:YES];
9892 [window_ setUserInteractionEnabled:NO];
9894 [self reloadDataWithInvocation:nil];
9895 [self refreshIfPossible];
9898 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9899 NSArray *saved = [[[Metadata_ objectForKey:@"InterfaceState"] mutableCopy] autorelease];
9900 int standardIndex = 0;
9901 NSArray *standard = [self defaultStartPages];
9908 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9909 if (valid && closed != nil) {
9910 NSTimeInterval interval([closed timeIntervalSinceNow]);
9911 // XXX: Is 30 minutes the optimal time here?
9912 if (interval <= -(30*60))
9916 if (valid && [saved count] != [standard count])
9920 for (unsigned int i = 0; i < [standard count]; i++) {
9921 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9922 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9923 // but it's good enough for now.
9924 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9931 NSArray *items = nil;
9933 [tabbar_ setSelectedIndex:savedIndex];
9936 [tabbar_ setSelectedIndex:standardIndex];
9940 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9941 NSArray *stack = [items objectAtIndex:tab];
9942 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9943 NSMutableArray *current = [NSMutableArray array];
9945 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9946 NSString *addr = [stack objectAtIndex:nav];
9947 NSURL *url = [NSURL URLWithString:addr];
9948 CyteViewController *page = [self pageForURL:url forExternal:NO withReferrer:nil];
9950 [current addObject:page];
9953 [navigation setViewControllers:current];
9956 // (Try to) show the startup URL.
9957 if (starturl_ != nil) {
9958 [self openCydiaURL:starturl_ forExternal:YES];
9963 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9964 if (item != nil && IsWildcat_) {
9965 [sheet showFromBarButtonItem:item animated:YES];
9967 [sheet showInView:window_];
9971 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9972 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9973 [progress setTitle:task];
9974 [progress addProgressEvent:event];
9977 - (void) addProgressEventForTask:(NSArray *)data {
9978 CydiaProgressEvent *event([data objectAtIndex:0]);
9979 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9980 [self addProgressEvent:event forTask:task];
9983 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9984 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9990 id Alloc_(id self, SEL selector) {
9991 id object = alloc_(self, selector);
9992 lprintf("[%s]A-%p\n", self->isa->name, object);
9997 id Dealloc_(id self, SEL selector) {
9998 id object = dealloc_(self, selector);
9999 lprintf("[%s]D-%p\n", self->isa->name, object);
10003 static NSSet *MobilizedFiles_;
10005 static NSURL *MobilizeURL(NSURL *url) {
10006 NSString *path([url path]);
10007 if ([path hasPrefix:@"/var/root/"]) {
10008 NSString *file([path substringFromIndex:10]);
10009 if ([MobilizedFiles_ containsObject:file])
10010 url = [NSURL fileURLWithPath:[@"/var/mobile/" stringByAppendingString:file] isDirectory:NO];
10016 Class $CFXPreferencesPropertyListSource;
10017 @class CFXPreferencesPropertyListSource;
10019 MSHook(BOOL, CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, CFXPreferencesPropertyListSource *self, SEL _cmd) {
10020 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
10021 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10023 url = MobilizeURL(url);
10025 value = _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(self, _cmd);
10026 //NSLog(@"CFX %@ %s", [url absoluteString], value ? "YES" : "NO");
10035 MSHook(void *, CFXPreferencesPropertyListSource$createPlistFromDisk, CFXPreferencesPropertyListSource *self, SEL _cmd) {
10036 NSURL *&url(MSHookIvar<NSURL *>(self, "_url")), *old(url);
10037 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10039 url = MobilizeURL(url);
10040 void *value; @try {
10041 value = _CFXPreferencesPropertyListSource$createPlistFromDisk(self, _cmd);
10042 //NSLog(@"CFX %@ %@", [url absoluteString], value);
10051 Class $NSURLConnection;
10053 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
10054 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
10056 NSURL *url([copy URL]);
10058 NSString *host([url host]);
10059 NSString *scheme([[url scheme] lowercaseString]);
10061 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
10063 @synchronized (HostConfig_) {
10064 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
10065 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
10066 [copy setHTTPShouldUsePipelining:YES];
10068 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
10069 if ([control isEqualToString:@"max-age=0"])
10070 if ([CachedURLs_ containsObject:url]) {
10072 NSLog(@"~~~: %@", url);
10075 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
10077 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
10078 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
10079 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
10083 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
10089 static CGSize $WAKWindow$screenSize(WAKWindow *self, SEL _cmd) {
10090 CGSize size([[UIScreen mainScreen] bounds].size);
10091 /*if ([$WAKWindow respondsToSelector:@selector(hasLandscapeOrientation)])
10092 if ([$WAKWindow hasLandscapeOrientation])
10093 std::swap(size.width, size.height);*/
10097 Class $NSUserDefaults;
10099 MSHook(id, NSUserDefaults$objectForKey$, NSUserDefaults *self, SEL _cmd, NSString *key) {
10100 if ([key respondsToSelector:@selector(isEqualToString:)] && [key isEqualToString:@"WebKitLocalStorageDatabasePathPreferenceKey"])
10101 return [NSString stringWithFormat:@"%@/LocalStorage", Cache_];
10102 return _NSUserDefaults$objectForKey$(self, _cmd, key);
10105 int main(int argc, char *argv[]) {
10106 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10110 UpdateExternalStatus(0);
10112 UIScreen *screen([UIScreen mainScreen]);
10113 if ([screen respondsToSelector:@selector(scale)])
10114 ScreenScale_ = [screen scale];
10118 UIDevice *device([UIDevice currentDevice]);
10119 if ([device respondsToSelector:@selector(userInterfaceIdiom)]) {
10120 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10121 if (idiom == UIUserInterfaceIdiomPad)
10125 Idiom_ = IsWildcat_ ? @"ipad" : @"iphone";
10127 Pcre pattern("^([0-9]+\\.[0-9]+)");
10129 if (pattern([device systemVersion]))
10130 Firmware_ = pattern[1];
10131 if (pattern(Cydia_))
10132 Major_ = pattern[1];
10134 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
10136 HostConfig_ = [[[NSObject alloc] init] autorelease];
10137 @synchronized (HostConfig_) {
10138 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10139 TokenHosts_ = [NSMutableSet setWithCapacity:4];
10140 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
10141 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
10142 CachedURLs_ = [NSMutableSet setWithCapacity:32];
10145 NSString *ui(@"ui/ios");
10147 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
10148 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"/%@", Major_]];
10149 UI_ = CydiaURL(ui);
10151 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10153 MobilizedFiles_ = [NSMutableSet setWithObjects:
10154 @"Library/Preferences/.GlobalPreferences.plist",
10155 @"Library/Preferences/com.apple.Accessibility.plist",
10156 @"Library/Preferences/com.apple.preferences.sounds.plist",
10159 /* Library Hacks {{{ */
10160 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10162 $WAKWindow = objc_getClass("WAKWindow");
10163 if ($WAKWindow != NULL)
10164 if (Method method = class_getInstanceMethod($WAKWindow, @selector(screenSize)))
10165 method_setImplementation(method, (IMP) &$WAKWindow$screenSize);
10167 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSourceSynchronizer");
10168 if ($CFXPreferencesPropertyListSource == Nil)
10169 $CFXPreferencesPropertyListSource = objc_getClass("CFXPreferencesPropertyListSource");
10171 Method CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(_backingPlistChangedSinceLastSync)));
10172 if (CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync != NULL) {
10173 _CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync = reinterpret_cast<BOOL (*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10174 method_setImplementation(CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$_backingPlistChangedSinceLastSync));
10177 Method CFXPreferencesPropertyListSource$createPlistFromDisk(class_getInstanceMethod($CFXPreferencesPropertyListSource, @selector(createPlistFromDisk)));
10178 if (CFXPreferencesPropertyListSource$createPlistFromDisk != NULL) {
10179 _CFXPreferencesPropertyListSource$createPlistFromDisk = reinterpret_cast<void *(*)(CFXPreferencesPropertyListSource *, SEL)>(method_getImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk));
10180 method_setImplementation(CFXPreferencesPropertyListSource$createPlistFromDisk, reinterpret_cast<IMP>(&$CFXPreferencesPropertyListSource$createPlistFromDisk));
10183 $NSURLConnection = objc_getClass("NSURLConnection");
10184 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10185 if (NSURLConnection$init$ != NULL) {
10186 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10187 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10190 $NSUserDefaults = objc_getClass("NSUserDefaults");
10191 Method NSUserDefaults$objectForKey$(class_getInstanceMethod($NSUserDefaults, @selector(objectForKey:)));
10192 if (NSUserDefaults$objectForKey$ != NULL) {
10193 _NSUserDefaults$objectForKey$ = reinterpret_cast<id (*)(NSUserDefaults *, SEL, NSString *)>(method_getImplementation(NSUserDefaults$objectForKey$));
10194 method_setImplementation(NSUserDefaults$objectForKey$, reinterpret_cast<IMP>(&$NSUserDefaults$objectForKey$));
10197 /* Set Locale {{{ */
10198 Locale_ = CFLocaleCopyCurrent();
10199 Languages_ = [NSLocale preferredLanguages];
10201 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10202 //NSLog(@"%@", [Languages_ description]);
10205 if (Locale_ != NULL)
10206 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10207 else if (Languages_ != nil && [Languages_ count] != 0)
10208 lang = [[Languages_ objectAtIndex:0] UTF8String];
10210 // XXX: consider just setting to C and then falling through?
10213 if (lang != NULL) {
10214 Pcre pattern("^([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?$");
10215 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10218 NSLog(@"Setting Language: %s", lang);
10220 if (lang != NULL) {
10221 setenv("LANG", lang, true);
10222 std::setlocale(LC_ALL, lang);
10225 /* Index Collation {{{ */
10226 if (Class $UILocalizedIndexedCollation = objc_getClass("UILocalizedIndexedCollation")) {
10227 NSBundle *bundle([NSBundle bundleForClass:$UILocalizedIndexedCollation]);
10228 NSString *path([bundle pathForResource:@"UITableViewLocalizedSectionIndex" ofType:@"plist"]);
10229 //path = @"/System/Library/Frameworks/UIKit.framework/.lproj/UITableViewLocalizedSectionIndex.plist";
10230 NSDictionary *dictionary([NSDictionary dictionaryWithContentsOfFile:path]);
10231 _H<UILocalizedIndexedCollation> collation([[[UILocalizedIndexedCollation alloc] initWithDictionary:dictionary] autorelease]);
10233 CollationLocale_ = MSHookIvar<NSLocale *>(collation, "_locale");
10235 CollationThumbs_ = [collation sectionIndexTitles];
10236 for (size_t index(0), end([CollationThumbs_ count]); index != end; ++index)
10237 CollationOffset_.push_back([collation sectionForSectionIndexTitleAtIndex:index]);
10239 CollationTitles_ = [collation sectionTitles];
10240 CollationStarts_ = MSHookIvar<NSArray *>(collation, "_sectionStartStrings");
10242 NSString *&transform(MSHookIvar<NSString *>(collation, "_transform"));
10243 if (&transform != NULL && transform != nil) {
10244 /*if ([collation respondsToSelector:@selector(transformedCollationStringForString:)])
10245 CollationModify_ = [=](NSString *value) { return [collation transformedCollationStringForString:value]; };*/
10246 const UChar *uid(reinterpret_cast<const UChar *>([transform cStringUsingEncoding:NSUnicodeStringEncoding]));
10247 UErrorCode code(U_ZERO_ERROR);
10248 CollationTransl_ = utrans_openU(uid, -1, UTRANS_FORWARD, NULL, 0, NULL, &code);
10249 if (!U_SUCCESS(code))
10250 NSLog(@"%s", u_errorName(code));
10253 CollationLocale_ = [[[NSLocale alloc] initWithLocaleIdentifier:@"en@collation=dictionary"] autorelease];
10255 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];
10256 for (NSInteger offset(0); offset != 28; ++offset)
10257 CollationOffset_.push_back(offset);
10259 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];
10260 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];
10264 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
10266 /* Parse Arguments {{{ */
10267 bool substrate(false);
10273 for (int argi(1); argi != argc; ++argi)
10274 if (strcmp(argv[argi], "--") == 0) {
10276 argv[argi] = argv[0];
10282 for (int argi(1); argi != arge; ++argi)
10283 if (strcmp(args[argi], "--substrate") == 0)
10286 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10290 App_ = [[NSBundle mainBundle] bundlePath];
10296 if (access("/var/mobile/Library/Keyboard/UserDictionary.sqlite", F_OK) == 0)
10297 system("mkdir -p /var/root/Library/Keyboard; cp -af /var/mobile/Library/Keyboard/UserDictionary.sqlite /var/root/Library/Keyboard/");
10299 Cache_ = [[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia", @"/var/root"] retain];
10301 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10302 alloc_ = alloc->method_imp;
10303 alloc->method_imp = (IMP) &Alloc_;*/
10305 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10306 dealloc_ = dealloc->method_imp;
10307 dealloc->method_imp = (IMP) &Dealloc_;*/
10309 void *gestalt(dlopen("/usr/lib/libMobileGestalt.dylib", RTLD_GLOBAL | RTLD_LAZY));
10310 $MGCopyAnswer = reinterpret_cast<CFStringRef (*)(CFStringRef)>(dlsym(gestalt, "MGCopyAnswer"));
10312 /* System Information {{{ */
10316 size = sizeof(maxproc);
10317 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10318 perror("sysctlbyname(\"kern.maxproc\", ?)");
10319 else if (maxproc < 64) {
10321 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10322 perror("sysctlbyname(\"kern.maxproc\", #)");
10325 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10326 char *osversion = new char[size];
10327 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10328 perror("sysctlbyname(\"kern.osversion\", ?)");
10330 System_ = [NSString stringWithUTF8String:osversion];
10332 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10333 char *machine = new char[size];
10334 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10335 perror("sysctlbyname(\"hw.machine\", ?)");
10337 Machine_ = machine;
10339 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10340 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10341 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10343 UniqueID_ = UniqueIdentifier(device);
10345 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10346 Product_ = [info objectForKey:@"SafariProductVersion"];
10347 Safari_ = [info objectForKey:@"CFBundleVersion"];
10350 NSString *agent([NSString stringWithFormat:@"Cydia/%@ CyF/%.2f", Cydia_, kCFCoreFoundationVersionNumber]);
10352 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Safari_))
10353 agent = [NSString stringWithFormat:@"Safari/%@ %@", match[0], agent];
10354 if (Pcre match = Pcre("^[0-9]+[A-Z][0-9]+[a-z]?", System_))
10355 agent = [NSString stringWithFormat:@"Mobile/%@ %@", match[0], agent];
10356 if (Pcre match = Pcre("^[0-9]+(\\.[0-9]+)+", Product_))
10357 agent = [NSString stringWithFormat:@"Version/%@ %@", match[0], agent];
10359 UserAgent_ = agent;
10361 /* Load Database {{{ */
10363 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10365 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10367 if (Metadata_ == NULL)
10368 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10370 Settings_ = [Metadata_ objectForKey:@"Settings"];
10372 Packages_ = [Metadata_ objectForKey:@"Packages"];
10374 Values_ = [Metadata_ objectForKey:@"Values"];
10375 Sections_ = [Metadata_ objectForKey:@"Sections"];
10376 Sources_ = [Metadata_ objectForKey:@"Sources"];
10378 Token_ = [Metadata_ objectForKey:@"Token"];
10380 Version_ = [Metadata_ objectForKey:@"Version"];
10383 if (Values_ == nil) {
10384 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10385 [Metadata_ setObject:Values_ forKey:@"Values"];
10388 if (Sections_ == nil) {
10389 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10390 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10393 if (Sources_ == nil) {
10394 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10395 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10398 if (Version_ == nil) {
10399 Version_ = [NSNumber numberWithUnsignedInt:0];
10400 [Metadata_ setObject:Version_ forKey:@"Version"];
10403 if ([Version_ unsignedIntValue] == 0) {
10404 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10405 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10406 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10407 CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./");
10409 Version_ = [NSNumber numberWithUnsignedInt:1];
10410 [Metadata_ setObject:Version_ forKey:@"Version"];
10412 [Metadata_ removeObjectForKey:@"LastUpdate"];
10417 _H<NSMutableArray> broken([NSMutableArray array]);
10418 for (NSString *key in (id) Sources_)
10419 if ([key rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"# "]].location != NSNotFound)
10420 [broken addObject:key];
10421 if ([broken count] != 0) {
10422 for (NSString *key in (id) broken)
10423 [Sources_ removeObjectForKey:key];
10428 CydiaWriteSources();
10431 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
10434 if (Packages_ != nil) {
10436 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10440 [Metadata_ removeObjectForKey:@"Packages"];
10446 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10448 #define MobileSubstrate_(name) \
10449 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10450 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10451 if (handle == NULL) \
10452 NSLog(@"%s", dlerror()); \
10455 MobileSubstrate_(Activator)
10456 MobileSubstrate_(libstatusbar)
10457 MobileSubstrate_(SimulatedKeyEvents)
10458 MobileSubstrate_(WinterBoard)
10460 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10461 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10463 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10465 if (access("/User", F_OK) != 0 || version != 6) {
10467 system("/usr/libexec/cydia/firmware.sh");
10471 _assert([[NSFileManager defaultManager]
10472 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
10473 withIntermediateDirectories:YES
10478 if (access("/tmp/cydia.chk", F_OK) == 0) {
10479 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
10480 _assert(errno == ENOENT);
10481 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
10482 _assert(errno == ENOENT);
10485 /* APT Initialization {{{ */
10486 _assert(pkgInitConfig(*_config));
10487 _assert(pkgInitSystem(*_config, _system));
10490 _config->Set("APT::Acquire::Translation", lang);
10492 // XXX: this timeout might be important :(
10493 //_config->Set("Acquire::http::Timeout", 15);
10495 _config->Set("Acquire::http::MaxParallel", 3);
10497 /* Color Choices {{{ */
10498 space_ = CGColorSpaceCreateDeviceRGB();
10500 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10501 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10502 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10503 Folder_.Set(space_, 0x8e/255.f, 0x8e/255.f, 0x93/255.f, 1.0);
10504 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10505 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10506 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10507 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10508 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10509 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10511 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10512 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10514 /* UIKit Configuration {{{ */
10515 // XXX: I have a feeling this was important
10516 //UIKeyboardDisableAutomaticAppearance();
10519 $SBSSetInterceptsMenuButtonForever = reinterpret_cast<void (*)(bool)>(dlsym(RTLD_DEFAULT, "SBSSetInterceptsMenuButtonForever"));
10521 const char *symbol(kCFCoreFoundationVersionNumber >= 800 ? "MGGetBoolAnswer" : "GSSystemHasCapability");
10522 BOOL (*GSSystemHasCapability)(CFStringRef) = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, symbol));
10523 bool fast = GSSystemHasCapability != NULL && GSSystemHasCapability(CFSTR("armv7"));
10525 PulseInterval_ = fast ? 50000 : 500000;
10527 Colon_ = UCLocalize("COLON_DELIMITED");
10528 Elision_ = UCLocalize("ELISION");
10529 Error_ = UCLocalize("ERROR");
10530 Warning_ = UCLocalize("WARNING");
10533 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10535 CGColorSpaceRelease(space_);
10536 CFRelease(Locale_);