1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2015 Jay Freeman (saurik)
5 /* GNU General Public License, Version 3 {{{ */
7 * Cydia is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published
9 * by the Free Software Foundation, either version 3 of the License,
10 * or (at your option) any later version.
12 * Cydia is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Cydia. If not, see <http://www.gnu.org/licenses/>.
22 // XXX: wtf/FastMalloc.h... wtf?
23 #define USE_SYSTEM_MALLOC 1
25 /* #include Directives {{{ */
26 #include "CyteKit/UCPlatform.h"
27 #include "CyteKit/Localize.h"
29 #include <unicode/ustring.h>
30 #include <unicode/utrans.h>
32 #include <objc/objc.h>
33 #include <objc/runtime.h>
35 #include <CoreGraphics/CoreGraphics.h>
36 #include <Foundation/Foundation.h>
39 #define DEPLOYMENT_TARGET_MACOSX 1
40 #define CF_BUILDING_CF 1
41 #include <CoreFoundation/CFInternal.h>
44 #include <CoreFoundation/CFUniChar.h>
46 #include <SystemConfiguration/SystemConfiguration.h>
48 #include <UIKit/UIKit.h>
49 #include "iPhonePrivate.h"
51 #include <IOKit/IOKitLib.h>
53 #include <QuartzCore/CALayer.h>
55 #include <WebCore/WebCoreThread.h>
56 #include <WebKit/DOMHTMLIFrameElement.h>
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 <sys/types.h>
88 #include <sys/sysctl.h>
89 #include <sys/param.h>
90 #include <sys/mount.h>
91 #include <sys/reboot.h>
98 #include <mach-o/nlist.h>
107 #include <Cytore.hpp>
110 #include "Substrate.hpp"
111 #include "Menes/Menes.h"
113 #include "CyteKit/IndirectDelegate.h"
114 #include "CyteKit/RegEx.hpp"
115 #include "CyteKit/TableViewCell.h"
116 #include "CyteKit/TabBarController.h"
117 #include "CyteKit/WebScriptObject-Cyte.h"
118 #include "CyteKit/WebViewController.h"
119 #include "CyteKit/WebViewTableViewCell.h"
120 #include "CyteKit/stringWithUTF8Bytes.h"
122 #include "Cydia/MIMEAddress.h"
123 #include "Cydia/LoadingViewController.h"
124 #include "Cydia/ProgressEvent.h"
126 #include "SDURLCache/SDURLCache.h"
133 #define _timestamp ({ \
135 gettimeofday(&tv, NULL); \
136 tv.tv_sec * 1000000 + tv.tv_usec; \
139 typedef std::vector<class ProfileTime *> TimeList;
149 ProfileTime(const char *name) :
153 times_.push_back(this);
156 void AddTime(uint64_t time) {
163 std::cerr << std::setw(7) << count_ << ", " << std::setw(8) << total_ << " : " << name_ << std::endl;
175 ProfileTimer(ProfileTime &time) :
182 time_.AddTime(_timestamp - start_);
187 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
189 std::cerr << "========" << std::endl;
192 #define _profile(name) { \
193 static ProfileTime name(#name); \
194 ProfileTimer _ ## name(name);
199 // XXX: I hate clang. Apple: please get over your petty hatred of GPL and fix your gcc fork
200 #define synchronized(lock) \
201 synchronized(static_cast<NSObject *>(lock))
203 extern NSString *Cydia_;
205 #define lprintf(args...) fprintf(stderr, args)
208 #define TraceLogging (1 && !ForRelease)
209 #define HistogramInsertionSort (0 && !ForRelease)
210 #define ProfileTimes (0 && !ForRelease)
211 #define ForSaurik (0 && !ForRelease)
212 #define LogBrowser (0 && !ForRelease)
213 #define TrackResize (0 && !ForRelease)
214 #define ManualRefresh (1 && !ForRelease)
215 #define ShowInternals (0 && !ForRelease)
216 #define AlwaysReload (0 && !ForRelease)
220 #define _trace(args...)
225 #define _profile(name) {
228 #define PrintTimes() do {} while (false)
231 // Hash Functions/Structures {{{
232 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
240 static NSString *Colon_;
242 static NSString *Error_;
243 static NSString *Warning_;
245 static NSString *Cache_;
246 #define Cache(file) \
247 [NSString stringWithFormat:@"%@/%s", Cache_, file]
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 _finline void UpdateExternalStatus(uint64_t newStatus) {
295 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
296 notify_set_state(notify_token, newStatus);
297 notify_cancel(notify_token);
299 notify_post("com.saurik.Cydia.status");
302 static CGFloat CYStatusBarHeight() {
303 CGSize size([[UIApplication sharedApplication] statusBarFrame].size);
304 return UIInterfaceOrientationIsPortrait([[UIApplication sharedApplication] statusBarOrientation]) ? size.height : size.width;
307 /* NSForcedOrderingSearch doesn't work on the iPhone */
308 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
309 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
310 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
312 /* Insertion Sort {{{ */
314 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
315 const char *ptr = (const char *)list;
317 CFIndex half = count / 2;
318 const char *probe = ptr + elementSize * half;
319 CFComparisonResult cr = comparator(element, probe, context);
320 if (0 == cr) return (probe - (const char *)list) / elementSize;
321 ptr = (cr < 0) ? ptr : probe + elementSize;
322 count = (cr < 0) ? half : (half + (count & 1) - 1);
324 return (ptr - (const char *)list) / elementSize;
327 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
328 const char *ptr = (const char *)list;
330 CFIndex half = count / 2;
331 const char *probe = ptr + elementSize * half;
332 CFComparisonResult cr = comparator(element, probe, context);
333 if (0 == cr) return (probe - (const char *)list) / elementSize;
334 ptr = (cr < 0) ? ptr : probe + elementSize;
335 count = (cr < 0) ? half : (half + (count & 1) - 1);
337 return (ptr - (const char *)list) / elementSize;
340 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
341 if (range.length == 0)
343 const void **values(new const void *[range.length]);
344 CFArrayGetValues(array, range, values);
346 #if HistogramInsertionSort > 0
347 uint32_t total(0), *offsets(new uint32_t[range.length]);
350 for (CFIndex index(1); index != range.length; ++index) {
351 const void *value(values[index]);
352 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
353 CFIndex correct(index);
354 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
355 #if HistogramInsertionSort > 1
356 NSLog(@"%@ < %@", value, values[correct - 1]);
361 if (correct != index) {
362 size_t offset(index - correct);
363 #if HistogramInsertionSort
367 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
369 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
370 values[correct] = value;
374 CFArrayReplaceValues(array, range, values, range.length);
377 #if HistogramInsertionSort > 0
378 for (CFIndex index(0); index != range.length; ++index)
379 if (offsets[index] != 0)
380 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
381 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
388 /* Apple Bug Fixes {{{ */
389 @implementation UIWebDocumentView (Cydia)
391 - (void) _setScrollerOffset:(CGPoint)offset {
392 UIScroller *scroller([self _scroller]);
394 CGSize size([scroller contentSize]);
395 CGSize bounds([scroller bounds].size);
398 max.x = size.width - bounds.width;
399 max.y = size.height - bounds.height;
407 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
408 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
410 [scroller setOffset:offset];
416 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
417 size_t length([self length] - state->state);
420 else if (length > count)
422 for (size_t i(0); i != length; ++i)
423 objects[i] = [self item:state->state++];
424 state->itemsPtr = objects;
425 state->mutationsPtr = (unsigned long *) self;
429 /* Cydia NSString Additions {{{ */
430 @interface NSString (Cydia)
431 - (NSComparisonResult) compareByPath:(NSString *)other;
432 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
435 @implementation NSString (Cydia)
437 - (NSComparisonResult) compareByPath:(NSString *)other {
438 NSString *prefix = [self commonPrefixWithString:other options:0];
439 size_t length = [prefix length];
441 NSRange lrange = NSMakeRange(length, [self length] - length);
442 NSRange rrange = NSMakeRange(length, [other length] - length);
444 lrange = [self rangeOfString:@"/" options:0 range:lrange];
445 rrange = [other rangeOfString:@"/" options:0 range:rrange];
447 NSComparisonResult value;
449 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
450 value = NSOrderedSame;
451 else if (lrange.location == NSNotFound)
452 value = NSOrderedAscending;
453 else if (rrange.location == NSNotFound)
454 value = NSOrderedDescending;
456 value = NSOrderedSame;
458 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
459 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
460 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
461 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
463 NSComparisonResult result = [lpath compare:rpath];
464 return result == NSOrderedSame ? value : result;
467 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
468 return [(id)CFURLCreateStringByAddingPercentEscapes(
473 kCFStringEncodingUTF8
480 /* C++ NSString Wrapper Cache {{{ */
481 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
482 return size == 0 ? NULL :
483 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
484 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
487 static _finline CFStringRef CYStringCreate(const char *data) {
488 return CYStringCreate(data, strlen(data));
497 _finline void clear_() {
498 if (cache_ != NULL) {
505 _finline bool empty() const {
509 _finline size_t size() const {
513 _finline char *data() const {
517 _finline void clear() {
522 _finline CYString() :
529 _finline ~CYString() {
533 void operator =(const CYString &rhs) {
537 if (rhs.cache_ == nil)
540 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
543 void copy(CYPool *pool) {
544 char *temp(pool->malloc<char>(size_ + 1));
545 memcpy(temp, data_, size_);
550 void set(CYPool *pool, const char *data, size_t size) {
556 data_ = const_cast<char *>(data);
564 _finline void set(CYPool *pool, const char *data) {
565 set(pool, data, data == NULL ? 0 : strlen(data));
568 _finline void set(CYPool *pool, const std::string &rhs) {
569 set(pool, rhs.data(), rhs.size());
572 bool operator ==(const CYString &rhs) const {
573 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
576 _finline operator CFStringRef() {
578 cache_ = CYStringCreate(data_, size_);
582 _finline operator id() {
583 return (NSString *) static_cast<CFStringRef>(*this);
586 _finline operator const char *() {
587 return reinterpret_cast<const char *>(data_);
591 /* C++ NSString Algorithm Adapters {{{ */
593 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
596 struct NSStringMapHash :
597 std::unary_function<NSString *, size_t>
599 _finline size_t operator ()(NSString *value) const {
600 return CFStringHashNSString((CFStringRef) value);
604 struct NSStringMapLess :
605 std::binary_function<NSString *, NSString *, bool>
607 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
608 return [lhs compare:rhs] == NSOrderedAscending;
612 struct NSStringMapEqual :
613 std::binary_function<NSString *, NSString *, bool>
615 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
616 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
617 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
618 //[lhs isEqualToString:rhs];
623 /* CoreGraphics Primitives {{{ */
628 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
629 CGFloat color[] = {red, green, blue, alpha};
630 return CGColorCreate(space, color);
639 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
640 color_(Create_(space, red, green, blue, alpha))
642 Set(space, red, green, blue, alpha);
647 CGColorRelease(color_);
654 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
656 color_ = Create_(space, red, green, blue, alpha);
659 operator CGColorRef() {
665 /* Random Global Variables {{{ */
666 static int PulseInterval_ = 500000;
668 static const NSString *UI_;
671 static bool RestartSubstrate_;
672 static NSArray *Finishes_;
674 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
675 #define NotifyConfig_ "/etc/notify.conf"
677 static bool Queuing_;
679 static CYColor Blue_;
680 static CYColor Blueish_;
681 static CYColor Black_;
682 static CYColor Folder_;
684 static CYColor White_;
685 static CYColor Gray_;
686 static CYColor Green_;
687 static CYColor Purple_;
688 static CYColor Purplish_;
690 static UIColor *InstallingColor_;
691 static UIColor *RemovingColor_;
693 static NSString *App_;
695 static BOOL Advanced_;
696 static BOOL Ignored_;
698 static _H<UIFont> Font12_;
699 static _H<UIFont> Font12Bold_;
700 static _H<UIFont> Font14_;
701 static _H<UIFont> Font18_;
702 static _H<UIFont> Font18Bold_;
703 static _H<UIFont> Font22Bold_;
705 static const char *Machine_ = NULL;
706 static _H<NSString> System_;
707 static NSString *SerialNumber_ = nil;
708 static NSString *ChipID_ = nil;
709 static NSString *BBSNum_ = nil;
710 static _H<NSString> UniqueID_;
711 static _H<NSString> UserAgent_;
712 static _H<NSString> Product_;
713 static _H<NSString> Safari_;
715 static _H<NSLocale> CollationLocale_;
716 static _H<NSArray> CollationThumbs_;
717 static std::vector<NSInteger> CollationOffset_;
718 static _H<NSArray> CollationTitles_;
719 static _H<NSArray> CollationStarts_;
720 static UTransliterator *CollationTransl_;
721 //static Function<NSString *, NSString *> CollationModify_;
723 typedef std::basic_string<UChar> ustring;
724 static ustring CollationString_;
726 #define CUC const ustring &str(*reinterpret_cast<const ustring *>(rep))
727 #define UC ustring &str(*reinterpret_cast<ustring *>(rep))
728 static struct UReplaceableCallbacks CollationUCalls_ = {
729 .length = [](const UReplaceable *rep) -> int32_t { CUC;
733 .charAt = [](const UReplaceable *rep, int32_t offset) -> UChar { CUC;
734 //fprintf(stderr, "charAt(%d) : %d\n", offset, str.size());
735 if (offset >= str.size())
740 .char32At = [](const UReplaceable *rep, int32_t offset) -> UChar32 { CUC;
741 //fprintf(stderr, "char32At(%d) : %d\n", offset, str.size());
742 if (offset >= str.size())
745 U16_GET(str.data(), 0, offset, str.size(), c);
749 .replace = [](UReplaceable *rep, int32_t start, int32_t limit, const UChar *text, int32_t length) -> void { UC;
750 //fprintf(stderr, "replace(%d, %d, %d) : %d\n", start, limit, length, str.size());
751 str.replace(start, limit - start, text, length);
754 .extract = [](UReplaceable *rep, int32_t start, int32_t limit, UChar *dst) -> void { UC;
755 //fprintf(stderr, "extract(%d, %d) : %d\n", start, limit, str.size());
756 str.copy(dst, limit - start, start);
759 .copy = [](UReplaceable *rep, int32_t start, int32_t limit, int32_t dest) -> void { UC;
760 //fprintf(stderr, "copy(%d, %d, %d) : %d\n", start, limit, dest, str.size());
761 str.replace(dest, 0, str, start, limit - start);
765 static CFLocaleRef Locale_;
766 static NSArray *Languages_;
767 static CGColorSpaceRef space_;
769 #define CacheState_ "/var/mobile/Library/Caches/com.saurik.Cydia/CacheState.plist"
770 #define SavedState_ "/var/mobile/Library/Caches/com.saurik.Cydia/SavedState.plist"
772 static NSDictionary *SectionMap_;
773 static _H<NSDate> Backgrounded_;
774 static _transient NSMutableDictionary *Values_;
775 static _transient NSMutableDictionary *Sections_;
776 _H<NSMutableDictionary> Sources_;
777 static _transient NSNumber *Version_;
781 CGFloat ScreenScale_;
782 static NSString *Idiom_;
783 static _H<NSString> Firmware_;
784 static NSString *Major_;
786 static _H<NSMutableDictionary> SessionData_;
787 static _H<NSObject> HostConfig_;
788 static _H<NSMutableSet> BridgedHosts_;
789 static _H<NSMutableSet> InsecureHosts_;
790 static _H<NSMutableSet> PipelinedHosts_;
791 static _H<NSMutableSet> CachedURLs_;
793 static NSString *kCydiaProgressEventTypeError = @"Error";
794 static NSString *kCydiaProgressEventTypeInformation = @"Information";
795 static NSString *kCydiaProgressEventTypeStatus = @"Status";
796 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
799 /* Display Helpers {{{ */
800 inline float Interpolate(float begin, float end, float fraction) {
801 return (end - begin) * fraction + begin;
804 static inline double Retina(double value) {
805 value *= ScreenScale_;
806 value = round(value);
807 value /= ScreenScale_;
811 static inline CGRect Retina(CGRect value) {
812 value.origin.x *= ScreenScale_;
813 value.origin.y *= ScreenScale_;
814 value.size.width *= ScreenScale_;
815 value.size.height *= ScreenScale_;
816 value = CGRectIntegral(value);
817 value.origin.x /= ScreenScale_;
818 value.origin.y /= ScreenScale_;
819 value.size.width /= ScreenScale_;
820 value.size.height /= ScreenScale_;
824 static _finline const char *StripVersion_(const char *version) {
825 const char *colon(strchr(version, ':'));
826 return colon == NULL ? version : colon + 1;
829 NSString *LocalizeSection(NSString *section) {
830 static RegEx title_r("(.*?) \\((.*)\\)");
831 if (title_r(section)) {
832 NSString *parent(title_r[1]);
833 NSString *child(title_r[2]);
835 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
836 LocalizeSection(parent),
837 LocalizeSection(child)
841 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
844 NSString *Simplify(NSString *title) {
845 const char *data = [title UTF8String];
846 size_t size = [title lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
848 static RegEx square_r("\\[(.*)\\]");
849 if (square_r(data, size))
850 return Simplify(square_r[1]);
852 static RegEx paren_r("\\((.*)\\)");
853 if (paren_r(data, size))
854 return Simplify(paren_r[1]);
856 static RegEx title_r("(.*?) \\((.*)\\)");
857 if (title_r(data, size))
858 return Simplify(title_r[1]);
864 bool isSectionVisible(NSString *section) {
865 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
866 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
867 return hidden == nil || ![hidden boolValue];
870 static NSObject *CYIOGetValue(const char *path, NSString *property) {
871 io_registry_entry_t entry(IORegistryEntryFromPath(kIOMasterPortDefault, path));
872 if (entry == MACH_PORT_NULL)
875 CFTypeRef value(IORegistryEntryCreateCFProperty(entry, (CFStringRef) property, kCFAllocatorDefault, 0));
876 IOObjectRelease(entry);
880 return [(id) value autorelease];
883 static NSString *CYHex(NSData *data, bool reverse = false) {
887 size_t length([data length]);
888 uint8_t bytes[length];
889 [data getBytes:bytes];
891 char string[length * 2 + 1];
892 for (size_t i(0); i != length; ++i)
893 sprintf(string + i * 2, "%.2x", bytes[reverse ? length - i - 1 : i]);
895 return [NSString stringWithUTF8String:string];
900 /* Delegate Prototypes {{{ */
903 @class CydiaProgressEvent;
905 @protocol DatabaseDelegate
906 - (void) repairWithSelector:(SEL)selector;
907 - (void) setConfigurationData:(NSString *)data;
908 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
911 @class CYPackageController;
913 @protocol SourceDelegate
914 - (void) setFetch:(NSNumber *)fetch;
917 @protocol FetchDelegate
918 - (bool) isSourceCancelled;
919 - (void) startSourceFetch:(NSString *)uri;
920 - (void) stopSourceFetch:(NSString *)uri;
923 @protocol CydiaDelegate
924 - (void) returnToCydia;
926 - (void) retainNetworkActivityIndicator;
927 - (void) releaseNetworkActivityIndicator;
928 - (void) clearPackage:(Package *)package;
929 - (void) installPackage:(Package *)package;
930 - (void) installPackages:(NSArray *)packages;
931 - (void) removePackage:(Package *)package;
932 - (void) beginUpdate;
934 - (bool) requestUpdate;
935 - (void) distUpgrade;
938 - (void) _saveConfig;
940 - (void) addSource:(NSDictionary *)source;
941 - (void) addTrivialSource:(NSString *)href;
942 - (UIProgressHUD *) addProgressHUD;
943 - (void) removeProgressHUD:(UIProgressHUD *)hud;
944 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
945 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
949 /* CancelStatus {{{ */
951 public pkgAcquireStatus
962 virtual bool MediaChange(std::string media, std::string drive) {
966 virtual void IMSHit(pkgAcquire::ItemDesc &desc) {
970 virtual bool Pulse_(pkgAcquire *Owner) = 0;
972 virtual bool Pulse(pkgAcquire *Owner) {
973 if (pkgAcquireStatus::Pulse(Owner) && Pulse_(Owner))
981 _finline bool WasCancelled() const {
986 /* DelegateStatus {{{ */
991 _transient NSObject<ProgressDelegate> *delegate_;
999 void setDelegate(NSObject<ProgressDelegate> *delegate) {
1000 delegate_ = delegate;
1003 virtual void Fetch(pkgAcquire::ItemDesc &desc) {
1004 NSString *name([NSString stringWithUTF8String:desc.ShortDesc.c_str()]);
1005 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItemDesc:desc]);
1006 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1009 virtual void Done(pkgAcquire::ItemDesc &desc) {
1010 NSString *name([NSString stringWithUTF8String:desc.ShortDesc.c_str()]);
1011 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:Colon_, UCLocalize("DONE"), name] ofType:kCydiaProgressEventTypeStatus forItemDesc:desc]);
1012 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1015 virtual void Fail(pkgAcquire::ItemDesc &desc) {
1017 desc.Owner->Status == pkgAcquire::Item::StatIdle ||
1018 desc.Owner->Status == pkgAcquire::Item::StatDone
1022 std::string &error(desc.Owner->ErrorText);
1026 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItemDesc:desc]);
1027 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1030 virtual bool Pulse_(pkgAcquire *Owner) {
1032 double(CurrentBytes + CurrentItems) /
1033 double(TotalBytes + TotalItems)
1036 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
1037 [NSNumber numberWithDouble:percent], @"Percent",
1039 [NSNumber numberWithDouble:CurrentBytes], @"Current",
1040 [NSNumber numberWithDouble:TotalBytes], @"Total",
1041 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
1042 nil] waitUntilDone:YES];
1044 return ![delegate_ isProgressCancelled];
1047 virtual void Start() {
1048 pkgAcquireStatus::Start();
1049 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
1052 virtual void Stop() {
1053 pkgAcquireStatus::Stop();
1054 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
1055 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
1059 /* Database Interface {{{ */
1060 typedef std::map< unsigned long, _H<Source> > SourceMap;
1062 @interface Database : NSObject {
1069 pkgCacheFile cache_;
1070 pkgDepCache::Policy *policy_;
1071 pkgRecords *records_;
1072 pkgProblemResolver *resolver_;
1073 pkgAcquire *fetcher_;
1075 SPtr<pkgPackageManager> manager_;
1076 pkgSourceList *list_;
1078 SourceMap sourceMap_;
1079 _H<NSMutableArray> sourceList_;
1081 CFMutableArrayRef packages_;
1083 _transient NSObject<DatabaseDelegate> *delegate_;
1084 _transient NSObject<ProgressDelegate> *progress_;
1086 CydiaStatus status_;
1092 std::map<const char *, _H<NSString> > sections_;
1095 + (Database *) sharedInstance;
1098 - (void) _readCydia:(NSNumber *)fd;
1099 - (void) _readStatus:(NSNumber *)fd;
1100 - (void) _readOutput:(NSNumber *)fd;
1104 - (Package *) packageWithName:(NSString *)name;
1106 - (pkgCacheFile &) cache;
1107 - (pkgDepCache::Policy *) policy;
1108 - (pkgRecords *) records;
1109 - (pkgProblemResolver *) resolver;
1110 - (pkgAcquire &) fetcher;
1111 - (pkgSourceList &) list;
1112 - (NSArray *) packages;
1113 - (NSArray *) sources;
1114 - (Source *) sourceWithKey:(NSString *)key;
1115 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1123 - (void) updateWithStatus:(CancelStatus &)status;
1125 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1127 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1128 - (NSObject<ProgressDelegate> *) progressDelegate;
1130 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1131 - (void) setFetch:(bool)fetch forURI:(const char *)uri;
1132 - (void) resetFetch;
1134 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1138 /* SourceStatus {{{ */
1139 class SourceStatus :
1143 _transient NSObject<FetchDelegate> *delegate_;
1144 _transient Database *database_;
1145 std::set<std::string> fetches_;
1148 SourceStatus(NSObject<FetchDelegate> *delegate, Database *database) :
1149 delegate_(delegate),
1154 void Set(bool fetch, const std::string &uri) {
1156 if (!fetches_.insert(uri).second)
1159 if (fetches_.erase(uri) == 0)
1163 //printf("Set(%s, %s)\n", fetch ? "true" : "false", uri.c_str());
1164 [database_ setFetch:fetch forURI:uri.c_str()];
1167 _finline void Set(bool fetch, pkgAcquire::Item *item) {
1168 /*unsigned long ID(fetch ? 1 : 0);
1172 Set(fetch, item->DescURI());
1175 void Log(const char *tag, pkgAcquire::Item *item) {
1176 //printf("%s(%s) S:%u Q:%u\n", tag, item->DescURI().c_str(), item->Status, item->QueueCounter);
1179 virtual void Fetch(pkgAcquire::ItemDesc &desc) {
1180 Log("Fetch", desc.Owner);
1181 Set(true, desc.Owner);
1184 virtual void Done(pkgAcquire::ItemDesc &desc) {
1185 Log("Done", desc.Owner);
1186 Set(false, desc.Owner);
1189 virtual void Fail(pkgAcquire::ItemDesc &desc) {
1190 Log("Fail", desc.Owner);
1191 Set(false, desc.Owner);
1194 virtual bool Pulse_(pkgAcquire *Owner) {
1195 std::set<std::string> fetches;
1196 for (pkgAcquire::ItemCIterator item(Owner->ItemsBegin()); item != Owner->ItemsEnd(); ++item) {
1198 if ((*item)->QueueCounter == 0)
1200 else switch ((*item)->Status) {
1201 case pkgAcquire::Item::StatFetching:
1202 fetches.insert((*item)->DescURI());
1211 Log(fetch ? "Pulse<true>" : "Pulse<false>", *item);
1215 std::vector<std::string> stops;
1216 std::set_difference(fetches_.begin(), fetches_.end(), fetches.begin(), fetches.end(), std::back_insert_iterator<std::vector<std::string>>(stops));
1217 for (std::vector<std::string>::const_iterator stop(stops.begin()); stop != stops.end(); ++stop) {
1218 //printf("Stop(%s)\n", stop->c_str());
1222 return ![delegate_ isSourceCancelled];
1225 virtual void Stop() {
1226 pkgAcquireStatus::Stop();
1227 [database_ resetFetch];
1231 /* ProgressEvent Implementation {{{ */
1232 @implementation CydiaProgressEvent
1234 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1235 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1238 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1239 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1240 [event setPackage:package];
1244 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItemDesc:(pkgAcquire::ItemDesc &)desc {
1245 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1247 NSString *description([NSString stringWithUTF8String:desc.Description.c_str()]);
1248 NSArray *fields([description componentsSeparatedByString:@" "]);
1249 [event setItem:fields];
1251 if ([fields count] > 3) {
1252 [event setPackage:[fields objectAtIndex:2]];
1253 [event setVersion:[fields objectAtIndex:3]];
1256 [event setURL:[NSString stringWithUTF8String:desc.URI.c_str()]];
1261 + (NSArray *) _attributeKeys {
1262 return [NSArray arrayWithObjects:
1272 - (NSArray *) attributeKeys {
1273 return [[self class] _attributeKeys];
1276 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1277 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1280 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1281 if ((self = [super init]) != nil) {
1287 - (NSString *) message {
1291 - (NSString *) type {
1295 - (NSArray *) item {
1296 return (id) item_ ?: [NSNull null];
1299 - (void) setItem:(NSArray *)item {
1303 - (NSString *) package {
1304 return (id) package_ ?: [NSNull null];
1307 - (void) setPackage:(NSString *)package {
1311 - (NSString *) url {
1312 return (id) url_ ?: [NSNull null];
1315 - (void) setURL:(NSString *)url {
1319 - (void) setVersion:(NSString *)version {
1323 - (NSString *) version {
1324 return (id) version_ ?: [NSNull null];
1327 - (NSString *) compound:(NSString *)value {
1329 NSString *mode(nil); {
1330 NSString *type([self type]);
1331 if ([type isEqualToString:kCydiaProgressEventTypeError])
1332 mode = UCLocalize("ERROR");
1333 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1334 mode = UCLocalize("WARNING");
1338 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1344 - (NSString *) compoundMessage {
1345 return [self compound:[self message]];
1348 - (NSString *) compoundTitle {
1351 if (package_ == nil)
1353 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1354 title = [package name];
1358 return [self compound:title];
1364 // Cytore Definitions {{{
1365 struct PackageValue :
1368 Cytore::Offset<PackageValue> next_;
1370 uint32_t index_ : 23;
1371 uint32_t subscribed_ : 1;
1388 Cytore::Offset<PackageValue> packages_[1 << 16];
1391 static Cytore::File<MetaValue> MetaFile_;
1393 // Cytore Helper Functions {{{
1394 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1395 SplitHash nhash = { hashlittle(name, length) };
1397 PackageValue *metadata;
1399 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1400 for (;; offset = &metadata->next_) { if (offset->IsNull()) {
1401 *offset = MetaFile_.New<PackageValue>(length + 1);
1402 metadata = &MetaFile_.Get(*offset);
1404 if (metadata == NULL) {
1408 metadata = new PackageValue();
1409 memset(metadata, 0, sizeof(*metadata));
1412 memcpy(metadata->name_, name, length);
1413 metadata->name_[length] = '\0';
1414 metadata->nhash_ = nhash.u16[1];
1416 metadata = &MetaFile_.Get(*offset);
1417 if (metadata->nhash_ != nhash.u16[1])
1419 if (strncmp(metadata->name_, name, length) != 0)
1421 if (metadata->name_[length] != '\0')
1428 static void PackageImport(const void *key, const void *value, void *context) {
1429 bool &fail(*reinterpret_cast<bool *>(context));
1432 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1433 NSLog(@"failed to import package %@", key);
1437 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1438 NSDictionary *package((NSDictionary *) value);
1440 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1441 if ([subscribed boolValue] && !metadata->subscribed_)
1442 metadata->subscribed_ = true;
1444 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1445 time_t time([date timeIntervalSince1970]);
1446 if (metadata->first_ > time || metadata->first_ == 0)
1447 metadata->first_ = time;
1450 NSDate *date([package objectForKey:@"LastSeen"]);
1451 NSString *version([package objectForKey:@"LastVersion"]);
1453 if (date != nil && version != nil) {
1454 time_t time([date timeIntervalSince1970]);
1455 if (metadata->last_ < time || metadata->last_ == 0)
1456 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1457 size_t length(strlen(buffer));
1458 uint16_t vhash(hashlittle(buffer, length));
1460 size_t capped(std::min<size_t>(8, length));
1461 char *latest(buffer + length - capped);
1463 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1464 metadata->vhash_ = vhash;
1466 metadata->last_ = time;
1472 static NSDate *GetStatusDate() {
1473 return [[[NSFileManager defaultManager] attributesOfItemAtPath:@"/var/lib/dpkg/status" error:NULL] fileModificationDate];
1476 static void SaveConfig(NSObject *lock) {
1477 @synchronized (lock) {
1483 CFPreferencesSetMultiple((CFDictionaryRef) [NSDictionary dictionaryWithObjectsAndKeys:
1484 Values_, @"CydiaValues",
1485 Sections_, @"CydiaSections",
1486 (id) Sources_, @"CydiaSources",
1487 Version_, @"CydiaVersion",
1488 nil], NULL, CFSTR("com.saurik.Cydia"), kCFPreferencesCurrentUser, kCFPreferencesCurrentHost);
1490 if (!CFPreferencesAppSynchronize(CFSTR("com.saurik.Cydia")))
1491 NSLog(@"CFPreferencesAppSynchronize(com.saurik.Cydia) == false");
1493 CydiaWriteSources();
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:(CYPool *)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:(CYPool *)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:(CYPool *)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];
1761 [record_ setObject:[NSMutableArray arrayWithObject:section] forKey:@"Sections"];
1764 - (bool) addSection:(NSString *)section {
1768 [self performSelectorOnMainThread:@selector(_addSection:) withObject:section waitUntilDone:NO];
1772 - (void) _removeSection:(NSString *)section {
1776 if (NSMutableArray *sections = [record_ objectForKey:@"Sections"])
1777 if ([sections containsObject:section])
1778 [sections removeObject:section];
1781 - (bool) removeSection:(NSString *)section {
1785 [self performSelectorOnMainThread:@selector(_removeSection:) withObject:section waitUntilDone:NO];
1790 [Sources_ removeObjectForKey:[self key]];
1794 bool value(record_ != nil);
1795 [self performSelectorOnMainThread:@selector(_remove) withObject:nil waitUntilDone:NO];
1799 - (NSDictionary *) record {
1807 - (NSString *) rooturi {
1811 - (NSString *) distribution {
1812 return distribution_;
1815 - (NSString *) type {
1819 - (NSString *) baseuri {
1820 return base_.empty() ? nil : (id) base_;
1823 - (NSString *) iconuri {
1824 if (NSString *base = [self baseuri])
1825 return [base stringByAppendingString:@"CydiaIcon.png"];
1830 - (NSURL *) iconURL {
1831 if (NSString *uri = [self iconuri])
1832 return [NSURL URLWithString:uri];
1836 - (NSString *) key {
1837 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1840 - (NSString *) host {
1844 - (NSString *) name {
1845 return origin_.empty() ? (id) authority_ : origin_;
1848 - (NSString *) shortDescription {
1849 return description_;
1852 - (NSString *) label {
1853 return label_.empty() ? (id) authority_ : label_;
1856 - (NSString *) origin {
1860 - (NSString *) version {
1864 - (NSString *) defaultIcon {
1865 return defaultIcon_;
1868 - (void) setDelegate:(NSObject<SourceDelegate> *)delegate {
1869 delegate_ = delegate;
1873 return !fetches_.empty();
1876 - (void) setFetch:(bool)fetch forURI:(const char *)uri {
1878 if (fetches_.erase(uri) == 0)
1880 } else if (files_.find(uri) == files_.end())
1882 else if (!fetches_.insert(uri).second)
1885 [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:[self fetch]] waitUntilDone:NO];
1888 - (void) resetFetch {
1890 [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:NO];
1895 /* CydiaOperation Class {{{ */
1896 @interface CydiaOperation : NSObject {
1897 _H<NSString> operator_;
1898 _H<NSString> value_;
1901 - (NSString *) operator;
1902 - (NSString *) value;
1906 @implementation CydiaOperation
1908 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1909 if ((self = [super init]) != nil) {
1910 operator_ = [NSString stringWithUTF8String:_operator];
1911 value_ = [NSString stringWithUTF8String:value];
1915 + (NSArray *) _attributeKeys {
1916 return [NSArray arrayWithObjects:
1922 - (NSArray *) attributeKeys {
1923 return [[self class] _attributeKeys];
1926 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1927 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1930 - (NSString *) operator {
1934 - (NSString *) value {
1940 /* CydiaClause Class {{{ */
1941 @interface CydiaClause : NSObject {
1942 _H<NSString> package_;
1943 _H<CydiaOperation> version_;
1946 - (NSString *) package;
1947 - (CydiaOperation *) version;
1951 @implementation CydiaClause
1953 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1954 if ((self = [super init]) != nil) {
1955 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1957 if (const char *version = dep.TargetVer())
1958 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1960 version_ = (id) [NSNull null];
1964 + (NSArray *) _attributeKeys {
1965 return [NSArray arrayWithObjects:
1971 - (NSArray *) attributeKeys {
1972 return [[self class] _attributeKeys];
1975 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1976 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1979 - (NSString *) package {
1983 - (CydiaOperation *) version {
1989 /* CydiaRelation Class {{{ */
1990 @interface CydiaRelation : NSObject {
1991 _H<NSString> relationship_;
1992 _H<NSMutableArray> clauses_;
1995 - (NSString *) relationship;
1996 - (NSArray *) clauses;
2000 @implementation CydiaRelation
2002 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
2003 if ((self = [super init]) != nil) {
2004 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
2005 clauses_ = [NSMutableArray arrayWithCapacity:8];
2007 pkgCache::DepIterator start;
2008 pkgCache::DepIterator end;
2009 dep.GlobOr(start, end); // ++dep
2012 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
2014 // yes, seriously. (wtf?)
2022 + (NSArray *) _attributeKeys {
2023 return [NSArray arrayWithObjects:
2029 - (NSArray *) attributeKeys {
2030 return [[self class] _attributeKeys];
2033 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2034 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2037 - (NSString *) relationship {
2038 return relationship_;
2041 - (NSArray *) clauses {
2045 - (void) addClause:(CydiaClause *)clause {
2046 [clauses_ addObject:clause];
2051 /* Package Class {{{ */
2052 struct ParsedPackage {
2056 CYString architecture_;
2059 CYString depiction_;
2066 @interface Package : NSObject {
2068 @public uint32_t role_ : 3;
2069 uint32_t essential_ : 1;
2070 uint32_t obsolete_ : 1;
2071 uint32_t ignored_ : 1;
2072 uint32_t pooled_ : 1;
2078 _transient Database *database_;
2080 pkgCache::VerIterator version_;
2081 pkgCache::PkgIterator iterator_;
2082 pkgCache::VerFileIterator file_;
2086 CYString transform_;
2089 CYString installed_;
2092 const char *section_;
2093 _transient NSString *section$_;
2097 PackageValue *metadata_;
2098 ParsedPackage *parsed_;
2100 _H<NSMutableArray> tags_;
2103 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database;
2104 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database;
2106 - (pkgCache::PkgIterator) iterator;
2109 - (NSString *) section;
2110 - (NSString *) simpleSection;
2112 - (NSString *) longSection;
2113 - (NSString *) shortSection;
2117 - (MIMEAddress *) maintainer;
2119 - (NSString *) longDescription;
2120 - (NSString *) shortDescription;
2123 - (PackageValue *) metadata;
2126 - (bool) subscribed;
2127 - (bool) setSubscribed:(bool)subscribed;
2131 - (NSString *) latest;
2132 - (NSString *) installed;
2133 - (BOOL) uninstalled;
2136 - (BOOL) upgradableAndEssential:(BOOL)essential;
2139 - (BOOL) unfiltered;
2143 - (BOOL) halfConfigured;
2144 - (BOOL) halfInstalled;
2146 - (NSString *) mode;
2149 - (NSString *) name;
2151 - (NSString *) homepage;
2152 - (NSString *) depiction;
2153 - (MIMEAddress *) author;
2155 - (NSString *) support;
2157 - (NSArray *) files;
2158 - (NSArray *) warnings;
2159 - (NSArray *) applications;
2161 - (Source *) source;
2164 - (BOOL) matches:(NSArray *)query;
2166 - (BOOL) hasTag:(NSString *)tag;
2167 - (NSString *) primaryPurpose;
2168 - (NSArray *) purposes;
2169 - (bool) isCommercial;
2171 - (void) setIndex:(size_t)index;
2173 - (CYString &) cyname;
2175 - (uint32_t) compareBySection:(NSArray *)sections;
2182 uint32_t PackageChangesRadix(Package *self, void *) {
2187 uint32_t timestamp : 30;
2188 uint32_t ignored : 1;
2189 uint32_t upgradable : 1;
2193 bool upgradable([self upgradableAndEssential:YES]);
2194 value.bits.upgradable = upgradable ? 1 : 0;
2197 value.bits.timestamp = 0;
2198 value.bits.ignored = [self ignored] ? 0 : 1;
2199 value.bits.upgradable = 1;
2201 value.bits.timestamp = [self seen] >> 2;
2202 value.bits.ignored = 0;
2203 value.bits.upgradable = 0;
2206 return _not(uint32_t) - value.key;
2209 CYString &(*PackageName)(Package *self, SEL sel);
2211 uint32_t PackagePrefixRadix(Package *self, void *context) {
2212 size_t offset(reinterpret_cast<size_t>(context));
2213 CYString &name(PackageName(self, @selector(cyname)));
2215 size_t size(name.size());
2218 char *text(name.data());
2221 if (!isdigit(text[0]))
2225 while (size != digits && isdigit(text[digits]))
2233 if (offset == 0 && zeros != 0) {
2234 memset(data, '0', zeros);
2235 memcpy(data + zeros, text, 4 - zeros);
2237 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2238 if (size <= offset - zeros)
2241 text += offset - zeros;
2242 size -= offset - zeros;
2245 memcpy(data, text, 4);
2247 memcpy(data, text, size);
2248 memset(data + size, 0, 4 - size);
2251 for (size_t i(0); i != 4; ++i)
2252 if (isalpha(data[i]))
2260 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2262 /* XXX: ntohl may be more honest */
2263 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2266 CFComparisonResult StringNameCompare(CFStringRef lhn, CFStringRef rhn, size_t length) {
2267 _profile(PackageNameCompare)
2269 return rhn == NULL ? kCFCompareEqualTo : kCFCompareLessThan;
2270 else if (rhn == NULL)
2271 return kCFCompareGreaterThan;
2273 CFIndex length(CFStringGetLength(lhn));
2275 _profile(PackageNameCompare$NumbersLast)
2276 if (length != 0 && CFStringGetLength(rhn) != 0) {
2277 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2278 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2279 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2280 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2281 return lha ? kCFCompareLessThan : kCFCompareGreaterThan;
2285 _profile(PackageNameCompare$Compare)
2286 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, (CFLocaleRef) (id) CollationLocale_);
2291 _finline CFComparisonResult StringNameCompare(NSString *lhn, NSString*rhn, size_t length) {
2292 return StringNameCompare((CFStringRef) lhn, (CFStringRef) rhn, length);
2295 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2296 CYString &lhn(PackageName(lhs, @selector(cyname)));
2297 NSString *rhn(PackageName(rhs, @selector(cyname)));
2298 return StringNameCompare(lhn, rhn, lhn.size());
2301 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *arg) {
2302 return PackageNameCompare(*lhs, *rhs, arg);
2305 struct PackageNameOrdering :
2306 std::binary_function<Package *, Package *, bool>
2308 _finline bool operator ()(Package *lhs, Package *rhs) const {
2309 return PackageNameCompare(lhs, rhs, NULL) == kCFCompareLessThan;
2313 @implementation Package
2315 - (NSString *) description {
2316 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2322 if (parsed_ != NULL)
2327 + (NSString *) webScriptNameForSelector:(SEL)selector {
2329 else if (selector == @selector(clear))
2331 else if (selector == @selector(getField:))
2333 else if (selector == @selector(getRecord))
2334 return @"getRecord";
2335 else if (selector == @selector(hasTag:))
2337 else if (selector == @selector(install))
2339 else if (selector == @selector(remove))
2345 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2346 return [self webScriptNameForSelector:selector] == nil;
2349 + (NSArray *) _attributeKeys {
2350 return [NSArray arrayWithObjects:
2371 @"shortDescription",
2384 - (NSArray *) attributeKeys {
2385 return [[self class] _attributeKeys];
2388 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2389 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2392 - (NSArray *) relations {
2393 @synchronized (database_) {
2394 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2395 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2396 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2400 - (NSString *) architecture {
2402 @synchronized (database_) {
2403 return parsed_->architecture_.empty() ? [NSNull null] : (id) parsed_->architecture_;
2406 - (NSString *) getField:(NSString *)name {
2407 @synchronized (database_) {
2408 if ([database_ era] != era_ || file_.end())
2411 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2413 const char *start, *end;
2414 if (!parser.Find([name UTF8String], start, end))
2415 return (NSString *) [NSNull null];
2417 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2420 - (NSString *) getRecord {
2421 @synchronized (database_) {
2422 if ([database_ era] != era_ || file_.end())
2425 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2427 const char *start, *end;
2428 parser.GetRec(start, end);
2430 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2434 if (parsed_ != NULL)
2436 @synchronized (database_) {
2437 if ([database_ era] != era_ || file_.end())
2440 ParsedPackage *parsed(new ParsedPackage);
2443 _profile(Package$parse)
2444 pkgRecords::Parser *parser;
2446 _profile(Package$parse$Lookup)
2447 parser = &[database_ records]->Lookup(file_);
2453 _profile(Package$parse$Find)
2458 {"architecture", &parsed->architecture_},
2459 {"icon", &parsed->icon_},
2460 {"depiction", &parsed->depiction_},
2461 {"homepage", &parsed->homepage_},
2462 {"website", &website},
2464 {"support", &parsed->support_},
2465 {"author", &parsed->author_},
2466 {"md5sum", &parsed->md5sum_},
2469 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2470 const char *start, *end;
2472 if (parser->Find(names[i].name_, start, end)) {
2473 CYString &value(*names[i].value_);
2474 _profile(Package$parse$Value)
2475 value.set(pool_, start, end - start);
2481 _profile(Package$parse$Tagline)
2482 const char *start, *end;
2483 if (parser->ShortDesc(start, end)) {
2484 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2487 while (stop != start && stop[-1] == '\r')
2489 parsed->tagline_.set(pool_, start, stop - start);
2493 _profile(Package$parse$Retain)
2494 if (parsed->homepage_.empty())
2495 parsed->homepage_ = website;
2496 if (parsed->homepage_ == parsed->depiction_)
2497 parsed->homepage_.clear();
2498 if (parsed->support_.empty())
2499 parsed->support_ = bugs;
2504 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database {
2505 if ((self = [super init]) != nil) {
2506 _profile(Package$initWithVersion)
2508 pool_ = new CYPool();
2514 database_ = database;
2515 era_ = [database era];
2519 pkgCache::PkgIterator iterator(version.ParentPkg());
2520 iterator_ = iterator;
2522 _profile(Package$initWithVersion$Version)
2523 if (!version_.end())
2524 file_ = version_.FileList();
2526 pkgCache &cache([database_ cache]);
2527 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2531 _profile(Package$initWithVersion$Cache)
2532 name_.set(NULL, iterator.Display());
2534 latest_.set(NULL, StripVersion_(version_.VerStr()));
2536 pkgCache::VerIterator current(iterator.CurrentVer());
2538 installed_.set(NULL, StripVersion_(current.VerStr()));
2541 _profile(Package$initWithVersion$Transliterate) do {
2542 if (CollationTransl_ == NULL)
2547 _profile(Package$initWithVersion$Transliterate$utf8)
2548 const uint8_t *data(reinterpret_cast<const uint8_t *>(name_.data()));
2549 for (size_t i(0), e(name_.size()); i != e; ++i)
2550 if (data[i] >= 0x80)
2555 UErrorCode code(U_ZERO_ERROR);
2558 _profile(Package$initWithVersion$Transliterate$u_strFromUTF8WithSub)
2559 CollationString_.resize(name_.size());
2560 u_strFromUTF8WithSub(&CollationString_[0], CollationString_.size(), &length, name_.data(), name_.size(), 0xfffd, NULL, &code);
2561 if (!U_SUCCESS(code))
2563 CollationString_.resize(length);
2566 _profile(Package$initWithVersion$Transliterate$utrans_trans)
2567 length = CollationString_.size();
2568 utrans_trans(CollationTransl_, reinterpret_cast<UReplaceable *>(&CollationString_), &CollationUCalls_, 0, &length, &code);
2569 if (!U_SUCCESS(code))
2571 _assert(CollationString_.size() == length);
2574 _profile(Package$initWithVersion$Transliterate$u_strToUTF8WithSub$preflight)
2575 u_strToUTF8WithSub(NULL, 0, &length, CollationString_.data(), CollationString_.size(), 0xfffd, NULL, &code);
2576 if (code == U_BUFFER_OVERFLOW_ERROR)
2577 code = U_ZERO_ERROR;
2578 else if (!U_SUCCESS(code))
2583 _profile(Package$initWithVersion$Transliterate$apr_palloc)
2584 transform = pool_->malloc<char>(length);
2586 _profile(Package$initWithVersion$Transliterate$u_strToUTF8WithSub$transform)
2587 u_strToUTF8WithSub(transform, length, NULL, CollationString_.data(), CollationString_.size(), 0xfffd, NULL, &code);
2588 if (!U_SUCCESS(code))
2592 transform_.set(NULL, transform, length);
2593 } while (false); _end
2595 _profile(Package$initWithVersion$Tags)
2596 pkgCache::TagIterator tag(iterator.TagList());
2598 tags_ = [NSMutableArray arrayWithCapacity:8];
2600 goto tag; for (; !tag.end(); ++tag) tag: {
2601 const char *name(tag.Name());
2602 NSString *string((NSString *) CYStringCreate(name));
2606 [tags_ addObject:[string autorelease]];
2608 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2609 if (strcmp(name + 6, "enduser") == 0)
2611 else if (strcmp(name + 6, "hacker") == 0)
2613 else if (strcmp(name + 6, "developer") == 0)
2615 else if (strcmp(name + 6, "cydia") == 0)
2621 if (strncmp(name, "cydia::", 7) == 0) {
2622 if (strcmp(name + 7, "essential") == 0)
2624 else if (strcmp(name + 7, "obsolete") == 0)
2631 _profile(Package$initWithVersion$Metadata)
2632 const char *mixed(iterator.Name());
2633 size_t size(strlen(mixed));
2634 static const size_t prefix(sizeof("/var/lib/dpkg/info/") - 1);
2635 char lower[prefix + size + 5 + 1];
2637 for (size_t i(0); i != size; ++i)
2638 lower[prefix + i] = mixed[i] | 0x20;
2640 if (!installed_.empty()) {
2641 memcpy(lower, "/var/lib/dpkg/info/", prefix);
2642 memcpy(lower + prefix + size, ".list", 6);
2644 if (stat(lower, &info) != -1)
2645 upgraded_ = info.st_birthtime;
2648 PackageValue *metadata(PackageFind(lower + prefix, size));
2649 metadata_ = metadata;
2651 id_.set(NULL, metadata->name_, size);
2653 const char *latest(version_.VerStr());
2654 size_t length(strlen(latest));
2656 uint16_t vhash(hashlittle(latest, length));
2658 size_t capped(std::min<size_t>(8, length));
2659 latest = latest + length - capped;
2661 if (metadata->first_ == 0)
2662 metadata->first_ = now_;
2664 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2665 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2666 metadata->vhash_ = vhash;
2667 metadata->last_ = now_;
2668 } else if (metadata->last_ == 0)
2669 metadata->last_ = metadata->first_;
2672 _profile(Package$initWithVersion$Section)
2673 section_ = version_.Section();
2676 _profile(Package$initWithVersion$Flags)
2677 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2678 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2683 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database {
2684 pkgCache::VerIterator version;
2686 _profile(Package$packageWithIterator$GetCandidateVer)
2687 version = [database policy]->GetCandidateVer(iterator);
2695 _profile(Package$packageWithIterator$Allocate)
2696 package = [Package allocWithZone:zone];
2699 _profile(Package$packageWithIterator$Initialize)
2701 initWithVersion:version
2708 _profile(Package$packageWithIterator$Autorelease)
2709 package = [package autorelease];
2715 - (pkgCache::PkgIterator) iterator {
2719 - (NSString *) section {
2720 if (section$_ == nil) {
2721 if (section_ == NULL)
2724 _profile(Package$section$mappedSectionForPointer)
2725 section$_ = [database_ mappedSectionForPointer:section_];
2730 - (NSString *) simpleSection {
2731 if (NSString *section = [self section])
2732 return Simplify(section);
2737 - (NSString *) longSection {
2738 return LocalizeSection([self section]);
2741 - (NSString *) shortSection {
2742 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2745 - (NSString *) uri {
2748 pkgIndexFile *index;
2749 pkgCache::PkgFileIterator file(file_.File());
2750 if (![database_ list].FindIndex(file, index))
2752 return [NSString stringWithUTF8String:iterator_->Path];
2753 //return [NSString stringWithUTF8String:file.Site()];
2754 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2758 - (MIMEAddress *) maintainer {
2759 @synchronized (database_) {
2760 if ([database_ era] != era_ || file_.end())
2763 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2764 const std::string &maintainer(parser->Maintainer());
2765 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2768 - (NSString *) md5sum {
2769 return parsed_ == NULL ? nil : (id) parsed_->md5sum_;
2773 @synchronized (database_) {
2774 if ([database_ era] != era_ || version_.end())
2777 return version_->InstalledSize;
2780 - (NSString *) longDescription {
2781 @synchronized (database_) {
2782 if ([database_ era] != era_ || file_.end())
2785 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2786 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2788 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2789 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2790 if ([lines count] < 2)
2793 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2794 for (size_t i(1), e([lines count]); i != e; ++i) {
2795 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2796 [trimmed addObject:trim];
2799 return [trimmed componentsJoinedByString:@"\n"];
2802 - (NSString *) shortDescription {
2803 if (parsed_ != NULL)
2804 return static_cast<NSString *>(parsed_->tagline_);
2806 @synchronized (database_) {
2807 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2809 const char *start, *end;
2810 if (!parser.ShortDesc(start, end))
2813 if (end - start > 200)
2817 if (const char *stop = reinterpret_cast<const char *>(memchr(start, '\n', end - start)))
2820 while (end != start && end[-1] == '\r')
2824 return [(id) CYStringCreate(start, end - start) autorelease];
2828 _profile(Package$index)
2829 CFStringRef name((CFStringRef) [self name]);
2830 if (CFStringGetLength(name) == 0)
2832 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2833 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2835 return toupper(character);
2839 - (PackageValue *) metadata {
2844 PackageValue *metadata([self metadata]);
2845 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2848 - (bool) subscribed {
2849 return [self metadata]->subscribed_;
2852 - (bool) setSubscribed:(bool)subscribed {
2853 PackageValue *metadata([self metadata]);
2854 if (metadata->subscribed_ == subscribed)
2856 metadata->subscribed_ = subscribed;
2864 - (NSString *) latest {
2868 - (NSString *) installed {
2872 - (BOOL) uninstalled {
2873 return installed_.empty();
2877 return !version_.end();
2880 - (BOOL) upgradableAndEssential:(BOOL)essential {
2881 _profile(Package$upgradableAndEssential)
2882 pkgCache::VerIterator current(iterator_.CurrentVer());
2884 return essential && essential_;
2886 return !version_.end() && version_ != current;
2890 - (BOOL) essential {
2895 return [database_ cache][iterator_].InstBroken();
2898 - (BOOL) unfiltered {
2899 _profile(Package$unfiltered$obsolete)
2900 if (_unlikely(obsolete_))
2904 _profile(Package$unfiltered$role)
2905 if (_unlikely(role_ > 3))
2913 if (![self unfiltered])
2918 _profile(Package$visible$section)
2919 section = [self section];
2922 _profile(Package$visible$isSectionVisible)
2923 if (!isSectionVisible(section))
2931 unsigned char current(iterator_->CurrentState);
2932 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2935 - (BOOL) halfConfigured {
2936 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2939 - (BOOL) halfInstalled {
2940 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2944 @synchronized (database_) {
2945 if ([database_ era] != era_ || iterator_.end())
2948 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2949 return state.Mode != pkgDepCache::ModeKeep;
2952 - (NSString *) mode {
2953 @synchronized (database_) {
2954 if ([database_ era] != era_ || iterator_.end())
2957 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2959 switch (state.Mode) {
2960 case pkgDepCache::ModeDelete:
2961 if ((state.iFlags & pkgDepCache::Purge) != 0)
2965 case pkgDepCache::ModeKeep:
2966 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2967 return @"REINSTALL";
2968 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2972 case pkgDepCache::ModeInstall:
2973 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2974 return @"REINSTALL";
2975 else*/ switch (state.Status) {
2977 return @"DOWNGRADE";
2983 return @"NEW_INSTALL";
2994 - (NSString *) name {
2995 return name_.empty() ? id_ : name_;
2998 - (UIImage *) icon {
2999 NSString *section = [self simpleSection];
3002 if (parsed_ != NULL)
3003 if (NSString *href = parsed_->icon_)
3004 if ([href hasPrefix:@"file:///"])
3005 icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
3006 if (icon == nil) if (section != nil)
3007 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]];
3008 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
3009 if ([dicon hasPrefix:@"file:///"])
3010 icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
3012 icon = [UIImage imageNamed:@"unknown.png"];
3016 - (NSString *) homepage {
3017 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
3020 - (NSString *) depiction {
3021 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
3024 - (MIMEAddress *) author {
3025 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
3028 - (NSString *) support {
3029 return parsed_ != NULL && !parsed_->support_.empty() ? parsed_->support_ : [[self source] supportForPackage:id_];
3032 - (NSArray *) files {
3033 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
3034 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
3037 fin.open([path UTF8String]);
3042 while (std::getline(fin, line))
3043 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
3048 - (NSString *) state {
3049 @synchronized (database_) {
3050 if ([database_ era] != era_ || file_.end())
3053 switch (iterator_->CurrentState) {
3054 case pkgCache::State::NotInstalled:
3055 return @"NotInstalled";
3056 case pkgCache::State::UnPacked:
3058 case pkgCache::State::HalfConfigured:
3059 return @"HalfConfigured";
3060 case pkgCache::State::HalfInstalled:
3061 return @"HalfInstalled";
3062 case pkgCache::State::ConfigFiles:
3063 return @"ConfigFiles";
3064 case pkgCache::State::Installed:
3065 return @"Installed";
3066 case pkgCache::State::TriggersAwaited:
3067 return @"TriggersAwaited";
3068 case pkgCache::State::TriggersPending:
3069 return @"TriggersPending";
3072 return (NSString *) [NSNull null];
3075 - (NSString *) selection {
3076 @synchronized (database_) {
3077 if ([database_ era] != era_ || file_.end())
3080 switch (iterator_->SelectedState) {
3081 case pkgCache::State::Unknown:
3083 case pkgCache::State::Install:
3085 case pkgCache::State::Hold:
3087 case pkgCache::State::DeInstall:
3088 return @"DeInstall";
3089 case pkgCache::State::Purge:
3093 return (NSString *) [NSNull null];
3096 - (NSArray *) warnings {
3097 @synchronized (database_) {
3098 if ([database_ era] != era_ || file_.end())
3101 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
3102 const char *name(iterator_.Name());
3104 size_t length(strlen(name));
3105 if (length < 2) invalid:
3106 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
3107 else for (size_t i(0); i != length; ++i)
3109 /* XXX: technically this is not allowed */
3110 (name[i] < 'A' || name[i] > 'Z') &&
3111 (name[i] < 'a' || name[i] > 'z') &&
3112 (name[i] < '0' || name[i] > '9') &&
3113 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
3116 if (strcmp(name, "cydia") != 0) {
3119 bool _private = false;
3121 bool dbstash = false;
3122 bool dsstore = false;
3124 bool repository = [[self section] isEqualToString:@"Repositories"];
3126 if (NSArray *files = [self files])
3127 for (NSString *file in files)
3128 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
3130 else if (!user && [file isEqualToString:@"/User"])
3132 else if (!_private && [file isEqualToString:@"/private"])
3134 else if (!stash && [file isEqualToString:@"/var/stash"])
3136 else if (!dbstash && [file isEqualToString:@"/var/db/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"), @"/var/db/stash"]];
3153 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @".DS_Store"]];
3156 return [warnings count] == 0 ? nil : warnings;
3159 - (NSArray *) applications {
3160 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
3162 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
3164 static RegEx application_r("/Applications/(.*)\\.app/Info.plist");
3165 if (NSArray *files = [self files])
3166 for (NSString *file in files)
3167 if (application_r(file)) {
3168 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
3171 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
3172 if (id == nil || [id isEqualToString:me])
3175 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
3177 display = application_r[1];
3179 NSString *bundle([file stringByDeletingLastPathComponent]);
3180 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
3181 // XXX: maybe this should check if this is really a string, not just for length
3182 if (icon == nil || ![icon respondsToSelector:@selector(length)] || [icon length] == 0)
3184 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
3186 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
3187 [applications addObject:application];
3189 [application addObject:id];
3190 [application addObject:display];
3191 [application addObject:url];
3194 return [applications count] == 0 ? nil : applications;
3197 - (Source *) source {
3198 if (source_ == nil) {
3199 @synchronized (database_) {
3200 if ([database_ era] != era_ || file_.end())
3201 source_ = (Source *) [NSNull null];
3203 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
3207 return source_ == (Source *) [NSNull null] ? nil : source_;
3210 - (time_t) upgraded {
3214 - (uint32_t) recent {
3215 return std::numeric_limits<uint32_t>::max() - upgraded_;
3222 - (BOOL) matches:(NSArray *)query {
3223 if (query == nil || [query count] == 0)
3232 string = [self name];
3233 length = [string length];
3236 for (NSString *term in query) {
3237 range = [string rangeOfString:term options:MatchCompareOptions_];
3238 if (range.location != NSNotFound)
3239 rank_ -= 6 * 1000000 / length;
3244 length = [string length];
3247 for (NSString *term in query) {
3248 range = [string rangeOfString:term options:MatchCompareOptions_];
3249 if (range.location != NSNotFound)
3250 rank_ -= 6 * 1000000 / length;
3254 string = [self shortDescription];
3255 length = [string length];
3256 NSUInteger stop(std::min<NSUInteger>(length, 200));
3259 for (NSString *term in query) {
3260 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
3261 if (range.location != NSNotFound)
3262 rank_ -= 2 * 100000;
3268 - (NSArray *) tags {
3272 - (BOOL) hasTag:(NSString *)tag {
3273 return tags_ == nil ? NO : [tags_ containsObject:tag];
3276 - (NSString *) primaryPurpose {
3277 for (NSString *tag in (NSArray *) tags_)
3278 if ([tag hasPrefix:@"purpose::"])
3279 return [tag substringFromIndex:9];
3283 - (NSArray *) purposes {
3284 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
3285 for (NSString *tag in (NSArray *) tags_)
3286 if ([tag hasPrefix:@"purpose::"])
3287 [purposes addObject:[tag substringFromIndex:9]];
3288 return [purposes count] == 0 ? nil : purposes;
3291 - (bool) isCommercial {
3292 return [self hasTag:@"cydia::commercial"];
3295 - (void) setIndex:(size_t)index {
3296 if (metadata_->index_ != index)
3297 metadata_->index_ = index;
3300 - (CYString &) cyname {
3301 return !transform_.empty() ? transform_ : !name_.empty() ? name_ : id_;
3304 - (uint32_t) compareBySection:(NSArray *)sections {
3305 NSString *section([self section]);
3306 for (size_t i(0), e([sections count]); i != e; ++i) {
3307 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3311 return _not(uint32_t);
3315 @synchronized (database_) {
3316 pkgProblemResolver *resolver = [database_ resolver];
3317 resolver->Clear(iterator_);
3319 pkgCacheFile &cache([database_ cache]);
3320 cache->SetReInstall(iterator_, false);
3321 cache->MarkKeep(iterator_, false);
3325 @synchronized (database_) {
3326 pkgProblemResolver *resolver = [database_ resolver];
3327 resolver->Clear(iterator_);
3328 resolver->Protect(iterator_);
3330 pkgCacheFile &cache([database_ cache]);
3331 cache->SetReInstall(iterator_, false);
3332 cache->MarkInstall(iterator_, false);
3334 pkgDepCache::StateCache &state((*cache)[iterator_]);
3335 if (!state.Install())
3336 cache->SetReInstall(iterator_, true);
3340 @synchronized (database_) {
3341 pkgProblemResolver *resolver = [database_ resolver];
3342 resolver->Clear(iterator_);
3343 resolver->Remove(iterator_);
3344 resolver->Protect(iterator_);
3346 pkgCacheFile &cache([database_ cache]);
3347 cache->SetReInstall(iterator_, false);
3348 cache->MarkDelete(iterator_, true);
3353 /* Section Class {{{ */
3354 @interface Section : NSObject {
3358 _H<NSString> localized_;
3361 - (NSComparisonResult) compareByLocalized:(Section *)section;
3362 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3363 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3364 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3366 - (NSString *) name;
3367 - (void) setName:(NSString *)name;
3373 - (void) addToCount;
3375 - (void) setCount:(size_t)count;
3376 - (NSString *) localized;
3380 @implementation Section
3382 - (NSComparisonResult) compareByLocalized:(Section *)section {
3383 NSString *lhs(localized_);
3384 NSString *rhs([section localized]);
3386 /*if ([lhs length] != 0 && [rhs length] != 0) {
3387 unichar lhc = [lhs characterAtIndex:0];
3388 unichar rhc = [rhs characterAtIndex:0];
3390 if (isalpha(lhc) && !isalpha(rhc))
3391 return NSOrderedAscending;
3392 else if (!isalpha(lhc) && isalpha(rhc))
3393 return NSOrderedDescending;
3396 return [lhs compare:rhs options:LaxCompareOptions_];
3399 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3400 if ((self = [self initWithName:name localize:NO]) != nil) {
3401 if (localized != nil)
3402 localized_ = localized;
3406 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3407 return [self initWithName:name row:0 localize:localize];
3410 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3411 if ((self = [super init]) != nil) {
3415 localized_ = LocalizeSection(name_);
3419 - (NSString *) name {
3423 - (void) setName:(NSString *)name {
3439 - (void) addToCount {
3443 - (void) setCount:(size_t)count {
3447 - (NSString *) localized {
3454 class CydiaLogCleaner :
3455 public pkgArchiveCleaner
3458 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3463 /* Database Implementation {{{ */
3464 @implementation Database
3466 + (Database *) sharedInstance {
3467 static _H<Database> instance;
3468 if (instance == nil)
3469 instance = [[[Database alloc] init] autorelease];
3477 - (void) releasePackages {
3478 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3479 CFArrayRemoveAllValues(packages_);
3483 // XXX: actually implement this thing
3485 [self releasePackages];
3486 NSRecycleZone(zone_);
3490 - (void) _readCydia:(NSNumber *)fd {
3491 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3492 std::istream is(&ib);
3495 static RegEx finish_r("finish:([^:]*)");
3497 while (std::getline(is, line)) {
3498 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3500 const char *data(line.c_str());
3501 size_t size = line.size();
3502 lprintf("C:%s\n", data);
3504 if (finish_r(data, size)) {
3505 NSString *finish = finish_r[1];
3506 int index = [Finishes_ indexOfObject:finish];
3507 if (index != INT_MAX && index > Finish_)
3517 - (void) _readStatus:(NSNumber *)fd {
3518 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3519 std::istream is(&ib);
3522 static RegEx conffile_r("status: [^ ]* : conffile-prompt : (.*?) *");
3523 static RegEx pmstatus_r("([^:]*):([^:]*):([^:]*):(.*)");
3525 while (std::getline(is, line)) {
3526 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3528 const char *data(line.c_str());
3529 size_t size(line.size());
3530 lprintf("S:%s\n", data);
3532 if (conffile_r(data, size)) {
3533 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3534 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3535 } else if (strncmp(data, "status: ", 8) == 0) {
3536 // status: <package>: {unpacked,half-configured,installed}
3537 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3538 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3539 } else if (strncmp(data, "processing: ", 12) == 0) {
3540 // processing: configure: config-test
3541 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3542 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3543 } else if (pmstatus_r(data, size)) {
3544 std::string type([pmstatus_r[1] UTF8String]);
3546 NSString *package = pmstatus_r[2];
3547 if ([package isEqualToString:@"dpkg-exec"])
3550 float percent([pmstatus_r[3] floatValue]);
3551 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3553 NSString *string = pmstatus_r[4];
3555 if (type == "pmerror") {
3556 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3557 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3558 } else if (type == "pmstatus") {
3559 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3560 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3561 } else if (type == "pmconffile")
3562 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3564 lprintf("E:unknown pmstatus\n");
3566 lprintf("E:unknown status\n");
3574 - (void) _readOutput:(NSNumber *)fd {
3575 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3576 std::istream is(&ib);
3579 while (std::getline(is, line)) {
3580 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3582 lprintf("O:%s\n", line.c_str());
3584 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3585 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3597 - (Package *) packageWithName:(NSString *)name {
3600 @synchronized (self) {
3601 if (static_cast<pkgDepCache *>(cache_) == NULL)
3603 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3604 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:NULL database:self];
3608 if ((self = [super init]) != nil) {
3615 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3617 size_t capacity(MetaFile_->active_);
3623 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3624 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3628 _assert(pipe(fds) != -1);
3631 _config->Set("APT::Keep-Fds::", cydiafd_);
3632 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3635 detachNewThreadSelector:@selector(_readCydia:)
3637 withObject:[NSNumber numberWithInt:fds[0]]
3640 _assert(pipe(fds) != -1);
3644 detachNewThreadSelector:@selector(_readStatus:)
3646 withObject:[NSNumber numberWithInt:fds[0]]
3649 _assert(pipe(fds) != -1);
3650 _assert(dup2(fds[0], 0) != -1);
3651 _assert(close(fds[0]) != -1);
3653 input_ = fdopen(fds[1], "a");
3655 _assert(pipe(fds) != -1);
3656 _assert(dup2(fds[1], 1) != -1);
3657 _assert(close(fds[1]) != -1);
3660 detachNewThreadSelector:@selector(_readOutput:)
3662 withObject:[NSNumber numberWithInt:fds[0]]
3667 - (pkgCacheFile &) cache {
3671 - (pkgDepCache::Policy *) policy {
3675 - (pkgRecords *) records {
3679 - (pkgProblemResolver *) resolver {
3683 - (pkgAcquire &) fetcher {
3687 - (pkgSourceList &) list {
3691 - (NSArray *) packages {
3692 return (NSArray *) packages_;
3695 - (NSArray *) sources {
3699 - (Source *) sourceWithKey:(NSString *)key {
3700 for (Source *source in [self sources]) {
3701 if ([[source key] isEqualToString:key])
3706 - (bool) popErrorWithTitle:(NSString *)title {
3709 while (!_error->empty()) {
3711 bool warning(!_error->PopMessage(error));
3716 size_t size(error.size());
3717 if (size == 0 || error[size - 1] != '\n')
3719 error.resize(size - 1);
3722 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3724 static RegEx no_pubkey("GPG error:.* NO_PUBKEY .*");
3725 if (warning && no_pubkey(error.c_str()))
3728 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3734 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3735 return [self popErrorWithTitle:title] || !success;
3738 - (bool) _isEtceteraAptSourcesListDirectoryCydiaListSymbolicallyLinkedToMobileCachesCydiaSourceList {
3740 ssize_t length(readlink("/etc/apt/sources.list.d/cydia.list", target, sizeof(target) - 1));
3743 if (length >= sizeof(target))
3745 target[length] = '\0';
3746 return strcmp(target, "/var/mobile/Library/Caches/com.saurik.Cydia/sources.list") == 0;
3749 - (bool) popErrorWithTitle:(NSString *)title forReadList:(pkgSourceList &)list {
3750 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3752 if (![self _isEtceteraAptSourcesListDirectoryCydiaListSymbolicallyLinkedToMobileCachesCydiaSourceList])
3753 if ([self popErrorWithTitle:title forOperation:list.Read(SOURCES_LIST)])
3758 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3759 @synchronized (self) {
3762 [self releasePackages];
3765 [sourceList_ removeAllObjects];
3786 new (&pool_) CYPool();
3788 NSRecycleZone(zone_);
3789 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3791 int chk(creat("/tmp/cydia.chk", 0644));
3795 if (invocation != nil)
3796 [invocation invoke];
3798 NSString *title(UCLocalize("DATABASE"));
3800 list_ = new pkgSourceList();
3801 _profile(reloadDataWithInvocation$ReadMainList)
3802 if ([self popErrorWithTitle:title forReadList:*list_])
3806 _profile(reloadDataWithInvocation$Source$initWithMetaIndex)
3807 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3808 Source *object([[[Source alloc] initWithMetaIndex:*source forDatabase:self inPool:&pool_] autorelease]);
3809 [sourceList_ addObject:object];
3814 OpProgress progress;
3817 delock_ = GetStatusDate();
3818 _profile(reloadDataWithInvocation$pkgCacheFile)
3819 opened = cache_.Open(progress, false);
3822 // XXX: what if there are errors, but Open() == true? this should be merged with popError:
3823 while (!_error->empty()) {
3825 bool warning(!_error->PopMessage(error));
3827 lprintf("cache_.Open():[%s]\n", error.c_str());
3829 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3833 else if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3834 repair = @selector(configure);
3835 //else if (error == "The package lists or status file could not be parsed or opened.")
3836 // repair = @selector(update);
3837 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3838 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3839 // else if (error == "Malformed Status line")
3840 // else if (error == "The list of sources could not be read.")
3842 if (repair != NULL) {
3844 [delegate_ repairWithSelector:repair];
3853 unlink("/tmp/cydia.chk");
3855 now_ = [[NSDate date] timeIntervalSince1970];
3857 policy_ = new pkgDepCache::Policy();
3858 records_ = new pkgRecords(cache_);
3859 resolver_ = new pkgProblemResolver(cache_);
3860 fetcher_ = new pkgAcquire(&status_);
3863 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3864 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3868 _profile(reloadDataWithInvocation$pkgApplyStatus)
3869 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3873 if (cache_->BrokenCount() != 0) {
3874 _profile(pkgApplyStatus$pkgFixBroken)
3875 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3879 if (cache_->BrokenCount() != 0) {
3880 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3884 _profile(pkgApplyStatus$pkgMinimizeUpgrade)
3885 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3890 for (Source *object in (id) sourceList_) {
3891 metaIndex *source([object metaIndex]);
3892 std::vector<pkgIndexFile *> *indices = source->GetIndexFiles();
3893 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3894 // XXX: this could be more intelligent
3895 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3896 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3898 sourceMap_[cached->ID] = object;
3903 /*std::vector<Package *> packages;
3904 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3907 _profile(reloadDataWithInvocation$packageWithIterator)
3908 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3909 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:&pool_ database:self])
3910 //packages.push_back(package);
3911 CFArrayAppendValue(packages_, CFRetain(package));
3915 /*if (packages.empty())
3916 packages_ = [[NSArray alloc] init];
3918 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3921 _profile(reloadDataWithInvocation$radix$8)
3922 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(8)];
3925 _profile(reloadDataWithInvocation$radix$4)
3926 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3929 _profile(reloadDataWithInvocation$radix$0)
3930 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3933 _profile(reloadDataWithInvocation$insertion)
3934 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3937 /*_profile(reloadDataWithInvocation$CFQSortArray)
3938 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);
3941 /*_profile(reloadDataWithInvocation$stdsort)
3942 std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3945 /*_profile(reloadDataWithInvocation$CFArraySortValues)
3946 CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3949 /*_profile(reloadDataWithInvocation$sortUsingFunction)
3950 [packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3954 size_t count(CFArrayGetCount(packages_));
3955 MetaFile_->active_ = count;
3956 for (size_t index(0); index != count; ++index)
3957 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3962 @synchronized (self) {
3964 resolver_ = new pkgProblemResolver(cache_);
3966 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3967 if (!cache_[iterator].Keep())
3968 cache_->MarkKeep(iterator, false);
3969 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3970 cache_->SetReInstall(iterator, false);
3973 - (void) configure {
3974 NSString *dpkg = [NSString stringWithFormat:@"/usr/libexec/cydo --configure -a --status-fd %u", statusfd_];
3976 system([dpkg UTF8String]);
3981 @synchronized (self) {
3982 // XXX: I don't remember this condition
3987 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3989 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3991 if ([self popErrorWithTitle:title])
3995 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3997 CydiaLogCleaner cleaner;
3998 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
4005 fetcher_->Shutdown();
4007 pkgRecords records(cache_);
4009 lock_ = new FileFd();
4010 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
4012 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
4014 if ([self popErrorWithTitle:title])
4018 if ([self popErrorWithTitle:title forReadList:list])
4021 manager_ = (_system->CreatePM(cache_));
4022 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
4029 bool substrate(RestartSubstrate_);
4030 RestartSubstrate_ = false;
4032 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
4034 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
4036 if ([self popErrorWithTitle:title forReadList:list])
4038 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
4039 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
4042 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4044 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
4046 [self popErrorWithTitle:title];
4050 bool failed = false;
4051 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
4052 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
4054 if ((*item)->Status == pkgAcquire::Item::StatIdle)
4057 std::string uri = (*item)->DescURI();
4058 std::string error = (*item)->ErrorText;
4060 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
4063 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError]);
4064 [delegate_ addProgressEventOnMainThread:event forTask:title];
4067 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4075 RestartSubstrate_ = true;
4077 if (![delock_ isEqual:GetStatusDate()]) {
4078 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("DPKG_LOCKED") ofType:kCydiaProgressEventTypeError] forTask:title];
4084 pkgPackageManager::OrderResult result(manager_->DoInstall(statusfd_));
4086 NSString *oextended(@"/var/lib/apt/extended_states");
4087 NSString *nextended(Cache("extended_states"));
4090 if (stat([nextended UTF8String], &info) != -1 && (info.st_mode & S_IFMT) == S_IFREG) {
4091 system([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /bin/mv -f %@ %@", nextended, oextended] UTF8String]);
4092 system([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /bin/chown 0:0 %@", oextended] UTF8String]);
4095 unlink([nextended UTF8String]);
4096 symlink([oextended UTF8String], [nextended UTF8String]);
4098 if ([self popErrorWithTitle:title])
4101 if (result == pkgPackageManager::Failed) {
4106 if (result != pkgPackageManager::Completed) {
4111 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
4113 if ([self popErrorWithTitle:title forReadList:list])
4115 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
4116 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
4119 if (![before isEqualToArray:after])
4124 return ![delock_ isEqual:GetStatusDate()];
4128 NSString *title(UCLocalize("UPGRADE"));
4129 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
4135 [self updateWithStatus:status_];
4138 - (void) updateWithStatus:(CancelStatus &)status {
4139 NSString *title(UCLocalize("REFRESHING_DATA"));
4142 if ([self popErrorWithTitle:title forReadList:list])
4146 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
4147 if ([self popErrorWithTitle:title])
4150 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4152 bool success(ListUpdate(status, list, PulseInterval_));
4153 if (status.WasCancelled())
4156 [self popErrorWithTitle:title forOperation:success];
4158 [[NSDictionary dictionaryWithObjectsAndKeys:
4159 [NSDate date], @"LastUpdate",
4160 nil] writeToFile:@ CacheState_ atomically:YES];
4163 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4166 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
4167 delegate_ = delegate;
4170 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
4171 progress_ = delegate;
4172 status_.setDelegate(delegate);
4175 - (NSObject<ProgressDelegate> *) progressDelegate {
4179 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
4180 SourceMap::const_iterator i(sourceMap_.find(file->ID));
4181 return i == sourceMap_.end() ? nil : i->second;
4184 - (void) setFetch:(bool)fetch forURI:(const char *)uri {
4185 for (Source *source in (id) sourceList_)
4186 [source setFetch:fetch forURI:uri];
4189 - (void) resetFetch {
4190 for (Source *source in (id) sourceList_)
4191 [source resetFetch];
4194 - (NSString *) mappedSectionForPointer:(const char *)section {
4195 _H<NSString> *mapped;
4197 _profile(Database$mappedSectionForPointer$Cache)
4198 mapped = §ions_[section];
4201 if (*mapped == NULL) {
4202 size_t length(strlen(section));
4203 char spaced[length + 1];
4205 _profile(Database$mappedSectionForPointer$Replace)
4206 for (size_t index(0); index != length; ++index)
4207 spaced[index] = section[index] == '_' ? ' ' : section[index];
4208 spaced[length] = '\0';
4213 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
4214 string = [NSString stringWithUTF8String:spaced];
4217 _profile(Database$mappedSectionForPointer$Map)
4218 string = [SectionMap_ objectForKey:string] ?: string;
4228 static _H<NSMutableSet> Diversions_;
4230 @interface Diversion : NSObject {
4233 _H<NSString> format_;
4238 @implementation Diversion
4240 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
4241 if ((self = [super init]) != nil) {
4242 pattern_ = [from UTF8String];
4248 - (NSString *) divert:(NSString *)url {
4249 return !pattern_(url) ? nil : pattern_->*format_;
4252 + (NSURL *) divertURL:(NSURL *)url {
4254 NSString *href([url absoluteString]);
4256 for (Diversion *diversion in (id) Diversions_)
4257 if (NSString *diverted = [diversion divert:href]) {
4259 NSLog(@"div: %@", diverted);
4261 url = [NSURL URLWithString:diverted];
4268 - (NSString *) key {
4272 - (NSUInteger) hash {
4276 - (BOOL) isEqual:(Diversion *)object {
4277 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
4282 @interface CydiaObject : NSObject {
4283 _H<CyteWebViewController> indirect_;
4284 _transient id delegate_;
4287 - (id) initWithDelegate:(IndirectDelegate *)indirect;
4293 @interface CydiaWebViewController : CyteWebViewController {
4294 _H<CydiaObject> cydia_;
4297 + (void) addDiversion:(Diversion *)diversion;
4298 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request;
4299 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia;
4300 - (void) setDelegate:(id)delegate;
4304 /* Web Scripting {{{ */
4305 @implementation CydiaObject
4307 - (id) initWithDelegate:(IndirectDelegate *)indirect {
4308 if ((self = [super init]) != nil) {
4309 indirect_ = (CyteWebViewController *) indirect;
4313 - (void) setDelegate:(id)delegate {
4314 delegate_ = delegate;
4317 + (NSArray *) _attributeKeys {
4318 return [NSArray arrayWithObjects:
4321 @"coreFoundationVersionNumber",
4337 - (NSArray *) attributeKeys {
4338 return [[self class] _attributeKeys];
4341 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4342 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4345 - (NSString *) version {
4349 - (NSString *) build {
4353 - (NSString *) coreFoundationVersionNumber {
4354 return [NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber];
4357 - (NSString *) device {
4358 return UniqueIdentifier();
4361 - (NSString *) firmware {
4362 return [[UIDevice currentDevice] systemVersion];
4365 - (NSString *) hostname {
4366 return [[UIDevice currentDevice] name];
4369 - (NSString *) idiom {
4370 return (id) Idiom_ ?: [NSNull null];
4373 - (NSString *) mcc {
4374 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode")))
4375 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault) autorelease];
4379 - (NSString *) mnc {
4380 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberNetworkCode")))
4381 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault) autorelease];
4385 - (NSString *) operator {
4386 if (CFStringRef (*$CTRegistrationCopyOperatorName)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTRegistrationCopyOperatorName")))
4387 return [(NSString *) (*$CTRegistrationCopyOperatorName)(kCFAllocatorDefault) autorelease];
4391 - (NSString *) bbsnum {
4392 return (id) BBSNum_ ?: [NSNull null];
4395 - (NSString *) ecid {
4396 return (id) ChipID_ ?: [NSNull null];
4399 - (NSString *) serial {
4400 return SerialNumber_;
4403 - (NSString *) role {
4404 return (id) [NSNull null];
4407 - (NSString *) model {
4408 return [NSString stringWithUTF8String:Machine_];
4411 + (NSString *) webScriptNameForSelector:(SEL)selector {
4413 else if (selector == @selector(addBridgedHost:))
4414 return @"addBridgedHost";
4415 else if (selector == @selector(addInsecureHost:))
4416 return @"addInsecureHost";
4417 else if (selector == @selector(addInternalRedirect::))
4418 return @"addInternalRedirect";
4419 else if (selector == @selector(addPipelinedHost:scheme:))
4420 return @"addPipelinedHost";
4421 else if (selector == @selector(addSource:::))
4422 return @"addSource";
4423 else if (selector == @selector(addTrivialSource:))
4424 return @"addTrivialSource";
4425 else if (selector == @selector(close))
4427 else if (selector == @selector(du:))
4429 else if (selector == @selector(stringWithFormat:arguments:))
4431 else if (selector == @selector(getAllSources))
4432 return @"getAllSources";
4433 else if (selector == @selector(getApplicationInfo:value:))
4434 return @"getApplicationInfoValue";
4435 else if (selector == @selector(getKernelNumber:))
4436 return @"getKernelNumber";
4437 else if (selector == @selector(getKernelString:))
4438 return @"getKernelString";
4439 else if (selector == @selector(getInstalledPackages))
4440 return @"getInstalledPackages";
4441 else if (selector == @selector(getIORegistryEntry::))
4442 return @"getIORegistryEntry";
4443 else if (selector == @selector(getLocaleIdentifier))
4444 return @"getLocaleIdentifier";
4445 else if (selector == @selector(getPreferredLanguages))
4446 return @"getPreferredLanguages";
4447 else if (selector == @selector(getPackageById:))
4448 return @"getPackageById";
4449 else if (selector == @selector(getMetadataKeys))
4450 return @"getMetadataKeys";
4451 else if (selector == @selector(getMetadataValue:))
4452 return @"getMetadataValue";
4453 else if (selector == @selector(getSessionValue:))
4454 return @"getSessionValue";
4455 else if (selector == @selector(installPackages:))
4456 return @"installPackages";
4457 else if (selector == @selector(isReachable:))
4458 return @"isReachable";
4459 else if (selector == @selector(localizedStringForKey:value:table:))
4461 else if (selector == @selector(popViewController:))
4462 return @"popViewController";
4463 else if (selector == @selector(refreshSources))
4464 return @"refreshSources";
4465 else if (selector == @selector(registerFrame:))
4466 return @"registerFrame";
4467 else if (selector == @selector(removeButton))
4468 return @"removeButton";
4469 else if (selector == @selector(saveConfig))
4470 return @"saveConfig";
4471 else if (selector == @selector(setMetadataValue::))
4472 return @"setMetadataValue";
4473 else if (selector == @selector(setSessionValue::))
4474 return @"setSessionValue";
4475 else if (selector == @selector(substitutePackageNames:))
4476 return @"substitutePackageNames";
4477 else if (selector == @selector(scrollToBottom:))
4478 return @"scrollToBottom";
4479 else if (selector == @selector(setAllowsNavigationAction:))
4480 return @"setAllowsNavigationAction";
4481 else if (selector == @selector(setBadgeValue:))
4482 return @"setBadgeValue";
4483 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4484 return @"setButtonImage";
4485 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4486 return @"setButtonTitle";
4487 else if (selector == @selector(setHidesBackButton:))
4488 return @"setHidesBackButton";
4489 else if (selector == @selector(setHidesNavigationBar:))
4490 return @"setHidesNavigationBar";
4491 else if (selector == @selector(setNavigationBarStyle:))
4492 return @"setNavigationBarStyle";
4493 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4494 return @"setNavigationBarTintColor";
4495 else if (selector == @selector(setPasteboardString:))
4496 return @"setPasteboardString";
4497 else if (selector == @selector(setPasteboardURL:))
4498 return @"setPasteboardURL";
4499 else if (selector == @selector(setScrollAlwaysBounceVertical:))
4500 return @"setScrollAlwaysBounceVertical";
4501 else if (selector == @selector(setScrollIndicatorStyle:))
4502 return @"setScrollIndicatorStyle";
4503 else if (selector == @selector(setToken:))
4505 else if (selector == @selector(setViewportWidth:))
4506 return @"setViewportWidth";
4507 else if (selector == @selector(statfs:))
4509 else if (selector == @selector(supports:))
4511 else if (selector == @selector(unload))
4517 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4518 return [self webScriptNameForSelector:selector] == nil;
4521 - (BOOL) supports:(NSString *)feature {
4522 return [feature isEqualToString:@"window.open"];
4526 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4529 - (void) setScrollAlwaysBounceVertical:(NSNumber *)value {
4530 [indirect_ performSelectorOnMainThread:@selector(setScrollAlwaysBounceVerticalNumber:) withObject:value waitUntilDone:NO];
4533 - (void) setScrollIndicatorStyle:(NSString *)style {
4534 [indirect_ performSelectorOnMainThread:@selector(setScrollIndicatorStyleWithName:) withObject:style waitUntilDone:NO];
4537 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4538 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4541 - (NSDictionary *) getApplicationInfo:(NSString *)display value:(NSString *)key {
4543 if (SBBundlePathForDisplayIdentifier(SBSSpringBoardServerPort(), [display UTF8String], path) != 0)
4544 return (id) [NSNull null];
4545 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:[[NSString stringWithUTF8String:path] stringByAppendingString:@"/Info.plist"]]);
4547 return (id) [NSNull null];
4548 return [info objectForKey:key];
4551 - (NSNumber *) getKernelNumber:(NSString *)name {
4552 const char *string([name UTF8String]);
4555 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4556 return (id) [NSNull null];
4558 if (size != sizeof(int))
4559 return (id) [NSNull null];
4562 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4563 return (id) [NSNull null];
4565 return [NSNumber numberWithInt:value];
4568 - (NSString *) getKernelString:(NSString *)name {
4569 const char *string([name UTF8String]);
4572 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4573 return (id) [NSNull null];
4575 char value[size + 1];
4576 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4577 return (id) [NSNull null];
4579 // XXX: just in case you request something ludicrous
4582 return [NSString stringWithCString:value];
4585 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4586 NSObject *value(CYIOGetValue([path UTF8String], entry));
4589 if ([value isKindOfClass:[NSData class]])
4590 value = CYHex((NSData *) value);
4595 - (NSArray *) getMetadataKeys {
4596 @synchronized (Values_) {
4597 return [Values_ allKeys];
4600 - (void) registerFrame:(DOMHTMLIFrameElement *)iframe {
4601 WebFrame *frame([iframe contentFrame]);
4602 [indirect_ registerFrame:frame];
4605 - (id) getMetadataValue:(NSString *)key {
4606 @synchronized (Values_) {
4607 return [Values_ objectForKey:key];
4610 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4611 @synchronized (Values_) {
4612 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4613 [Values_ removeObjectForKey:key];
4615 [Values_ setObject:value forKey:key];
4618 - (id) getSessionValue:(NSString *)key {
4619 @synchronized (SessionData_) {
4620 return [SessionData_ objectForKey:key];
4623 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4624 @synchronized (SessionData_) {
4625 if (value == (id) [WebUndefined undefined])
4626 [SessionData_ removeObjectForKey:key];
4628 [SessionData_ setObject:value forKey:key];
4631 - (void) addBridgedHost:(NSString *)host {
4632 @synchronized (HostConfig_) {
4633 [BridgedHosts_ addObject:host];
4636 - (void) addInsecureHost:(NSString *)host {
4637 @synchronized (HostConfig_) {
4638 [InsecureHosts_ addObject:host];
4641 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4642 @synchronized (HostConfig_) {
4643 if (scheme != (id) [WebUndefined undefined])
4644 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4646 [PipelinedHosts_ addObject:host];
4649 - (void) popViewController:(NSNumber *)value {
4650 if (value == (id) [WebUndefined undefined])
4651 value = [NSNumber numberWithBool:YES];
4652 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4655 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4656 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4658 for (NSString *section in sections)
4659 [array addObject:section];
4661 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4664 distribution, @"Distribution",
4666 nil] waitUntilDone:NO];
4669 - (void) addTrivialSource:(NSString *)href {
4670 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4673 - (void) refreshSources {
4674 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4677 - (void) saveConfig {
4678 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4681 - (NSArray *) getAllSources {
4682 return [[Database sharedInstance] sources];
4685 - (NSArray *) getInstalledPackages {
4686 Database *database([Database sharedInstance]);
4687 @synchronized (database) {
4688 NSArray *packages([database packages]);
4689 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4690 for (Package *package in packages)
4691 if (![package uninstalled])
4692 [installed addObject:package];
4696 - (Package *) getPackageById:(NSString *)id {
4697 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4701 return (Package *) [NSNull null];
4704 - (NSString *) getLocaleIdentifier {
4705 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4708 - (NSArray *) getPreferredLanguages {
4712 - (NSArray *) statfs:(NSString *)path {
4715 if (path == nil || statfs([path UTF8String], &stat) == -1)
4718 return [NSArray arrayWithObjects:
4719 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4720 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4721 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4725 - (NSNumber *) du:(NSString *)path {
4726 NSNumber *value(nil);
4728 FILE *du(popen([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /usr/libexec/cydia/du -ks %@", path] UTF8String], "r"));
4731 while (fgets(line, sizeof(line), du) != NULL) {
4732 size_t length(strlen(line));
4733 while (length != 0 && line[length - 1] == '\n')
4734 line[--length] = '\0';
4735 if (char *tab = strchr(line, '\t')) {
4737 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
4747 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4750 - (NSNumber *) isReachable:(NSString *)name {
4751 return [NSNumber numberWithBool:IsReachable([name UTF8String])];
4754 - (void) installPackages:(NSArray *)packages {
4755 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4758 - (NSString *) substitutePackageNames:(NSString *)message {
4759 NSMutableArray *words([[[message componentsSeparatedByString:@" "] mutableCopy] autorelease]);
4760 for (size_t i(0), e([words count]); i != e; ++i) {
4761 NSString *word([words objectAtIndex:i]);
4762 if (Package *package = [[Database sharedInstance] packageWithName:word])
4763 [words replaceObjectAtIndex:i withObject:[package name]];
4766 return [words componentsJoinedByString:@" "];
4769 - (void) removeButton {
4770 [indirect_ removeButton];
4773 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4774 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4777 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4778 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4781 - (void) setBadgeValue:(id)value {
4782 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4785 - (void) setAllowsNavigationAction:(NSString *)value {
4786 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4789 - (void) setHidesBackButton:(NSString *)value {
4790 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4793 - (void) setHidesNavigationBar:(NSString *)value {
4794 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4797 - (void) setNavigationBarStyle:(NSString *)value {
4798 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4801 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4802 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4803 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4804 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4807 - (void) setPasteboardString:(NSString *)value {
4808 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4811 - (void) setPasteboardURL:(NSString *)value {
4812 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4815 - (void) setToken:(NSString *)token {
4816 // XXX: the website expects this :/
4819 - (void) scrollToBottom:(NSNumber *)animated {
4820 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4823 - (void) setViewportWidth:(float)width {
4824 [indirect_ setViewportWidthOnMainThread:width];
4827 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4828 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4829 unsigned count([arguments count]);
4831 for (unsigned i(0); i != count; ++i)
4832 values[i] = [arguments objectAtIndex:i];
4833 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4836 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4837 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4839 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4841 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4847 @interface NSURL (CydiaSecure)
4850 @implementation NSURL (CydiaSecure)
4852 - (bool) isCydiaSecure {
4853 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4856 @synchronized (HostConfig_) {
4857 if ([InsecureHosts_ containsObject:[self host]])
4866 /* Cydia Browser Controller {{{ */
4867 @implementation CydiaWebViewController
4869 - (NSURL *) navigationURL {
4870 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4873 + (void) _initialize {
4874 [super _initialize];
4876 Diversions_ = [NSMutableSet setWithCapacity:0];
4879 + (void) addDiversion:(Diversion *)diversion {
4880 [Diversions_ addObject:diversion];
4883 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4884 [super webView:view didClearWindowObject:window forFrame:frame];
4885 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
4888 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia {
4889 WebDataSource *source([frame dataSource]);
4890 NSURLResponse *response([source response]);
4891 NSURL *url([response URL]);
4892 NSString *scheme([[url scheme] lowercaseString]);
4894 bool bridged(false);
4896 @synchronized (HostConfig_) {
4897 if ([scheme isEqualToString:@"file"])
4899 else if ([scheme isEqualToString:@"https"])
4900 if ([BridgedHosts_ containsObject:[url host]])
4905 [window setValue:cydia forKey:@"cydia"];
4908 - (void) _setupMail:(MFMailComposeViewController *)controller {
4909 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4911 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4912 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4915 - (NSURL *) URLWithURL:(NSURL *)url {
4916 return [Diversion divertURL:url];
4919 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4920 return [CydiaWebViewController requestWithHeaders:[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
4923 - (NSURLRequest *) webThreadWebView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4924 return [CydiaWebViewController requestWithHeaders:[super webThreadWebView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
4927 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request {
4928 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
4930 NSURL *url([copy URL]);
4931 NSString *href([url absoluteString]);
4932 NSString *host([url host]);
4934 if ([href hasPrefix:@"https://cydia.saurik.com/TSS/"]) {
4935 if (NSString *agent = [copy valueForHTTPHeaderField:@"X-User-Agent"]) {
4936 [copy setValue:agent forHTTPHeaderField:@"User-Agent"];
4937 [copy setValue:nil forHTTPHeaderField:@"X-User-Agent"];
4940 [copy setValue:nil forHTTPHeaderField:@"Referer"];
4941 [copy setValue:nil forHTTPHeaderField:@"Origin"];
4943 [copy setURL:[NSURL URLWithString:[@"http://gs.apple.com/TSS/" stringByAppendingString:[href substringFromIndex:29]]]];
4947 if ([copy valueForHTTPHeaderField:@"X-Cydia-Cf"] == nil)
4948 [copy setValue:[NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber] forHTTPHeaderField:@"X-Cydia-Cf"];
4949 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4950 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4952 bool bridged; @synchronized (HostConfig_) {
4953 bridged = [BridgedHosts_ containsObject:host];
4956 if ([url isCydiaSecure] && bridged && UniqueID_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Id"] == nil)
4957 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
4962 - (void) setDelegate:(id)delegate {
4963 [super setDelegate:delegate];
4964 [cydia_ setDelegate:delegate];
4967 - (NSString *) applicationNameForUserAgent {
4972 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4973 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
4979 @interface AppCacheController : CydiaWebViewController {
4984 @implementation AppCacheController
4986 - (void) didReceiveMemoryWarning {
4987 // XXX: this doesn't work
4990 - (bool) retainsNetworkActivityIndicator {
4998 @interface NSObject (CydiaScript)
4999 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
5002 @implementation NSObject (CydiaScript)
5004 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5010 @implementation NSArray (CydiaScript)
5012 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5013 WebScriptObject *object([context evaluateWebScript:@"[]"]);
5014 for (size_t i(0), e([self count]); i != e; ++i)
5015 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
5021 @implementation NSDictionary (CydiaScript)
5023 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5024 WebScriptObject *object([context evaluateWebScript:@"({})"]);
5026 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
5033 /* Confirmation Controller {{{ */
5034 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
5035 if (!iterator.end())
5036 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
5037 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
5039 pkgCache::PkgIterator package(dep.TargetPkg());
5042 if (strcmp(package.Name(), "mobilesubstrate") == 0)
5049 @protocol ConfirmationControllerDelegate
5050 - (void) cancelAndClear:(bool)clear;
5051 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
5055 @interface ConfirmationController : CydiaWebViewController {
5056 _transient Database *database_;
5058 _H<UIAlertView> essential_;
5060 _H<NSDictionary> changes_;
5061 _H<NSMutableArray> issues_;
5062 _H<NSDictionary> sizes_;
5067 - (id) initWithDatabase:(Database *)database;
5071 @implementation ConfirmationController
5075 RestartSubstrate_ = true;
5076 [delegate_ confirmWithNavigationController:[self navigationController]];
5079 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
5080 NSString *context([alert context]);
5082 if ([context isEqualToString:@"remove"]) {
5083 if (button == [alert cancelButtonIndex])
5085 else if (button == [alert firstOtherButtonIndex]) {
5086 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
5089 [alert dismissWithClickedButtonIndex:-1 animated:YES];
5090 } else if ([context isEqualToString:@"unable"]) {
5091 [self dismissModalViewControllerAnimated:YES];
5092 [alert dismissWithClickedButtonIndex:-1 animated:YES];
5094 [super alertView:alert clickedButtonAtIndex:button];
5098 - (void) _doContinue {
5099 [delegate_ cancelAndClear:NO];
5100 [self dismissModalViewControllerAnimated:YES];
5103 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
5104 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
5108 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5109 [super webView:view didClearWindowObject:window forFrame:frame];
5111 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
5112 (id) changes_, @"changes",
5113 (id) issues_, @"issues",
5114 (id) sizes_, @"sizes",
5116 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
5119 - (id) initWithDatabase:(Database *)database {
5120 if ((self = [super init]) != nil) {
5121 database_ = database;
5123 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
5124 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
5125 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
5126 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
5127 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
5131 pkgCacheFile &cache([database_ cache]);
5132 NSArray *packages([database_ packages]);
5133 pkgDepCache::Policy *policy([database_ policy]);
5135 issues_ = [NSMutableArray arrayWithCapacity:4];
5137 for (Package *package in packages) {
5138 pkgCache::PkgIterator iterator([package iterator]);
5139 NSString *name([package id]);
5141 if ([package broken]) {
5142 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
5144 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5146 reasons, @"reasons",
5149 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
5153 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
5154 pkgCache::DepIterator start;
5155 pkgCache::DepIterator end;
5156 dep.GlobOr(start, end); // ++dep
5158 if (!cache->IsImportantDep(end))
5160 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
5163 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
5165 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5166 [NSString stringWithUTF8String:start.DepType()], @"relationship",
5167 clauses, @"clauses",
5171 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
5173 pkgCache::PkgIterator target(start.TargetPkg());
5174 if (target->ProvidesList != 0)
5175 reason = @"missing";
5177 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
5179 reason = @"installed";
5180 installed = [NSString stringWithUTF8String:ver.VerStr()];
5181 } else if (!cache[target].CandidateVerIter(cache).end())
5182 reason = @"uninstalled";
5183 else if (target->ProvidesList == 0)
5184 reason = @"uninstallable";
5186 reason = @"virtual";
5189 NSDictionary *version(start.TargetVer() == 0 ? (NSDictionary *) [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
5190 [NSString stringWithUTF8String:start.CompType()], @"operator",
5191 [NSString stringWithUTF8String:start.TargetVer()], @"value",
5194 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5195 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
5196 version, @"version",
5198 installed, @"installed",
5201 // yes, seriously. (wtf?)
5209 pkgDepCache::StateCache &state(cache[iterator]);
5211 static RegEx special_r("(firmware|gsc\\..*|cy\\+.*)");
5213 if (state.NewInstall())
5214 [installs addObject:name];
5215 // XXX: else if (state.Install())
5216 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
5217 [reinstalls addObject:name];
5218 // XXX: move before previous if
5219 else if (state.Upgrade())
5220 [upgrades addObject:name];
5221 else if (state.Downgrade())
5222 [downgrades addObject:name];
5223 else if (!state.Delete())
5224 // XXX: _assert(state.Keep());
5226 else if (special_r(name))
5227 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5228 [NSNull null], @"package",
5229 [NSArray arrayWithObjects:
5230 [NSDictionary dictionaryWithObjectsAndKeys:
5231 @"Conflicts", @"relationship",
5232 [NSArray arrayWithObjects:
5233 [NSDictionary dictionaryWithObjectsAndKeys:
5235 [NSNull null], @"version",
5236 @"installed", @"reason",
5243 if ([package essential])
5245 [removes addObject:name];
5248 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
5249 substrate_ |= DepSubstrate(iterator.CurrentVer());
5254 else if (Advanced_) {
5255 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
5257 essential_ = [[[UIAlertView alloc]
5258 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
5259 message:UCLocalize("REMOVING_ESSENTIALS_EX")
5261 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
5263 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
5267 [essential_ setContext:@"remove"];
5268 [essential_ setNumberOfRows:2];
5270 essential_ = [[[UIAlertView alloc]
5271 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
5272 message:UCLocalize("UNABLE_TO_COMPLY_EX")
5274 cancelButtonTitle:UCLocalize("OKAY")
5275 otherButtonTitles:nil
5278 [essential_ setContext:@"unable"];
5281 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5282 installs, @"installs",
5283 reinstalls, @"reinstalls",
5284 upgrades, @"upgrades",
5285 downgrades, @"downgrades",
5286 removes, @"removes",
5289 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5290 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
5291 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
5294 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
5298 - (UIBarButtonItem *) leftButton {
5299 return [[[UIBarButtonItem alloc]
5300 initWithTitle:UCLocalize("CANCEL")
5301 style:UIBarButtonItemStylePlain
5303 action:@selector(cancelButtonClicked)
5308 - (void) applyRightButton {
5309 if ([issues_ count] == 0 && ![self isLoading])
5310 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
5311 initWithTitle:UCLocalize("CONFIRM")
5312 style:UIBarButtonItemStyleDone
5314 action:@selector(confirmButtonClicked)
5317 [[self navigationItem] setRightBarButtonItem:nil];
5321 - (void) cancelButtonClicked {
5322 [delegate_ cancelAndClear:YES];
5323 [self dismissModalViewControllerAnimated:YES];
5327 - (void) confirmButtonClicked {
5328 if (essential_ != nil)
5338 /* Progress Data {{{ */
5339 @interface CydiaProgressData : NSObject {
5340 _transient id delegate_;
5349 _H<NSMutableArray> events_;
5350 _H<NSString> title_;
5352 _H<NSString> status_;
5353 _H<NSString> finish_;
5358 @implementation CydiaProgressData
5360 + (NSArray *) _attributeKeys {
5361 return [NSArray arrayWithObjects:
5373 - (NSArray *) attributeKeys {
5374 return [[self class] _attributeKeys];
5377 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5378 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5382 if ((self = [super init]) != nil) {
5383 events_ = [NSMutableArray arrayWithCapacity:32];
5391 - (void) setDelegate:(id)delegate {
5392 delegate_ = delegate;
5395 - (void) setPercent:(float)value {
5399 - (NSNumber *) percent {
5400 return [NSNumber numberWithFloat:percent_];
5403 - (void) setCurrent:(float)value {
5407 - (NSNumber *) current {
5408 return [NSNumber numberWithFloat:current_];
5411 - (void) setTotal:(float)value {
5415 - (NSNumber *) total {
5416 return [NSNumber numberWithFloat:total_];
5419 - (void) setSpeed:(float)value {
5423 - (NSNumber *) speed {
5424 return [NSNumber numberWithFloat:speed_];
5427 - (NSArray *) events {
5431 - (void) removeAllEvents {
5432 [events_ removeAllObjects];
5435 - (void) addEvent:(CydiaProgressEvent *)event {
5436 [events_ addObject:event];
5439 - (void) setTitle:(NSString *)text {
5443 - (NSString *) title {
5447 - (void) setFinish:(NSString *)text {
5451 - (NSString *) finish {
5452 return (id) finish_ ?: [NSNull null];
5455 - (void) setRunning:(bool)running {
5459 - (NSNumber *) running {
5460 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5465 /* Progress Controller {{{ */
5466 @interface ProgressController : CydiaWebViewController <
5469 _transient Database *database_;
5470 _H<CydiaProgressData, 1> progress_;
5474 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5476 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5478 - (void) setTitle:(NSString *)title;
5479 - (void) setCancellable:(bool)cancellable;
5483 @implementation ProgressController
5486 [database_ setProgressDelegate:nil];
5490 - (UIBarButtonItem *) leftButton {
5491 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5492 initWithTitle:UCLocalize("CANCEL")
5493 style:UIBarButtonItemStylePlain
5495 action:@selector(cancel)
5496 ] autorelease] : nil;
5499 - (void) updateCancel {
5500 [super applyLeftButton];
5503 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5504 if ((self = [super init]) != nil) {
5505 database_ = database;
5506 delegate_ = delegate;
5508 [database_ setProgressDelegate:self];
5510 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5511 [progress_ setDelegate:self];
5513 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5515 [scroller_ setBackgroundColor:[UIColor blackColor]];
5517 [[self navigationItem] setHidesBackButton:YES];
5519 [self updateCancel];
5523 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5524 [super webView:view didClearWindowObject:window forFrame:frame];
5525 [window setValue:progress_ forKey:@"cydiaProgress"];
5528 - (void) updateProgress {
5529 [self dispatchEvent:@"CydiaProgressUpdate"];
5532 - (void) viewWillAppear:(BOOL)animated {
5533 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5534 [super viewWillAppear:animated];
5538 UpdateExternalStatus(0);
5541 [delegate_ saveState];
5545 [delegate_ returnToCydia];
5549 [delegate_ terminateWithSuccess];
5550 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5551 [delegate_ suspendWithAnimation:YES];
5553 [delegate_ suspend];*/
5565 UIProgressHUD *hud([delegate_ addProgressHUD]);
5566 [hud setText:UCLocalize("LOADING")];
5567 [delegate_ performSelector:@selector(reloadSpringBoard) withObject:nil afterDelay:0.5];
5573 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5574 SBReboot(SBSSpringBoardServerPort());
5576 reboot2(RB_AUTOBOOT);
5583 - (void) setTitle:(NSString *)title {
5584 [progress_ setTitle:title];
5585 [self updateProgress];
5588 - (UIBarButtonItem *) rightButton {
5589 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5590 initWithTitle:UCLocalize("CLOSE")
5591 style:UIBarButtonItemStylePlain
5593 action:@selector(close)
5597 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5598 UpdateExternalStatus(1);
5600 [progress_ setRunning:true];
5601 [self setTitle:title];
5602 // implicit updateProgress
5604 SHA1SumValue notifyconf; {
5606 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5609 MMap mmap(file, MMap::ReadOnly);
5611 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5612 notifyconf = sha1.Result();
5616 SHA1SumValue springlist; {
5618 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5621 MMap mmap(file, MMap::ReadOnly);
5623 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5624 springlist = sha1.Result();
5628 if (invocation != nil) {
5629 [invocation yieldToSelector:@selector(invoke)];
5630 [self setTitle:@"COMPLETE"];
5635 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5638 MMap mmap(file, MMap::ReadOnly);
5640 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5641 if (!(notifyconf == sha1.Result()))
5648 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5651 MMap mmap(file, MMap::ReadOnly);
5653 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5654 if (!(springlist == sha1.Result()))
5660 if (RestartSubstrate_)
5664 RestartSubstrate_ = false;
5667 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5668 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5669 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5670 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5671 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5674 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5676 [progress_ setRunning:false];
5677 [self updateProgress];
5679 [self applyRightButton];
5682 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5683 [progress_ addEvent:event];
5684 [self updateProgress];
5687 - (bool) isProgressCancelled {
5688 return cancel_ == 2;
5693 [self updateCancel];
5696 - (void) setCancellable:(bool)cancellable {
5697 unsigned cancel(cancel_);
5701 else if (cancel_ == 0)
5704 if (cancel != cancel_)
5705 [self updateCancel];
5708 - (void) setProgressCancellable:(NSNumber *)cancellable {
5709 [self setCancellable:[cancellable boolValue]];
5712 - (void) setProgressPercent:(NSNumber *)percent {
5713 [progress_ setPercent:[percent floatValue]];
5714 [self updateProgress];
5717 - (void) setProgressStatus:(NSDictionary *)status {
5718 if (status == nil) {
5719 [progress_ setCurrent:0];
5720 [progress_ setTotal:0];
5721 [progress_ setSpeed:0];
5723 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5725 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5726 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5727 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5730 [self updateProgress];
5736 /* Package Cell {{{ */
5737 @interface PackageCell : CyteTableViewCell <
5738 CyteTableViewCellDelegate
5742 _H<NSString> description_;
5744 _H<NSString> source_;
5746 _H<UIImage> placard_;
5750 - (PackageCell *) init;
5751 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5753 - (void) drawContentRect:(CGRect)rect;
5757 @implementation PackageCell
5759 - (PackageCell *) init {
5760 CGRect frame(CGRectMake(0, 0, 320, 74));
5761 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5762 UIView *content([self contentView]);
5763 CGRect bounds([content bounds]);
5765 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5766 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5767 [content addSubview:content_];
5769 [content_ setDelegate:self];
5770 [content_ setOpaque:YES];
5774 - (NSString *) accessibilityLabel {
5778 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5779 summarized_ = summary;
5789 [content_ setBackgroundColor:[UIColor whiteColor]];
5793 Source *source = [package source];
5795 icon_ = [package icon];
5797 if (NSString *name = [package name])
5798 name_ = [NSString stringWithString:name];
5800 if (NSString *description = [package shortDescription])
5801 description_ = [NSString stringWithString:description];
5803 commercial_ = [package isCommercial];
5805 NSString *label = nil;
5806 bool trusted = false;
5808 if (source != nil) {
5809 label = [source label];
5810 trusted = [source trusted];
5811 } else if ([[package id] isEqualToString:@"firmware"])
5812 label = UCLocalize("APPLE");
5814 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5816 NSString *from(label);
5818 NSString *section = [package simpleSection];
5819 if (section != nil && ![section isEqualToString:label]) {
5820 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5821 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5824 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5826 if (NSString *purpose = [package primaryPurpose])
5827 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5832 if (NSString *mode = [package mode]) {
5833 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5834 color = RemovingColor_;
5835 placard = @"removing";
5837 color = InstallingColor_;
5838 placard = @"installing";
5841 color = [UIColor whiteColor];
5843 if ([package installed] != nil)
5844 placard = @"installed";
5849 [content_ setBackgroundColor:color];
5852 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5855 [self setNeedsDisplay];
5856 [content_ setNeedsDisplay];
5859 - (void) drawSummaryContentRect:(CGRect)rect {
5860 bool highlighted(highlighted_);
5861 float width([self bounds].size.width);
5865 rect.size = [(UIImage *) icon_ size];
5867 while (rect.size.width > 16 || rect.size.height > 16) {
5868 rect.size.width /= 2;
5869 rect.size.height /= 2;
5872 rect.origin.x = 19 - rect.size.width / 2;
5873 rect.origin.y = 19 - rect.size.height / 2;
5875 [icon_ drawInRect:Retina(rect)];
5878 if (badge_ != nil) {
5880 rect.size = [(UIImage *) badge_ size];
5882 rect.size.width /= 4;
5883 rect.size.height /= 4;
5885 rect.origin.x = 25 - rect.size.width / 2;
5886 rect.origin.y = 25 - rect.size.height / 2;
5888 [badge_ drawInRect:Retina(rect)];
5891 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5895 UISetColor(commercial_ ? Purple_ : Black_);
5896 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
5898 if (placard_ != nil)
5899 [placard_ drawAtPoint:CGPointMake(width - 52, 11)];
5902 - (void) drawNormalContentRect:(CGRect)rect {
5903 bool highlighted(highlighted_);
5904 float width([self bounds].size.width);
5908 rect.size = [(UIImage *) icon_ size];
5910 while (rect.size.width > 32 || rect.size.height > 32) {
5911 rect.size.width /= 2;
5912 rect.size.height /= 2;
5915 rect.origin.x = 25 - rect.size.width / 2;
5916 rect.origin.y = 25 - rect.size.height / 2;
5918 [icon_ drawInRect:Retina(rect)];
5921 if (badge_ != nil) {
5923 rect.size = [(UIImage *) badge_ size];
5925 rect.size.width /= 2;
5926 rect.size.height /= 2;
5928 rect.origin.x = 36 - rect.size.width / 2;
5929 rect.origin.y = 36 - rect.size.height / 2;
5931 [badge_ drawInRect:Retina(rect)];
5934 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5938 UISetColor(commercial_ ? Purple_ : Black_);
5939 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
5940 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
5943 UISetColor(commercial_ ? Purplish_ : Gray_);
5944 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:NSLineBreakByTruncatingTail];
5946 if (placard_ != nil)
5947 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5950 - (void) drawContentRect:(CGRect)rect {
5952 [self drawSummaryContentRect:rect];
5954 [self drawNormalContentRect:rect];
5959 /* Section Cell {{{ */
5960 @interface SectionCell : CyteTableViewCell <
5961 CyteTableViewCellDelegate
5963 _H<NSString> basic_;
5964 _H<NSString> section_;
5966 _H<NSString> count_;
5968 _H<UISwitch> switch_;
5972 - (void) setSection:(Section *)section editing:(BOOL)editing;
5976 @implementation SectionCell
5978 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5979 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5980 icon_ = [UIImage imageNamed:@"folder.png"];
5981 // XXX: this initial frame is wrong, but is fixed later
5982 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
5983 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5985 UIView *content([self contentView]);
5986 CGRect bounds([content bounds]);
5988 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5989 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5990 [content addSubview:content_];
5991 [content_ setBackgroundColor:[UIColor whiteColor]];
5993 [content_ setDelegate:self];
5997 - (void) onSwitch:(id)sender {
5998 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5999 if (metadata == nil) {
6000 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
6001 [Sections_ setObject:metadata forKey:basic_];
6004 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
6007 - (void) setSection:(Section *)section editing:(BOOL)editing {
6008 if (editing != editing_) {
6010 [switch_ removeFromSuperview];
6012 [self addSubview:switch_];
6021 if (section == nil) {
6022 name_ = UCLocalize("ALL_PACKAGES");
6025 basic_ = [section name];
6026 section_ = [section localized];
6028 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
6029 count_ = [NSString stringWithFormat:@"%zd", [section count]];
6032 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
6035 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
6036 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
6038 [content_ setNeedsDisplay];
6041 - (void) setFrame:(CGRect)frame {
6042 [super setFrame:frame];
6044 CGRect rect([switch_ frame]);
6045 [switch_ setFrame:CGRectMake(frame.size.width - rect.size.width - 9, 9, rect.size.width, rect.size.height)];
6048 - (NSString *) accessibilityLabel {
6052 - (void) drawContentRect:(CGRect)rect {
6053 bool highlighted(highlighted_ && !editing_);
6055 [icon_ drawInRect:CGRectMake(7, 7, 32, 32)];
6057 if (highlighted && kCFCoreFoundationVersionNumber < 800)
6060 float width(rect.size.width);
6062 width -= 9 + [switch_ frame].size.width;
6066 [name_ drawAtPoint:CGPointMake(48, 12) forWidth:(width - 58) withFont:Font18_ lineBreakMode:NSLineBreakByTruncatingTail];
6068 CGSize size = [count_ sizeWithFont:Font14_];
6070 UISetColor(Folder_);
6072 [count_ drawAtPoint:CGPointMake(Retina(10 + (30 - size.width) / 2), 18) withFont:Font12Bold_];
6078 /* File Table {{{ */
6079 @interface FileTable : CyteViewController <
6080 UITableViewDataSource,
6083 _transient Database *database_;
6084 _H<Package> package_;
6086 _H<NSMutableArray> files_;
6087 _H<UITableView, 2> list_;
6090 - (id) initWithDatabase:(Database *)database;
6091 - (void) setPackage:(Package *)package;
6095 @implementation FileTable
6097 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6098 return files_ == nil ? 0 : [files_ count];
6101 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6105 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6106 static NSString *reuseIdentifier = @"Cell";
6108 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6110 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6111 [cell setFont:[UIFont systemFontOfSize:16]];
6113 [cell setText:[files_ objectAtIndex:indexPath.row]];
6114 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
6119 - (NSURL *) navigationURL {
6120 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
6124 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
6125 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6126 [list_ setRowHeight:24.0f];
6127 [(UITableView *) list_ setDataSource:self];
6128 [list_ setDelegate:self];
6129 [self setView:list_];
6132 - (void) viewDidLoad {
6133 [super viewDidLoad];
6135 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
6138 - (void) releaseSubviews {
6144 [super releaseSubviews];
6147 - (id) initWithDatabase:(Database *)database {
6148 if ((self = [super init]) != nil) {
6149 database_ = database;
6153 - (void) setPackage:(Package *)package {
6157 files_ = [NSMutableArray arrayWithCapacity:32];
6159 if (package != nil) {
6161 name_ = [package id];
6163 if (NSArray *files = [package files])
6164 [files_ addObjectsFromArray:files];
6166 if ([files_ count] != 0) {
6167 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
6168 [files_ removeObjectAtIndex:0];
6169 [files_ sortUsingSelector:@selector(compareByPath:)];
6171 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
6172 [stack addObject:@"/"];
6174 for (int i(0), e([files_ count]); i != e; ++i) {
6175 NSString *file = [files_ objectAtIndex:i];
6176 while (![file hasPrefix:[stack lastObject]])
6177 [stack removeLastObject];
6178 NSString *directory = [stack lastObject];
6179 [stack addObject:[file stringByAppendingString:@"/"]];
6180 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
6181 ([stack count] - 2) * 3, "",
6182 [file substringFromIndex:[directory length]]
6191 - (void) reloadData {
6194 [self setPackage:[database_ packageWithName:name_]];
6199 /* Package Controller {{{ */
6200 @interface CYPackageController : CydiaWebViewController <
6201 UIActionSheetDelegate
6203 _transient Database *database_;
6204 _H<Package> package_;
6207 std::vector<std::pair<_H<NSString>, _H<NSString>>> buttons_;
6208 _H<UIBarButtonItem> button_;
6211 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer;
6215 @implementation CYPackageController
6217 - (NSURL *) navigationURL {
6218 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
6221 - (void) _clickButtonWithName:(NSString *)name {
6222 if ([name isEqualToString:@"CLEAR"])
6223 [delegate_ clearPackage:package_];
6224 else if ([name isEqualToString:@"INSTALL"])
6225 [delegate_ installPackage:package_];
6226 else if ([name isEqualToString:@"REINSTALL"])
6227 [delegate_ installPackage:package_];
6228 else if ([name isEqualToString:@"REMOVE"])
6229 [delegate_ removePackage:package_];
6230 else if ([name isEqualToString:@"UPGRADE"])
6231 [delegate_ installPackage:package_];
6232 else _assert(false);
6235 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
6236 NSString *context([sheet context]);
6238 if ([context isEqualToString:@"modify"]) {
6239 if (button != [sheet cancelButtonIndex]) {
6241 [self performSelector:@selector(_clickButtonWithName:) withObject:buttons_[button].first afterDelay:0];
6243 [self _clickButtonWithName:buttons_[button].first];
6246 [sheet dismissWithClickedButtonIndex:button animated:YES];
6250 - (bool) _allowJavaScriptPanel {
6255 - (void) _customButtonClicked {
6256 size_t count(buttons_.size());
6261 [self _clickButtonWithName:buttons_[0].first];
6263 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
6264 for (const auto &button : buttons_)
6265 [buttons addObject:button.second];
6267 UIActionSheet *sheet = [[[UIActionSheet alloc]
6270 cancelButtonTitle:nil
6271 destructiveButtonTitle:nil
6272 otherButtonTitles:nil
6275 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
6277 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
6278 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
6280 [sheet setContext:@"modify"];
6282 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
6286 - (void) reloadButtonClicked {
6287 if (commercial_ && function_ == nil && [package_ uninstalled])
6289 [self customButtonClicked];
6292 - (void) applyLoadingTitle {
6293 // Don't show "Loading" as the title. Ever.
6296 - (UIBarButtonItem *) rightButton {
6301 - (void) setPageColor:(UIColor *)color {
6302 return [super setPageColor:nil];
6305 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer {
6306 if ((self = [super init]) != nil) {
6307 database_ = database;
6308 name_ = name == nil ? @"" : [NSString stringWithString:name];
6309 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]] withReferrer:referrer];
6313 - (void) reloadData {
6316 package_ = [database_ packageWithName:name_];
6320 if (package_ != nil) {
6321 [(Package *) package_ parse];
6323 commercial_ = [package_ isCommercial];
6325 if ([package_ mode] != nil)
6326 buttons_.push_back(std::make_pair(@"CLEAR", UCLocalize("CLEAR")));
6327 if ([package_ source] == nil);
6328 else if ([package_ upgradableAndEssential:NO])
6329 buttons_.push_back(std::make_pair(@"UPGRADE", UCLocalize("UPGRADE")));
6330 else if ([package_ uninstalled])
6331 buttons_.push_back(std::make_pair(@"INSTALL", UCLocalize("INSTALL")));
6333 buttons_.push_back(std::make_pair(@"REINSTALL", UCLocalize("REINSTALL")));
6334 if (![package_ uninstalled])
6335 buttons_.push_back(std::make_pair(@"REMOVE", UCLocalize("REMOVE")));
6339 switch (buttons_.size()) {
6340 case 0: title = nil; break;
6341 case 1: title = buttons_[0].second; break;
6342 default: title = UCLocalize("MODIFY"); break;
6345 button_ = [[[UIBarButtonItem alloc]
6347 style:UIBarButtonItemStylePlain
6349 action:@selector(customButtonClicked)
6353 - (bool) isLoading {
6354 return commercial_ ? [super isLoading] : false;
6360 /* Package List Controller {{{ */
6361 @interface PackageListController : CyteViewController <
6362 UITableViewDataSource,
6365 _transient Database *database_;
6367 _H<NSArray> packages_;
6368 _H<NSArray> sections_;
6369 _H<UITableView, 2> list_;
6371 _H<NSArray> thumbs_;
6372 std::vector<NSInteger> offset_;
6374 _H<NSString> title_;
6375 unsigned reloading_;
6378 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6379 - (void) setDelegate:(id)delegate;
6380 - (void) resetCursor;
6383 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages;
6387 @implementation PackageListController
6389 - (NSURL *) referrerURL {
6390 return [self navigationURL];
6393 - (bool) isSummarized {
6397 - (bool) showsSections {
6401 - (void) deselectWithAnimation:(BOOL)animated {
6402 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6405 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6406 CGRect base = [[self view] bounds];
6407 base.size.height -= bounds.size.height;
6408 base.origin = [list_ frame].origin;
6410 [UIView beginAnimations:nil context:NULL];
6411 [UIView setAnimationBeginsFromCurrentState:YES];
6412 [UIView setAnimationCurve:curve];
6413 [UIView setAnimationDuration:duration];
6414 [list_ setFrame:base];
6415 [UIView commitAnimations];
6418 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6419 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6422 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6423 [self resizeForKeyboardBounds:bounds duration:0];
6426 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6427 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6428 *curve = UIViewAnimationCurveEaseInOut;
6430 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6432 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6435 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6438 - (void) keyboardWillShow:(NSNotification *)notification {
6441 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6442 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6444 NSTimeInterval duration;
6445 UIViewAnimationCurve curve;
6446 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6448 CGRect kbframe = CGRectMake(Retina(center.x - bounds.size.width / 2), Retina(center.y - bounds.size.height / 2), bounds.size.width, bounds.size.height);
6449 UIViewController *base = self;
6450 while ([base parentOrPresentingViewController] != nil)
6451 base = [base parentOrPresentingViewController];
6452 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6453 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6455 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6456 intersection.size.height += CYStatusBarHeight();
6458 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6461 - (void) keyboardWillHide:(NSNotification *)notification {
6462 NSTimeInterval duration;
6463 UIViewAnimationCurve curve;
6464 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6466 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6469 - (void) viewWillAppear:(BOOL)animated {
6470 [super viewWillAppear:animated];
6472 [self resizeForKeyboardBounds:CGRectZero];
6473 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6474 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6477 - (void) viewWillDisappear:(BOOL)animated {
6478 [super viewWillDisappear:animated];
6480 [self resizeForKeyboardBounds:CGRectZero];
6481 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6482 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6485 - (void) viewDidAppear:(BOOL)animated {
6486 [super viewDidAppear:animated];
6487 [self deselectWithAnimation:animated];
6490 - (void) didSelectPackage:(Package *)package {
6491 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[[self referrerURL] absoluteString]] autorelease]);
6492 [view setDelegate:delegate_];
6493 [[self navigationController] pushViewController:view animated:YES];
6496 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6497 NSInteger count([sections_ count]);
6498 return count == 0 ? 1 : count;
6501 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6502 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6504 return [[sections_ objectAtIndex:section] name];
6507 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6508 if ([sections_ count] == 0)
6510 return [[sections_ objectAtIndex:section] count];
6513 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6514 @synchronized (database_) {
6515 if ([database_ era] != era_)
6518 Section *section([sections_ objectAtIndex:[path section]]);
6519 NSInteger row([path row]);
6520 Package *package([packages_ objectAtIndex:([section row] + row)]);
6521 return [[package retain] autorelease];
6524 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6525 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6527 cell = [[[PackageCell alloc] init] autorelease];
6529 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6530 [cell setPackage:package asSummary:[self isSummarized]];
6534 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6535 Package *package([self packageAtIndexPath:path]);
6536 package = [database_ packageWithName:[package id]];
6537 [self didSelectPackage:package];
6540 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6544 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6545 return offset_[index];
6548 - (void) updateHeight {
6549 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6552 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6553 if ((self = [super init]) != nil) {
6554 database_ = database;
6555 title_ = [title copy];
6556 [[self navigationItem] setTitle:title_];
6561 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
6562 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
6563 [self setView:view];
6565 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6566 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6567 [view addSubview:list_];
6569 // XXX: is 20 the most optimal number here?
6570 [list_ setSectionIndexMinimumDisplayRowCount:20];
6572 [(UITableView *) list_ setDataSource:self];
6573 [list_ setDelegate:self];
6575 [self updateHeight];
6578 - (void) releaseSubviews {
6587 [super releaseSubviews];
6590 - (void) setDelegate:(id)delegate {
6591 delegate_ = delegate;
6594 - (bool) shouldYield {
6598 - (bool) shouldBlock {
6602 - (NSMutableArray *) _reloadPackages {
6603 @synchronized (database_) {
6604 era_ = [database_ era];
6605 NSArray *packages([database_ packages]);
6607 return [NSMutableArray arrayWithArray:packages];
6610 - (void) _reloadData {
6611 if (reloading_ != 0) {
6616 NSMutableArray *packages;
6619 if ([self shouldYield]) {
6623 if (![self shouldBlock])
6626 hud = [delegate_ addProgressHUD];
6627 [hud setText:UCLocalize("LOADING")];
6631 packages = [self yieldToSelector:@selector(_reloadPackages)];
6634 [delegate_ removeProgressHUD:hud];
6635 } while (reloading_ == 2);
6637 packages = [self _reloadPackages];
6640 @synchronized (database_) {
6641 if (era_ != [database_ era])
6648 packages_ = packages;
6650 if ([self showsSections])
6651 sections_ = [self sectionsForPackages:packages];
6653 Section *section([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6654 [section setCount:[packages_ count]];
6655 sections_ = [NSArray arrayWithObject:section];
6658 [self updateHeight];
6660 _profile(PackageTable$reloadData$List)
6661 [(UITableView *) list_ setDataSource:self];
6669 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
6670 Section *prefix([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6671 size_t end([packages count]);
6673 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
6674 Section *section(prefix);
6676 thumbs_ = CollationThumbs_;
6677 offset_ = CollationOffset_;
6680 size_t offsets([CollationStarts_ count]);
6682 NSString *start([CollationStarts_ objectAtIndex:offset]);
6683 size_t length([start length]);
6685 for (size_t index(0); index != end; ++index) {
6687 Package *package([packages objectAtIndex:index]);
6688 NSString *name(PackageName(package, @selector(cyname)));
6690 //while ([start compare:name options:NSNumericSearch range:NSMakeRange(0, length) locale:CollationLocale_] != NSOrderedDescending) {
6691 while (StringNameCompare(start, name, length) != kCFCompareGreaterThan) {
6692 NSString *title([CollationTitles_ objectAtIndex:offset]);
6693 section = [[[Section alloc] initWithName:title row:index localize:NO] autorelease];
6694 [sections addObject:section];
6696 start = ++offset == offsets ? nil : [CollationStarts_ objectAtIndex:offset];
6699 length = [start length];
6703 [section addToCount];
6706 for (; offset != offsets; ++offset) {
6707 NSString *title([CollationTitles_ objectAtIndex:offset]);
6708 Section *section([[[Section alloc] initWithName:title row:end localize:NO] autorelease]);
6709 [sections addObject:section];
6712 if ([prefix count] != 0) {
6713 Section *suffix([sections lastObject]);
6714 [prefix setName:[suffix name]];
6715 [suffix setName:nil];
6716 [sections insertObject:prefix atIndex:(offsets - 1)];
6722 - (void) reloadData {
6725 if ([self shouldYield])
6726 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6731 - (void) resetCursor {
6732 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6735 - (void) clearData {
6736 [self updateHeight];
6738 [list_ setDataSource:nil];
6746 /* Filtered Package List Controller {{{ */
6747 typedef Function<bool, Package *> PackageFilter;
6748 typedef Function<void, NSMutableArray *> PackageSorter;
6749 @interface FilteredPackageListController : PackageListController {
6750 PackageFilter filter_;
6751 PackageSorter sorter_;
6754 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter;
6756 - (void) setFilter:(PackageFilter)filter;
6757 - (void) setSorter:(PackageSorter)sorter;
6761 @implementation FilteredPackageListController
6763 - (void) setFilter:(PackageFilter)filter {
6764 @synchronized (self) {
6768 - (void) setSorter:(PackageSorter)sorter {
6769 @synchronized (self) {
6773 - (NSMutableArray *) _reloadPackages {
6774 @synchronized (database_) {
6775 era_ = [database_ era];
6777 NSArray *packages([database_ packages]);
6778 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6780 PackageFilter filter;
6781 PackageSorter sorter;
6783 @synchronized (self) {
6788 _profile(PackageTable$reloadData$Filter)
6789 for (Package *package in packages)
6790 if ([package valid] && filter(package))
6791 [filtered addObject:package];
6799 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter {
6800 if ((self = [super initWithDatabase:database title:title]) != nil) {
6801 [self setFilter:filter];
6808 /* Home Controller {{{ */
6809 @interface HomeController : CydiaWebViewController {
6810 CFRunLoopRef runloop_;
6811 SCNetworkReachabilityRef reachability_;
6816 @implementation HomeController
6818 static void HomeControllerReachabilityCallback(SCNetworkReachabilityRef reachability, SCNetworkReachabilityFlags flags, void *info) {
6819 [(HomeController *) info dispatchEvent:@"CydiaReachabilityCallback"];
6823 if ((self = [super init]) != nil) {
6824 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6827 reachability_ = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "cydia.saurik.com");
6828 if (reachability_ != NULL) {
6829 SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
6830 SCNetworkReachabilitySetCallback(reachability_, HomeControllerReachabilityCallback, &context);
6832 CFRunLoopRef runloop(CFRunLoopGetCurrent());
6833 if (SCNetworkReachabilityScheduleWithRunLoop(reachability_, runloop, kCFRunLoopDefaultMode))
6840 if (reachability_ != NULL && runloop_ != NULL)
6841 SCNetworkReachabilityUnscheduleFromRunLoop(reachability_, runloop_, kCFRunLoopDefaultMode);
6845 - (NSURL *) navigationURL {
6846 return [NSURL URLWithString:@"cydia://home"];
6849 - (void) aboutButtonClicked {
6850 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6852 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6853 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6854 [alert setCancelButtonIndex:0];
6857 @"Copyright \u00a9 2008-2015\n"
6860 "Jay Freeman (saurik)\n"
6861 "saurik@saurik.com\n"
6862 "http://www.saurik.com/"
6868 - (UIBarButtonItem *) leftButton {
6869 return [[[UIBarButtonItem alloc]
6870 initWithTitle:UCLocalize("ABOUT")
6871 style:UIBarButtonItemStylePlain
6873 action:@selector(aboutButtonClicked)
6880 /* Cydia Navigation Controller Interface {{{ */
6881 @interface UINavigationController (Cydia)
6883 - (NSArray *) navigationURLCollection;
6884 - (void) unloadData;
6889 /* Cydia Tab Bar Controller {{{ */
6890 @interface CydiaTabBarController : CyteTabBarController <
6891 UITabBarControllerDelegate,
6894 _transient Database *database_;
6896 _H<UIActivityIndicatorView> indicator_;
6899 // XXX: ok, "updatedelegate_"?...
6900 _transient NSObject<CydiaDelegate> *updatedelegate_;
6903 - (NSArray *) navigationURLCollection;
6904 - (void) beginUpdate;
6909 @implementation CydiaTabBarController
6911 - (NSArray *) navigationURLCollection {
6912 NSMutableArray *items([NSMutableArray array]);
6914 // XXX: Should this deal with transient view controllers?
6915 for (id navigation in [self viewControllers]) {
6916 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6918 [items addObject:stack];
6924 - (id) initWithDatabase:(Database *)database {
6925 if ((self = [super init]) != nil) {
6926 database_ = database;
6927 [self setDelegate:self];
6929 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteTiny] autorelease];
6930 [indicator_ setOrigin:CGPointMake(kCFCoreFoundationVersionNumber >= 800 ? 2 : 4, 2)];
6932 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6936 - (void) beginUpdate {
6940 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
6941 UITabBarItem *item([controller tabBarItem]);
6943 [item setBadgeValue:@""];
6944 UIView *badge(MSHookIvar<UIView *>([item view], "_badge"));
6946 [indicator_ startAnimating];
6947 [badge addSubview:indicator_];
6949 [updatedelegate_ retainNetworkActivityIndicator];
6953 detachNewThreadSelector:@selector(performUpdate)
6959 - (void) performUpdate {
6960 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
6962 SourceStatus status(self, database_);
6963 [database_ updateWithStatus:status];
6966 performSelectorOnMainThread:@selector(completeUpdate)
6974 - (void) stopUpdateWithSelector:(SEL)selector {
6976 [updatedelegate_ releaseNetworkActivityIndicator];
6978 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
6979 [[controller tabBarItem] setBadgeValue:nil];
6981 [indicator_ removeFromSuperview];
6982 [indicator_ stopAnimating];
6984 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6987 - (void) completeUpdate {
6990 [self stopUpdateWithSelector:@selector(reloadData)];
6993 - (void) cancelUpdate {
6994 [self stopUpdateWithSelector:@selector(updateDataAndLoad)];
6997 - (void) cancelPressed {
6998 [self cancelUpdate];
7005 - (bool) isSourceCancelled {
7009 - (void) startSourceFetch:(NSString *)uri {
7012 - (void) stopSourceFetch:(NSString *)uri {
7015 - (void) setUpdateDelegate:(id)delegate {
7016 updatedelegate_ = delegate;
7022 /* Cydia Navigation Controller Implementation {{{ */
7023 @implementation UINavigationController (Cydia)
7025 - (NSArray *) navigationURLCollection {
7026 NSMutableArray *stack([NSMutableArray array]);
7028 for (CyteViewController *controller in [self viewControllers]) {
7029 NSString *url = [[controller navigationURL] absoluteString];
7031 [stack addObject:url];
7037 - (void) reloadData {
7040 UIViewController *visible([self visibleViewController]);
7042 [visible reloadData];
7044 // on the iPad, this view controller is ALSO visible. :(
7046 if (UIViewController *modal = [self modalViewController])
7047 if ([modal modalPresentationStyle] == UIModalPresentationFormSheet)
7048 if (UIViewController *top = [self topViewController])
7053 - (void) unloadData {
7054 for (CyteViewController *page in [self viewControllers])
7063 /* Cydia:// Protocol {{{ */
7064 @interface CydiaURLProtocol : NSURLProtocol {
7069 @implementation CydiaURLProtocol
7071 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7072 NSURL *url([request URL]);
7076 NSString *scheme([[url scheme] lowercaseString]);
7077 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7079 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7085 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7089 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7090 id<NSURLProtocolClient> client([self client]);
7092 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7094 NSData *data(UIImagePNGRepresentation(icon));
7096 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7097 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7098 [client URLProtocol:self didLoadData:data];
7099 [client URLProtocolDidFinishLoading:self];
7103 - (void) startLoading {
7104 id<NSURLProtocolClient> client([self client]);
7105 NSURLRequest *request([self request]);
7107 NSURL *url([request URL]);
7108 NSString *href([url absoluteString]);
7109 NSString *scheme([[url scheme] lowercaseString]);
7113 if ([scheme isEqualToString:@"cydia"])
7114 path = [href substringFromIndex:8];
7115 else if ([scheme isEqualToString:@"about"])
7116 path = [href substringFromIndex:12];
7117 else _assert(false);
7119 NSRange slash([path rangeOfString:@"/"]);
7122 if (slash.location == NSNotFound) {
7126 command = [path substringToIndex:slash.location];
7127 path = [path substringFromIndex:(slash.location + 1)];
7130 Database *database([Database sharedInstance]);
7132 if ([command isEqualToString:@"package-icon"]) {
7135 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7136 Package *package([database packageWithName:path]);
7140 UIImage *icon([package icon]);
7141 [self _returnPNGWithImage:icon forRequest:request];
7142 } else if ([command isEqualToString:@"uikit-image"]) {
7145 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7146 UIImage *icon(_UIImageWithName(path));
7147 [self _returnPNGWithImage:icon forRequest:request];
7148 } else if ([command isEqualToString:@"section-icon"]) {
7151 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7152 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7154 icon = [UIImage imageNamed:@"unknown.png"];
7155 [self _returnPNGWithImage:icon forRequest:request];
7157 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7161 - (void) stopLoading {
7167 /* Section Controller {{{ */
7168 @interface SectionController : FilteredPackageListController {
7170 _H<NSString> section_;
7173 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section;
7177 @implementation SectionController
7179 - (NSURL *) referrerURL {
7180 NSString *name(section_);
7181 name = name ?: @"*";
7182 NSString *key(key_);
7184 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sections/%@/%@", UI_, [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7187 - (NSURL *) navigationURL {
7188 NSString *name(section_);
7189 name = name ?: @"*";
7190 NSString *key(key_);
7192 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@/%@", [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7195 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section {
7198 title = UCLocalize("ALL_PACKAGES");
7199 else if (![section isEqual:@""])
7200 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(section) value:nil table:@"Sections"];
7202 title = UCLocalize("NO_SECTION");
7204 if ((self = [super initWithDatabase:database title:title]) != nil) {
7205 key_ = [source key];
7210 - (void) reloadData {
7211 Source *source([database_ sourceWithKey:key_]);
7212 _H<NSString> name(section_);
7214 [self setFilter:[=](Package *package) {
7215 NSString *section([package section]);
7219 section == nil && [name length] == 0 ||
7220 [name isEqualToString:section]
7223 [package source] == source
7224 ) && [package visible];
7232 /* Sections Controller {{{ */
7233 @interface SectionsController : CyteViewController <
7234 UITableViewDataSource,
7237 _transient Database *database_;
7239 _H<NSMutableArray> sections_;
7240 _H<NSMutableArray> filtered_;
7241 _H<UITableView, 2> list_;
7244 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7245 - (void) editButtonClicked;
7249 @implementation SectionsController
7251 - (NSURL *) navigationURL {
7252 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
7255 - (Source *) source {
7258 return [database_ sourceWithKey:key_];
7261 - (void) updateNavigationItem {
7262 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7263 if ([sections_ count] == 0) {
7264 [[self navigationItem] setRightBarButtonItem:nil];
7266 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7267 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7269 action:@selector(editButtonClicked)
7270 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7274 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7275 [super setEditing:editing animated:animated];
7280 [delegate_ updateData];
7282 [self updateNavigationItem];
7285 - (void) viewDidAppear:(BOOL)animated {
7286 [super viewDidAppear:animated];
7287 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7290 - (void) viewWillDisappear:(BOOL)animated {
7291 [super viewWillDisappear:animated];
7292 [self setEditing:NO];
7295 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7296 Section *section = nil;
7297 int index = [indexPath row];
7298 if (![self isEditing]) {
7301 section = [filtered_ objectAtIndex:index];
7303 section = [sections_ objectAtIndex:index];
7308 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7309 if ([self isEditing])
7310 return [sections_ count];
7312 return [filtered_ count] + 1;
7315 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7319 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7320 static NSString *reuseIdentifier = @"SectionCell";
7322 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7324 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7326 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7331 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7332 if ([self isEditing])
7335 Section *section = [self sectionAtIndexPath:indexPath];
7337 SectionController *controller = [[[SectionController alloc]
7338 initWithDatabase:database_
7339 source:[self source]
7340 section:[section name]
7342 [controller setDelegate:delegate_];
7344 [[self navigationController] pushViewController:controller animated:YES];
7348 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
7349 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7350 [list_ setRowHeight:46];
7351 [(UITableView *) list_ setDataSource:self];
7352 [list_ setDelegate:self];
7353 [self setView:list_];
7356 - (void) viewDidLoad {
7357 [super viewDidLoad];
7359 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7362 - (void) releaseSubviews {
7368 [super releaseSubviews];
7371 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7372 if ((self = [super init]) != nil) {
7373 database_ = database;
7374 key_ = [source key];
7378 - (void) reloadData {
7381 NSArray *packages = [database_ packages];
7383 sections_ = [NSMutableArray arrayWithCapacity:16];
7384 filtered_ = [NSMutableArray arrayWithCapacity:16];
7386 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7388 Source *source([self source]);
7391 for (Package *package in packages) {
7392 if (source != nil && [package source] != source)
7395 NSString *name([package section]);
7396 NSString *key(name == nil ? @"" : name);
7400 _profile(SectionsView$reloadData$Section)
7401 section = [sections objectForKey:key];
7402 if (section == nil) {
7403 _profile(SectionsView$reloadData$Section$Allocate)
7404 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7405 [sections setObject:section forKey:key];
7410 [section addToCount];
7412 _profile(SectionsView$reloadData$Filter)
7413 if (![package valid] || ![package visible])
7421 [sections_ addObjectsFromArray:[sections allValues]];
7423 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7425 for (Section *section in (id) sections_) {
7426 size_t count([section row]);
7430 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7431 [section setCount:count];
7432 [filtered_ addObject:section];
7435 [self updateNavigationItem];
7440 - (void) editButtonClicked {
7441 [self setEditing:![self isEditing] animated:YES];
7447 /* Changes Controller {{{ */
7448 @interface ChangesController : FilteredPackageListController {
7452 - (id) initWithDatabase:(Database *)database;
7456 @implementation ChangesController
7458 - (NSURL *) referrerURL {
7459 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/changes/", UI_]];
7462 - (NSURL *) navigationURL {
7463 return [NSURL URLWithString:@"cydia://changes"];
7466 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7467 @synchronized (database_) {
7468 if ([database_ era] != era_)
7471 NSUInteger sectionIndex([path section]);
7472 if (sectionIndex >= [sections_ count])
7474 Section *section([sections_ objectAtIndex:sectionIndex]);
7475 NSInteger row([path row]);
7476 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7479 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7480 NSString *context([alert context]);
7482 if ([context isEqualToString:@"norefresh"])
7483 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7486 - (void) setLeftBarButtonItem {
7487 if ([delegate_ updating])
7488 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7489 initWithTitle:UCLocalize("CANCEL")
7490 style:UIBarButtonItemStyleDone
7492 action:@selector(cancelButtonClicked)
7493 ] autorelease] animated:YES];
7495 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7496 initWithTitle:UCLocalize("REFRESH")
7497 style:UIBarButtonItemStylePlain
7499 action:@selector(refreshButtonClicked)
7500 ] autorelease] animated:YES];
7503 - (void) refreshButtonClicked {
7504 if ([delegate_ requestUpdate])
7505 [self setLeftBarButtonItem];
7508 - (void) cancelButtonClicked {
7509 [delegate_ cancelUpdate];
7512 - (void) upgradeButtonClicked {
7513 [delegate_ distUpgrade];
7514 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7517 - (bool) shouldYield {
7521 - (bool) shouldBlock {
7525 - (void) useFilter {
7526 @synchronized (self) {
7527 [self setFilter:[](Package *package) {
7528 return [package upgradableAndEssential:YES] || [package visible];
7531 [self setSorter:[](NSMutableArray *packages) {
7532 [packages radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7536 - (id) initWithDatabase:(Database *)database {
7537 if ((self = [super initWithDatabase:database title:UCLocalize("CHANGES")]) != nil) {
7542 - (void) viewDidLoad {
7543 [super viewDidLoad];
7544 [self setLeftBarButtonItem];
7547 - (void) viewWillAppear:(BOOL)animated {
7548 [super viewWillAppear:animated];
7549 [self setLeftBarButtonItem];
7552 - (void) reloadData {
7553 [self setLeftBarButtonItem];
7557 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
7558 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
7560 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7561 Section *ignored = nil;
7562 Section *section = nil;
7566 bool unseens = false;
7568 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7570 for (size_t offset = 0, count = [packages count]; offset != count; ++offset) {
7571 Package *package = [packages objectAtIndex:offset];
7573 BOOL uae = [package upgradableAndEssential:YES];
7577 time_t seen([package seen]);
7579 if (section == nil || last != seen) {
7583 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7586 _profile(ChangesController$reloadData$Allocate)
7587 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7588 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7589 [sections addObject:section];
7593 [section addToCount];
7594 } else if ([package ignored]) {
7595 if (ignored == nil) {
7596 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7598 [ignored addToCount];
7601 [upgradable addToCount];
7606 CFRelease(formatter);
7609 Section *last = [sections lastObject];
7610 size_t count = [last count];
7611 [packages removeObjectsInRange:NSMakeRange([packages count] - count, count)];
7612 [sections removeLastObject];
7615 if ([ignored count] != 0)
7616 [sections insertObject:ignored atIndex:0];
7618 [sections insertObject:upgradable atIndex:0];
7622 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7623 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7624 style:UIBarButtonItemStylePlain
7626 action:@selector(upgradeButtonClicked)
7627 ] autorelease]) animated:YES];
7634 /* Search Controller {{{ */
7635 @interface SearchController : FilteredPackageListController <
7638 _H<UISearchBar, 1> search_;
7643 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7644 - (void) reloadData;
7648 @implementation SearchController
7650 - (NSURL *) referrerURL {
7651 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/search?q=%@", UI_, [([search_ text] ?: @"") stringByAddingPercentEscapesIncludingReserved]]];
7654 - (NSURL *) navigationURL {
7655 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7656 return [NSURL URLWithString:@"cydia://search"];
7658 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [[search_ text] stringByAddingPercentEscapesIncludingReserved]]];
7661 - (NSArray *) termsForQuery:(NSString *)query {
7662 NSMutableArray *terms([NSMutableArray arrayWithCapacity:2]);
7663 for (NSString *component in [query componentsSeparatedByString:@" "])
7664 if ([component length] != 0)
7665 [terms addObject:component];
7670 - (void) useSearch {
7671 _H<NSArray> query([self termsForQuery:[search_ text]]);
7674 @synchronized (self) {
7675 [self setFilter:[=](Package *package) {
7676 if (![package unfiltered])
7678 if (![package matches:query])
7683 [self setSorter:[](NSMutableArray *packages) {
7684 [packages radixSortUsingSelector:@selector(rank)];
7692 - (void) usePrefix:(NSString *)prefix {
7693 _H<NSString> query(prefix);
7696 @synchronized (self) {
7697 [self setFilter:[=](Package *package) {
7698 if ([query length] == 0)
7700 if (![package unfiltered])
7702 if ([[package name] compare:query options:MatchCompareOptions_ range:NSMakeRange(0, [query length])] != NSOrderedSame)
7707 [self setSorter:nullptr];
7713 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7715 [self usePrefix:[search_ text]];
7718 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7719 [search_ resignFirstResponder];
7723 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7724 [search_ setText:@""];
7725 [self searchBarButtonClicked:searchBar];
7728 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7729 [self searchBarButtonClicked:searchBar];
7732 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7733 [self usePrefix:text];
7736 - (bool) shouldYield {
7740 - (bool) shouldBlock {
7744 - (bool) isSummarized {
7748 - (bool) showsSections {
7752 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7753 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH")])) {
7754 search_ = [[[UISearchBar alloc] init] autorelease];
7755 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7756 [search_ setDelegate:self];
7758 UITextField *textField;
7759 if ([search_ respondsToSelector:@selector(searchField)])
7760 textField = [search_ searchField];
7762 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7764 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7765 [textField setEnablesReturnKeyAutomatically:NO];
7766 [[self navigationItem] setTitleView:textField];
7769 [search_ setText:query];
7774 - (void) viewDidAppear:(BOOL)animated {
7775 [super viewDidAppear:animated];
7777 if (!searchloaded_) {
7778 searchloaded_ = YES;
7779 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7780 [search_ layoutSubviews];
7783 if ([self isSummarized])
7784 [search_ becomeFirstResponder];
7787 - (void) reloadData {
7792 - (void) didSelectPackage:(Package *)package {
7793 [search_ resignFirstResponder];
7794 [super didSelectPackage:package];
7799 /* Package Settings Controller {{{ */
7800 @interface PackageSettingsController : CyteViewController <
7801 UITableViewDataSource,
7804 _transient Database *database_;
7806 _H<Package> package_;
7807 _H<UITableView, 2> table_;
7808 _H<UISwitch> subscribedSwitch_;
7809 _H<UISwitch> ignoredSwitch_;
7810 _H<UITableViewCell> subscribedCell_;
7811 _H<UITableViewCell> ignoredCell_;
7814 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7818 @implementation PackageSettingsController
7820 - (NSURL *) navigationURL {
7821 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
7824 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7825 if (package_ == nil)
7828 if ([package_ installed] == nil)
7834 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7835 if (package_ == nil)
7838 // both sections contain just one item right now.
7842 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7846 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7848 return UCLocalize("SHOW_ALL_CHANGES_EX");
7850 return UCLocalize("IGNORE_UPGRADES_EX");
7853 - (void) onSubscribed:(id)control {
7854 bool value([control isOn]);
7855 if (package_ == nil)
7857 if ([package_ setSubscribed:value])
7858 [delegate_ updateData];
7861 - (void) _updateIgnored {
7862 const char *package([name_ UTF8String]);
7863 bool on([ignoredSwitch_ isOn]);
7865 FILE *dpkg(popen("/usr/libexec/cydia/cydo --set-selections", "w"));
7866 fwrite(package, strlen(package), 1, dpkg);
7869 fwrite(" hold\n", 6, 1, dpkg);
7871 fwrite(" install\n", 9, 1, dpkg);
7876 - (void) onIgnored:(id)control {
7877 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7878 [invocation setTarget:self];
7879 [invocation setSelector:@selector(_updateIgnored)];
7881 [delegate_ reloadDataWithInvocation:invocation];
7884 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7885 if (package_ == nil)
7888 switch ([indexPath section]) {
7889 case 0: return subscribedCell_;
7890 case 1: return ignoredCell_;
7899 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
7900 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
7901 [self setView:view];
7903 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7904 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7905 [(UITableView *) table_ setDataSource:self];
7906 [table_ setDelegate:self];
7907 [view addSubview:table_];
7909 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7910 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7911 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7913 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7914 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7915 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7917 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7918 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7919 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7920 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7922 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7923 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7924 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7925 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7928 - (void) viewDidLoad {
7929 [super viewDidLoad];
7931 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7934 - (void) releaseSubviews {
7936 subscribedCell_ = nil;
7938 ignoredSwitch_ = nil;
7939 subscribedSwitch_ = nil;
7941 [super releaseSubviews];
7944 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7945 if ((self = [super init]) != nil) {
7946 database_ = database;
7951 - (void) reloadData {
7954 package_ = [database_ packageWithName:name_];
7956 if (package_ != nil) {
7957 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7958 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7959 } // XXX: what now, G?
7961 [table_ reloadData];
7967 /* Installed Controller {{{ */
7968 @interface InstalledController : FilteredPackageListController {
7972 - (id) initWithDatabase:(Database *)database;
7973 - (void) queueStatusDidChange;
7977 @implementation InstalledController
7979 - (NSURL *) referrerURL {
7980 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/installed/", UI_]];
7983 - (NSURL *) navigationURL {
7984 return [NSURL URLWithString:@"cydia://installed"];
7987 - (void) useRecent {
7990 @synchronized (self) {
7991 [self setFilter:[](Package *package) {
7992 return ![package uninstalled] && package->role_ < 7;
7995 [self setSorter:[](NSMutableArray *packages) {
7996 [packages radixSortUsingSelector:@selector(recent)];
8000 - (void) useFilter:(UISegmentedControl *)segmented {
8001 NSInteger selected([segmented selectedSegmentIndex]);
8003 return [self useRecent];
8004 bool simple(selected == 0);
8007 @synchronized (self) {
8008 [self setFilter:[=](Package *package) {
8009 return ![package uninstalled] && package->role_ <= (simple ? 1 : 3);
8012 [self setSorter:nullptr];
8015 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
8017 return [super sectionsForPackages:packages];
8019 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterLongStyle, kCFDateFormatterNoStyle));
8021 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
8022 Section *section(nil);
8025 for (size_t offset(0), count([packages count]); offset != count; ++offset) {
8026 Package *package([packages objectAtIndex:offset]);
8028 time_t upgraded([package upgraded]);
8029 if (upgraded < 1168364520)
8032 upgraded -= upgraded % (60 * 60 * 24);
8034 if (section == nil || upgraded != last) {
8039 continue; // XXX: name = UCLocalize("...");
8041 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:upgraded]);
8045 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
8046 [sections addObject:section];
8049 [section addToCount];
8052 CFRelease(formatter);
8056 - (id) initWithDatabase:(Database *)database {
8057 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED")]) != nil) {
8058 UISegmentedControl *segmented([[[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:UCLocalize("USER"), UCLocalize("EXPERT"), UCLocalize("RECENT"), nil]] autorelease]);
8059 [segmented setSelectedSegmentIndex:0];
8060 [segmented setSegmentedControlStyle:UISegmentedControlStyleBar];
8061 [[self navigationItem] setTitleView:segmented];
8063 [segmented addTarget:self action:@selector(modeChanged:) forEvents:UIControlEventValueChanged];
8064 [self useFilter:segmented];
8066 [self queueStatusDidChange];
8071 - (void) queueButtonClicked {
8076 - (void) queueStatusDidChange {
8079 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8080 initWithTitle:UCLocalize("QUEUE")
8081 style:UIBarButtonItemStyleDone
8083 action:@selector(queueButtonClicked)
8086 [[self navigationItem] setRightBarButtonItem:nil];
8091 - (void) modeChanged:(UISegmentedControl *)segmented {
8092 [self useFilter:segmented];
8099 /* Source Cell {{{ */
8100 @interface SourceCell : CyteTableViewCell <
8101 CyteTableViewCellDelegate,
8104 _H<Source, 1> source_;
8107 _H<NSString> origin_;
8108 _H<NSString> label_;
8109 _H<UIActivityIndicatorView> indicator_;
8112 - (void) setSource:(Source *)source;
8113 - (void) setFetch:(NSNumber *)fetch;
8117 @implementation SourceCell
8119 - (void) _setImage:(NSArray *)data {
8120 if ([url_ isEqual:[data objectAtIndex:0]]) {
8121 icon_ = [data objectAtIndex:1];
8122 [content_ setNeedsDisplay];
8126 - (void) _setSource:(NSURL *) url {
8127 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8129 if (NSData *data = [NSURLConnection
8130 sendSynchronousRequest:[NSURLRequest
8132 cachePolicy:NSURLRequestUseProtocolCachePolicy
8136 returningResponse:NULL
8139 if (UIImage *image = [UIImage imageWithData:data])
8140 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
8145 - (void) setSource:(Source *)source {
8147 [source_ setDelegate:self];
8149 [self setFetch:[NSNumber numberWithBool:[source_ fetch]]];
8151 icon_ = [UIImage imageNamed:@"unknown.png"];
8153 origin_ = [source name];
8154 label_ = [source rooturi];
8156 [content_ setNeedsDisplay];
8158 url_ = [source iconURL];
8159 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
8162 - (void) setAllSource {
8164 [indicator_ stopAnimating];
8166 icon_ = [UIImage imageNamed:@"folder.png"];
8167 origin_ = UCLocalize("ALL_SOURCES");
8168 label_ = UCLocalize("ALL_SOURCES_EX");
8169 [content_ setNeedsDisplay];
8172 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8173 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8174 UIView *content([self contentView]);
8175 CGRect bounds([content bounds]);
8177 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8178 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8179 [content_ setBackgroundColor:[UIColor whiteColor]];
8180 [content addSubview:content_];
8182 [content_ setDelegate:self];
8183 [content_ setOpaque:YES];
8185 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGraySmall] autorelease];
8186 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin];// | UIViewAutoresizingFlexibleBottomMargin];
8187 [content addSubview:indicator_];
8189 [[content_ layer] setContentsGravity:kCAGravityTopLeft];
8193 - (void) layoutSubviews {
8194 [super layoutSubviews];
8196 UIView *content([self contentView]);
8197 CGRect bounds([content bounds]);
8199 CGRect frame([indicator_ frame]);
8200 frame.origin.x = bounds.size.width - frame.size.width;
8201 frame.origin.y = Retina((bounds.size.height - frame.size.height) / 2);
8203 if (kCFCoreFoundationVersionNumber < 800)
8204 frame.origin.x -= 8;
8205 [indicator_ setFrame:frame];
8208 - (NSString *) accessibilityLabel {
8212 - (void) drawContentRect:(CGRect)rect {
8213 bool highlighted(highlighted_);
8214 float width(rect.size.width);
8218 rect.size = [(UIImage *) icon_ size];
8220 while (rect.size.width > 32 || rect.size.height > 32) {
8221 rect.size.width /= 2;
8222 rect.size.height /= 2;
8225 rect.origin.x = 26 - rect.size.width / 2;
8226 rect.origin.y = 26 - rect.size.height / 2;
8228 [icon_ drawInRect:Retina(rect)];
8231 if (highlighted && kCFCoreFoundationVersionNumber < 800)
8236 [origin_ drawAtPoint:CGPointMake(52, 8) forWidth:(width - 49) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
8240 [label_ drawAtPoint:CGPointMake(52, 29) forWidth:(width - 49) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
8243 - (void) setFetch:(NSNumber *)fetch {
8244 if ([fetch boolValue])
8245 [indicator_ startAnimating];
8247 [indicator_ stopAnimating];
8252 /* Sources Controller {{{ */
8253 @interface SourcesController : CyteViewController <
8254 UITableViewDataSource,
8257 _transient Database *database_;
8260 _H<UITableView, 2> list_;
8261 _H<NSMutableArray> sources_;
8265 _H<UIProgressHUD> hud_;
8268 NSURLConnection *trivial_bz2_;
8269 NSURLConnection *trivial_gz_;
8274 - (id) initWithDatabase:(Database *)database;
8275 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated;
8279 @implementation SourcesController
8281 - (void) _releaseConnection:(NSURLConnection *)connection {
8282 if (connection != nil) {
8283 [connection cancel];
8284 //[connection setDelegate:nil];
8285 [connection release];
8290 [self _releaseConnection:trivial_gz_];
8291 [self _releaseConnection:trivial_bz2_];
8296 - (NSURL *) navigationURL {
8297 return [NSURL URLWithString:@"cydia://sources"];
8300 - (void) viewDidAppear:(BOOL)animated {
8301 [super viewDidAppear:animated];
8302 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8305 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8309 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8311 return UCLocalize("INDIVIDUAL_SOURCES");
8315 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8318 case 1: return [sources_ count];
8323 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8324 @synchronized (database_) {
8325 if ([database_ era] != era_)
8327 if ([indexPath section] != 1)
8329 NSUInteger index([indexPath row]);
8330 if (index >= [sources_ count])
8332 return [sources_ objectAtIndex:index];
8335 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8336 static NSString *cellIdentifier = @"SourceCell";
8338 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8339 if (cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8340 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8342 Source *source([self sourceAtIndexPath:indexPath]);
8344 [cell setAllSource];
8346 [cell setSource:source];
8351 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8352 SectionsController *controller([[[SectionsController alloc]
8353 initWithDatabase:database_
8354 source:[self sourceAtIndexPath:indexPath]
8357 [controller setDelegate:delegate_];
8358 [[self navigationController] pushViewController:controller animated:YES];
8361 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8362 if ([indexPath section] != 1)
8364 Source *source = [self sourceAtIndexPath:indexPath];
8365 return [source record] != nil;
8368 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8369 _assert([indexPath section] == 1);
8370 if (editingStyle == UITableViewCellEditingStyleDelete) {
8371 Source *source = [self sourceAtIndexPath:indexPath];
8372 if (source == nil) return;
8374 [Sources_ removeObjectForKey:[source key]];
8376 [delegate_ _saveConfig];
8377 [delegate_ reloadDataWithInvocation:nil];
8381 - (void) tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath {
8382 [self updateButtonsForEditingStatusAnimated:YES];
8386 [delegate_ addTrivialSource:href_];
8389 [delegate_ syncData];
8392 - (NSString *) getWarning {
8393 NSString *href(href_);
8394 NSRange colon([href rangeOfString:@"://"]);
8395 if (colon.location != NSNotFound)
8396 href = [href substringFromIndex:(colon.location + 3)];
8397 href = [href stringByAddingPercentEscapes];
8398 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8400 NSURL *url([NSURL URLWithString:href]);
8402 NSStringEncoding encoding;
8403 NSError *error(nil);
8405 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8406 return [warning length] == 0 ? nil : warning;
8410 - (void) _endConnection:(NSURLConnection *)connection {
8411 // XXX: the memory management in this method is horribly awkward
8413 NSURLConnection **field = NULL;
8414 if (connection == trivial_bz2_)
8415 field = &trivial_bz2_;
8416 else if (connection == trivial_gz_)
8417 field = &trivial_gz_;
8418 _assert(field != NULL);
8419 [connection release];
8423 trivial_bz2_ == nil &&
8426 NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil);
8428 [delegate_ releaseNetworkActivityIndicator];
8430 [delegate_ removeProgressHUD:hud_];
8434 if (warning != nil) {
8435 UIAlertView *alert = [[[UIAlertView alloc]
8436 initWithTitle:UCLocalize("SOURCE_WARNING")
8439 cancelButtonTitle:UCLocalize("CANCEL")
8441 UCLocalize("ADD_ANYWAY"),
8445 [alert setContext:@"warning"];
8446 [alert setNumberOfRows:1];
8449 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
8455 } else if (error_ != nil) {
8456 UIAlertView *alert = [[[UIAlertView alloc]
8457 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8458 message:[error_ localizedDescription]
8460 cancelButtonTitle:UCLocalize("OK")
8461 otherButtonTitles:nil
8464 [alert setContext:@"urlerror"];
8469 UIAlertView *alert = [[[UIAlertView alloc]
8470 initWithTitle:UCLocalize("NOT_REPOSITORY")
8471 message:UCLocalize("NOT_REPOSITORY_EX")
8473 cancelButtonTitle:UCLocalize("OK")
8474 otherButtonTitles:nil
8477 [alert setContext:@"trivial"];
8487 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8488 switch ([response statusCode]) {
8494 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8495 lprintf("connection:\"%s\" didFailWithError:\"%s\"\n", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8497 [self _endConnection:connection];
8500 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8501 [self _endConnection:connection];
8504 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8505 NSURL *url([NSURL URLWithString:href]);
8507 NSMutableURLRequest *request = [NSMutableURLRequest
8509 cachePolicy:NSURLRequestUseProtocolCachePolicy
8513 [request setHTTPMethod:method];
8515 if (Machine_ != NULL)
8516 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8518 if (UniqueID_ != nil)
8519 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8521 if ([url isCydiaSecure]) {
8522 if (UniqueID_ != nil)
8523 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
8526 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8529 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8530 NSString *context([alert context]);
8532 if ([context isEqualToString:@"source"]) {
8535 NSString *href = [[alert textField] text];
8537 static RegEx href_r("(http(s?)://|file:///)[^# ]*");
8538 if (!href_r(href)) {
8539 UIAlertView *alert = [[[UIAlertView alloc]
8540 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("INVALID_URL")]
8541 message:UCLocalize("INVALID_URL_EX")
8543 cancelButtonTitle:UCLocalize("OK")
8544 otherButtonTitles:nil
8547 [alert setContext:@"badurl"];
8553 if (![href hasSuffix:@"/"])
8554 href_ = [href stringByAppendingString:@"/"];
8558 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8559 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8563 // XXX: this is stupid
8564 hud_ = [delegate_ addProgressHUD];
8565 [hud_ setText:UCLocalize("VERIFYING_URL")];
8566 [delegate_ retainNetworkActivityIndicator];
8575 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8576 } else if ([context isEqualToString:@"trivial"])
8577 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8578 else if ([context isEqualToString:@"urlerror"])
8579 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8580 else if ([context isEqualToString:@"warning"]) {
8583 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
8592 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8596 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated {
8597 BOOL editing([list_ isEditing]);
8600 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8601 initWithTitle:UCLocalize("ADD")
8602 style:UIBarButtonItemStylePlain
8604 action:@selector(addButtonClicked)
8605 ] autorelease] animated:animated];
8606 else if ([delegate_ updating])
8607 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8608 initWithTitle:UCLocalize("CANCEL")
8609 style:UIBarButtonItemStyleDone
8611 action:@selector(cancelButtonClicked)
8612 ] autorelease] animated:animated];
8614 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8615 initWithTitle:UCLocalize("REFRESH")
8616 style:UIBarButtonItemStylePlain
8618 action:@selector(refreshButtonClicked)
8619 ] autorelease] animated:animated];
8621 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8622 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8623 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8625 action:@selector(editButtonClicked)
8626 ] autorelease] animated:animated];
8630 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease];
8631 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8632 [list_ setRowHeight:53];
8633 [(UITableView *) list_ setDataSource:self];
8634 [list_ setDelegate:self];
8635 [self setView:list_];
8638 - (void) viewDidLoad {
8639 [super viewDidLoad];
8641 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8642 [self updateButtonsForEditingStatusAnimated:NO];
8645 - (void) viewWillAppear:(BOOL)animated {
8646 [super viewWillAppear:animated];
8648 [list_ setEditing:NO];
8649 [self updateButtonsForEditingStatusAnimated:NO];
8652 - (void) releaseSubviews {
8657 [super releaseSubviews];
8660 - (id) initWithDatabase:(Database *)database {
8661 if ((self = [super init]) != nil) {
8662 database_ = database;
8666 - (void) reloadData {
8668 [self updateButtonsForEditingStatusAnimated:YES];
8670 @synchronized (database_) {
8671 era_ = [database_ era];
8673 sources_ = [NSMutableArray arrayWithCapacity:16];
8674 [sources_ addObjectsFromArray:[database_ sources]];
8676 [sources_ sortUsingSelector:@selector(compareByName:)];
8679 int count([sources_ count]);
8681 for (int i = 0; i != count; i++) {
8682 if ([[sources_ objectAtIndex:i] record] == nil)
8690 - (void) showAddSourcePrompt {
8691 UIAlertView *alert = [[[UIAlertView alloc]
8692 initWithTitle:UCLocalize("ENTER_APT_URL")
8695 cancelButtonTitle:UCLocalize("CANCEL")
8697 UCLocalize("ADD_SOURCE"),
8701 [alert setContext:@"source"];
8703 [alert setNumberOfRows:1];
8704 [alert addTextFieldWithValue:@"http://" label:@""];
8706 UITextInputTraits *traits = [[alert textField] textInputTraits];
8707 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8708 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8709 [traits setKeyboardType:UIKeyboardTypeURL];
8710 // XXX: UIReturnKeyDone
8711 [traits setReturnKeyType:UIReturnKeyNext];
8716 - (void) addButtonClicked {
8717 [self showAddSourcePrompt];
8720 - (void) refreshButtonClicked {
8721 if ([delegate_ requestUpdate])
8722 [self updateButtonsForEditingStatusAnimated:YES];
8725 - (void) cancelButtonClicked {
8726 [delegate_ cancelUpdate];
8729 - (void) editButtonClicked {
8730 [list_ setEditing:![list_ isEditing] animated:YES];
8731 [self updateButtonsForEditingStatusAnimated:YES];
8737 /* Stash Controller {{{ */
8738 @interface StashController : CyteViewController {
8739 _H<UIActivityIndicatorView> spinner_;
8740 _H<UILabel> status_;
8741 _H<UILabel> caption_;
8746 @implementation StashController
8749 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8750 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8751 [self setView:view];
8753 [view setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8755 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8756 CGRect spinrect = [spinner_ frame];
8757 spinrect.origin.x = Retina([[self view] frame].size.width / 2 - spinrect.size.width / 2);
8758 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8759 [spinner_ setFrame:spinrect];
8760 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8761 [view addSubview:spinner_];
8762 [spinner_ startAnimating];
8765 captrect.size.width = [[self view] frame].size.width;
8766 captrect.size.height = 40.0f;
8767 captrect.origin.x = 0;
8768 captrect.origin.y = Retina([[self view] frame].size.height / 2 - captrect.size.height * 2);
8769 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8770 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8771 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8772 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8773 [caption_ setTextColor:[UIColor whiteColor]];
8774 [caption_ setBackgroundColor:[UIColor clearColor]];
8775 [caption_ setShadowColor:[UIColor blackColor]];
8776 [caption_ setTextAlignment:NSTextAlignmentCenter];
8777 [view addSubview:caption_];
8780 statusrect.size.width = [[self view] frame].size.width;
8781 statusrect.size.height = 30.0f;
8782 statusrect.origin.x = 0;
8783 statusrect.origin.y = Retina([[self view] frame].size.height / 2 - statusrect.size.height);
8784 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8785 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8786 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8787 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8788 [status_ setTextColor:[UIColor whiteColor]];
8789 [status_ setBackgroundColor:[UIColor clearColor]];
8790 [status_ setShadowColor:[UIColor blackColor]];
8791 [status_ setTextAlignment:NSTextAlignmentCenter];
8792 [view addSubview:status_];
8795 - (void) releaseSubviews {
8800 [super releaseSubviews];
8806 @interface CYURLCache : SDURLCache {
8811 @implementation CYURLCache
8813 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8816 else if ([event isEqualToString:@"no-cache"])
8818 else if ([event isEqualToString:@"store"])
8820 else if ([event isEqualToString:@"invalid"])
8822 else if ([event isEqualToString:@"memory"])
8824 else if ([event isEqualToString:@"disk"])
8826 else if ([event isEqualToString:@"miss"])
8829 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8833 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
8834 if (NSURLResponse *response = [cached response])
8835 if (NSString *mime = [response MIMEType])
8836 if ([mime isEqualToString:@"text/cache-manifest"]) {
8837 NSURL *url([response URL]);
8840 NSLog(@"###: %@", [url absoluteString]);
8843 @synchronized (HostConfig_) {
8844 [CachedURLs_ addObject:url];
8848 [super storeCachedResponse:cached forRequest:request];
8851 - (void) createDiskCachePath {
8852 [super createDiskCachePath];
8857 @interface Cydia : UIApplication <
8858 ConfirmationControllerDelegate,
8862 _H<UIWindow> window_;
8863 _H<CydiaTabBarController> tabbar_;
8864 _H<CyteTabBarController> emulated_;
8865 _H<AppCacheController> appcache_;
8867 _H<NSMutableArray> essential_;
8868 _H<NSMutableArray> broken_;
8870 Database *database_;
8872 _H<NSURL> starturl_;
8877 _H<StashController> stash_;
8886 @implementation Cydia
8888 - (void) lockSuspend {
8889 if (locked_++ == 0) {
8890 if ($SBSSetInterceptsMenuButtonForever != NULL)
8891 (*$SBSSetInterceptsMenuButtonForever)(true);
8893 [self setIdleTimerDisabled:YES];
8897 - (void) unlockSuspend {
8898 if (--locked_ == 0) {
8899 [self setIdleTimerDisabled:NO];
8901 if ($SBSSetInterceptsMenuButtonForever != NULL)
8902 (*$SBSSetInterceptsMenuButtonForever)(false);
8906 - (void) beginUpdate {
8907 [tabbar_ beginUpdate];
8910 - (void) cancelUpdate {
8911 [tabbar_ cancelUpdate];
8914 - (bool) requestUpdate {
8915 if (IsReachable("cydia.saurik.com")) {
8919 UIAlertView *alert = [[[UIAlertView alloc]
8920 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("REFRESH")]
8921 message:@"Host Unreachable" // XXX: Localize
8923 cancelButtonTitle:UCLocalize("OK")
8924 otherButtonTitles:nil
8927 [alert setContext:@"norefresh"];
8935 return [tabbar_ updating];
8939 if ([broken_ count] != 0) {
8940 int count = [broken_ count];
8942 UIAlertView *alert = [[[UIAlertView alloc]
8943 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8944 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8946 cancelButtonTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("FORCIBLY_CLEAR"), UCLocalize("UNSAFE")]
8948 UCLocalize("TEMPORARY_IGNORE"),
8952 [alert setContext:@"fixhalf"];
8953 [alert setNumberOfRows:2];
8955 } else if (!Ignored_ && [essential_ count] != 0) {
8956 int count = [essential_ count];
8958 UIAlertView *alert = [[[UIAlertView alloc]
8959 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8960 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8962 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8964 UCLocalize("UPGRADE_ESSENTIAL"),
8965 UCLocalize("COMPLETE_UPGRADE"),
8969 [alert setContext:@"upgrade"];
8974 - (void) returnToCydia {
8978 - (void) reloadSpringBoard {
8979 if (kCFCoreFoundationVersionNumber >= 700) // XXX: iOS 6.x
8980 system("/bin/launchctl stop com.apple.backboardd");
8982 system("/bin/launchctl stop com.apple.SpringBoard");
8984 system("/usr/bin/killall backboardd SpringBoard");
8987 - (void) _saveConfig {
8988 SaveConfig(database_);
8991 // Navigation controller for the queuing badge.
8992 - (UINavigationController *) queueNavigationController {
8993 NSArray *controllers = [tabbar_ viewControllers];
8994 return [controllers objectAtIndex:3];
8997 - (void) unloadData {
8998 [tabbar_ unloadData];
9001 - (void) _updateData {
9005 UINavigationController *navigation = [self queueNavigationController];
9007 id queuedelegate = nil;
9008 if ([[navigation viewControllers] count] > 0)
9009 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9011 [queuedelegate queueStatusDidChange];
9012 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9015 - (void) _refreshIfPossible {
9016 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9018 NSDate *update([[NSDictionary dictionaryWithContentsOfFile:@ CacheState_] objectForKey:@"LastUpdate"]);
9020 bool recently = false;
9021 if (update != nil) {
9022 NSTimeInterval interval([update timeIntervalSinceNow]);
9023 if (interval > -(15*60))
9027 // Don't automatic refresh if:
9028 // - We already refreshed recently.
9029 // - We already auto-refreshed this launch.
9030 // - Auto-refresh is disabled.
9031 // - Cydia's server is not reachable
9032 if (recently || loaded_ || ManualRefresh || !IsReachable("cydia.saurik.com")) {
9033 // If we are cancelling, we need to make sure it knows it's already loaded.
9036 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9038 // We are going to load, so remember that.
9041 [tabbar_ performSelectorOnMainThread:@selector(beginUpdate) withObject:nil waitUntilDone:NO];
9047 - (void) refreshIfPossible {
9048 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
9051 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9052 _profile(reloadDataWithInvocation)
9053 @synchronized (self) {
9054 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9056 [hud setText:UCLocalize("RELOADING_DATA")];
9058 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9062 [essential_ removeAllObjects];
9063 [broken_ removeAllObjects];
9065 _profile(reloadDataWithInvocation$Essential)
9066 NSArray *packages([database_ packages]);
9067 for (Package *package in packages) {
9069 [broken_ addObject:package];
9070 if ([package upgradableAndEssential:YES] && ![package ignored]) {
9071 if ([package essential] && [package installed] != nil)
9072 [essential_ addObject:package];
9078 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9081 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9082 [changesItem setBadgeValue:badge];
9083 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9084 [self setApplicationIconBadgeNumber:changes];
9087 [changesItem setBadgeValue:nil];
9088 [changesItem setAnimatedBadge:NO];
9089 [self setApplicationIconBadgeNumber:0];
9096 [self removeProgressHUD:hud];
9103 - (void) updateData {
9107 - (void) updateDataAndLoad {
9109 if ([database_ progressDelegate] == nil)
9115 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9118 - (void) disemulate {
9119 if (emulated_ == nil)
9122 if ([window_ respondsToSelector:@selector(setRootViewController:)])
9123 [window_ setRootViewController:tabbar_];
9125 [window_ addSubview:[tabbar_ view]];
9126 [[emulated_ view] removeFromSuperview];
9130 [window_ setUserInteractionEnabled:YES];
9133 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9134 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9136 UIViewController *parent;
9137 if (emulated_ == nil)
9147 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9148 [parent presentModalViewController:navigation animated:YES];
9151 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9152 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9154 if (navigation != nil)
9155 [navigation pushViewController:progress animated:YES];
9157 [self presentModalViewController:progress force:YES];
9159 [progress invoke:invocation withTitle:title];
9163 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9164 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9167 - (void) repairWithInvocation:(NSInvocation *)invocation {
9169 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9173 - (void) repairWithSelector:(SEL)selector {
9174 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9177 - (void) reloadData {
9178 [self reloadDataWithInvocation:nil];
9179 if ([database_ progressDelegate] == nil)
9185 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9188 - (void) addSource:(NSDictionary *) source {
9189 CydiaAddSource(source);
9192 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9193 CydiaAddSource(href, distribution, sections);
9196 - (void) addTrivialSource:(NSString *)href {
9197 CydiaAddSource(href, @"./");
9201 pkgProblemResolver *resolver = [database_ resolver];
9203 resolver->InstallProtect();
9204 if (!resolver->Resolve(true))
9209 // XXX: this is a really crappy way of doing this.
9210 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9211 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9212 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9213 if ([tabbar_ updating])
9214 [tabbar_ cancelUpdate];
9216 if (![database_ prepare])
9219 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9220 [page setDelegate:self];
9221 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9224 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9225 [tabbar_ presentModalViewController:confirm_ animated:YES];
9231 @synchronized (self) {
9236 - (void) clearPackage:(Package *)package {
9237 @synchronized (self) {
9244 - (void) installPackages:(NSArray *)packages {
9245 @synchronized (self) {
9246 for (Package *package in packages)
9253 - (void) installPackage:(Package *)package {
9254 @synchronized (self) {
9261 - (void) removePackage:(Package *)package {
9262 @synchronized (self) {
9269 - (void) distUpgrade {
9270 @synchronized (self) {
9271 if (![database_ upgrade])
9279 system("/usr/bin/uicache");
9284 UIProgressHUD *hud([self addProgressHUD]);
9285 [hud setText:UCLocalize("LOADING")];
9286 [self yieldToSelector:@selector(_uicache)];
9287 [self removeProgressHUD:hud];
9291 [database_ perform];
9292 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9293 [self performSelectorOnMainThread:@selector(uicache) withObject:nil waitUntilDone:YES];
9296 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9299 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9300 [self unlockSuspend];
9303 - (void) retainNetworkActivityIndicator {
9304 if (activity_++ == 0)
9305 [self setNetworkActivityIndicatorVisible:YES];
9308 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9312 - (void) releaseNetworkActivityIndicator {
9313 if (--activity_ == 0)
9314 [self setNetworkActivityIndicatorVisible:NO];
9317 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9322 - (void) cancelAndClear:(bool)clear {
9323 @synchronized (self) {
9335 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9336 NSString *context([alert context]);
9338 if ([context isEqualToString:@"conffile"]) {
9339 FILE *input = [database_ input];
9340 if (button == [alert cancelButtonIndex])
9341 fprintf(input, "N\n");
9342 else if (button == [alert firstOtherButtonIndex])
9343 fprintf(input, "Y\n");
9346 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9347 } else if ([context isEqualToString:@"fixhalf"]) {
9348 if (button == [alert cancelButtonIndex]) {
9349 @synchronized (self) {
9350 for (Package *broken in (id) broken_) {
9352 NSString *id([broken id]);
9353 system([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /bin/rm -f"
9354 " /var/lib/dpkg/info/%@.prerm"
9355 " /var/lib/dpkg/info/%@.postrm"
9356 " /var/lib/dpkg/info/%@.preinst"
9357 " /var/lib/dpkg/info/%@.postinst"
9358 " /var/lib/dpkg/info/%@.extrainst_"
9359 "", id, id, id, id, id] UTF8String]);
9365 } else if (button == [alert firstOtherButtonIndex]) {
9366 [broken_ removeAllObjects];
9370 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9371 } else if ([context isEqualToString:@"upgrade"]) {
9372 if (button == [alert firstOtherButtonIndex]) {
9373 @synchronized (self) {
9374 for (Package *essential in (id) essential_)
9375 [essential install];
9380 } else if (button == [alert firstOtherButtonIndex] + 1) {
9382 } else if (button == [alert cancelButtonIndex]) {
9386 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9390 - (void) system:(NSString *)command {
9391 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9394 system([command UTF8String]);
9400 - (void) applicationWillSuspend {
9402 [super applicationWillSuspend];
9405 - (BOOL) isSafeToSuspend {
9408 NSLog(@"isSafeToSuspend: locked_ != 0");
9413 if ([tabbar_ modalViewController] != nil)
9416 // Use external process status API internally.
9417 // This is probably a really bad idea.
9418 // XXX: what is the point of this? does this solve anything at all?
9419 uint64_t status = 0;
9421 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9422 notify_get_state(notify_token, &status);
9423 notify_cancel(notify_token);
9428 NSLog(@"isSafeToSuspend: status != 0");
9434 NSLog(@"isSafeToSuspend: -> true");
9439 - (void) suspendReturningToLastApp:(BOOL)returning {
9440 if ([self isSafeToSuspend])
9441 [super suspendReturningToLastApp:returning];
9445 if ([self isSafeToSuspend])
9449 - (void) applicationSuspend {
9450 if ([self isSafeToSuspend])
9451 [super applicationSuspend];
9454 - (void) applicationSuspend:(__GSEvent *)event {
9455 if ([self isSafeToSuspend])
9456 [super applicationSuspend:event];
9459 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9460 if ([self isSafeToSuspend])
9461 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9464 - (void) _setSuspended:(BOOL)value {
9465 if ([self isSafeToSuspend])
9466 [super _setSuspended:value];
9469 - (UIProgressHUD *) addProgressHUD {
9470 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9471 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9473 [window_ setUserInteractionEnabled:NO];
9475 UIViewController *target(tabbar_);
9476 if (UIViewController *modal = [target modalViewController])
9479 [hud showInView:[target view]];
9485 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9486 [self unlockSuspend];
9488 [hud removeFromSuperview];
9489 [window_ setUserInteractionEnabled:YES];
9492 - (CyteViewController *) pageForPackage:(NSString *)name withReferrer:(NSString *)referrer {
9493 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name withReferrer:referrer] autorelease];
9496 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external withReferrer:(NSString *)referrer {
9497 NSString *scheme([[url scheme] lowercaseString]);
9498 if ([[url absoluteString] length] <= [scheme length] + 3)
9500 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9501 NSArray *components([path componentsSeparatedByString:@"/"]);
9503 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"]) {
9504 CyteViewController *controller([self pageForPackage:[components objectAtIndex:1] withReferrer:referrer]);
9505 if (controller != nil)
9506 [controller setDelegate:self];
9510 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9513 NSString *base([components objectAtIndex:0]);
9515 CyteViewController *controller = nil;
9517 if ([base isEqualToString:@"url"]) {
9518 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9519 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9520 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9521 } else if (!external && [components count] == 1) {
9522 if ([base isEqualToString:@"sources"]) {
9523 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9526 if ([base isEqualToString:@"home"]) {
9527 controller = [[[HomeController alloc] init] autorelease];
9530 if ([base isEqualToString:@"sections"]) {
9531 controller = [[[SectionsController alloc] initWithDatabase:database_ source:nil] autorelease];
9534 if ([base isEqualToString:@"search"]) {
9535 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9538 if ([base isEqualToString:@"changes"]) {
9539 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9542 if ([base isEqualToString:@"installed"]) {
9543 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9545 } else if ([components count] == 2) {
9546 NSString *argument = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9548 if ([base isEqualToString:@"package"]) {
9549 controller = [self pageForPackage:argument withReferrer:referrer];
9552 if (!external && [base isEqualToString:@"search"]) {
9553 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9556 if (!external && [base isEqualToString:@"sections"]) {
9557 if ([argument isEqualToString:@"all"] || [argument isEqualToString:@"*"])
9559 controller = [[[SectionController alloc] initWithDatabase:database_ source:nil section:argument] autorelease];
9562 if ([base isEqualToString:@"sources"]) {
9563 if ([argument isEqualToString:@"add"]) {
9564 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9565 [(SourcesController *)controller showAddSourcePrompt];
9567 Source *source([database_ sourceWithKey:argument]);
9568 controller = [[[SectionsController alloc] initWithDatabase:database_ source:source] autorelease];
9572 if (!external && [base isEqualToString:@"launch"]) {
9573 [self launchApplicationWithIdentifier:argument suspended:NO];
9576 } else if (!external && [components count] == 3) {
9577 NSString *arg1 = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9578 NSString *arg2 = [[components objectAtIndex:2] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9580 if ([base isEqualToString:@"package"]) {
9581 if ([arg2 isEqualToString:@"settings"]) {
9582 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9583 } else if ([arg2 isEqualToString:@"files"]) {
9584 if (Package *package = [database_ packageWithName:arg1]) {
9585 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9586 [(FileTable *)controller setPackage:package];
9591 if ([base isEqualToString:@"sections"]) {
9592 Source *source([arg1 isEqualToString:@"*"] ? nil : [database_ sourceWithKey:arg1]);
9593 NSString *section([arg2 isEqualToString:@"*"] ? nil : arg2);
9594 controller = [[[SectionController alloc] initWithDatabase:database_ source:source section:section] autorelease];
9598 [controller setDelegate:self];
9602 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9603 CyteViewController *page([self pageForURL:url forExternal:external withReferrer:nil]);
9606 [tabbar_ setUnselectedViewController:page];
9611 - (void) applicationOpenURL:(NSURL *)url {
9612 [super applicationOpenURL:url];
9617 [self openCydiaURL:url forExternal:YES];
9620 - (void) applicationWillResignActive:(UIApplication *)application {
9621 // Stop refreshing if you get a phone call or lock the device.
9622 if ([tabbar_ updating])
9623 [tabbar_ cancelUpdate];
9625 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9626 [super applicationWillResignActive:application];
9629 - (void) saveState {
9630 [[NSDictionary dictionaryWithObjectsAndKeys:
9631 @"InterfaceState", [tabbar_ navigationURLCollection],
9632 @"LastClosed", [NSDate date],
9633 @"InterfaceIndex", [NSNumber numberWithInt:[tabbar_ selectedIndex]],
9634 nil] writeToFile:@ SavedState_ atomically:YES];
9639 - (void) applicationWillTerminate:(UIApplication *)application {
9643 - (void) applicationDidEnterBackground:(UIApplication *)application {
9644 if (kCFCoreFoundationVersionNumber < 1000 && [self isSafeToSuspend])
9645 return [self terminateWithSuccess];
9646 Backgrounded_ = [NSDate date];
9650 - (void) applicationWillEnterForeground:(UIApplication *)application {
9651 if (Backgrounded_ == nil)
9654 NSTimeInterval interval([Backgrounded_ timeIntervalSinceNow]);
9656 if (interval <= -(30*60)) {
9657 [tabbar_ setSelectedIndex:0];
9658 [[[tabbar_ viewControllers] objectAtIndex:0] popToRootViewControllerAnimated:NO];
9661 if (interval <= -(15*60)) {
9662 if (IsReachable("cydia.saurik.com")) {
9663 [tabbar_ beginUpdate];
9664 [appcache_ reloadURLWithCache:YES];
9668 if ([database_ delocked])
9672 - (void) setConfigurationData:(NSString *)data {
9673 static RegEx conffile_r("'(.*)' '(.*)' ([01]) ([01])");
9675 if (!conffile_r(data)) {
9676 lprintf("E:invalid conffile\n");
9680 NSString *ofile = conffile_r[1];
9681 //NSString *nfile = conffile_r[2];
9683 UIAlertView *alert = [[[UIAlertView alloc]
9684 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9685 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9687 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9689 UCLocalize("ACCEPT_NEW_COPY"),
9690 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9694 [alert setContext:@"conffile"];
9695 [alert setNumberOfRows:2];
9699 - (void) addStashController {
9701 stash_ = [[[StashController alloc] init] autorelease];
9702 [window_ addSubview:[stash_ view]];
9705 - (void) removeStashController {
9706 [[stash_ view] removeFromSuperview];
9708 [self unlockSuspend];
9712 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9713 UpdateExternalStatus(1);
9714 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/cydo /usr/libexec/cydia/free.sh"];
9715 UpdateExternalStatus(0);
9717 [self removeStashController];
9718 [self reloadSpringBoard];
9721 - (void) setupViewControllers {
9722 tabbar_ = [[[CydiaTabBarController alloc] initWithDatabase:database_] autorelease];
9724 NSMutableArray *items;
9725 if (kCFCoreFoundationVersionNumber < 800) {
9726 items = [NSMutableArray arrayWithObjects:
9727 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage imageNamed:@"home.png"] tag:0] autorelease],
9728 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage imageNamed:@"install.png"] tag:0] autorelease],
9729 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage imageNamed:@"changes.png"] tag:0] autorelease],
9730 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage imageNamed:@"manage.png"] tag:0] autorelease],
9731 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage imageNamed:@"search.png"] tag:0] autorelease],
9734 items = [NSMutableArray arrayWithObjects:
9735 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage imageNamed:@"home7.png"] selectedImage:[UIImage imageNamed:@"home7s.png"]] autorelease],
9736 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage imageNamed:@"install7.png"] selectedImage:[UIImage imageNamed:@"install7s.png"]] autorelease],
9737 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage imageNamed:@"changes7.png"] selectedImage:[UIImage imageNamed:@"changes7s.png"]] autorelease],
9738 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage imageNamed:@"manage7.png"] selectedImage:[UIImage imageNamed:@"manage7s.png"]] autorelease],
9739 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage imageNamed:@"search7.png"] selectedImage:[UIImage imageNamed:@"search7s.png"]] autorelease],
9743 NSMutableArray *controllers([NSMutableArray array]);
9744 for (UITabBarItem *item in items) {
9745 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9746 [controller setTabBarItem:item];
9747 [controllers addObject:controller];
9749 [tabbar_ setViewControllers:controllers];
9751 [tabbar_ setUpdateDelegate:self];
9754 - (void) _sendMemoryWarningNotification {
9755 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: maybe 4_0?
9756 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationMemoryWarningNotification" object:[UIApplication sharedApplication]];
9758 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
9761 - (void) _sendMemoryWarningNotifications {
9763 [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO];
9769 - (void) applicationDidReceiveMemoryWarning:(UIApplication *)application {
9771 [[NSURLCache sharedURLCache] removeAllCachedResponses];
9774 - (void) applicationDidFinishLaunching:(id)unused {
9775 //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil];
9778 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9779 [self setApplicationSupportsShakeToEdit:NO];
9781 @synchronized (HostConfig_) {
9782 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9785 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9786 initWithMemoryCapacity:524288
9787 diskCapacity:10485760
9788 diskPath:Cache("SDURLCache")
9791 [CydiaWebViewController _initialize];
9793 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9795 // this would disallow http{,s} URLs from accessing this data
9796 //[WebView registerURLSchemeAsLocal:@"cydia"];
9798 Font12_ = [UIFont systemFontOfSize:12];
9799 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9800 Font14_ = [UIFont systemFontOfSize:14];
9801 Font18_ = [UIFont systemFontOfSize:18];
9802 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9803 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9805 essential_ = [NSMutableArray arrayWithCapacity:4];
9806 broken_ = [NSMutableArray arrayWithCapacity:4];
9808 // XXX: I really need this thing... like, seriously... I'm sorry
9809 appcache_ = [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] autorelease];
9810 [appcache_ reloadData];
9812 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9813 [window_ orderFront:self];
9814 [window_ makeKey:self];
9815 [window_ setHidden:NO];
9818 [self addStashController];
9819 // XXX: this would be much cleaner as a yieldToSelector:
9820 // that way the removeStashController could happen right here inline
9821 // we also could no longer require the useless stash_ field anymore
9822 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9827 int error(stat("/", &root));
9828 _assert(error != -1);
9830 #define Stash_(path) do { \
9831 struct stat folder; \
9832 int error(lstat((path), &folder)); \
9833 if (error != -1 && ( \
9834 folder.st_dev == root.st_dev && \
9835 S_ISDIR(folder.st_mode) \
9836 ) || error == -1 && ( \
9837 errno == ENOENT || \
9842 Stash_("/Applications");
9843 Stash_("/Library/Ringtones");
9844 Stash_("/Library/Wallpaper");
9845 //Stash_("/usr/bin");
9846 Stash_("/usr/include");
9847 Stash_("/usr/share");
9848 //Stash_("/var/lib");
9850 database_ = [Database sharedInstance];
9851 [database_ setDelegate:self];
9853 [window_ setUserInteractionEnabled:NO];
9854 [self setupViewControllers];
9856 CydiaLoadingViewController *loading([[[CydiaLoadingViewController alloc] init] autorelease]);
9857 UINavigationController *navigation([[[UINavigationController alloc] init] autorelease]);
9858 [navigation setViewControllers:[NSArray arrayWithObject:loading]];
9860 emulated_ = [[[CyteTabBarController alloc] init] autorelease];
9861 [emulated_ setViewControllers:[NSArray arrayWithObject:navigation]];
9862 [emulated_ setSelectedIndex:0];
9864 if ([emulated_ respondsToSelector:@selector(concealTabBarSelection)])
9865 [emulated_ concealTabBarSelection];
9867 if ([window_ respondsToSelector:@selector(setRootViewController:)])
9868 [window_ setRootViewController:emulated_];
9870 [window_ addSubview:[emulated_ view]];
9872 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9876 - (NSArray *) defaultStartPages {
9877 NSMutableArray *standard = [NSMutableArray array];
9878 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9879 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9880 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9881 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9882 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9888 if ([emulated_ modalViewController] != nil)
9889 [emulated_ dismissModalViewControllerAnimated:YES];
9890 [window_ setUserInteractionEnabled:NO];
9892 [self reloadDataWithInvocation:nil];
9893 [self refreshIfPossible];
9896 NSDictionary *state([NSDictionary dictionaryWithContentsOfFile:@ SavedState_]);
9898 int savedIndex = [[state objectForKey:@"InterfaceIndex"] intValue];
9899 NSArray *saved = [[[state objectForKey:@"InterfaceState"] mutableCopy] autorelease];
9900 int standardIndex = 0;
9901 NSArray *standard = [self defaultStartPages];
9908 NSDate *closed = [state objectForKey:@"LastClosed"];
9909 if (valid && closed != nil) {
9910 NSTimeInterval interval([closed timeIntervalSinceNow]);
9911 if (interval <= -(30*60))
9915 if (valid && [saved count] != [standard count])
9919 for (unsigned int i = 0; i < [standard count]; i++) {
9920 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9921 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9922 // but it's good enough for now.
9923 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9930 NSArray *items = nil;
9932 [tabbar_ setSelectedIndex:savedIndex];
9935 [tabbar_ setSelectedIndex:standardIndex];
9939 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
9940 NSArray *stack = [items objectAtIndex:tab];
9941 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
9942 NSMutableArray *current = [NSMutableArray array];
9944 for (unsigned int nav = 0; nav < [stack count]; nav++) {
9945 NSString *addr = [stack objectAtIndex:nav];
9946 NSURL *url = [NSURL URLWithString:addr];
9947 CyteViewController *page = [self pageForURL:url forExternal:NO withReferrer:nil];
9949 [current addObject:page];
9952 [navigation setViewControllers:current];
9955 // (Try to) show the startup URL.
9956 if (starturl_ != nil) {
9957 [self openCydiaURL:starturl_ forExternal:YES];
9962 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9963 if (item != nil && IsWildcat_) {
9964 [sheet showFromBarButtonItem:item animated:YES];
9966 [sheet showInView:window_];
9970 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
9971 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
9972 [progress setTitle:task];
9973 [progress addProgressEvent:event];
9976 - (void) addProgressEventForTask:(NSArray *)data {
9977 CydiaProgressEvent *event([data objectAtIndex:0]);
9978 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
9979 [self addProgressEvent:event forTask:task];
9982 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
9983 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
9989 id Alloc_(id self, SEL selector) {
9990 id object = alloc_(self, selector);
9991 lprintf("[%s]A-%p\n", self->isa->name, object);
9996 id Dealloc_(id self, SEL selector) {
9997 id object = dealloc_(self, selector);
9998 lprintf("[%s]D-%p\n", self->isa->name, object);
10002 Class $NSURLConnection;
10004 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
10005 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
10007 NSURL *url([copy URL]);
10009 NSString *host([url host]);
10010 NSString *scheme([[url scheme] lowercaseString]);
10012 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
10014 @synchronized (HostConfig_) {
10015 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
10016 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
10017 [copy setHTTPShouldUsePipelining:YES];
10019 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
10020 if ([control isEqualToString:@"max-age=0"])
10021 if ([CachedURLs_ containsObject:url]) {
10023 NSLog(@"~~~: %@", url);
10026 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
10028 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
10029 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
10030 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
10034 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
10040 static CGSize $WAKWindow$screenSize(WAKWindow *self, SEL _cmd) {
10041 CGSize size([[UIScreen mainScreen] bounds].size);
10042 /*if ([$WAKWindow respondsToSelector:@selector(hasLandscapeOrientation)])
10043 if ([$WAKWindow hasLandscapeOrientation])
10044 std::swap(size.width, size.height);*/
10048 Class $NSUserDefaults;
10050 MSHook(id, NSUserDefaults$objectForKey$, NSUserDefaults *self, SEL _cmd, NSString *key) {
10051 if ([key respondsToSelector:@selector(isEqualToString:)] && [key isEqualToString:@"WebKitLocalStorageDatabasePathPreferenceKey"])
10052 return Cache("LocalStorage");
10053 return _NSUserDefaults$objectForKey$(self, _cmd, key);
10056 static NSMutableDictionary *AutoreleaseDeepMutableCopyOfDictionary(CFTypeRef type) {
10059 if (CFGetTypeID(type) != CFDictionaryGetTypeID())
10061 CFTypeRef copy(CFPropertyListCreateDeepCopy(kCFAllocatorDefault, type, kCFPropertyListMutableContainers));
10063 return [(NSMutableDictionary *) copy autorelease];
10066 int main(int argc, char *argv[]) {
10067 int fd(open("/tmp/cydia.log", O_WRONLY | O_APPEND | O_CREAT, 0644));
10071 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10075 UpdateExternalStatus(0);
10077 UIScreen *screen([UIScreen mainScreen]);
10078 if ([screen respondsToSelector:@selector(scale)])
10079 ScreenScale_ = [screen scale];
10083 UIDevice *device([UIDevice currentDevice]);
10084 if ([device respondsToSelector:@selector(userInterfaceIdiom)]) {
10085 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10086 if (idiom == UIUserInterfaceIdiomPad)
10090 Idiom_ = IsWildcat_ ? @"ipad" : @"iphone";
10092 RegEx pattern("([0-9]+\\.[0-9]+).*");
10094 if (pattern([device systemVersion]))
10095 Firmware_ = pattern[1];
10096 if (pattern(Cydia_))
10097 Major_ = pattern[1];
10099 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
10101 HostConfig_ = [[[NSObject alloc] init] autorelease];
10102 @synchronized (HostConfig_) {
10103 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10104 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
10105 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
10106 CachedURLs_ = [NSMutableSet setWithCapacity:32];
10109 NSString *ui(@"ui/ios");
10111 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
10112 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"/%@", Major_]];
10113 UI_ = CydiaURL(ui);
10115 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10117 /* Library Hacks {{{ */
10118 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10120 $WAKWindow = objc_getClass("WAKWindow");
10121 if ($WAKWindow != NULL)
10122 if (Method method = class_getInstanceMethod($WAKWindow, @selector(screenSize)))
10123 method_setImplementation(method, (IMP) &$WAKWindow$screenSize);
10125 $NSURLConnection = objc_getClass("NSURLConnection");
10126 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10127 if (NSURLConnection$init$ != NULL) {
10128 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10129 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10132 $NSUserDefaults = objc_getClass("NSUserDefaults");
10133 Method NSUserDefaults$objectForKey$(class_getInstanceMethod($NSUserDefaults, @selector(objectForKey:)));
10134 if (NSUserDefaults$objectForKey$ != NULL) {
10135 _NSUserDefaults$objectForKey$ = reinterpret_cast<id (*)(NSUserDefaults *, SEL, NSString *)>(method_getImplementation(NSUserDefaults$objectForKey$));
10136 method_setImplementation(NSUserDefaults$objectForKey$, reinterpret_cast<IMP>(&$NSUserDefaults$objectForKey$));
10139 /* Set Locale {{{ */
10140 Locale_ = CFLocaleCopyCurrent();
10141 Languages_ = [NSLocale preferredLanguages];
10143 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10144 //NSLog(@"%@", [Languages_ description]);
10147 if (Locale_ != NULL)
10148 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10149 else if (Languages_ != nil && [Languages_ count] != 0)
10150 lang = [[Languages_ objectAtIndex:0] UTF8String];
10152 // XXX: consider just setting to C and then falling through?
10155 if (lang != NULL) {
10156 RegEx pattern("([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?");
10157 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10160 NSLog(@"Setting Language: %s", lang);
10162 if (lang != NULL) {
10163 setenv("LANG", lang, true);
10164 std::setlocale(LC_ALL, lang);
10167 /* Index Collation {{{ */
10168 if (Class $UILocalizedIndexedCollation = objc_getClass("UILocalizedIndexedCollation")) { @try {
10169 NSBundle *bundle([NSBundle bundleForClass:$UILocalizedIndexedCollation]);
10170 NSString *path([bundle pathForResource:@"UITableViewLocalizedSectionIndex" ofType:@"plist"]);
10171 //path = @"/System/Library/Frameworks/UIKit.framework/.lproj/UITableViewLocalizedSectionIndex.plist";
10172 NSDictionary *dictionary([NSDictionary dictionaryWithContentsOfFile:path]);
10173 _H<UILocalizedIndexedCollation> collation([[[$UILocalizedIndexedCollation alloc] initWithDictionary:dictionary] autorelease]);
10175 CollationLocale_ = MSHookIvar<NSLocale *>(collation, "_locale");
10177 if (kCFCoreFoundationVersionNumber >= 800 && [[CollationLocale_ localeIdentifier] isEqualToString:@"zh@collation=stroke"]) {
10178 CollationThumbs_ = [NSArray arrayWithObjects:@"1",@"•",@"4",@"•",@"7",@"•",@"10",@"•",@"13",@"•",@"16",@"•",@"19",@"A",@"•",@"E",@"•",@"I",@"•",@"M",@"•",@"R",@"•",@"V",@"•",@"Z",@"#",nil];
10179 for (NSInteger offset : (NSInteger[]) {0,1,3,4,6,7,9,10,12,13,15,16,18,25,26,29,30,33,34,37,38,42,43,46,47,50,51})
10180 CollationOffset_.push_back(offset);
10181 CollationTitles_ = [NSArray arrayWithObjects:@"1 畫",@"2 畫",@"3 畫",@"4 畫",@"5 畫",@"6 畫",@"7 畫",@"8 畫",@"9 畫",@"10 畫",@"11 畫",@"12 畫",@"13 畫",@"14 畫",@"15 畫",@"16 畫",@"17 畫",@"18 畫",@"19 畫",@"20 畫",@"21 畫",@"22 畫",@"23 畫",@"24 畫",@"25 畫以上",@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J",@"K",@"L",@"M",@"N",@"O",@"P",@"Q",@"R",@"S",@"T",@"U",@"V",@"W",@"X",@"Y",@"Z",@"#",nil];
10182 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];
10185 CollationThumbs_ = [collation sectionIndexTitles];
10186 for (size_t index(0), end([CollationThumbs_ count]); index != end; ++index)
10187 CollationOffset_.push_back([collation sectionForSectionIndexTitleAtIndex:index]);
10189 CollationTitles_ = [collation sectionTitles];
10190 CollationStarts_ = MSHookIvar<NSArray *>(collation, "_sectionStartStrings");
10192 NSString *&transform(MSHookIvar<NSString *>(collation, "_transform"));
10193 if (&transform != NULL && transform != nil) {
10194 /*if ([collation respondsToSelector:@selector(transformedCollationStringForString:)])
10195 CollationModify_ = [=](NSString *value) { return [collation transformedCollationStringForString:value]; };*/
10196 const UChar *uid(reinterpret_cast<const UChar *>([transform cStringUsingEncoding:NSUnicodeStringEncoding]));
10197 UErrorCode code(U_ZERO_ERROR);
10198 CollationTransl_ = utrans_openU(uid, -1, UTRANS_FORWARD, NULL, 0, NULL, &code);
10199 if (!U_SUCCESS(code))
10200 NSLog(@"%s", u_errorName(code));
10204 } @catch (NSException *e) {
10208 CollationLocale_ = [[[NSLocale alloc] initWithLocaleIdentifier:@"en@collation=dictionary"] autorelease];
10210 CollationThumbs_ = [NSArray arrayWithObjects:@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J",@"K",@"L",@"M",@"N",@"O",@"P",@"Q",@"R",@"S",@"T",@"U",@"V",@"W",@"X",@"Y",@"Z",@"#",nil];
10211 for (NSInteger offset(0); offset != 28; ++offset)
10212 CollationOffset_.push_back(offset);
10214 CollationTitles_ = [NSArray arrayWithObjects:@"A",@"B",@"C",@"D",@"E",@"F",@"G",@"H",@"I",@"J",@"K",@"L",@"M",@"N",@"O",@"P",@"Q",@"R",@"S",@"T",@"U",@"V",@"W",@"X",@"Y",@"Z",@"#",nil];
10215 CollationStarts_ = [NSArray arrayWithObjects:@"a",@"b",@"c",@"d",@"e",@"f",@"g",@"h",@"i",@"j",@"k",@"l",@"m",@"n",@"o",@"p",@"q",@"r",@"s",@"t",@"u",@"v",@"w",@"x",@"y",@"z",@"ʒ",nil];
10218 /* Parse Arguments {{{ */
10219 bool substrate(false);
10225 for (int argi(1); argi != argc; ++argi)
10226 if (strcmp(argv[argi], "--") == 0) {
10228 argv[argi] = argv[0];
10234 for (int argi(1); argi != arge; ++argi)
10235 if (strcmp(args[argi], "--substrate") == 0)
10238 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10242 App_ = [[NSBundle mainBundle] bundlePath];
10245 Cache_ = [[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia", @"/var/mobile"] retain];
10247 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10248 alloc_ = alloc->method_imp;
10249 alloc->method_imp = (IMP) &Alloc_;*/
10251 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10252 dealloc_ = dealloc->method_imp;
10253 dealloc->method_imp = (IMP) &Dealloc_;*/
10255 void *gestalt(dlopen("/usr/lib/libMobileGestalt.dylib", RTLD_GLOBAL | RTLD_LAZY));
10256 $MGCopyAnswer = reinterpret_cast<CFStringRef (*)(CFStringRef)>(dlsym(gestalt, "MGCopyAnswer"));
10258 /* System Information {{{ */
10262 size = sizeof(maxproc);
10263 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10264 perror("sysctlbyname(\"kern.maxproc\", ?)");
10265 else if (maxproc < 64) {
10267 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10268 perror("sysctlbyname(\"kern.maxproc\", #)");
10271 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10272 char *osversion = new char[size];
10273 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10274 perror("sysctlbyname(\"kern.osversion\", ?)");
10276 System_ = [NSString stringWithUTF8String:osversion];
10278 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10279 char *machine = new char[size];
10280 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10281 perror("sysctlbyname(\"hw.machine\", ?)");
10283 Machine_ = machine;
10285 int64_t usermem(0);
10286 size = sizeof(usermem);
10287 if (sysctlbyname("hw.usermem", &usermem, &size, NULL, 0) == -1)
10290 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10291 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10292 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10294 UniqueID_ = UniqueIdentifier(device);
10296 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10297 Product_ = [info objectForKey:@"SafariProductVersion"];
10298 Safari_ = [info objectForKey:@"CFBundleVersion"];
10301 NSString *agent([NSString stringWithFormat:@"Cydia/%@ CyF/%.2f", Cydia_, kCFCoreFoundationVersionNumber]);
10303 if (RegEx match = RegEx("([0-9]+(\\.[0-9]+)+).*", Safari_))
10304 agent = [NSString stringWithFormat:@"Safari/%@ %@", match[1], agent];
10305 if (RegEx match = RegEx("([0-9]+[A-Z][0-9]+[a-z]?).*", System_))
10306 agent = [NSString stringWithFormat:@"Mobile/%@ %@", match[1], agent];
10307 if (RegEx match = RegEx("([0-9]+(\\.[0-9]+)+).*", Product_))
10308 agent = [NSString stringWithFormat:@"Version/%@ %@", match[1], agent];
10310 UserAgent_ = agent;
10312 /* Load Database {{{ */
10313 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10316 mkdir("/var/mobile/Library/Cydia", 0755);
10317 MetaFile_.Open("/var/mobile/Library/Cydia/metadata.cb0");
10320 Values_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaValues"), CFSTR("com.saurik.Cydia")));
10321 Sections_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaSections"), CFSTR("com.saurik.Cydia")));
10322 Sources_ = AutoreleaseDeepMutableCopyOfDictionary(CFPreferencesCopyAppValue(CFSTR("CydiaSources"), CFSTR("com.saurik.Cydia")));
10323 Version_ = [(NSNumber *) CFPreferencesCopyAppValue(CFSTR("CydiaVersion"), CFSTR("com.saurik.Cydia")) autorelease];
10326 NSDictionary *metadata([[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease]);
10328 if (Values_ == nil)
10329 Values_ = [metadata objectForKey:@"Values"];
10330 if (Values_ == nil)
10331 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10333 if (Sections_ == nil)
10334 Sections_ = [metadata objectForKey:@"Sections"];
10335 if (Sections_ == nil)
10336 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10338 if (Sources_ == nil)
10339 Sources_ = [metadata objectForKey:@"Sources"];
10340 if (Sources_ == nil)
10341 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10343 // XXX: this wrong, but in a way that doesn't matter :/
10344 if (Version_ == nil)
10345 Version_ = [metadata objectForKey:@"Version"];
10346 if (Version_ == nil)
10347 Version_ = [NSNumber numberWithUnsignedInt:0];
10349 if (NSDictionary *packages = [metadata objectForKey:@"Packages"]) {
10351 CFDictionaryApplyFunction((CFDictionaryRef) packages, &PackageImport, &fail);
10354 NSLog(@"unable to import package preferences... from 2010? oh well :/");
10357 if ([Version_ unsignedIntValue] == 0) {
10358 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10359 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10360 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10361 CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./");
10363 Version_ = [NSNumber numberWithUnsignedInt:1];
10365 if (NSMutableDictionary *cache = [NSMutableDictionary dictionaryWithContentsOfFile:@ CacheState_]) {
10366 [cache removeObjectForKey:@"LastUpdate"];
10367 [cache writeToFile:@ CacheState_ atomically:YES];
10371 _H<NSMutableArray> broken([NSMutableArray array]);
10372 for (NSString *key in (id) Sources_)
10373 if ([key rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"# "]].location != NSNotFound)
10374 [broken addObject:key];
10375 if ([broken count] != 0)
10376 for (NSString *key in (id) broken)
10377 [Sources_ removeObjectForKey:key];
10381 system("/usr/libexec/cydia/cydo /bin/rm -f /var/lib/cydia/metadata.plist");
10384 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10386 if (kCFCoreFoundationVersionNumber > 1000)
10387 system("/usr/libexec/cydia/cydo /usr/libexec/cydia/setnsfpn /var/lib");
10389 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10391 if (access("/User", F_OK) != 0 || version != 6) {
10393 system("/usr/libexec/cydia/cydo /usr/libexec/cydia/firmware.sh");
10397 if (access("/tmp/cydia.chk", F_OK) == 0) {
10398 if (unlink([Cache("pkgcache.bin") UTF8String]) == -1)
10399 _assert(errno == ENOENT);
10400 if (unlink([Cache("srcpkgcache.bin") UTF8String]) == -1)
10401 _assert(errno == ENOENT);
10404 system("/usr/libexec/cydia/cydo /bin/ln -sf /var/mobile/Library/Caches/com.saurik.Cydia/sources.list /etc/apt/sources.list.d/cydia.list");
10406 /* APT Initialization {{{ */
10407 _assert(pkgInitConfig(*_config));
10408 _assert(pkgInitSystem(*_config, _system));
10411 _config->Set("APT::Acquire::Translation", lang);
10413 // XXX: this timeout might be important :(
10414 //_config->Set("Acquire::http::Timeout", 15);
10416 _config->Set("Acquire::http::MaxParallel", usermem >= 384 * 1024 * 1024 ? 16 : 3);
10418 mkdir([Cache_ UTF8String], 0755);
10419 mkdir([Cache("archives") UTF8String], 0755);
10420 mkdir([Cache("archives/partial") UTF8String], 0755);
10421 _config->Set("Dir::Cache", [Cache_ UTF8String]);
10423 symlink("/var/lib/apt/extended_states", [Cache("extended_states") UTF8String]);
10424 _config->Set("Dir::State", [Cache_ UTF8String]);
10426 mkdir([Cache("lists") UTF8String], 0755);
10427 mkdir([Cache("lists/partial") UTF8String], 0755);
10428 mkdir([Cache("periodic") UTF8String], 0755);
10429 _config->Set("Dir::State::Lists", [Cache("lists") UTF8String]);
10431 std::string logs("/var/mobile/Library/Logs/Cydia");
10432 mkdir(logs.c_str(), 0755);
10433 _config->Set("Dir::Log::Terminal", logs + "/apt.log");
10435 _config->Set("Dir::Bin::dpkg", "/usr/libexec/cydia/cydo");
10437 /* Color Choices {{{ */
10438 space_ = CGColorSpaceCreateDeviceRGB();
10440 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10441 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10442 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10443 Folder_.Set(space_, 0x8e/255.f, 0x8e/255.f, 0x93/255.f, 1.0);
10444 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10445 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10446 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10447 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10448 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10449 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10451 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10452 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10454 /* UIKit Configuration {{{ */
10455 // XXX: I have a feeling this was important
10456 //UIKeyboardDisableAutomaticAppearance();
10459 $SBSSetInterceptsMenuButtonForever = reinterpret_cast<void (*)(bool)>(dlsym(RTLD_DEFAULT, "SBSSetInterceptsMenuButtonForever"));
10461 const char *symbol(kCFCoreFoundationVersionNumber >= 800 ? "MGGetBoolAnswer" : "GSSystemHasCapability");
10462 BOOL (*GSSystemHasCapability)(CFStringRef) = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, symbol));
10463 bool fast = GSSystemHasCapability != NULL && GSSystemHasCapability(CFSTR("armv7"));
10465 PulseInterval_ = fast ? 50000 : 500000;
10467 Colon_ = UCLocalize("COLON_DELIMITED");
10468 Elision_ = UCLocalize("ELISION");
10469 Error_ = UCLocalize("ERROR");
10470 Warning_ = UCLocalize("WARNING");
10473 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10475 CGColorSpaceRelease(space_);
10476 CFRelease(Locale_);