1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2014 Jay Freeman (saurik)
5 /* GNU General Public License, Version 3 {{{ */
7 * Cydia is free software: you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published
9 * by the Free Software Foundation, either version 3 of the License,
10 * or (at your option) any later version.
12 * Cydia is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Cydia. If not, see <http://www.gnu.org/licenses/>.
22 // XXX: wtf/FastMalloc.h... wtf?
23 #define USE_SYSTEM_MALLOC 1
25 /* #include Directives {{{ */
26 #include "CyteKit/UCPlatform.h"
27 #include "CyteKit/Localize.h"
29 #include <unicode/ustring.h>
30 #include <unicode/utrans.h>
32 #include <objc/objc.h>
33 #include <objc/runtime.h>
35 #include <CoreGraphics/CoreGraphics.h>
36 #include <Foundation/Foundation.h>
39 #define DEPLOYMENT_TARGET_MACOSX 1
40 #define CF_BUILDING_CF 1
41 #include <CoreFoundation/CFInternal.h>
44 #include <CoreFoundation/CFUniChar.h>
46 #include <SystemConfiguration/SystemConfiguration.h>
48 #include <UIKit/UIKit.h>
49 #include "iPhonePrivate.h"
51 #include <IOKit/IOKitLib.h>
53 #include <QuartzCore/CALayer.h>
55 #include <WebCore/WebCoreThread.h>
56 #include <WebKit/DOMHTMLIFrameElement.h>
64 #include <ext/stdio_filebuf.h>
68 #include <apt-pkg/acquire.h>
69 #include <apt-pkg/acquire-item.h>
70 #include <apt-pkg/algorithms.h>
71 #include <apt-pkg/cachefile.h>
72 #include <apt-pkg/clean.h>
73 #include <apt-pkg/configuration.h>
74 #include <apt-pkg/debindexfile.h>
75 #include <apt-pkg/debmetaindex.h>
76 #include <apt-pkg/error.h>
77 #include <apt-pkg/init.h>
78 #include <apt-pkg/mmap.h>
79 #include <apt-pkg/pkgrecords.h>
80 #include <apt-pkg/sha1.h>
81 #include <apt-pkg/sourcelist.h>
82 #include <apt-pkg/sptr.h>
83 #include <apt-pkg/strutl.h>
84 #include <apt-pkg/tagfile.h>
86 #include <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 void setreugid(uid_t uid, gid_t gid) {
241 _assert(setreuid(uid, uid) != -1);
242 _assert(setregid(gid, gid) != -1);
245 static void setreguid(gid_t gid, uid_t uid) {
246 _assert(setregid(gid, gid) != -1);
247 _assert(setreuid(uid, uid) != -1);
254 _assert(pthread_setugid_np(0, 0) != -1);
261 _assert(pthread_setugid_np(KAUTH_UID_NONE, KAUTH_GID_NONE) != -1);
266 #define _root(code) \
267 ({ Root _root; code; })
269 static NSString *Colon_;
271 static NSString *Error_;
272 static NSString *Warning_;
274 static NSString *Cache_;
275 #define Cache(file) \
276 [NSString stringWithFormat:@"%@/%s", Cache_, file]
278 static void (*$SBSSetInterceptsMenuButtonForever)(bool);
280 static CFStringRef (*$MGCopyAnswer)(CFStringRef);
282 static NSString *UniqueIdentifier(UIDevice *device = nil) {
283 if (kCFCoreFoundationVersionNumber < 800) // iOS 7.x
284 return [device ?: [UIDevice currentDevice] uniqueIdentifier];
286 return [(id)$MGCopyAnswer(CFSTR("UniqueDeviceID")) autorelease];
289 static bool IsReachable(const char *name) {
290 SCNetworkReachabilityFlags flags; {
291 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, name));
292 SCNetworkReachabilityGetFlags(reachability, &flags);
293 CFRelease(reachability);
296 // XXX: this elaborate mess is what Apple is using to determine this? :(
297 // XXX: do we care if the user has to intervene? maybe that's ok?
299 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
300 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
301 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
302 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
303 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
304 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
309 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
311 static _finline NSString *CydiaURL(NSString *path) {
313 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = 's';
314 page[5] = ':'; page[6] = '/'; page[7] = '/'; page[8] = 'c'; page[9] = 'y';
315 page[10] = 'd'; page[11] = 'i'; page[12] = 'a'; page[13] = '.'; page[14] = 's';
316 page[15] = 'a'; page[16] = 'u'; page[17] = 'r'; page[18] = 'i'; page[19] = 'k';
317 page[20] = '.'; page[21] = 'c'; page[22] = 'o'; page[23] = 'm'; page[24] = '/';
319 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
322 static void ReapZombie(pid_t pid) {
325 if (waitpid(pid, &status, 0) == -1)
331 static _finline void UpdateExternalStatus(uint64_t newStatus) {
333 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
334 notify_set_state(notify_token, newStatus);
335 notify_cancel(notify_token);
337 notify_post("com.saurik.Cydia.status");
340 static CGFloat CYStatusBarHeight() {
341 CGSize size([[UIApplication sharedApplication] statusBarFrame].size);
342 return UIInterfaceOrientationIsPortrait([[UIApplication sharedApplication] statusBarOrientation]) ? size.height : size.width;
345 /* NSForcedOrderingSearch doesn't work on the iPhone */
346 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
347 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
348 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
350 /* Insertion Sort {{{ */
352 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
353 const char *ptr = (const char *)list;
355 CFIndex half = count / 2;
356 const char *probe = ptr + elementSize * half;
357 CFComparisonResult cr = comparator(element, probe, context);
358 if (0 == cr) return (probe - (const char *)list) / elementSize;
359 ptr = (cr < 0) ? ptr : probe + elementSize;
360 count = (cr < 0) ? half : (half + (count & 1) - 1);
362 return (ptr - (const char *)list) / elementSize;
365 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
366 const char *ptr = (const char *)list;
368 CFIndex half = count / 2;
369 const char *probe = ptr + elementSize * half;
370 CFComparisonResult cr = comparator(element, probe, context);
371 if (0 == cr) return (probe - (const char *)list) / elementSize;
372 ptr = (cr < 0) ? ptr : probe + elementSize;
373 count = (cr < 0) ? half : (half + (count & 1) - 1);
375 return (ptr - (const char *)list) / elementSize;
378 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
379 if (range.length == 0)
381 const void **values(new const void *[range.length]);
382 CFArrayGetValues(array, range, values);
384 #if HistogramInsertionSort > 0
385 uint32_t total(0), *offsets(new uint32_t[range.length]);
388 for (CFIndex index(1); index != range.length; ++index) {
389 const void *value(values[index]);
390 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
391 CFIndex correct(index);
392 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
393 #if HistogramInsertionSort > 1
394 NSLog(@"%@ < %@", value, values[correct - 1]);
399 if (correct != index) {
400 size_t offset(index - correct);
401 #if HistogramInsertionSort
405 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
407 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
408 values[correct] = value;
412 CFArrayReplaceValues(array, range, values, range.length);
415 #if HistogramInsertionSort > 0
416 for (CFIndex index(0); index != range.length; ++index)
417 if (offsets[index] != 0)
418 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
419 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
426 /* Apple Bug Fixes {{{ */
427 @implementation UIWebDocumentView (Cydia)
429 - (void) _setScrollerOffset:(CGPoint)offset {
430 UIScroller *scroller([self _scroller]);
432 CGSize size([scroller contentSize]);
433 CGSize bounds([scroller bounds].size);
436 max.x = size.width - bounds.width;
437 max.y = size.height - bounds.height;
445 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
446 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
448 [scroller setOffset:offset];
454 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
455 size_t length([self length] - state->state);
458 else if (length > count)
460 for (size_t i(0); i != length; ++i)
461 objects[i] = [self item:state->state++];
462 state->itemsPtr = objects;
463 state->mutationsPtr = (unsigned long *) self;
467 /* Cydia NSString Additions {{{ */
468 @interface NSString (Cydia)
469 - (NSComparisonResult) compareByPath:(NSString *)other;
470 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
473 @implementation NSString (Cydia)
475 - (NSComparisonResult) compareByPath:(NSString *)other {
476 NSString *prefix = [self commonPrefixWithString:other options:0];
477 size_t length = [prefix length];
479 NSRange lrange = NSMakeRange(length, [self length] - length);
480 NSRange rrange = NSMakeRange(length, [other length] - length);
482 lrange = [self rangeOfString:@"/" options:0 range:lrange];
483 rrange = [other rangeOfString:@"/" options:0 range:rrange];
485 NSComparisonResult value;
487 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
488 value = NSOrderedSame;
489 else if (lrange.location == NSNotFound)
490 value = NSOrderedAscending;
491 else if (rrange.location == NSNotFound)
492 value = NSOrderedDescending;
494 value = NSOrderedSame;
496 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
497 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
498 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
499 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
501 NSComparisonResult result = [lpath compare:rpath];
502 return result == NSOrderedSame ? value : result;
505 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
506 return [(id)CFURLCreateStringByAddingPercentEscapes(
511 kCFStringEncodingUTF8
518 /* C++ NSString Wrapper Cache {{{ */
519 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
520 return size == 0 ? NULL :
521 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
522 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
525 static _finline CFStringRef CYStringCreate(const char *data) {
526 return CYStringCreate(data, strlen(data));
535 _finline void clear_() {
536 if (cache_ != NULL) {
543 _finline bool empty() const {
547 _finline size_t size() const {
551 _finline char *data() const {
555 _finline void clear() {
560 _finline CYString() :
567 _finline ~CYString() {
571 void operator =(const CYString &rhs) {
575 if (rhs.cache_ == nil)
578 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
581 void copy(CYPool *pool) {
582 char *temp(pool->malloc<char>(size_ + 1));
583 memcpy(temp, data_, size_);
588 void set(CYPool *pool, const char *data, size_t size) {
594 data_ = const_cast<char *>(data);
602 _finline void set(CYPool *pool, const char *data) {
603 set(pool, data, data == NULL ? 0 : strlen(data));
606 _finline void set(CYPool *pool, const std::string &rhs) {
607 set(pool, rhs.data(), rhs.size());
610 bool operator ==(const CYString &rhs) const {
611 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
614 _finline operator CFStringRef() {
616 cache_ = CYStringCreate(data_, size_);
620 _finline operator id() {
621 return (NSString *) static_cast<CFStringRef>(*this);
624 _finline operator const char *() {
625 return reinterpret_cast<const char *>(data_);
629 /* C++ NSString Algorithm Adapters {{{ */
631 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
634 struct NSStringMapHash :
635 std::unary_function<NSString *, size_t>
637 _finline size_t operator ()(NSString *value) const {
638 return CFStringHashNSString((CFStringRef) value);
642 struct NSStringMapLess :
643 std::binary_function<NSString *, NSString *, bool>
645 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
646 return [lhs compare:rhs] == NSOrderedAscending;
650 struct NSStringMapEqual :
651 std::binary_function<NSString *, NSString *, bool>
653 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
654 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
655 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
656 //[lhs isEqualToString:rhs];
661 /* CoreGraphics Primitives {{{ */
666 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
667 CGFloat color[] = {red, green, blue, alpha};
668 return CGColorCreate(space, color);
677 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
678 color_(Create_(space, red, green, blue, alpha))
680 Set(space, red, green, blue, alpha);
685 CGColorRelease(color_);
692 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
694 color_ = Create_(space, red, green, blue, alpha);
697 operator CGColorRef() {
703 /* Random Global Variables {{{ */
704 static int PulseInterval_ = 500000;
706 static const NSString *UI_;
709 static bool RestartSubstrate_;
710 static bool UpgradeCydia_;
711 static NSArray *Finishes_;
713 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
714 #define NotifyConfig_ "/etc/notify.conf"
716 static bool Queuing_;
718 static CYColor Blue_;
719 static CYColor Blueish_;
720 static CYColor Black_;
721 static CYColor Folder_;
723 static CYColor White_;
724 static CYColor Gray_;
725 static CYColor Green_;
726 static CYColor Purple_;
727 static CYColor Purplish_;
729 static UIColor *InstallingColor_;
730 static UIColor *RemovingColor_;
732 static NSString *App_;
734 static BOOL Advanced_;
735 static BOOL Ignored_;
737 static _H<UIFont> Font12_;
738 static _H<UIFont> Font12Bold_;
739 static _H<UIFont> Font14_;
740 static _H<UIFont> Font18_;
741 static _H<UIFont> Font18Bold_;
742 static _H<UIFont> Font22Bold_;
744 static const char *Machine_ = NULL;
745 static _H<NSString> System_;
746 static NSString *SerialNumber_ = nil;
747 static NSString *ChipID_ = nil;
748 static NSString *BBSNum_ = nil;
749 static _H<NSString> UniqueID_;
750 static _H<NSString> UserAgent_;
751 static _H<NSString> Product_;
752 static _H<NSString> Safari_;
754 static _H<NSLocale> CollationLocale_;
755 static _H<NSArray> CollationThumbs_;
756 static std::vector<NSInteger> CollationOffset_;
757 static _H<NSArray> CollationTitles_;
758 static _H<NSArray> CollationStarts_;
759 static UTransliterator *CollationTransl_;
760 //static Function<NSString *, NSString *> CollationModify_;
762 typedef std::basic_string<UChar> ustring;
763 static ustring CollationString_;
765 #define CUC const ustring &str(*reinterpret_cast<const ustring *>(rep))
766 #define UC ustring &str(*reinterpret_cast<ustring *>(rep))
767 static struct UReplaceableCallbacks CollationUCalls_ = {
768 .length = [](const UReplaceable *rep) -> int32_t { CUC;
772 .charAt = [](const UReplaceable *rep, int32_t offset) -> UChar { CUC;
773 //fprintf(stderr, "charAt(%d) : %d\n", offset, str.size());
774 if (offset >= str.size())
779 .char32At = [](const UReplaceable *rep, int32_t offset) -> UChar32 { CUC;
780 //fprintf(stderr, "char32At(%d) : %d\n", offset, str.size());
781 if (offset >= str.size())
784 U16_GET(str.data(), 0, offset, str.size(), c);
788 .replace = [](UReplaceable *rep, int32_t start, int32_t limit, const UChar *text, int32_t length) -> void { UC;
789 //fprintf(stderr, "replace(%d, %d, %d) : %d\n", start, limit, length, str.size());
790 str.replace(start, limit - start, text, length);
793 .extract = [](UReplaceable *rep, int32_t start, int32_t limit, UChar *dst) -> void { UC;
794 //fprintf(stderr, "extract(%d, %d) : %d\n", start, limit, str.size());
795 str.copy(dst, limit - start, start);
798 .copy = [](UReplaceable *rep, int32_t start, int32_t limit, int32_t dest) -> void { UC;
799 //fprintf(stderr, "copy(%d, %d, %d) : %d\n", start, limit, dest, str.size());
800 str.replace(dest, 0, str, start, limit - start);
804 static CFLocaleRef Locale_;
805 static NSArray *Languages_;
806 static CGColorSpaceRef space_;
808 #define SavedState_ "/var/mobile/Library/Caches/com.saurik.Cydia/SavedState.plist"
810 static NSDictionary *SectionMap_;
811 static NSMutableDictionary *Metadata_;
812 static _H<NSDate> Backgrounded_;
813 static _transient NSMutableDictionary *Settings_;
814 static _transient NSMutableDictionary *Values_;
815 static _transient NSMutableDictionary *Sections_;
816 _H<NSMutableDictionary> Sources_;
817 static _transient NSNumber *Version_;
822 CGFloat ScreenScale_;
823 static NSString *Idiom_;
824 static _H<NSString> Firmware_;
825 static NSString *Major_;
827 static _H<NSMutableDictionary> SessionData_;
828 static _H<NSObject> HostConfig_;
829 static _H<NSMutableSet> BridgedHosts_;
830 static _H<NSMutableSet> InsecureHosts_;
831 static _H<NSMutableSet> PipelinedHosts_;
832 static _H<NSMutableSet> CachedURLs_;
834 static NSString *kCydiaProgressEventTypeError = @"Error";
835 static NSString *kCydiaProgressEventTypeInformation = @"Information";
836 static NSString *kCydiaProgressEventTypeStatus = @"Status";
837 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
840 /* Display Helpers {{{ */
841 inline float Interpolate(float begin, float end, float fraction) {
842 return (end - begin) * fraction + begin;
845 static inline double Retina(double value) {
846 value *= ScreenScale_;
847 value = round(value);
848 value /= ScreenScale_;
852 static inline CGRect Retina(CGRect value) {
853 value.origin.x *= ScreenScale_;
854 value.origin.y *= ScreenScale_;
855 value.size.width *= ScreenScale_;
856 value.size.height *= ScreenScale_;
857 value = CGRectIntegral(value);
858 value.origin.x /= ScreenScale_;
859 value.origin.y /= ScreenScale_;
860 value.size.width /= ScreenScale_;
861 value.size.height /= ScreenScale_;
865 static _finline const char *StripVersion_(const char *version) {
866 const char *colon(strchr(version, ':'));
867 return colon == NULL ? version : colon + 1;
870 NSString *LocalizeSection(NSString *section) {
871 static RegEx title_r("(.*?) \\((.*)\\)");
872 if (title_r(section)) {
873 NSString *parent(title_r[1]);
874 NSString *child(title_r[2]);
876 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
877 LocalizeSection(parent),
878 LocalizeSection(child)
882 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
885 NSString *Simplify(NSString *title) {
886 const char *data = [title UTF8String];
887 size_t size = [title lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
889 static RegEx square_r("\\[(.*)\\]");
890 if (square_r(data, size))
891 return Simplify(square_r[1]);
893 static RegEx paren_r("\\((.*)\\)");
894 if (paren_r(data, size))
895 return Simplify(paren_r[1]);
897 static RegEx title_r("(.*?) \\((.*)\\)");
898 if (title_r(data, size))
899 return Simplify(title_r[1]);
905 NSString *GetLastUpdate() {
906 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
909 return UCLocalize("NEVER_OR_UNKNOWN");
911 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
912 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
914 CFRelease(formatter);
916 return [(NSString *) formatted autorelease];
919 bool isSectionVisible(NSString *section) {
920 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
921 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
922 return hidden == nil || ![hidden boolValue];
925 static NSObject *CYIOGetValue(const char *path, NSString *property) {
926 io_registry_entry_t entry(IORegistryEntryFromPath(kIOMasterPortDefault, path));
927 if (entry == MACH_PORT_NULL)
930 CFTypeRef value(IORegistryEntryCreateCFProperty(entry, (CFStringRef) property, kCFAllocatorDefault, 0));
931 IOObjectRelease(entry);
935 return [(id) value autorelease];
938 static NSString *CYHex(NSData *data, bool reverse = false) {
942 size_t length([data length]);
943 uint8_t bytes[length];
944 [data getBytes:bytes];
946 char string[length * 2 + 1];
947 for (size_t i(0); i != length; ++i)
948 sprintf(string + i * 2, "%.2x", bytes[reverse ? length - i - 1 : i]);
950 return [NSString stringWithUTF8String:string];
955 /* Delegate Prototypes {{{ */
958 @class CydiaProgressEvent;
960 @protocol DatabaseDelegate
961 - (void) repairWithSelector:(SEL)selector;
962 - (void) setConfigurationData:(NSString *)data;
963 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
966 @class CYPackageController;
968 @protocol SourceDelegate
969 - (void) setFetch:(NSNumber *)fetch;
972 @protocol FetchDelegate
973 - (bool) isSourceCancelled;
974 - (void) startSourceFetch:(NSString *)uri;
975 - (void) stopSourceFetch:(NSString *)uri;
978 @protocol CydiaDelegate
979 - (void) returnToCydia;
981 - (void) retainNetworkActivityIndicator;
982 - (void) releaseNetworkActivityIndicator;
983 - (void) clearPackage:(Package *)package;
984 - (void) installPackage:(Package *)package;
985 - (void) installPackages:(NSArray *)packages;
986 - (void) removePackage:(Package *)package;
987 - (void) beginUpdate;
989 - (bool) requestUpdate;
990 - (void) distUpgrade;
993 - (void) _saveConfig;
995 - (void) addSource:(NSDictionary *)source;
996 - (void) addTrivialSource:(NSString *)href;
997 - (UIProgressHUD *) addProgressHUD;
998 - (void) removeProgressHUD:(UIProgressHUD *)hud;
999 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
1000 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1004 /* CancelStatus {{{ */
1005 class CancelStatus :
1006 public pkgAcquireStatus
1017 virtual bool MediaChange(std::string media, std::string drive) {
1021 virtual void IMSHit(pkgAcquire::ItemDesc &desc) {
1025 virtual bool Pulse_(pkgAcquire *Owner) = 0;
1027 virtual bool Pulse(pkgAcquire *Owner) {
1028 if (pkgAcquireStatus::Pulse(Owner) && Pulse_(Owner))
1036 _finline bool WasCancelled() const {
1041 /* DelegateStatus {{{ */
1046 _transient NSObject<ProgressDelegate> *delegate_;
1054 void setDelegate(NSObject<ProgressDelegate> *delegate) {
1055 delegate_ = delegate;
1058 virtual void Fetch(pkgAcquire::ItemDesc &desc) {
1059 NSString *name([NSString stringWithUTF8String:desc.ShortDesc.c_str()]);
1060 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItemDesc:desc]);
1061 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1064 virtual void Done(pkgAcquire::ItemDesc &desc) {
1065 NSString *name([NSString stringWithUTF8String:desc.ShortDesc.c_str()]);
1066 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:Colon_, UCLocalize("DONE"), name] ofType:kCydiaProgressEventTypeStatus forItemDesc:desc]);
1067 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1070 virtual void Fail(pkgAcquire::ItemDesc &desc) {
1072 desc.Owner->Status == pkgAcquire::Item::StatIdle ||
1073 desc.Owner->Status == pkgAcquire::Item::StatDone
1077 std::string &error(desc.Owner->ErrorText);
1081 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItemDesc:desc]);
1082 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1085 virtual bool Pulse_(pkgAcquire *Owner) {
1087 double(CurrentBytes + CurrentItems) /
1088 double(TotalBytes + TotalItems)
1091 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
1092 [NSNumber numberWithDouble:percent], @"Percent",
1094 [NSNumber numberWithDouble:CurrentBytes], @"Current",
1095 [NSNumber numberWithDouble:TotalBytes], @"Total",
1096 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
1097 nil] waitUntilDone:YES];
1099 return ![delegate_ isProgressCancelled];
1102 virtual void Start() {
1103 pkgAcquireStatus::Start();
1104 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
1107 virtual void Stop() {
1108 pkgAcquireStatus::Stop();
1109 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
1110 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
1114 /* Database Interface {{{ */
1115 typedef std::map< unsigned long, _H<Source> > SourceMap;
1117 @interface Database : NSObject {
1123 pkgCacheFile cache_;
1124 pkgDepCache::Policy *policy_;
1125 pkgRecords *records_;
1126 pkgProblemResolver *resolver_;
1127 pkgAcquire *fetcher_;
1129 SPtr<pkgPackageManager> manager_;
1130 pkgSourceList *list_;
1132 SourceMap sourceMap_;
1133 _H<NSMutableArray> sourceList_;
1135 CFMutableArrayRef packages_;
1137 _transient NSObject<DatabaseDelegate> *delegate_;
1138 _transient NSObject<ProgressDelegate> *progress_;
1140 CydiaStatus status_;
1146 std::map<const char *, _H<NSString> > sections_;
1149 + (Database *) sharedInstance;
1152 - (void) _readCydia:(NSNumber *)fd;
1153 - (void) _readStatus:(NSNumber *)fd;
1154 - (void) _readOutput:(NSNumber *)fd;
1158 - (Package *) packageWithName:(NSString *)name;
1160 - (pkgCacheFile &) cache;
1161 - (pkgDepCache::Policy *) policy;
1162 - (pkgRecords *) records;
1163 - (pkgProblemResolver *) resolver;
1164 - (pkgAcquire &) fetcher;
1165 - (pkgSourceList &) list;
1166 - (NSArray *) packages;
1167 - (NSArray *) sources;
1168 - (Source *) sourceWithKey:(NSString *)key;
1169 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1177 - (void) updateWithStatus:(CancelStatus &)status;
1179 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1181 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1182 - (NSObject<ProgressDelegate> *) progressDelegate;
1184 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1185 - (void) setFetch:(bool)fetch forURI:(const char *)uri;
1186 - (void) resetFetch;
1188 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1192 /* SourceStatus {{{ */
1193 class SourceStatus :
1197 _transient NSObject<FetchDelegate> *delegate_;
1198 _transient Database *database_;
1199 std::set<std::string> fetches_;
1202 SourceStatus(NSObject<FetchDelegate> *delegate, Database *database) :
1203 delegate_(delegate),
1208 void Set(bool fetch, const std::string &uri) {
1210 if (!fetches_.insert(uri).second)
1213 if (fetches_.erase(uri) == 0)
1217 //printf("Set(%s, %s)\n", fetch ? "true" : "false", uri.c_str());
1218 [database_ setFetch:fetch forURI:uri.c_str()];
1221 _finline void Set(bool fetch, pkgAcquire::Item *item) {
1222 /*unsigned long ID(fetch ? 1 : 0);
1226 Set(fetch, item->DescURI());
1229 void Log(const char *tag, pkgAcquire::Item *item) {
1230 //printf("%s(%s) S:%u Q:%u\n", tag, item->DescURI().c_str(), item->Status, item->QueueCounter);
1233 virtual void Fetch(pkgAcquire::ItemDesc &desc) {
1234 Log("Fetch", desc.Owner);
1235 Set(true, desc.Owner);
1238 virtual void Done(pkgAcquire::ItemDesc &desc) {
1239 Log("Done", desc.Owner);
1240 Set(false, desc.Owner);
1243 virtual void Fail(pkgAcquire::ItemDesc &desc) {
1244 Log("Fail", desc.Owner);
1245 Set(false, desc.Owner);
1248 virtual bool Pulse_(pkgAcquire *Owner) {
1249 std::set<std::string> fetches;
1250 for (pkgAcquire::ItemCIterator item(Owner->ItemsBegin()); item != Owner->ItemsEnd(); ++item) {
1252 if ((*item)->QueueCounter == 0)
1254 else switch ((*item)->Status) {
1255 case pkgAcquire::Item::StatFetching:
1256 fetches.insert((*item)->DescURI());
1265 Log(fetch ? "Pulse<true>" : "Pulse<false>", *item);
1269 std::vector<std::string> stops;
1270 std::set_difference(fetches_.begin(), fetches_.end(), fetches.begin(), fetches.end(), std::back_insert_iterator<std::vector<std::string>>(stops));
1271 for (std::vector<std::string>::const_iterator stop(stops.begin()); stop != stops.end(); ++stop) {
1272 //printf("Stop(%s)\n", stop->c_str());
1276 return ![delegate_ isSourceCancelled];
1279 virtual void Stop() {
1280 pkgAcquireStatus::Stop();
1281 [database_ resetFetch];
1285 /* ProgressEvent Implementation {{{ */
1286 @implementation CydiaProgressEvent
1288 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1289 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1292 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1293 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1294 [event setPackage:package];
1298 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItemDesc:(pkgAcquire::ItemDesc &)desc {
1299 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1301 NSString *description([NSString stringWithUTF8String:desc.Description.c_str()]);
1302 NSArray *fields([description componentsSeparatedByString:@" "]);
1303 [event setItem:fields];
1305 if ([fields count] > 3) {
1306 [event setPackage:[fields objectAtIndex:2]];
1307 [event setVersion:[fields objectAtIndex:3]];
1310 [event setURL:[NSString stringWithUTF8String:desc.URI.c_str()]];
1315 + (NSArray *) _attributeKeys {
1316 return [NSArray arrayWithObjects:
1326 - (NSArray *) attributeKeys {
1327 return [[self class] _attributeKeys];
1330 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1331 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1334 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1335 if ((self = [super init]) != nil) {
1341 - (NSString *) message {
1345 - (NSString *) type {
1349 - (NSArray *) item {
1350 return (id) item_ ?: [NSNull null];
1353 - (void) setItem:(NSArray *)item {
1357 - (NSString *) package {
1358 return (id) package_ ?: [NSNull null];
1361 - (void) setPackage:(NSString *)package {
1365 - (NSString *) url {
1366 return (id) url_ ?: [NSNull null];
1369 - (void) setURL:(NSString *)url {
1373 - (void) setVersion:(NSString *)version {
1377 - (NSString *) version {
1378 return (id) version_ ?: [NSNull null];
1381 - (NSString *) compound:(NSString *)value {
1383 NSString *mode(nil); {
1384 NSString *type([self type]);
1385 if ([type isEqualToString:kCydiaProgressEventTypeError])
1386 mode = UCLocalize("ERROR");
1387 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1388 mode = UCLocalize("WARNING");
1392 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1398 - (NSString *) compoundMessage {
1399 return [self compound:[self message]];
1402 - (NSString *) compoundTitle {
1405 if (package_ == nil)
1407 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1408 title = [package name];
1412 return [self compound:title];
1418 // Cytore Definitions {{{
1419 struct PackageValue :
1422 Cytore::Offset<PackageValue> next_;
1424 uint32_t index_ : 23;
1425 uint32_t subscribed_ : 1;
1442 Cytore::Offset<PackageValue> packages_[1 << 16];
1445 static Cytore::File<MetaValue> MetaFile_;
1447 // Cytore Helper Functions {{{
1448 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1449 SplitHash nhash = { hashlittle(name, length) };
1451 PackageValue *metadata;
1453 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1454 for (;; offset = &metadata->next_) { if (offset->IsNull()) {
1455 *offset = MetaFile_.New<PackageValue>(length + 1);
1456 metadata = &MetaFile_.Get(*offset);
1458 if (metadata == NULL) {
1462 metadata = new PackageValue();
1463 memset(metadata, 0, sizeof(*metadata));
1466 memcpy(metadata->name_, name, length);
1467 metadata->name_[length] = '\0';
1468 metadata->nhash_ = nhash.u16[1];
1470 metadata = &MetaFile_.Get(*offset);
1471 if (metadata->nhash_ != nhash.u16[1])
1473 if (strncmp(metadata->name_, name, length) != 0)
1475 if (metadata->name_[length] != '\0')
1482 static void PackageImport(const void *key, const void *value, void *context) {
1483 bool &fail(*reinterpret_cast<bool *>(context));
1486 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1487 NSLog(@"failed to import package %@", key);
1491 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1492 NSDictionary *package((NSDictionary *) value);
1494 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1495 if ([subscribed boolValue] && !metadata->subscribed_)
1496 metadata->subscribed_ = true;
1498 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1499 time_t time([date timeIntervalSince1970]);
1500 if (metadata->first_ > time || metadata->first_ == 0)
1501 metadata->first_ = time;
1504 NSDate *date([package objectForKey:@"LastSeen"]);
1505 NSString *version([package objectForKey:@"LastVersion"]);
1507 if (date != nil && version != nil) {
1508 time_t time([date timeIntervalSince1970]);
1509 if (metadata->last_ < time || metadata->last_ == 0)
1510 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1511 size_t length(strlen(buffer));
1512 uint16_t vhash(hashlittle(buffer, length));
1514 size_t capped(std::min<size_t>(8, length));
1515 char *latest(buffer + length - capped);
1517 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1518 metadata->vhash_ = vhash;
1520 metadata->last_ = time;
1526 /* Source Class {{{ */
1527 @interface Source : NSObject {
1529 Database *database_;
1532 CYString depiction_;
1533 CYString description_;
1539 CYString distribution_;
1545 _H<NSString> authority_;
1547 CYString defaultIcon_;
1549 _H<NSMutableDictionary> record_;
1552 std::set<std::string> fetches_;
1553 std::set<std::string> files_;
1554 _transient NSObject<SourceDelegate> *delegate_;
1557 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(CYPool *)pool;
1559 - (NSComparisonResult) compareByName:(Source *)source;
1561 - (NSString *) depictionForPackage:(NSString *)package;
1562 - (NSString *) supportForPackage:(NSString *)package;
1564 - (metaIndex *) metaIndex;
1565 - (NSDictionary *) record;
1568 - (NSString *) rooturi;
1569 - (NSString *) distribution;
1570 - (NSString *) type;
1573 - (NSString *) host;
1575 - (NSString *) name;
1576 - (NSString *) shortDescription;
1577 - (NSString *) label;
1578 - (NSString *) origin;
1579 - (NSString *) version;
1581 - (NSString *) defaultIcon;
1582 - (NSURL *) iconURL;
1584 - (void) setFetch:(bool)fetch forURI:(const char *)uri;
1585 - (void) resetFetch;
1589 @implementation Source
1591 + (NSString *) webScriptNameForSelector:(SEL)selector {
1593 else if (selector == @selector(addSection:))
1594 return @"addSection";
1595 else if (selector == @selector(getField:))
1597 else if (selector == @selector(removeSection:))
1598 return @"removeSection";
1599 else if (selector == @selector(remove))
1605 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1606 return [self webScriptNameForSelector:selector] == nil;
1609 + (NSArray *) _attributeKeys {
1610 return [NSArray arrayWithObjects:
1621 @"shortDescription",
1628 - (NSArray *) attributeKeys {
1629 return [[self class] _attributeKeys];
1632 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1633 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1636 - (metaIndex *) metaIndex {
1640 - (void) setMetaIndex:(metaIndex *)index inPool:(CYPool *)pool {
1641 trusted_ = index->IsTrusted();
1643 uri_.set(pool, index->GetURI());
1644 distribution_.set(pool, index->GetDist());
1645 type_.set(pool, index->GetType());
1647 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1648 if (dindex != NULL) {
1649 std::string file(dindex->MetaIndexURI(""));
1650 base_.set(pool, file);
1653 _profile(Source$setMetaIndex$GetIndexes)
1654 dindex->GetIndexes(&acquire, true);
1656 _profile(Source$setMetaIndex$DescURI)
1657 for (pkgAcquire::ItemIterator item(acquire.ItemsBegin()); item != acquire.ItemsEnd(); item++) {
1658 std::string file((*item)->DescURI());
1659 files_.insert(file);
1660 if (file.length() < sizeof("Packages.bz2") || file.substr(file.length() - sizeof("Packages.bz2")) != "/Packages.bz2")
1662 file = file.substr(0, file.length() - 4);
1663 files_.insert(file);
1664 files_.insert(file + ".gz");
1665 files_.insert(file + "Index");
1670 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1673 pkgTagFile tags(&fd);
1675 pkgTagSection section;
1682 {"default-icon", &defaultIcon_},
1683 {"depiction", &depiction_},
1684 {"description", &description_},
1686 {"origin", &origin_},
1687 {"support", &support_},
1688 {"version", &version_},
1691 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1692 const char *start, *end;
1694 if (section.Find(names[i].name_, start, end)) {
1695 CYString &value(*names[i].value_);
1696 value.set(pool, start, end - start);
1702 record_ = [Sources_ objectForKey:[self key]];
1704 NSURL *url([NSURL URLWithString:uri_]);
1708 host_ = [host_ lowercaseString];
1713 authority_ = [url path];
1716 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(CYPool *)pool {
1717 if ((self = [super init]) != nil) {
1718 era_ = [database era];
1719 database_ = database;
1722 _profile(Source$initWithMetaIndex$setMetaIndex)
1723 [self setMetaIndex:index inPool:pool];
1728 - (NSString *) getField:(NSString *)name {
1729 @synchronized (database_) {
1730 if ([database_ era] != era_ || index_ == NULL)
1733 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index_));
1738 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly)) {
1743 pkgTagFile tags(&fd);
1745 pkgTagSection section;
1748 const char *start, *end;
1749 if (!section.Find([name UTF8String], start, end))
1750 return (NSString *) [NSNull null];
1752 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
1755 - (NSComparisonResult) compareByName:(Source *)source {
1756 NSString *lhs = [self name];
1757 NSString *rhs = [source name];
1759 if ([lhs length] != 0 && [rhs length] != 0) {
1760 unichar lhc = [lhs characterAtIndex:0];
1761 unichar rhc = [rhs characterAtIndex:0];
1763 if (isalpha(lhc) && !isalpha(rhc))
1764 return NSOrderedAscending;
1765 else if (!isalpha(lhc) && isalpha(rhc))
1766 return NSOrderedDescending;
1769 return [lhs compare:rhs options:LaxCompareOptions_];
1772 - (NSString *) depictionForPackage:(NSString *)package {
1773 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1776 - (NSString *) supportForPackage:(NSString *)package {
1777 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1780 - (NSArray *) sections {
1781 return record_ == nil ? (id) [NSNull null] : [record_ objectForKey:@"Sections"] ?: [NSArray array];
1784 - (void) _addSection:(NSString *)section {
1787 else if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) {
1788 if (![sections containsObject:section]) {
1789 [sections addObject:section];
1793 [record_ setObject:[NSMutableArray arrayWithObject:section] forKey:@"Sections"];
1798 - (bool) addSection:(NSString *)section {
1802 [self performSelectorOnMainThread:@selector(_addSection:) withObject:section waitUntilDone:NO];
1806 - (void) _removeSection:(NSString *)section {
1810 if (NSMutableArray *sections = [record_ objectForKey:@"Sections"])
1811 if ([sections containsObject:section]) {
1812 [sections removeObject:section];
1817 - (bool) removeSection:(NSString *)section {
1821 [self performSelectorOnMainThread:@selector(_removeSection:) withObject:section waitUntilDone:NO];
1826 [Sources_ removeObjectForKey:[self key]];
1831 bool value(record_ != nil);
1832 [self performSelectorOnMainThread:@selector(_remove) withObject:nil waitUntilDone:NO];
1836 - (NSDictionary *) record {
1844 - (NSString *) rooturi {
1848 - (NSString *) distribution {
1849 return distribution_;
1852 - (NSString *) type {
1856 - (NSString *) baseuri {
1857 return base_.empty() ? nil : (id) base_;
1860 - (NSString *) iconuri {
1861 if (NSString *base = [self baseuri])
1862 return [base stringByAppendingString:@"CydiaIcon.png"];
1867 - (NSURL *) iconURL {
1868 if (NSString *uri = [self iconuri])
1869 return [NSURL URLWithString:uri];
1873 - (NSString *) key {
1874 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1877 - (NSString *) host {
1881 - (NSString *) name {
1882 return origin_.empty() ? (id) authority_ : origin_;
1885 - (NSString *) shortDescription {
1886 return description_;
1889 - (NSString *) label {
1890 return label_.empty() ? (id) authority_ : label_;
1893 - (NSString *) origin {
1897 - (NSString *) version {
1901 - (NSString *) defaultIcon {
1902 return defaultIcon_;
1905 - (void) setDelegate:(NSObject<SourceDelegate> *)delegate {
1906 delegate_ = delegate;
1910 return !fetches_.empty();
1913 - (void) setFetch:(bool)fetch forURI:(const char *)uri {
1915 if (fetches_.erase(uri) == 0)
1917 } else if (files_.find(uri) == files_.end())
1919 else if (!fetches_.insert(uri).second)
1922 [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:[self fetch]] waitUntilDone:NO];
1925 - (void) resetFetch {
1927 [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:NO];
1932 /* CydiaOperation Class {{{ */
1933 @interface CydiaOperation : NSObject {
1934 _H<NSString> operator_;
1935 _H<NSString> value_;
1938 - (NSString *) operator;
1939 - (NSString *) value;
1943 @implementation CydiaOperation
1945 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1946 if ((self = [super init]) != nil) {
1947 operator_ = [NSString stringWithUTF8String:_operator];
1948 value_ = [NSString stringWithUTF8String:value];
1952 + (NSArray *) _attributeKeys {
1953 return [NSArray arrayWithObjects:
1959 - (NSArray *) attributeKeys {
1960 return [[self class] _attributeKeys];
1963 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1964 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1967 - (NSString *) operator {
1971 - (NSString *) value {
1977 /* CydiaClause Class {{{ */
1978 @interface CydiaClause : NSObject {
1979 _H<NSString> package_;
1980 _H<CydiaOperation> version_;
1983 - (NSString *) package;
1984 - (CydiaOperation *) version;
1988 @implementation CydiaClause
1990 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1991 if ((self = [super init]) != nil) {
1992 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1994 if (const char *version = dep.TargetVer())
1995 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1997 version_ = (id) [NSNull null];
2001 + (NSArray *) _attributeKeys {
2002 return [NSArray arrayWithObjects:
2008 - (NSArray *) attributeKeys {
2009 return [[self class] _attributeKeys];
2012 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2013 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2016 - (NSString *) package {
2020 - (CydiaOperation *) version {
2026 /* CydiaRelation Class {{{ */
2027 @interface CydiaRelation : NSObject {
2028 _H<NSString> relationship_;
2029 _H<NSMutableArray> clauses_;
2032 - (NSString *) relationship;
2033 - (NSArray *) clauses;
2037 @implementation CydiaRelation
2039 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
2040 if ((self = [super init]) != nil) {
2041 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
2042 clauses_ = [NSMutableArray arrayWithCapacity:8];
2044 pkgCache::DepIterator start;
2045 pkgCache::DepIterator end;
2046 dep.GlobOr(start, end); // ++dep
2049 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
2051 // yes, seriously. (wtf?)
2059 + (NSArray *) _attributeKeys {
2060 return [NSArray arrayWithObjects:
2066 - (NSArray *) attributeKeys {
2067 return [[self class] _attributeKeys];
2070 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2071 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2074 - (NSString *) relationship {
2075 return relationship_;
2078 - (NSArray *) clauses {
2082 - (void) addClause:(CydiaClause *)clause {
2083 [clauses_ addObject:clause];
2088 /* Package Class {{{ */
2089 struct ParsedPackage {
2093 CYString architecture_;
2096 CYString depiction_;
2103 @interface Package : NSObject {
2105 @public uint32_t role_ : 3;
2106 uint32_t essential_ : 1;
2107 uint32_t obsolete_ : 1;
2108 uint32_t ignored_ : 1;
2109 uint32_t pooled_ : 1;
2115 _transient Database *database_;
2117 pkgCache::VerIterator version_;
2118 pkgCache::PkgIterator iterator_;
2119 pkgCache::VerFileIterator file_;
2123 CYString transform_;
2126 CYString installed_;
2129 const char *section_;
2130 _transient NSString *section$_;
2134 PackageValue *metadata_;
2135 ParsedPackage *parsed_;
2137 _H<NSMutableArray> tags_;
2140 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database;
2141 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database;
2143 - (pkgCache::PkgIterator) iterator;
2146 - (NSString *) section;
2147 - (NSString *) simpleSection;
2149 - (NSString *) longSection;
2150 - (NSString *) shortSection;
2154 - (MIMEAddress *) maintainer;
2156 - (NSString *) longDescription;
2157 - (NSString *) shortDescription;
2160 - (PackageValue *) metadata;
2163 - (bool) subscribed;
2164 - (bool) setSubscribed:(bool)subscribed;
2168 - (NSString *) latest;
2169 - (NSString *) installed;
2170 - (BOOL) uninstalled;
2173 - (BOOL) upgradableAndEssential:(BOOL)essential;
2176 - (BOOL) unfiltered;
2180 - (BOOL) halfConfigured;
2181 - (BOOL) halfInstalled;
2183 - (NSString *) mode;
2186 - (NSString *) name;
2188 - (NSString *) homepage;
2189 - (NSString *) depiction;
2190 - (MIMEAddress *) author;
2192 - (NSString *) support;
2194 - (NSArray *) files;
2195 - (NSArray *) warnings;
2196 - (NSArray *) applications;
2198 - (Source *) source;
2201 - (BOOL) matches:(NSArray *)query;
2203 - (BOOL) hasTag:(NSString *)tag;
2204 - (NSString *) primaryPurpose;
2205 - (NSArray *) purposes;
2206 - (bool) isCommercial;
2208 - (void) setIndex:(size_t)index;
2210 - (CYString &) cyname;
2212 - (uint32_t) compareBySection:(NSArray *)sections;
2219 uint32_t PackageChangesRadix(Package *self, void *) {
2224 uint32_t timestamp : 30;
2225 uint32_t ignored : 1;
2226 uint32_t upgradable : 1;
2230 bool upgradable([self upgradableAndEssential:YES]);
2231 value.bits.upgradable = upgradable ? 1 : 0;
2234 value.bits.timestamp = 0;
2235 value.bits.ignored = [self ignored] ? 0 : 1;
2236 value.bits.upgradable = 1;
2238 value.bits.timestamp = [self seen] >> 2;
2239 value.bits.ignored = 0;
2240 value.bits.upgradable = 0;
2243 return _not(uint32_t) - value.key;
2246 CYString &(*PackageName)(Package *self, SEL sel);
2248 uint32_t PackagePrefixRadix(Package *self, void *context) {
2249 size_t offset(reinterpret_cast<size_t>(context));
2250 CYString &name(PackageName(self, @selector(cyname)));
2252 size_t size(name.size());
2255 char *text(name.data());
2258 if (!isdigit(text[0]))
2262 while (size != digits && isdigit(text[digits]))
2270 if (offset == 0 && zeros != 0) {
2271 memset(data, '0', zeros);
2272 memcpy(data + zeros, text, 4 - zeros);
2274 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2275 if (size <= offset - zeros)
2278 text += offset - zeros;
2279 size -= offset - zeros;
2282 memcpy(data, text, 4);
2284 memcpy(data, text, size);
2285 memset(data + size, 0, 4 - size);
2288 for (size_t i(0); i != 4; ++i)
2289 if (isalpha(data[i]))
2297 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2299 /* XXX: ntohl may be more honest */
2300 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2303 CFComparisonResult StringNameCompare(CFStringRef lhn, CFStringRef rhn, size_t length) {
2304 _profile(PackageNameCompare)
2306 return rhn == NULL ? kCFCompareEqualTo : kCFCompareLessThan;
2307 else if (rhn == NULL)
2308 return kCFCompareGreaterThan;
2310 CFIndex length(CFStringGetLength(lhn));
2312 _profile(PackageNameCompare$NumbersLast)
2313 if (length != 0 && CFStringGetLength(rhn) != 0) {
2314 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2315 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2316 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2317 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2318 return lha ? kCFCompareLessThan : kCFCompareGreaterThan;
2322 _profile(PackageNameCompare$Compare)
2323 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, (CFLocaleRef) (id) CollationLocale_);
2328 _finline CFComparisonResult StringNameCompare(NSString *lhn, NSString*rhn, size_t length) {
2329 return StringNameCompare((CFStringRef) lhn, (CFStringRef) rhn, length);
2332 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2333 CYString &lhn(PackageName(lhs, @selector(cyname)));
2334 NSString *rhn(PackageName(rhs, @selector(cyname)));
2335 return StringNameCompare(lhn, rhn, lhn.size());
2338 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *arg) {
2339 return PackageNameCompare(*lhs, *rhs, arg);
2342 struct PackageNameOrdering :
2343 std::binary_function<Package *, Package *, bool>
2345 _finline bool operator ()(Package *lhs, Package *rhs) const {
2346 return PackageNameCompare(lhs, rhs, NULL) == kCFCompareLessThan;
2350 @implementation Package
2352 - (NSString *) description {
2353 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2359 if (parsed_ != NULL)
2364 + (NSString *) webScriptNameForSelector:(SEL)selector {
2366 else if (selector == @selector(clear))
2368 else if (selector == @selector(getField:))
2370 else if (selector == @selector(getRecord))
2371 return @"getRecord";
2372 else if (selector == @selector(hasTag:))
2374 else if (selector == @selector(install))
2376 else if (selector == @selector(remove))
2382 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2383 return [self webScriptNameForSelector:selector] == nil;
2386 + (NSArray *) _attributeKeys {
2387 return [NSArray arrayWithObjects:
2408 @"shortDescription",
2421 - (NSArray *) attributeKeys {
2422 return [[self class] _attributeKeys];
2425 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2426 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2429 - (NSArray *) relations {
2430 @synchronized (database_) {
2431 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2432 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2433 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2437 - (NSString *) architecture {
2439 @synchronized (database_) {
2440 return parsed_->architecture_.empty() ? [NSNull null] : (id) parsed_->architecture_;
2443 - (NSString *) getField:(NSString *)name {
2444 @synchronized (database_) {
2445 if ([database_ era] != era_ || file_.end())
2448 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2450 const char *start, *end;
2451 if (!parser.Find([name UTF8String], start, end))
2452 return (NSString *) [NSNull null];
2454 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2457 - (NSString *) getRecord {
2458 @synchronized (database_) {
2459 if ([database_ era] != era_ || file_.end())
2462 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2464 const char *start, *end;
2465 parser.GetRec(start, end);
2467 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2471 if (parsed_ != NULL)
2473 @synchronized (database_) {
2474 if ([database_ era] != era_ || file_.end())
2477 ParsedPackage *parsed(new ParsedPackage);
2480 _profile(Package$parse)
2481 pkgRecords::Parser *parser;
2483 _profile(Package$parse$Lookup)
2484 parser = &[database_ records]->Lookup(file_);
2490 _profile(Package$parse$Find)
2495 {"architecture", &parsed->architecture_},
2496 {"icon", &parsed->icon_},
2497 {"depiction", &parsed->depiction_},
2498 {"homepage", &parsed->homepage_},
2499 {"website", &website},
2501 {"support", &parsed->support_},
2502 {"author", &parsed->author_},
2503 {"md5sum", &parsed->md5sum_},
2506 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2507 const char *start, *end;
2509 if (parser->Find(names[i].name_, start, end)) {
2510 CYString &value(*names[i].value_);
2511 _profile(Package$parse$Value)
2512 value.set(pool_, start, end - start);
2518 _profile(Package$parse$Tagline)
2519 const char *start, *end;
2520 if (parser->ShortDesc(start, end)) {
2521 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2524 while (stop != start && stop[-1] == '\r')
2526 parsed->tagline_.set(pool_, start, stop - start);
2530 _profile(Package$parse$Retain)
2531 if (parsed->homepage_.empty())
2532 parsed->homepage_ = website;
2533 if (parsed->homepage_ == parsed->depiction_)
2534 parsed->homepage_.clear();
2535 if (parsed->support_.empty())
2536 parsed->support_ = bugs;
2541 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database {
2542 if ((self = [super init]) != nil) {
2543 _profile(Package$initWithVersion)
2545 pool_ = new CYPool();
2551 database_ = database;
2552 era_ = [database era];
2556 pkgCache::PkgIterator iterator(version.ParentPkg());
2557 iterator_ = iterator;
2559 _profile(Package$initWithVersion$Version)
2560 if (!version_.end())
2561 file_ = version_.FileList();
2563 pkgCache &cache([database_ cache]);
2564 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2568 _profile(Package$initWithVersion$Cache)
2569 name_.set(NULL, iterator.Display());
2571 latest_.set(NULL, StripVersion_(version_.VerStr()));
2573 pkgCache::VerIterator current(iterator.CurrentVer());
2575 installed_.set(NULL, StripVersion_(current.VerStr()));
2578 _profile(Package$initWithVersion$Transliterate) do {
2579 if (CollationTransl_ == NULL)
2584 _profile(Package$initWithVersion$Transliterate$utf8)
2585 const uint8_t *data(reinterpret_cast<const uint8_t *>(name_.data()));
2586 for (size_t i(0), e(name_.size()); i != e; ++i)
2587 if (data[i] >= 0x80)
2592 UErrorCode code(U_ZERO_ERROR);
2595 _profile(Package$initWithVersion$Transliterate$u_strFromUTF8WithSub)
2596 CollationString_.resize(name_.size());
2597 u_strFromUTF8WithSub(&CollationString_[0], CollationString_.size(), &length, name_.data(), name_.size(), 0xfffd, NULL, &code);
2598 if (!U_SUCCESS(code))
2600 CollationString_.resize(length);
2603 _profile(Package$initWithVersion$Transliterate$utrans_trans)
2604 length = CollationString_.size();
2605 utrans_trans(CollationTransl_, reinterpret_cast<UReplaceable *>(&CollationString_), &CollationUCalls_, 0, &length, &code);
2606 if (!U_SUCCESS(code))
2608 _assert(CollationString_.size() == length);
2611 _profile(Package$initWithVersion$Transliterate$u_strToUTF8WithSub$preflight)
2612 u_strToUTF8WithSub(NULL, 0, &length, CollationString_.data(), CollationString_.size(), 0xfffd, NULL, &code);
2613 if (code == U_BUFFER_OVERFLOW_ERROR)
2614 code = U_ZERO_ERROR;
2615 else if (!U_SUCCESS(code))
2620 _profile(Package$initWithVersion$Transliterate$apr_palloc)
2621 transform = pool_->malloc<char>(length);
2623 _profile(Package$initWithVersion$Transliterate$u_strToUTF8WithSub$transform)
2624 u_strToUTF8WithSub(transform, length, NULL, CollationString_.data(), CollationString_.size(), 0xfffd, NULL, &code);
2625 if (!U_SUCCESS(code))
2629 transform_.set(NULL, transform, length);
2630 } while (false); _end
2632 _profile(Package$initWithVersion$Tags)
2633 pkgCache::TagIterator tag(iterator.TagList());
2635 tags_ = [NSMutableArray arrayWithCapacity:8];
2637 goto tag; for (; !tag.end(); ++tag) tag: {
2638 const char *name(tag.Name());
2639 NSString *string((NSString *) CYStringCreate(name));
2643 [tags_ addObject:[string autorelease]];
2645 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2646 if (strcmp(name + 6, "enduser") == 0)
2648 else if (strcmp(name + 6, "hacker") == 0)
2650 else if (strcmp(name + 6, "developer") == 0)
2652 else if (strcmp(name + 6, "cydia") == 0)
2658 if (strncmp(name, "cydia::", 7) == 0) {
2659 if (strcmp(name + 7, "essential") == 0)
2661 else if (strcmp(name + 7, "obsolete") == 0)
2668 _profile(Package$initWithVersion$Metadata)
2669 const char *mixed(iterator.Name());
2670 size_t size(strlen(mixed));
2671 static const size_t prefix(sizeof("/var/lib/dpkg/info/") - 1);
2672 char lower[prefix + size + 5 + 1];
2674 for (size_t i(0); i != size; ++i)
2675 lower[prefix + i] = mixed[i] | 0x20;
2677 if (!installed_.empty()) {
2678 memcpy(lower, "/var/lib/dpkg/info/", prefix);
2679 memcpy(lower + prefix + size, ".list", 6);
2681 if (stat(lower, &info) != -1)
2682 upgraded_ = info.st_birthtime;
2685 PackageValue *metadata(PackageFind(lower + prefix, size));
2686 metadata_ = metadata;
2688 id_.set(NULL, metadata->name_, size);
2690 const char *latest(version_.VerStr());
2691 size_t length(strlen(latest));
2693 uint16_t vhash(hashlittle(latest, length));
2695 size_t capped(std::min<size_t>(8, length));
2696 latest = latest + length - capped;
2698 if (metadata->first_ == 0)
2699 metadata->first_ = now_;
2701 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2702 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2703 metadata->vhash_ = vhash;
2704 metadata->last_ = now_;
2705 } else if (metadata->last_ == 0)
2706 metadata->last_ = metadata->first_;
2709 _profile(Package$initWithVersion$Section)
2710 section_ = version_.Section();
2713 _profile(Package$initWithVersion$Flags)
2714 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2715 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2720 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database {
2721 pkgCache::VerIterator version;
2723 _profile(Package$packageWithIterator$GetCandidateVer)
2724 version = [database policy]->GetCandidateVer(iterator);
2732 _profile(Package$packageWithIterator$Allocate)
2733 package = [Package allocWithZone:zone];
2736 _profile(Package$packageWithIterator$Initialize)
2738 initWithVersion:version
2745 _profile(Package$packageWithIterator$Autorelease)
2746 package = [package autorelease];
2752 - (pkgCache::PkgIterator) iterator {
2756 - (NSString *) section {
2757 if (section$_ == nil) {
2758 if (section_ == NULL)
2761 _profile(Package$section$mappedSectionForPointer)
2762 section$_ = [database_ mappedSectionForPointer:section_];
2767 - (NSString *) simpleSection {
2768 if (NSString *section = [self section])
2769 return Simplify(section);
2774 - (NSString *) longSection {
2775 return LocalizeSection([self section]);
2778 - (NSString *) shortSection {
2779 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2782 - (NSString *) uri {
2785 pkgIndexFile *index;
2786 pkgCache::PkgFileIterator file(file_.File());
2787 if (![database_ list].FindIndex(file, index))
2789 return [NSString stringWithUTF8String:iterator_->Path];
2790 //return [NSString stringWithUTF8String:file.Site()];
2791 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2795 - (MIMEAddress *) maintainer {
2796 @synchronized (database_) {
2797 if ([database_ era] != era_ || file_.end())
2800 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2801 const std::string &maintainer(parser->Maintainer());
2802 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2805 - (NSString *) md5sum {
2806 return parsed_ == NULL ? nil : (id) parsed_->md5sum_;
2810 @synchronized (database_) {
2811 if ([database_ era] != era_ || version_.end())
2814 return version_->InstalledSize;
2817 - (NSString *) longDescription {
2818 @synchronized (database_) {
2819 if ([database_ era] != era_ || file_.end())
2822 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2823 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2825 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2826 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2827 if ([lines count] < 2)
2830 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2831 for (size_t i(1), e([lines count]); i != e; ++i) {
2832 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2833 [trimmed addObject:trim];
2836 return [trimmed componentsJoinedByString:@"\n"];
2839 - (NSString *) shortDescription {
2840 if (parsed_ != NULL)
2841 return static_cast<NSString *>(parsed_->tagline_);
2843 @synchronized (database_) {
2844 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2846 const char *start, *end;
2847 if (!parser.ShortDesc(start, end))
2850 if (end - start > 200)
2854 if (const char *stop = reinterpret_cast<const char *>(memchr(start, '\n', end - start)))
2857 while (end != start && end[-1] == '\r')
2861 return [(id) CYStringCreate(start, end - start) autorelease];
2865 _profile(Package$index)
2866 CFStringRef name((CFStringRef) [self name]);
2867 if (CFStringGetLength(name) == 0)
2869 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2870 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2872 return toupper(character);
2876 - (PackageValue *) metadata {
2881 PackageValue *metadata([self metadata]);
2882 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2885 - (bool) subscribed {
2886 return [self metadata]->subscribed_;
2889 - (bool) setSubscribed:(bool)subscribed {
2890 PackageValue *metadata([self metadata]);
2891 if (metadata->subscribed_ == subscribed)
2893 metadata->subscribed_ = subscribed;
2901 - (NSString *) latest {
2905 - (NSString *) installed {
2909 - (BOOL) uninstalled {
2910 return installed_.empty();
2914 return !version_.end();
2917 - (BOOL) upgradableAndEssential:(BOOL)essential {
2918 _profile(Package$upgradableAndEssential)
2919 pkgCache::VerIterator current(iterator_.CurrentVer());
2921 return essential && essential_;
2923 return !version_.end() && version_ != current;
2927 - (BOOL) essential {
2932 return [database_ cache][iterator_].InstBroken();
2935 - (BOOL) unfiltered {
2936 _profile(Package$unfiltered$obsolete)
2937 if (_unlikely(obsolete_))
2941 _profile(Package$unfiltered$role)
2942 if (_unlikely(role_ > 3))
2950 if (![self unfiltered])
2955 _profile(Package$visible$section)
2956 section = [self section];
2959 _profile(Package$visible$isSectionVisible)
2960 if (!isSectionVisible(section))
2968 unsigned char current(iterator_->CurrentState);
2969 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2972 - (BOOL) halfConfigured {
2973 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2976 - (BOOL) halfInstalled {
2977 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2981 @synchronized (database_) {
2982 if ([database_ era] != era_ || iterator_.end())
2985 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2986 return state.Mode != pkgDepCache::ModeKeep;
2989 - (NSString *) mode {
2990 @synchronized (database_) {
2991 if ([database_ era] != era_ || iterator_.end())
2994 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2996 switch (state.Mode) {
2997 case pkgDepCache::ModeDelete:
2998 if ((state.iFlags & pkgDepCache::Purge) != 0)
3002 case pkgDepCache::ModeKeep:
3003 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
3004 return @"REINSTALL";
3005 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
3009 case pkgDepCache::ModeInstall:
3010 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
3011 return @"REINSTALL";
3012 else*/ switch (state.Status) {
3014 return @"DOWNGRADE";
3020 return @"NEW_INSTALL";
3031 - (NSString *) name {
3032 return name_.empty() ? id_ : name_;
3035 - (UIImage *) icon {
3036 NSString *section = [self simpleSection];
3039 if (parsed_ != NULL)
3040 if (NSString *href = parsed_->icon_)
3041 if ([href hasPrefix:@"file:///"])
3042 icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
3043 if (icon == nil) if (section != nil)
3044 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]];
3045 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
3046 if ([dicon hasPrefix:@"file:///"])
3047 icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
3049 icon = [UIImage imageNamed:@"unknown.png"];
3053 - (NSString *) homepage {
3054 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
3057 - (NSString *) depiction {
3058 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
3061 - (MIMEAddress *) author {
3062 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
3065 - (NSString *) support {
3066 return parsed_ != NULL && !parsed_->support_.empty() ? parsed_->support_ : [[self source] supportForPackage:id_];
3069 - (NSArray *) files {
3070 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
3071 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
3074 fin.open([path UTF8String]);
3079 while (std::getline(fin, line))
3080 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
3085 - (NSString *) state {
3086 @synchronized (database_) {
3087 if ([database_ era] != era_ || file_.end())
3090 switch (iterator_->CurrentState) {
3091 case pkgCache::State::NotInstalled:
3092 return @"NotInstalled";
3093 case pkgCache::State::UnPacked:
3095 case pkgCache::State::HalfConfigured:
3096 return @"HalfConfigured";
3097 case pkgCache::State::HalfInstalled:
3098 return @"HalfInstalled";
3099 case pkgCache::State::ConfigFiles:
3100 return @"ConfigFiles";
3101 case pkgCache::State::Installed:
3102 return @"Installed";
3103 case pkgCache::State::TriggersAwaited:
3104 return @"TriggersAwaited";
3105 case pkgCache::State::TriggersPending:
3106 return @"TriggersPending";
3109 return (NSString *) [NSNull null];
3112 - (NSString *) selection {
3113 @synchronized (database_) {
3114 if ([database_ era] != era_ || file_.end())
3117 switch (iterator_->SelectedState) {
3118 case pkgCache::State::Unknown:
3120 case pkgCache::State::Install:
3122 case pkgCache::State::Hold:
3124 case pkgCache::State::DeInstall:
3125 return @"DeInstall";
3126 case pkgCache::State::Purge:
3130 return (NSString *) [NSNull null];
3133 - (NSArray *) warnings {
3134 @synchronized (database_) {
3135 if ([database_ era] != era_ || file_.end())
3138 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
3139 const char *name(iterator_.Name());
3141 size_t length(strlen(name));
3142 if (length < 2) invalid:
3143 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
3144 else for (size_t i(0); i != length; ++i)
3146 /* XXX: technically this is not allowed */
3147 (name[i] < 'A' || name[i] > 'Z') &&
3148 (name[i] < 'a' || name[i] > 'z') &&
3149 (name[i] < '0' || name[i] > '9') &&
3150 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
3153 if (strcmp(name, "cydia") != 0) {
3156 bool _private = false;
3158 bool dbstash = false;
3159 bool dsstore = false;
3161 bool repository = [[self section] isEqualToString:@"Repositories"];
3163 if (NSArray *files = [self files])
3164 for (NSString *file in files)
3165 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
3167 else if (!user && [file isEqualToString:@"/User"])
3169 else if (!_private && [file isEqualToString:@"/private"])
3171 else if (!stash && [file isEqualToString:@"/var/stash"])
3173 else if (!dbstash && [file isEqualToString:@"/var/db/stash"])
3175 else if (!dsstore && [file hasSuffix:@"/.DS_Store"])
3178 /* XXX: this is not sensitive enough. only some folders are valid. */
3179 if (cydia && !repository)
3180 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
3182 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
3184 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
3186 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
3188 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/db/stash"]];
3190 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @".DS_Store"]];
3193 return [warnings count] == 0 ? nil : warnings;
3196 - (NSArray *) applications {
3197 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
3199 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
3201 static RegEx application_r("/Applications/(.*)\\.app/Info.plist");
3202 if (NSArray *files = [self files])
3203 for (NSString *file in files)
3204 if (application_r(file)) {
3205 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
3206 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
3207 if ([id isEqualToString:me])
3210 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
3212 display = application_r[1];
3214 NSString *bundle([file stringByDeletingLastPathComponent]);
3215 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
3216 // XXX: maybe this should check if this is really a string, not just for length
3217 if (icon == nil || ![icon respondsToSelector:@selector(length)] || [icon length] == 0)
3219 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
3221 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
3222 [applications addObject:application];
3224 [application addObject:id];
3225 [application addObject:display];
3226 [application addObject:url];
3229 return [applications count] == 0 ? nil : applications;
3232 - (Source *) source {
3233 if (source_ == nil) {
3234 @synchronized (database_) {
3235 if ([database_ era] != era_ || file_.end())
3236 source_ = (Source *) [NSNull null];
3238 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
3242 return source_ == (Source *) [NSNull null] ? nil : source_;
3245 - (time_t) upgraded {
3249 - (uint32_t) recent {
3250 return std::numeric_limits<uint32_t>::max() - upgraded_;
3257 - (BOOL) matches:(NSArray *)query {
3258 if (query == nil || [query count] == 0)
3267 string = [self name];
3268 length = [string length];
3271 for (NSString *term in query) {
3272 range = [string rangeOfString:term options:MatchCompareOptions_];
3273 if (range.location != NSNotFound)
3274 rank_ -= 6 * 1000000 / length;
3279 length = [string length];
3282 for (NSString *term in query) {
3283 range = [string rangeOfString:term options:MatchCompareOptions_];
3284 if (range.location != NSNotFound)
3285 rank_ -= 6 * 1000000 / length;
3289 string = [self shortDescription];
3290 length = [string length];
3291 NSUInteger stop(std::min<NSUInteger>(length, 200));
3294 for (NSString *term in query) {
3295 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
3296 if (range.location != NSNotFound)
3297 rank_ -= 2 * 100000;
3303 - (NSArray *) tags {
3307 - (BOOL) hasTag:(NSString *)tag {
3308 return tags_ == nil ? NO : [tags_ containsObject:tag];
3311 - (NSString *) primaryPurpose {
3312 for (NSString *tag in (NSArray *) tags_)
3313 if ([tag hasPrefix:@"purpose::"])
3314 return [tag substringFromIndex:9];
3318 - (NSArray *) purposes {
3319 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
3320 for (NSString *tag in (NSArray *) tags_)
3321 if ([tag hasPrefix:@"purpose::"])
3322 [purposes addObject:[tag substringFromIndex:9]];
3323 return [purposes count] == 0 ? nil : purposes;
3326 - (bool) isCommercial {
3327 return [self hasTag:@"cydia::commercial"];
3330 - (void) setIndex:(size_t)index {
3331 if (metadata_->index_ != index)
3332 metadata_->index_ = index;
3335 - (CYString &) cyname {
3336 return !transform_.empty() ? transform_ : !name_.empty() ? name_ : id_;
3339 - (uint32_t) compareBySection:(NSArray *)sections {
3340 NSString *section([self section]);
3341 for (size_t i(0), e([sections count]); i != e; ++i) {
3342 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3346 return _not(uint32_t);
3350 @synchronized (database_) {
3351 pkgProblemResolver *resolver = [database_ resolver];
3352 resolver->Clear(iterator_);
3354 pkgCacheFile &cache([database_ cache]);
3355 cache->SetReInstall(iterator_, false);
3356 cache->MarkKeep(iterator_, false);
3360 @synchronized (database_) {
3361 pkgProblemResolver *resolver = [database_ resolver];
3362 resolver->Clear(iterator_);
3363 resolver->Protect(iterator_);
3365 pkgCacheFile &cache([database_ cache]);
3366 cache->SetReInstall(iterator_, false);
3367 cache->MarkInstall(iterator_, false);
3369 pkgDepCache::StateCache &state((*cache)[iterator_]);
3370 if (!state.Install())
3371 cache->SetReInstall(iterator_, true);
3375 @synchronized (database_) {
3376 pkgProblemResolver *resolver = [database_ resolver];
3377 resolver->Clear(iterator_);
3378 resolver->Remove(iterator_);
3379 resolver->Protect(iterator_);
3381 pkgCacheFile &cache([database_ cache]);
3382 cache->SetReInstall(iterator_, false);
3383 cache->MarkDelete(iterator_, true);
3388 /* Section Class {{{ */
3389 @interface Section : NSObject {
3393 _H<NSString> localized_;
3396 - (NSComparisonResult) compareByLocalized:(Section *)section;
3397 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3398 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3399 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3401 - (NSString *) name;
3402 - (void) setName:(NSString *)name;
3408 - (void) addToCount;
3410 - (void) setCount:(size_t)count;
3411 - (NSString *) localized;
3415 @implementation Section
3417 - (NSComparisonResult) compareByLocalized:(Section *)section {
3418 NSString *lhs(localized_);
3419 NSString *rhs([section localized]);
3421 /*if ([lhs length] != 0 && [rhs length] != 0) {
3422 unichar lhc = [lhs characterAtIndex:0];
3423 unichar rhc = [rhs characterAtIndex:0];
3425 if (isalpha(lhc) && !isalpha(rhc))
3426 return NSOrderedAscending;
3427 else if (!isalpha(lhc) && isalpha(rhc))
3428 return NSOrderedDescending;
3431 return [lhs compare:rhs options:LaxCompareOptions_];
3434 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3435 if ((self = [self initWithName:name localize:NO]) != nil) {
3436 if (localized != nil)
3437 localized_ = localized;
3441 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3442 return [self initWithName:name row:0 localize:localize];
3445 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3446 if ((self = [super init]) != nil) {
3450 localized_ = LocalizeSection(name_);
3454 - (NSString *) name {
3458 - (void) setName:(NSString *)name {
3474 - (void) addToCount {
3478 - (void) setCount:(size_t)count {
3482 - (NSString *) localized {
3489 class CydiaLogCleaner :
3490 public pkgArchiveCleaner
3493 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3498 /* Database Implementation {{{ */
3499 @implementation Database
3501 + (Database *) sharedInstance {
3502 static _H<Database> instance;
3503 if (instance == nil)
3504 instance = [[[Database alloc] init] autorelease];
3512 - (void) releasePackages {
3513 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3514 CFArrayRemoveAllValues(packages_);
3518 // XXX: actually implement this thing
3520 [self releasePackages];
3521 NSRecycleZone(zone_);
3525 - (void) _readCydia:(NSNumber *)fd {
3526 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3527 std::istream is(&ib);
3530 static RegEx finish_r("finish:([^:]*)");
3532 while (std::getline(is, line)) {
3533 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3535 const char *data(line.c_str());
3536 size_t size = line.size();
3537 lprintf("C:%s\n", data);
3539 if (finish_r(data, size)) {
3540 NSString *finish = finish_r[1];
3541 int index = [Finishes_ indexOfObject:finish];
3542 if (index != INT_MAX && index > Finish_)
3552 - (void) _readStatus:(NSNumber *)fd {
3553 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3554 std::istream is(&ib);
3557 static RegEx conffile_r("status: [^ ]* : conffile-prompt : (.*?) *");
3558 static RegEx pmstatus_r("([^:]*):([^:]*):([^:]*):(.*)");
3560 while (std::getline(is, line)) {
3561 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3563 const char *data(line.c_str());
3564 size_t size(line.size());
3565 lprintf("S:%s\n", data);
3567 if (conffile_r(data, size)) {
3568 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3569 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3570 } else if (strncmp(data, "status: ", 8) == 0) {
3571 // status: <package>: {unpacked,half-configured,installed}
3572 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3573 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3574 } else if (strncmp(data, "processing: ", 12) == 0) {
3575 // processing: configure: config-test
3576 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3577 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3578 } else if (pmstatus_r(data, size)) {
3579 std::string type([pmstatus_r[1] UTF8String]);
3581 NSString *package = pmstatus_r[2];
3582 if ([package isEqualToString:@"dpkg-exec"])
3585 float percent([pmstatus_r[3] floatValue]);
3586 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3588 NSString *string = pmstatus_r[4];
3590 if (type == "pmerror") {
3591 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3592 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3593 } else if (type == "pmstatus") {
3594 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3595 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3596 } else if (type == "pmconffile")
3597 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3599 lprintf("E:unknown pmstatus\n");
3601 lprintf("E:unknown status\n");
3609 - (void) _readOutput:(NSNumber *)fd {
3610 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3611 std::istream is(&ib);
3614 while (std::getline(is, line)) {
3615 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3617 lprintf("O:%s\n", line.c_str());
3619 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3620 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3632 - (Package *) packageWithName:(NSString *)name {
3635 @synchronized (self) {
3636 if (static_cast<pkgDepCache *>(cache_) == NULL)
3638 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3639 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:NULL database:self];
3643 if ((self = [super init]) != nil) {
3650 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3652 size_t capacity(MetaFile_->active_);
3658 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3659 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3663 _assert(pipe(fds) != -1);
3666 _config->Set("APT::Keep-Fds::", cydiafd_);
3667 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3670 detachNewThreadSelector:@selector(_readCydia:)
3672 withObject:[NSNumber numberWithInt:fds[0]]
3675 _assert(pipe(fds) != -1);
3679 detachNewThreadSelector:@selector(_readStatus:)
3681 withObject:[NSNumber numberWithInt:fds[0]]
3684 _assert(pipe(fds) != -1);
3685 _assert(dup2(fds[0], 0) != -1);
3686 _assert(close(fds[0]) != -1);
3688 input_ = fdopen(fds[1], "a");
3690 _assert(pipe(fds) != -1);
3691 _assert(dup2(fds[1], 1) != -1);
3692 _assert(close(fds[1]) != -1);
3695 detachNewThreadSelector:@selector(_readOutput:)
3697 withObject:[NSNumber numberWithInt:fds[0]]
3702 - (pkgCacheFile &) cache {
3706 - (pkgDepCache::Policy *) policy {
3710 - (pkgRecords *) records {
3714 - (pkgProblemResolver *) resolver {
3718 - (pkgAcquire &) fetcher {
3722 - (pkgSourceList &) list {
3726 - (NSArray *) packages {
3727 return (NSArray *) packages_;
3730 - (NSArray *) sources {
3734 - (Source *) sourceWithKey:(NSString *)key {
3735 for (Source *source in [self sources]) {
3736 if ([[source key] isEqualToString:key])
3741 - (bool) popErrorWithTitle:(NSString *)title {
3744 while (!_error->empty()) {
3746 bool warning(!_error->PopMessage(error));
3751 size_t size(error.size());
3752 if (size == 0 || error[size - 1] != '\n')
3754 error.resize(size - 1);
3757 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3759 static RegEx no_pubkey("GPG error:.* NO_PUBKEY .*");
3760 if (warning && no_pubkey(error.c_str()))
3763 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3769 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3770 return [self popErrorWithTitle:title] || !success;
3773 - (bool) popErrorWithTitle:(NSString *)title forReadList:(pkgSourceList &)list {
3774 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3776 if ([self popErrorWithTitle:title forOperation:list.Read(SOURCES_LIST)])
3781 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3782 @synchronized (self) {
3785 [self releasePackages];
3788 [sourceList_ removeAllObjects];
3809 new (&pool_) CYPool();
3811 NSRecycleZone(zone_);
3812 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3814 int chk(creat("/tmp/cydia.chk", 0644));
3818 if (invocation != nil)
3819 [invocation invoke];
3821 NSString *title(UCLocalize("DATABASE"));
3823 list_ = new pkgSourceList();
3824 _profile(reloadDataWithInvocation$ReadMainList)
3825 if ([self popErrorWithTitle:title forReadList:*list_])
3829 _profile(reloadDataWithInvocation$Source$initWithMetaIndex)
3830 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3831 Source *object([[[Source alloc] initWithMetaIndex:*source forDatabase:self inPool:&pool_] autorelease]);
3832 [sourceList_ addObject:object];
3836 _root(_system->Lock());
3839 OpProgress progress;
3842 _profile(reloadDataWithInvocation$pkgCacheFile)
3843 opened = cache_.Open(progress, false);
3846 // XXX: what if there are errors, but Open() == true? this should be merged with popError:
3847 while (!_error->empty()) {
3849 bool warning(!_error->PopMessage(error));
3851 lprintf("cache_.Open():[%s]\n", error.c_str());
3853 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3857 else if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3858 repair = @selector(configure);
3859 //else if (error == "The package lists or status file could not be parsed or opened.")
3860 // repair = @selector(update);
3861 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3862 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3863 // else if (error == "Malformed Status line")
3864 // else if (error == "The list of sources could not be read.")
3866 if (repair != NULL) {
3868 [delegate_ repairWithSelector:repair];
3878 unlink("/tmp/cydia.chk");
3880 now_ = [[NSDate date] timeIntervalSince1970];
3882 policy_ = new pkgDepCache::Policy();
3883 records_ = new pkgRecords(cache_);
3884 resolver_ = new pkgProblemResolver(cache_);
3885 fetcher_ = new pkgAcquire(&status_);
3888 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3889 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3893 _profile(reloadDataWithInvocation$pkgApplyStatus)
3894 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3898 if (cache_->BrokenCount() != 0) {
3899 _profile(pkgApplyStatus$pkgFixBroken)
3900 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3904 if (cache_->BrokenCount() != 0) {
3905 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3909 _profile(pkgApplyStatus$pkgMinimizeUpgrade)
3910 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3915 for (Source *object in (id) sourceList_) {
3916 metaIndex *source([object metaIndex]);
3917 std::vector<pkgIndexFile *> *indices = source->GetIndexFiles();
3918 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3919 // XXX: this could be more intelligent
3920 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3921 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3923 sourceMap_[cached->ID] = object;
3928 /*std::vector<Package *> packages;
3929 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3932 _profile(reloadDataWithInvocation$packageWithIterator)
3933 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3934 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:&pool_ database:self])
3935 //packages.push_back(package);
3936 CFArrayAppendValue(packages_, CFRetain(package));
3940 /*if (packages.empty())
3941 packages_ = [[NSArray alloc] init];
3943 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3946 _profile(reloadDataWithInvocation$radix$8)
3947 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(8)];
3950 _profile(reloadDataWithInvocation$radix$4)
3951 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3954 _profile(reloadDataWithInvocation$radix$0)
3955 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3958 _profile(reloadDataWithInvocation$insertion)
3959 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3962 /*_profile(reloadDataWithInvocation$CFQSortArray)
3963 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);
3966 /*_profile(reloadDataWithInvocation$stdsort)
3967 std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3970 /*_profile(reloadDataWithInvocation$CFArraySortValues)
3971 CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3974 /*_profile(reloadDataWithInvocation$sortUsingFunction)
3975 [packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3979 size_t count(CFArrayGetCount(packages_));
3980 MetaFile_->active_ = count;
3981 for (size_t index(0); index != count; ++index)
3982 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3987 @synchronized (self) {
3989 resolver_ = new pkgProblemResolver(cache_);
3991 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3992 if (!cache_[iterator].Keep())
3993 cache_->MarkKeep(iterator, false);
3994 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3995 cache_->SetReInstall(iterator, false);
3998 - (void) configure {
3999 NSString *dpkg = [NSString stringWithFormat:@"/usr/libexec/cydo --configure -a --status-fd %u", statusfd_];
4001 system([dpkg UTF8String]);
4006 @synchronized (self) {
4007 // XXX: I don't remember this condition
4012 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
4014 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
4016 if ([self popErrorWithTitle:title])
4020 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
4022 CydiaLogCleaner cleaner;
4023 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
4030 fetcher_->Shutdown();
4032 pkgRecords records(cache_);
4034 lock_ = new FileFd();
4035 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
4037 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
4039 if ([self popErrorWithTitle:title])
4043 if ([self popErrorWithTitle:title forReadList:list])
4046 manager_ = (_system->CreatePM(cache_));
4047 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
4054 bool substrate(RestartSubstrate_);
4055 RestartSubstrate_ = false;
4057 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
4059 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
4061 if ([self popErrorWithTitle:title forReadList:list])
4063 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
4064 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
4067 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4069 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
4071 [self popErrorWithTitle:title];
4075 bool failed = false;
4076 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
4077 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
4079 if ((*item)->Status == pkgAcquire::Item::StatIdle)
4082 std::string uri = (*item)->DescURI();
4083 std::string error = (*item)->ErrorText;
4085 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
4088 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError]);
4089 [delegate_ addProgressEventOnMainThread:event forTask:title];
4092 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4100 RestartSubstrate_ = true;
4103 pkgPackageManager::OrderResult result(manager_->DoInstall(statusfd_));
4104 if ([self popErrorWithTitle:title])
4107 if (result == pkgPackageManager::Failed) {
4112 if (result != pkgPackageManager::Completed) {
4117 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
4119 if ([self popErrorWithTitle:title forReadList:list])
4121 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
4122 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
4125 if (![before isEqualToArray:after])
4130 NSString *title(UCLocalize("UPGRADE"));
4131 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
4137 [self updateWithStatus:status_];
4140 - (void) updateWithStatus:(CancelStatus &)status {
4141 NSString *title(UCLocalize("REFRESHING_DATA"));
4144 if ([self popErrorWithTitle:title forReadList:list])
4148 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
4149 if ([self popErrorWithTitle:title])
4152 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4154 bool success(ListUpdate(status, list, PulseInterval_));
4155 if (status.WasCancelled())
4158 [self popErrorWithTitle:title forOperation:success];
4159 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
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];
4617 [delegate_ performSelectorOnMainThread:@selector(updateValues) withObject:nil waitUntilDone:YES];
4620 - (id) getSessionValue:(NSString *)key {
4621 @synchronized (SessionData_) {
4622 return [SessionData_ objectForKey:key];
4625 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4626 @synchronized (SessionData_) {
4627 if (value == (id) [WebUndefined undefined])
4628 [SessionData_ removeObjectForKey:key];
4630 [SessionData_ setObject:value forKey:key];
4633 - (void) addBridgedHost:(NSString *)host {
4634 @synchronized (HostConfig_) {
4635 [BridgedHosts_ addObject:host];
4638 - (void) addInsecureHost:(NSString *)host {
4639 @synchronized (HostConfig_) {
4640 [InsecureHosts_ addObject:host];
4643 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4644 @synchronized (HostConfig_) {
4645 if (scheme != (id) [WebUndefined undefined])
4646 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4648 [PipelinedHosts_ addObject:host];
4651 - (void) popViewController:(NSNumber *)value {
4652 if (value == (id) [WebUndefined undefined])
4653 value = [NSNumber numberWithBool:YES];
4654 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4657 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4658 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4660 for (NSString *section in sections)
4661 [array addObject:section];
4663 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4666 distribution, @"Distribution",
4668 nil] waitUntilDone:NO];
4671 - (void) addTrivialSource:(NSString *)href {
4672 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4675 - (void) refreshSources {
4676 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4679 - (void) saveConfig {
4680 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4683 - (NSArray *) getAllSources {
4684 return [[Database sharedInstance] sources];
4687 - (NSArray *) getInstalledPackages {
4688 Database *database([Database sharedInstance]);
4689 @synchronized (database) {
4690 NSArray *packages([database packages]);
4691 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4692 for (Package *package in packages)
4693 if (![package uninstalled])
4694 [installed addObject:package];
4698 - (Package *) getPackageById:(NSString *)id {
4699 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4703 return (Package *) [NSNull null];
4706 - (NSString *) getLocaleIdentifier {
4707 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4710 - (NSArray *) getPreferredLanguages {
4714 - (NSArray *) statfs:(NSString *)path {
4717 if (path == nil || statfs([path UTF8String], &stat) == -1)
4720 return [NSArray arrayWithObjects:
4721 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4722 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4723 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4727 ssize_t DiskUsage(const char *path);
4729 - (NSNumber *) du:(NSString *)path {
4730 ssize_t usage(DiskUsage([path UTF8String]));
4733 return [NSNumber numberWithUnsignedLong:usage];
4737 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4740 - (NSNumber *) isReachable:(NSString *)name {
4741 return [NSNumber numberWithBool:IsReachable([name UTF8String])];
4744 - (void) installPackages:(NSArray *)packages {
4745 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4748 - (NSString *) substitutePackageNames:(NSString *)message {
4749 NSMutableArray *words([[[message componentsSeparatedByString:@" "] mutableCopy] autorelease]);
4750 for (size_t i(0), e([words count]); i != e; ++i) {
4751 NSString *word([words objectAtIndex:i]);
4752 if (Package *package = [[Database sharedInstance] packageWithName:word])
4753 [words replaceObjectAtIndex:i withObject:[package name]];
4756 return [words componentsJoinedByString:@" "];
4759 - (void) removeButton {
4760 [indirect_ removeButton];
4763 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4764 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4767 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4768 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4771 - (void) setBadgeValue:(id)value {
4772 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4775 - (void) setAllowsNavigationAction:(NSString *)value {
4776 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4779 - (void) setHidesBackButton:(NSString *)value {
4780 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4783 - (void) setHidesNavigationBar:(NSString *)value {
4784 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4787 - (void) setNavigationBarStyle:(NSString *)value {
4788 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4791 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4792 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4793 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4794 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4797 - (void) setPasteboardString:(NSString *)value {
4798 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4801 - (void) setPasteboardURL:(NSString *)value {
4802 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4805 - (void) setToken:(NSString *)token {
4806 // XXX: the website expects this :/
4809 - (void) scrollToBottom:(NSNumber *)animated {
4810 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4813 - (void) setViewportWidth:(float)width {
4814 [indirect_ setViewportWidthOnMainThread:width];
4817 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4818 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4819 unsigned count([arguments count]);
4821 for (unsigned i(0); i != count; ++i)
4822 values[i] = [arguments objectAtIndex:i];
4823 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4826 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4827 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4829 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4831 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4837 @interface NSURL (CydiaSecure)
4840 @implementation NSURL (CydiaSecure)
4842 - (bool) isCydiaSecure {
4843 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4846 @synchronized (HostConfig_) {
4847 if ([InsecureHosts_ containsObject:[self host]])
4856 /* Cydia Browser Controller {{{ */
4857 @implementation CydiaWebViewController
4859 - (NSURL *) navigationURL {
4860 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4863 + (void) _initialize {
4864 [super _initialize];
4866 Diversions_ = [NSMutableSet setWithCapacity:0];
4869 + (void) addDiversion:(Diversion *)diversion {
4870 [Diversions_ addObject:diversion];
4873 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4874 [super webView:view didClearWindowObject:window forFrame:frame];
4875 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
4878 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia {
4879 WebDataSource *source([frame dataSource]);
4880 NSURLResponse *response([source response]);
4881 NSURL *url([response URL]);
4882 NSString *scheme([[url scheme] lowercaseString]);
4884 bool bridged(false);
4886 @synchronized (HostConfig_) {
4887 if ([scheme isEqualToString:@"file"])
4889 else if ([scheme isEqualToString:@"https"])
4890 if ([BridgedHosts_ containsObject:[url host]])
4895 [window setValue:cydia forKey:@"cydia"];
4898 - (void) _setupMail:(MFMailComposeViewController *)controller {
4899 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4901 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4902 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4905 - (NSURL *) URLWithURL:(NSURL *)url {
4906 return [Diversion divertURL:url];
4909 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4910 return [CydiaWebViewController requestWithHeaders:[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
4913 - (NSURLRequest *) webThreadWebView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4914 return [CydiaWebViewController requestWithHeaders:[super webThreadWebView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
4917 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request {
4918 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
4920 NSURL *url([copy URL]);
4921 NSString *href([url absoluteString]);
4922 NSString *host([url host]);
4924 if ([href hasPrefix:@"https://cydia.saurik.com/TSS/"]) {
4925 if (NSString *agent = [copy valueForHTTPHeaderField:@"X-User-Agent"]) {
4926 [copy setValue:agent forHTTPHeaderField:@"User-Agent"];
4927 [copy setValue:nil forHTTPHeaderField:@"X-User-Agent"];
4930 [copy setValue:nil forHTTPHeaderField:@"Referer"];
4931 [copy setValue:nil forHTTPHeaderField:@"Origin"];
4933 [copy setURL:[NSURL URLWithString:[@"http://gs.apple.com/TSS/" stringByAppendingString:[href substringFromIndex:29]]]];
4937 if ([copy valueForHTTPHeaderField:@"X-Cydia-Cf"] == nil)
4938 [copy setValue:[NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber] forHTTPHeaderField:@"X-Cydia-Cf"];
4939 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4940 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4942 bool bridged; @synchronized (HostConfig_) {
4943 bridged = [BridgedHosts_ containsObject:host];
4946 if ([url isCydiaSecure] && bridged && UniqueID_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Id"] == nil)
4947 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
4952 - (void) setDelegate:(id)delegate {
4953 [super setDelegate:delegate];
4954 [cydia_ setDelegate:delegate];
4957 - (NSString *) applicationNameForUserAgent {
4962 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4963 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
4969 @interface AppCacheController : CydiaWebViewController {
4974 @implementation AppCacheController
4976 - (void) didReceiveMemoryWarning {
4977 // XXX: this doesn't work
4980 - (bool) retainsNetworkActivityIndicator {
4988 @interface NSObject (CydiaScript)
4989 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4992 @implementation NSObject (CydiaScript)
4994 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5000 @implementation NSArray (CydiaScript)
5002 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5003 WebScriptObject *object([context evaluateWebScript:@"[]"]);
5004 for (size_t i(0), e([self count]); i != e; ++i)
5005 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
5011 @implementation NSDictionary (CydiaScript)
5013 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5014 WebScriptObject *object([context evaluateWebScript:@"({})"]);
5016 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
5023 /* Confirmation Controller {{{ */
5024 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
5025 if (!iterator.end())
5026 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
5027 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
5029 pkgCache::PkgIterator package(dep.TargetPkg());
5032 if (strcmp(package.Name(), "mobilesubstrate") == 0)
5039 @protocol ConfirmationControllerDelegate
5040 - (void) cancelAndClear:(bool)clear;
5041 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
5045 @interface ConfirmationController : CydiaWebViewController {
5046 _transient Database *database_;
5048 _H<UIAlertView> essential_;
5050 _H<NSDictionary> changes_;
5051 _H<NSMutableArray> issues_;
5052 _H<NSDictionary> sizes_;
5057 - (id) initWithDatabase:(Database *)database;
5061 @implementation ConfirmationController
5065 RestartSubstrate_ = true;
5066 [delegate_ confirmWithNavigationController:[self navigationController]];
5069 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
5070 NSString *context([alert context]);
5072 if ([context isEqualToString:@"remove"]) {
5073 if (button == [alert cancelButtonIndex])
5075 else if (button == [alert firstOtherButtonIndex]) {
5076 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
5079 [alert dismissWithClickedButtonIndex:-1 animated:YES];
5080 } else if ([context isEqualToString:@"unable"]) {
5081 [self dismissModalViewControllerAnimated:YES];
5082 [alert dismissWithClickedButtonIndex:-1 animated:YES];
5084 [super alertView:alert clickedButtonAtIndex:button];
5088 - (void) _doContinue {
5089 [delegate_ cancelAndClear:NO];
5090 [self dismissModalViewControllerAnimated:YES];
5093 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
5094 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
5098 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5099 [super webView:view didClearWindowObject:window forFrame:frame];
5101 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
5102 (id) changes_, @"changes",
5103 (id) issues_, @"issues",
5104 (id) sizes_, @"sizes",
5106 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
5109 - (id) initWithDatabase:(Database *)database {
5110 if ((self = [super init]) != nil) {
5111 database_ = database;
5113 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
5114 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
5115 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
5116 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
5117 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
5121 pkgCacheFile &cache([database_ cache]);
5122 NSArray *packages([database_ packages]);
5123 pkgDepCache::Policy *policy([database_ policy]);
5125 issues_ = [NSMutableArray arrayWithCapacity:4];
5127 UpgradeCydia_ = false;
5129 for (Package *package in packages) {
5130 pkgCache::PkgIterator iterator([package iterator]);
5131 NSString *name([package id]);
5133 if ([package broken]) {
5134 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
5136 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5138 reasons, @"reasons",
5141 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
5145 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
5146 pkgCache::DepIterator start;
5147 pkgCache::DepIterator end;
5148 dep.GlobOr(start, end); // ++dep
5150 if (!cache->IsImportantDep(end))
5152 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
5155 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
5157 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5158 [NSString stringWithUTF8String:start.DepType()], @"relationship",
5159 clauses, @"clauses",
5163 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
5165 pkgCache::PkgIterator target(start.TargetPkg());
5166 if (target->ProvidesList != 0)
5167 reason = @"missing";
5169 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
5171 reason = @"installed";
5172 installed = [NSString stringWithUTF8String:ver.VerStr()];
5173 } else if (!cache[target].CandidateVerIter(cache).end())
5174 reason = @"uninstalled";
5175 else if (target->ProvidesList == 0)
5176 reason = @"uninstallable";
5178 reason = @"virtual";
5181 NSDictionary *version(start.TargetVer() == 0 ? (NSDictionary *) [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
5182 [NSString stringWithUTF8String:start.CompType()], @"operator",
5183 [NSString stringWithUTF8String:start.TargetVer()], @"value",
5186 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5187 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
5188 version, @"version",
5190 installed, @"installed",
5193 // yes, seriously. (wtf?)
5201 pkgDepCache::StateCache &state(cache[iterator]);
5203 static RegEx special_r("(firmware|gsc\\..*|cy\\+.*)");
5205 if (state.NewInstall())
5206 [installs addObject:name];
5207 // XXX: else if (state.Install())
5208 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
5209 [reinstalls addObject:name];
5210 // XXX: move before previous if
5211 else if (state.Upgrade())
5212 [upgrades addObject:name];
5213 else if (state.Downgrade())
5214 [downgrades addObject:name];
5215 else if (!state.Delete())
5216 // XXX: _assert(state.Keep());
5218 else if (special_r(name))
5219 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5220 [NSNull null], @"package",
5221 [NSArray arrayWithObjects:
5222 [NSDictionary dictionaryWithObjectsAndKeys:
5223 @"Conflicts", @"relationship",
5224 [NSArray arrayWithObjects:
5225 [NSDictionary dictionaryWithObjectsAndKeys:
5227 [NSNull null], @"version",
5228 @"installed", @"reason",
5235 if ([package essential])
5237 [removes addObject:name];
5240 if ([name isEqualToString:@"cydia"])
5241 UpgradeCydia_ = true;
5243 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
5244 substrate_ |= DepSubstrate(iterator.CurrentVer());
5249 else if (Advanced_) {
5250 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
5252 essential_ = [[[UIAlertView alloc]
5253 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
5254 message:UCLocalize("REMOVING_ESSENTIALS_EX")
5256 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
5258 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
5262 [essential_ setContext:@"remove"];
5263 [essential_ setNumberOfRows:2];
5265 essential_ = [[[UIAlertView alloc]
5266 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
5267 message:UCLocalize("UNABLE_TO_COMPLY_EX")
5269 cancelButtonTitle:UCLocalize("OKAY")
5270 otherButtonTitles:nil
5273 [essential_ setContext:@"unable"];
5276 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5277 installs, @"installs",
5278 reinstalls, @"reinstalls",
5279 upgrades, @"upgrades",
5280 downgrades, @"downgrades",
5281 removes, @"removes",
5284 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5285 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
5286 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
5289 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
5293 - (UIBarButtonItem *) leftButton {
5294 return [[[UIBarButtonItem alloc]
5295 initWithTitle:UCLocalize("CANCEL")
5296 style:UIBarButtonItemStylePlain
5298 action:@selector(cancelButtonClicked)
5303 - (void) applyRightButton {
5304 if ([issues_ count] == 0 && ![self isLoading])
5305 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
5306 initWithTitle:UCLocalize("CONFIRM")
5307 style:UIBarButtonItemStyleDone
5309 action:@selector(confirmButtonClicked)
5312 [[self navigationItem] setRightBarButtonItem:nil];
5316 - (void) cancelButtonClicked {
5317 [delegate_ cancelAndClear:YES];
5318 [self dismissModalViewControllerAnimated:YES];
5322 - (void) confirmButtonClicked {
5323 if (essential_ != nil)
5333 /* Progress Data {{{ */
5334 @interface CydiaProgressData : NSObject {
5335 _transient id delegate_;
5344 _H<NSMutableArray> events_;
5345 _H<NSString> title_;
5347 _H<NSString> status_;
5348 _H<NSString> finish_;
5353 @implementation CydiaProgressData
5355 + (NSArray *) _attributeKeys {
5356 return [NSArray arrayWithObjects:
5368 - (NSArray *) attributeKeys {
5369 return [[self class] _attributeKeys];
5372 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5373 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5377 if ((self = [super init]) != nil) {
5378 events_ = [NSMutableArray arrayWithCapacity:32];
5386 - (void) setDelegate:(id)delegate {
5387 delegate_ = delegate;
5390 - (void) setPercent:(float)value {
5394 - (NSNumber *) percent {
5395 return [NSNumber numberWithFloat:percent_];
5398 - (void) setCurrent:(float)value {
5402 - (NSNumber *) current {
5403 return [NSNumber numberWithFloat:current_];
5406 - (void) setTotal:(float)value {
5410 - (NSNumber *) total {
5411 return [NSNumber numberWithFloat:total_];
5414 - (void) setSpeed:(float)value {
5418 - (NSNumber *) speed {
5419 return [NSNumber numberWithFloat:speed_];
5422 - (NSArray *) events {
5426 - (void) removeAllEvents {
5427 [events_ removeAllObjects];
5430 - (void) addEvent:(CydiaProgressEvent *)event {
5431 [events_ addObject:event];
5434 - (void) setTitle:(NSString *)text {
5438 - (NSString *) title {
5442 - (void) setFinish:(NSString *)text {
5446 - (NSString *) finish {
5447 return (id) finish_ ?: [NSNull null];
5450 - (void) setRunning:(bool)running {
5454 - (NSNumber *) running {
5455 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5460 /* Progress Controller {{{ */
5461 @interface ProgressController : CydiaWebViewController <
5464 _transient Database *database_;
5465 _H<CydiaProgressData, 1> progress_;
5469 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5471 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5473 - (void) setTitle:(NSString *)title;
5474 - (void) setCancellable:(bool)cancellable;
5478 @implementation ProgressController
5481 [database_ setProgressDelegate:nil];
5485 - (UIBarButtonItem *) leftButton {
5486 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5487 initWithTitle:UCLocalize("CANCEL")
5488 style:UIBarButtonItemStylePlain
5490 action:@selector(cancel)
5491 ] autorelease] : nil;
5494 - (void) updateCancel {
5495 [super applyLeftButton];
5498 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5499 if ((self = [super init]) != nil) {
5500 database_ = database;
5501 delegate_ = delegate;
5503 [database_ setProgressDelegate:self];
5505 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5506 [progress_ setDelegate:self];
5508 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5510 [scroller_ setBackgroundColor:[UIColor blackColor]];
5512 [[self navigationItem] setHidesBackButton:YES];
5514 [self updateCancel];
5518 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5519 [super webView:view didClearWindowObject:window forFrame:frame];
5520 [window setValue:progress_ forKey:@"cydiaProgress"];
5523 - (void) updateProgress {
5524 [self dispatchEvent:@"CydiaProgressUpdate"];
5527 - (void) viewWillAppear:(BOOL)animated {
5528 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5529 [super viewWillAppear:animated];
5532 - (void) reloadSpringBoard {
5533 if (kCFCoreFoundationVersionNumber > 700) { // XXX: iOS 6.x
5534 system("/bin/launchctl stop com.apple.backboardd");
5536 system("/usr/bin/killall backboardd SpringBoard sbreload");
5540 pid_t pid(ExecFork());
5545 pid_t pid(ExecFork());
5547 execl("/usr/libexec/cydia/cydo", "cydo", "/usr/bin/sbreload", NULL);
5557 system("/usr/bin/killall backboardd SpringBoard sbreload");
5561 UpdateExternalStatus(0);
5564 [delegate_ saveState];
5568 [delegate_ returnToCydia];
5572 [delegate_ terminateWithSuccess];
5573 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5574 [delegate_ suspendWithAnimation:YES];
5576 [delegate_ suspend];*/
5588 UIProgressHUD *hud([delegate_ addProgressHUD]);
5589 [hud setText:UCLocalize("LOADING")];
5590 [self performSelector:@selector(reloadSpringBoard) withObject:nil afterDelay:0.5];
5596 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5597 SBReboot(SBSSpringBoardServerPort());
5599 reboot2(RB_AUTOBOOT);
5606 - (void) setTitle:(NSString *)title {
5607 [progress_ setTitle:title];
5608 [self updateProgress];
5611 - (UIBarButtonItem *) rightButton {
5612 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5613 initWithTitle:UCLocalize("CLOSE")
5614 style:UIBarButtonItemStylePlain
5616 action:@selector(close)
5620 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5621 UpdateExternalStatus(1);
5623 [progress_ setRunning:true];
5624 [self setTitle:title];
5625 // implicit updateProgress
5627 SHA1SumValue notifyconf; {
5629 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5632 MMap mmap(file, MMap::ReadOnly);
5634 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5635 notifyconf = sha1.Result();
5639 SHA1SumValue springlist; {
5641 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5644 MMap mmap(file, MMap::ReadOnly);
5646 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5647 springlist = sha1.Result();
5651 if (invocation != nil) {
5652 [invocation yieldToSelector:@selector(invoke)];
5653 [self setTitle:@"COMPLETE"];
5658 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5661 MMap mmap(file, MMap::ReadOnly);
5663 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5664 if (!(notifyconf == sha1.Result()))
5671 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5674 MMap mmap(file, MMap::ReadOnly);
5676 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5677 if (!(springlist == sha1.Result()))
5683 if (RestartSubstrate_)
5687 RestartSubstrate_ = false;
5690 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5691 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5692 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5693 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5694 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5697 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5699 [progress_ setRunning:false];
5700 [self updateProgress];
5702 [self applyRightButton];
5705 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5706 [progress_ addEvent:event];
5707 [self updateProgress];
5710 - (bool) isProgressCancelled {
5711 return cancel_ == 2;
5716 [self updateCancel];
5719 - (void) setCancellable:(bool)cancellable {
5720 unsigned cancel(cancel_);
5724 else if (cancel_ == 0)
5727 if (cancel != cancel_)
5728 [self updateCancel];
5731 - (void) setProgressCancellable:(NSNumber *)cancellable {
5732 [self setCancellable:[cancellable boolValue]];
5735 - (void) setProgressPercent:(NSNumber *)percent {
5736 [progress_ setPercent:[percent floatValue]];
5737 [self updateProgress];
5740 - (void) setProgressStatus:(NSDictionary *)status {
5741 if (status == nil) {
5742 [progress_ setCurrent:0];
5743 [progress_ setTotal:0];
5744 [progress_ setSpeed:0];
5746 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5748 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5749 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5750 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5753 [self updateProgress];
5759 /* Package Cell {{{ */
5760 @interface PackageCell : CyteTableViewCell <
5761 CyteTableViewCellDelegate
5765 _H<NSString> description_;
5767 _H<NSString> source_;
5769 _H<UIImage> placard_;
5773 - (PackageCell *) init;
5774 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5776 - (void) drawContentRect:(CGRect)rect;
5780 @implementation PackageCell
5782 - (PackageCell *) init {
5783 CGRect frame(CGRectMake(0, 0, 320, 74));
5784 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5785 UIView *content([self contentView]);
5786 CGRect bounds([content bounds]);
5788 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5789 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5790 [content addSubview:content_];
5792 [content_ setDelegate:self];
5793 [content_ setOpaque:YES];
5797 - (NSString *) accessibilityLabel {
5801 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5802 summarized_ = summary;
5812 [content_ setBackgroundColor:[UIColor whiteColor]];
5816 Source *source = [package source];
5818 icon_ = [package icon];
5820 if (NSString *name = [package name])
5821 name_ = [NSString stringWithString:name];
5823 if (NSString *description = [package shortDescription])
5824 description_ = [NSString stringWithString:description];
5826 commercial_ = [package isCommercial];
5828 NSString *label = nil;
5829 bool trusted = false;
5831 if (source != nil) {
5832 label = [source label];
5833 trusted = [source trusted];
5834 } else if ([[package id] isEqualToString:@"firmware"])
5835 label = UCLocalize("APPLE");
5837 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5839 NSString *from(label);
5841 NSString *section = [package simpleSection];
5842 if (section != nil && ![section isEqualToString:label]) {
5843 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5844 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5847 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5849 if (NSString *purpose = [package primaryPurpose])
5850 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5855 if (NSString *mode = [package mode]) {
5856 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5857 color = RemovingColor_;
5858 placard = @"removing";
5860 color = InstallingColor_;
5861 placard = @"installing";
5864 color = [UIColor whiteColor];
5866 if ([package installed] != nil)
5867 placard = @"installed";
5872 [content_ setBackgroundColor:color];
5875 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5878 [self setNeedsDisplay];
5879 [content_ setNeedsDisplay];
5882 - (void) drawSummaryContentRect:(CGRect)rect {
5883 bool highlighted(highlighted_);
5884 float width([self bounds].size.width);
5888 rect.size = [(UIImage *) icon_ size];
5890 while (rect.size.width > 16 || rect.size.height > 16) {
5891 rect.size.width /= 2;
5892 rect.size.height /= 2;
5895 rect.origin.x = 19 - rect.size.width / 2;
5896 rect.origin.y = 19 - rect.size.height / 2;
5898 [icon_ drawInRect:Retina(rect)];
5901 if (badge_ != nil) {
5903 rect.size = [(UIImage *) badge_ size];
5905 rect.size.width /= 4;
5906 rect.size.height /= 4;
5908 rect.origin.x = 25 - rect.size.width / 2;
5909 rect.origin.y = 25 - rect.size.height / 2;
5911 [badge_ drawInRect:Retina(rect)];
5914 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5918 UISetColor(commercial_ ? Purple_ : Black_);
5919 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
5921 if (placard_ != nil)
5922 [placard_ drawAtPoint:CGPointMake(width - 52, 11)];
5925 - (void) drawNormalContentRect:(CGRect)rect {
5926 bool highlighted(highlighted_);
5927 float width([self bounds].size.width);
5931 rect.size = [(UIImage *) icon_ size];
5933 while (rect.size.width > 32 || rect.size.height > 32) {
5934 rect.size.width /= 2;
5935 rect.size.height /= 2;
5938 rect.origin.x = 25 - rect.size.width / 2;
5939 rect.origin.y = 25 - rect.size.height / 2;
5941 [icon_ drawInRect:Retina(rect)];
5944 if (badge_ != nil) {
5946 rect.size = [(UIImage *) badge_ size];
5948 rect.size.width /= 2;
5949 rect.size.height /= 2;
5951 rect.origin.x = 36 - rect.size.width / 2;
5952 rect.origin.y = 36 - rect.size.height / 2;
5954 [badge_ drawInRect:Retina(rect)];
5957 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5961 UISetColor(commercial_ ? Purple_ : Black_);
5962 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
5963 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
5966 UISetColor(commercial_ ? Purplish_ : Gray_);
5967 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:NSLineBreakByTruncatingTail];
5969 if (placard_ != nil)
5970 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5973 - (void) drawContentRect:(CGRect)rect {
5975 [self drawSummaryContentRect:rect];
5977 [self drawNormalContentRect:rect];
5982 /* Section Cell {{{ */
5983 @interface SectionCell : CyteTableViewCell <
5984 CyteTableViewCellDelegate
5986 _H<NSString> basic_;
5987 _H<NSString> section_;
5989 _H<NSString> count_;
5991 _H<UISwitch> switch_;
5995 - (void) setSection:(Section *)section editing:(BOOL)editing;
5999 @implementation SectionCell
6001 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
6002 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
6003 icon_ = [UIImage imageNamed:@"folder.png"];
6004 // XXX: this initial frame is wrong, but is fixed later
6005 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
6006 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
6008 UIView *content([self contentView]);
6009 CGRect bounds([content bounds]);
6011 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
6012 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6013 [content addSubview:content_];
6014 [content_ setBackgroundColor:[UIColor whiteColor]];
6016 [content_ setDelegate:self];
6020 - (void) onSwitch:(id)sender {
6021 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
6022 if (metadata == nil) {
6023 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
6024 [Sections_ setObject:metadata forKey:basic_];
6027 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
6031 - (void) setSection:(Section *)section editing:(BOOL)editing {
6032 if (editing != editing_) {
6034 [switch_ removeFromSuperview];
6036 [self addSubview:switch_];
6045 if (section == nil) {
6046 name_ = UCLocalize("ALL_PACKAGES");
6049 basic_ = [section name];
6050 section_ = [section localized];
6052 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
6053 count_ = [NSString stringWithFormat:@"%zd", [section count]];
6056 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
6059 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
6060 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
6062 [content_ setNeedsDisplay];
6065 - (void) setFrame:(CGRect)frame {
6066 [super setFrame:frame];
6068 CGRect rect([switch_ frame]);
6069 [switch_ setFrame:CGRectMake(frame.size.width - rect.size.width - 9, 9, rect.size.width, rect.size.height)];
6072 - (NSString *) accessibilityLabel {
6076 - (void) drawContentRect:(CGRect)rect {
6077 bool highlighted(highlighted_ && !editing_);
6079 [icon_ drawInRect:CGRectMake(7, 7, 32, 32)];
6081 if (highlighted && kCFCoreFoundationVersionNumber < 800)
6084 float width(rect.size.width);
6086 width -= 9 + [switch_ frame].size.width;
6090 [name_ drawAtPoint:CGPointMake(48, 12) forWidth:(width - 58) withFont:Font18_ lineBreakMode:NSLineBreakByTruncatingTail];
6092 CGSize size = [count_ sizeWithFont:Font14_];
6094 UISetColor(Folder_);
6096 [count_ drawAtPoint:CGPointMake(Retina(10 + (30 - size.width) / 2), 18) withFont:Font12Bold_];
6102 /* File Table {{{ */
6103 @interface FileTable : CyteViewController <
6104 UITableViewDataSource,
6107 _transient Database *database_;
6108 _H<Package> package_;
6110 _H<NSMutableArray> files_;
6111 _H<UITableView, 2> list_;
6114 - (id) initWithDatabase:(Database *)database;
6115 - (void) setPackage:(Package *)package;
6119 @implementation FileTable
6121 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6122 return files_ == nil ? 0 : [files_ count];
6125 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6129 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6130 static NSString *reuseIdentifier = @"Cell";
6132 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6134 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6135 [cell setFont:[UIFont systemFontOfSize:16]];
6137 [cell setText:[files_ objectAtIndex:indexPath.row]];
6138 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
6143 - (NSURL *) navigationURL {
6144 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
6148 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
6149 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6150 [list_ setRowHeight:24.0f];
6151 [(UITableView *) list_ setDataSource:self];
6152 [list_ setDelegate:self];
6153 [self setView:list_];
6156 - (void) viewDidLoad {
6157 [super viewDidLoad];
6159 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
6162 - (void) releaseSubviews {
6168 [super releaseSubviews];
6171 - (id) initWithDatabase:(Database *)database {
6172 if ((self = [super init]) != nil) {
6173 database_ = database;
6177 - (void) setPackage:(Package *)package {
6181 files_ = [NSMutableArray arrayWithCapacity:32];
6183 if (package != nil) {
6185 name_ = [package id];
6187 if (NSArray *files = [package files])
6188 [files_ addObjectsFromArray:files];
6190 if ([files_ count] != 0) {
6191 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
6192 [files_ removeObjectAtIndex:0];
6193 [files_ sortUsingSelector:@selector(compareByPath:)];
6195 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
6196 [stack addObject:@"/"];
6198 for (int i(0), e([files_ count]); i != e; ++i) {
6199 NSString *file = [files_ objectAtIndex:i];
6200 while (![file hasPrefix:[stack lastObject]])
6201 [stack removeLastObject];
6202 NSString *directory = [stack lastObject];
6203 [stack addObject:[file stringByAppendingString:@"/"]];
6204 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
6205 ([stack count] - 2) * 3, "",
6206 [file substringFromIndex:[directory length]]
6215 - (void) reloadData {
6218 [self setPackage:[database_ packageWithName:name_]];
6223 /* Package Controller {{{ */
6224 @interface CYPackageController : CydiaWebViewController <
6225 UIActionSheetDelegate
6227 _transient Database *database_;
6228 _H<Package> package_;
6231 std::vector<std::pair<_H<NSString>, _H<NSString>>> buttons_;
6232 _H<UIBarButtonItem> button_;
6235 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer;
6239 @implementation CYPackageController
6241 - (NSURL *) navigationURL {
6242 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
6245 - (void) _clickButtonWithName:(NSString *)name {
6246 if ([name isEqualToString:@"CLEAR"])
6247 [delegate_ clearPackage:package_];
6248 else if ([name isEqualToString:@"INSTALL"])
6249 [delegate_ installPackage:package_];
6250 else if ([name isEqualToString:@"REINSTALL"])
6251 [delegate_ installPackage:package_];
6252 else if ([name isEqualToString:@"REMOVE"])
6253 [delegate_ removePackage:package_];
6254 else if ([name isEqualToString:@"UPGRADE"])
6255 [delegate_ installPackage:package_];
6256 else _assert(false);
6259 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
6260 NSString *context([sheet context]);
6262 if ([context isEqualToString:@"modify"]) {
6263 if (button != [sheet cancelButtonIndex]) {
6265 [self performSelector:@selector(_clickButtonWithName:) withObject:buttons_[button].first afterDelay:0];
6267 [self _clickButtonWithName:buttons_[button].first];
6270 [sheet dismissWithClickedButtonIndex:button animated:YES];
6274 - (bool) _allowJavaScriptPanel {
6279 - (void) _customButtonClicked {
6280 size_t count(buttons_.size());
6285 [self _clickButtonWithName:buttons_[0].first];
6287 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
6288 for (const auto &button : buttons_)
6289 [buttons addObject:button.second];
6291 UIActionSheet *sheet = [[[UIActionSheet alloc]
6294 cancelButtonTitle:nil
6295 destructiveButtonTitle:nil
6296 otherButtonTitles:nil
6299 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
6301 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
6302 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
6304 [sheet setContext:@"modify"];
6306 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
6310 - (void) reloadButtonClicked {
6311 if (commercial_ && function_ == nil && [package_ uninstalled])
6313 [self customButtonClicked];
6316 - (void) applyLoadingTitle {
6317 // Don't show "Loading" as the title. Ever.
6320 - (UIBarButtonItem *) rightButton {
6325 - (void) setPageColor:(UIColor *)color {
6326 return [super setPageColor:nil];
6329 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer {
6330 if ((self = [super init]) != nil) {
6331 database_ = database;
6332 name_ = name == nil ? @"" : [NSString stringWithString:name];
6333 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]] withReferrer:referrer];
6337 - (void) reloadData {
6340 package_ = [database_ packageWithName:name_];
6344 if (package_ != nil) {
6345 [(Package *) package_ parse];
6347 commercial_ = [package_ isCommercial];
6349 if ([package_ mode] != nil)
6350 buttons_.push_back(std::make_pair(@"CLEAR", UCLocalize("CLEAR")));
6351 if ([package_ source] == nil);
6352 else if ([package_ upgradableAndEssential:NO])
6353 buttons_.push_back(std::make_pair(@"UPGRADE", UCLocalize("UPGRADE")));
6354 else if ([package_ uninstalled])
6355 buttons_.push_back(std::make_pair(@"INSTALL", UCLocalize("INSTALL")));
6357 buttons_.push_back(std::make_pair(@"REINSTALL", UCLocalize("REINSTALL")));
6358 if (![package_ uninstalled])
6359 buttons_.push_back(std::make_pair(@"REMOVE", UCLocalize("REMOVE")));
6363 switch (buttons_.size()) {
6364 case 0: title = nil; break;
6365 case 1: title = buttons_[0].second; break;
6366 default: title = UCLocalize("MODIFY"); break;
6369 button_ = [[[UIBarButtonItem alloc]
6371 style:UIBarButtonItemStylePlain
6373 action:@selector(customButtonClicked)
6377 - (bool) isLoading {
6378 return commercial_ ? [super isLoading] : false;
6384 /* Package List Controller {{{ */
6385 @interface PackageListController : CyteViewController <
6386 UITableViewDataSource,
6389 _transient Database *database_;
6391 _H<NSArray> packages_;
6392 _H<NSArray> sections_;
6393 _H<UITableView, 2> list_;
6395 _H<NSArray> thumbs_;
6396 std::vector<NSInteger> offset_;
6398 _H<NSString> title_;
6399 unsigned reloading_;
6402 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6403 - (void) setDelegate:(id)delegate;
6404 - (void) resetCursor;
6407 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages;
6411 @implementation PackageListController
6413 - (NSURL *) referrerURL {
6414 return [self navigationURL];
6417 - (bool) isSummarized {
6421 - (bool) showsSections {
6425 - (void) deselectWithAnimation:(BOOL)animated {
6426 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6429 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6430 CGRect base = [[self view] bounds];
6431 base.size.height -= bounds.size.height;
6432 base.origin = [list_ frame].origin;
6434 [UIView beginAnimations:nil context:NULL];
6435 [UIView setAnimationBeginsFromCurrentState:YES];
6436 [UIView setAnimationCurve:curve];
6437 [UIView setAnimationDuration:duration];
6438 [list_ setFrame:base];
6439 [UIView commitAnimations];
6442 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6443 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6446 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6447 [self resizeForKeyboardBounds:bounds duration:0];
6450 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6451 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6452 *curve = UIViewAnimationCurveEaseInOut;
6454 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6456 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6459 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6462 - (void) keyboardWillShow:(NSNotification *)notification {
6465 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6466 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6468 NSTimeInterval duration;
6469 UIViewAnimationCurve curve;
6470 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6472 CGRect kbframe = CGRectMake(Retina(center.x - bounds.size.width / 2), Retina(center.y - bounds.size.height / 2), bounds.size.width, bounds.size.height);
6473 UIViewController *base = self;
6474 while ([base parentOrPresentingViewController] != nil)
6475 base = [base parentOrPresentingViewController];
6476 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6477 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6479 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6480 intersection.size.height += CYStatusBarHeight();
6482 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6485 - (void) keyboardWillHide:(NSNotification *)notification {
6486 NSTimeInterval duration;
6487 UIViewAnimationCurve curve;
6488 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6490 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6493 - (void) viewWillAppear:(BOOL)animated {
6494 [super viewWillAppear:animated];
6496 [self resizeForKeyboardBounds:CGRectZero];
6497 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6498 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6501 - (void) viewWillDisappear:(BOOL)animated {
6502 [super viewWillDisappear:animated];
6504 [self resizeForKeyboardBounds:CGRectZero];
6505 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6506 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6509 - (void) viewDidAppear:(BOOL)animated {
6510 [super viewDidAppear:animated];
6511 [self deselectWithAnimation:animated];
6514 - (void) didSelectPackage:(Package *)package {
6515 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[[self referrerURL] absoluteString]] autorelease]);
6516 [view setDelegate:delegate_];
6517 [[self navigationController] pushViewController:view animated:YES];
6520 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6521 NSInteger count([sections_ count]);
6522 return count == 0 ? 1 : count;
6525 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6526 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6528 return [[sections_ objectAtIndex:section] name];
6531 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6532 if ([sections_ count] == 0)
6534 return [[sections_ objectAtIndex:section] count];
6537 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6538 @synchronized (database_) {
6539 if ([database_ era] != era_)
6542 Section *section([sections_ objectAtIndex:[path section]]);
6543 NSInteger row([path row]);
6544 Package *package([packages_ objectAtIndex:([section row] + row)]);
6545 return [[package retain] autorelease];
6548 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6549 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6551 cell = [[[PackageCell alloc] init] autorelease];
6553 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6554 [cell setPackage:package asSummary:[self isSummarized]];
6558 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6559 Package *package([self packageAtIndexPath:path]);
6560 package = [database_ packageWithName:[package id]];
6561 [self didSelectPackage:package];
6564 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6568 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6569 return offset_[index];
6572 - (void) updateHeight {
6573 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6576 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6577 if ((self = [super init]) != nil) {
6578 database_ = database;
6579 title_ = [title copy];
6580 [[self navigationItem] setTitle:title_];
6585 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
6586 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
6587 [self setView:view];
6589 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6590 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6591 [view addSubview:list_];
6593 // XXX: is 20 the most optimal number here?
6594 [list_ setSectionIndexMinimumDisplayRowCount:20];
6596 [(UITableView *) list_ setDataSource:self];
6597 [list_ setDelegate:self];
6599 [self updateHeight];
6602 - (void) releaseSubviews {
6611 [super releaseSubviews];
6614 - (void) setDelegate:(id)delegate {
6615 delegate_ = delegate;
6618 - (bool) shouldYield {
6622 - (bool) shouldBlock {
6626 - (NSMutableArray *) _reloadPackages {
6627 @synchronized (database_) {
6628 era_ = [database_ era];
6629 NSArray *packages([database_ packages]);
6631 return [NSMutableArray arrayWithArray:packages];
6634 - (void) _reloadData {
6635 if (reloading_ != 0) {
6640 NSMutableArray *packages;
6643 if ([self shouldYield]) {
6647 if (![self shouldBlock])
6650 hud = [delegate_ addProgressHUD];
6651 [hud setText:UCLocalize("LOADING")];
6655 packages = [self yieldToSelector:@selector(_reloadPackages)];
6658 [delegate_ removeProgressHUD:hud];
6659 } while (reloading_ == 2);
6661 packages = [self _reloadPackages];
6664 @synchronized (database_) {
6665 if (era_ != [database_ era])
6672 packages_ = packages;
6674 if ([self showsSections])
6675 sections_ = [self sectionsForPackages:packages];
6677 Section *section([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6678 [section setCount:[packages_ count]];
6679 sections_ = [NSArray arrayWithObject:section];
6682 [self updateHeight];
6684 _profile(PackageTable$reloadData$List)
6685 [(UITableView *) list_ setDataSource:self];
6693 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
6694 Section *prefix([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6695 size_t end([packages count]);
6697 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
6698 Section *section(prefix);
6700 thumbs_ = CollationThumbs_;
6701 offset_ = CollationOffset_;
6704 size_t offsets([CollationStarts_ count]);
6706 NSString *start([CollationStarts_ objectAtIndex:offset]);
6707 size_t length([start length]);
6709 for (size_t index(0); index != end; ++index) {
6711 Package *package([packages objectAtIndex:index]);
6712 NSString *name(PackageName(package, @selector(cyname)));
6714 //while ([start compare:name options:NSNumericSearch range:NSMakeRange(0, length) locale:CollationLocale_] != NSOrderedDescending) {
6715 while (StringNameCompare(start, name, length) != kCFCompareGreaterThan) {
6716 NSString *title([CollationTitles_ objectAtIndex:offset]);
6717 section = [[[Section alloc] initWithName:title row:index localize:NO] autorelease];
6718 [sections addObject:section];
6720 start = ++offset == offsets ? nil : [CollationStarts_ objectAtIndex:offset];
6723 length = [start length];
6727 [section addToCount];
6730 for (; offset != offsets; ++offset) {
6731 NSString *title([CollationTitles_ objectAtIndex:offset]);
6732 Section *section([[[Section alloc] initWithName:title row:end localize:NO] autorelease]);
6733 [sections addObject:section];
6736 if ([prefix count] != 0) {
6737 Section *suffix([sections lastObject]);
6738 [prefix setName:[suffix name]];
6739 [suffix setName:nil];
6740 [sections insertObject:prefix atIndex:(offsets - 1)];
6746 - (void) reloadData {
6749 if ([self shouldYield])
6750 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6755 - (void) resetCursor {
6756 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6759 - (void) clearData {
6760 [self updateHeight];
6762 [list_ setDataSource:nil];
6770 /* Filtered Package List Controller {{{ */
6771 typedef Function<bool, Package *> PackageFilter;
6772 typedef Function<void, NSMutableArray *> PackageSorter;
6773 @interface FilteredPackageListController : PackageListController {
6774 PackageFilter filter_;
6775 PackageSorter sorter_;
6778 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter;
6780 - (void) setFilter:(PackageFilter)filter;
6781 - (void) setSorter:(PackageSorter)sorter;
6785 @implementation FilteredPackageListController
6787 - (void) setFilter:(PackageFilter)filter {
6788 @synchronized (self) {
6792 - (void) setSorter:(PackageSorter)sorter {
6793 @synchronized (self) {
6797 - (NSMutableArray *) _reloadPackages {
6798 @synchronized (database_) {
6799 era_ = [database_ era];
6801 NSArray *packages([database_ packages]);
6802 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6804 PackageFilter filter;
6805 PackageSorter sorter;
6807 @synchronized (self) {
6812 _profile(PackageTable$reloadData$Filter)
6813 for (Package *package in packages)
6814 if ([package valid] && filter(package))
6815 [filtered addObject:package];
6823 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter {
6824 if ((self = [super initWithDatabase:database title:title]) != nil) {
6825 [self setFilter:filter];
6832 /* Home Controller {{{ */
6833 @interface HomeController : CydiaWebViewController {
6834 CFRunLoopRef runloop_;
6835 SCNetworkReachabilityRef reachability_;
6840 @implementation HomeController
6842 static void HomeControllerReachabilityCallback(SCNetworkReachabilityRef reachability, SCNetworkReachabilityFlags flags, void *info) {
6843 [(HomeController *) info dispatchEvent:@"CydiaReachabilityCallback"];
6847 if ((self = [super init]) != nil) {
6848 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6851 reachability_ = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "cydia.saurik.com");
6852 if (reachability_ != NULL) {
6853 SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
6854 SCNetworkReachabilitySetCallback(reachability_, HomeControllerReachabilityCallback, &context);
6856 CFRunLoopRef runloop(CFRunLoopGetCurrent());
6857 if (SCNetworkReachabilityScheduleWithRunLoop(reachability_, runloop, kCFRunLoopDefaultMode))
6864 if (reachability_ != NULL && runloop_ != NULL)
6865 SCNetworkReachabilityUnscheduleFromRunLoop(reachability_, runloop_, kCFRunLoopDefaultMode);
6869 - (NSURL *) navigationURL {
6870 return [NSURL URLWithString:@"cydia://home"];
6873 - (void) aboutButtonClicked {
6874 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6876 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6877 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6878 [alert setCancelButtonIndex:0];
6881 @"Copyright \u00a9 2008-2014\n"
6884 "Jay Freeman (saurik)\n"
6885 "saurik@saurik.com\n"
6886 "http://www.saurik.com/"
6892 - (UIBarButtonItem *) leftButton {
6893 return [[[UIBarButtonItem alloc]
6894 initWithTitle:UCLocalize("ABOUT")
6895 style:UIBarButtonItemStylePlain
6897 action:@selector(aboutButtonClicked)
6904 /* Cydia Navigation Controller Interface {{{ */
6905 @interface UINavigationController (Cydia)
6907 - (NSArray *) navigationURLCollection;
6908 - (void) unloadData;
6913 /* Cydia Tab Bar Controller {{{ */
6914 @interface CydiaTabBarController : CyteTabBarController <
6915 UITabBarControllerDelegate,
6918 _transient Database *database_;
6920 _H<UIActivityIndicatorView> indicator_;
6923 // XXX: ok, "updatedelegate_"?...
6924 _transient NSObject<CydiaDelegate> *updatedelegate_;
6927 - (NSArray *) navigationURLCollection;
6928 - (void) beginUpdate;
6933 @implementation CydiaTabBarController
6935 - (NSArray *) navigationURLCollection {
6936 NSMutableArray *items([NSMutableArray array]);
6938 // XXX: Should this deal with transient view controllers?
6939 for (id navigation in [self viewControllers]) {
6940 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6942 [items addObject:stack];
6948 - (id) initWithDatabase:(Database *)database {
6949 if ((self = [super init]) != nil) {
6950 database_ = database;
6951 [self setDelegate:self];
6953 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteTiny] autorelease];
6954 [indicator_ setOrigin:CGPointMake(kCFCoreFoundationVersionNumber >= 800 ? 2 : 4, 2)];
6956 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6960 - (void) setUpdate:(NSDate *)date {
6964 - (void) beginUpdate {
6968 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
6969 UITabBarItem *item([controller tabBarItem]);
6971 [item setBadgeValue:@""];
6972 UIView *badge(MSHookIvar<UIView *>([item view], "_badge"));
6974 [indicator_ startAnimating];
6975 [badge addSubview:indicator_];
6977 [updatedelegate_ retainNetworkActivityIndicator];
6981 detachNewThreadSelector:@selector(performUpdate)
6987 - (void) performUpdate {
6988 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
6990 SourceStatus status(self, database_);
6991 [database_ updateWithStatus:status];
6994 performSelectorOnMainThread:@selector(completeUpdate)
7002 - (void) stopUpdateWithSelector:(SEL)selector {
7004 [updatedelegate_ releaseNetworkActivityIndicator];
7006 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
7007 [[controller tabBarItem] setBadgeValue:nil];
7009 [indicator_ removeFromSuperview];
7010 [indicator_ stopAnimating];
7012 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
7015 - (void) completeUpdate {
7018 [self stopUpdateWithSelector:@selector(reloadData)];
7021 - (void) cancelUpdate {
7022 [self stopUpdateWithSelector:@selector(updateDataAndLoad)];
7025 - (void) cancelPressed {
7026 [self cancelUpdate];
7033 - (bool) isSourceCancelled {
7037 - (void) startSourceFetch:(NSString *)uri {
7040 - (void) stopSourceFetch:(NSString *)uri {
7043 - (void) setUpdateDelegate:(id)delegate {
7044 updatedelegate_ = delegate;
7050 /* Cydia Navigation Controller Implementation {{{ */
7051 @implementation UINavigationController (Cydia)
7053 - (NSArray *) navigationURLCollection {
7054 NSMutableArray *stack([NSMutableArray array]);
7056 for (CyteViewController *controller in [self viewControllers]) {
7057 NSString *url = [[controller navigationURL] absoluteString];
7059 [stack addObject:url];
7065 - (void) reloadData {
7068 UIViewController *visible([self visibleViewController]);
7070 [visible reloadData];
7072 // on the iPad, this view controller is ALSO visible. :(
7074 if (UIViewController *modal = [self modalViewController])
7075 if ([modal modalPresentationStyle] == UIModalPresentationFormSheet)
7076 if (UIViewController *top = [self topViewController])
7081 - (void) unloadData {
7082 for (CyteViewController *page in [self viewControllers])
7091 /* Cydia:// Protocol {{{ */
7092 @interface CydiaURLProtocol : NSURLProtocol {
7097 @implementation CydiaURLProtocol
7099 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7100 NSURL *url([request URL]);
7104 NSString *scheme([[url scheme] lowercaseString]);
7105 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7107 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7113 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7117 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7118 id<NSURLProtocolClient> client([self client]);
7120 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7122 NSData *data(UIImagePNGRepresentation(icon));
7124 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7125 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7126 [client URLProtocol:self didLoadData:data];
7127 [client URLProtocolDidFinishLoading:self];
7131 - (void) startLoading {
7132 id<NSURLProtocolClient> client([self client]);
7133 NSURLRequest *request([self request]);
7135 NSURL *url([request URL]);
7136 NSString *href([url absoluteString]);
7137 NSString *scheme([[url scheme] lowercaseString]);
7141 if ([scheme isEqualToString:@"cydia"])
7142 path = [href substringFromIndex:8];
7143 else if ([scheme isEqualToString:@"about"])
7144 path = [href substringFromIndex:12];
7145 else _assert(false);
7147 NSRange slash([path rangeOfString:@"/"]);
7150 if (slash.location == NSNotFound) {
7154 command = [path substringToIndex:slash.location];
7155 path = [path substringFromIndex:(slash.location + 1)];
7158 Database *database([Database sharedInstance]);
7160 if ([command isEqualToString:@"package-icon"]) {
7163 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7164 Package *package([database packageWithName:path]);
7168 UIImage *icon([package icon]);
7169 [self _returnPNGWithImage:icon forRequest:request];
7170 } else if ([command isEqualToString:@"uikit-image"]) {
7173 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7174 UIImage *icon(_UIImageWithName(path));
7175 [self _returnPNGWithImage:icon forRequest:request];
7176 } else if ([command isEqualToString:@"section-icon"]) {
7179 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7180 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7182 icon = [UIImage imageNamed:@"unknown.png"];
7183 [self _returnPNGWithImage:icon forRequest:request];
7185 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7189 - (void) stopLoading {
7195 /* Section Controller {{{ */
7196 @interface SectionController : FilteredPackageListController {
7198 _H<NSString> section_;
7201 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section;
7205 @implementation SectionController
7207 - (NSURL *) referrerURL {
7208 NSString *name(section_);
7209 name = name ?: @"*";
7210 NSString *key(key_);
7212 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sections/%@/%@", UI_, [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7215 - (NSURL *) navigationURL {
7216 NSString *name(section_);
7217 name = name ?: @"*";
7218 NSString *key(key_);
7220 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@/%@", [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7223 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section {
7226 title = UCLocalize("ALL_PACKAGES");
7227 else if (![section isEqual:@""])
7228 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(section) value:nil table:@"Sections"];
7230 title = UCLocalize("NO_SECTION");
7232 if ((self = [super initWithDatabase:database title:title]) != nil) {
7233 key_ = [source key];
7238 - (void) reloadData {
7239 Source *source([database_ sourceWithKey:key_]);
7240 _H<NSString> name(section_);
7242 [self setFilter:[=](Package *package) {
7243 NSString *section([package section]);
7247 section == nil && [name length] == 0 ||
7248 [name isEqualToString:section]
7251 [package source] == source
7252 ) && [package visible];
7260 /* Sections Controller {{{ */
7261 @interface SectionsController : CyteViewController <
7262 UITableViewDataSource,
7265 _transient Database *database_;
7267 _H<NSMutableArray> sections_;
7268 _H<NSMutableArray> filtered_;
7269 _H<UITableView, 2> list_;
7272 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7273 - (void) editButtonClicked;
7277 @implementation SectionsController
7279 - (NSURL *) navigationURL {
7280 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
7283 - (Source *) source {
7286 return [database_ sourceWithKey:key_];
7289 - (void) updateNavigationItem {
7290 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7291 if ([sections_ count] == 0) {
7292 [[self navigationItem] setRightBarButtonItem:nil];
7294 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7295 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7297 action:@selector(editButtonClicked)
7298 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7302 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7303 [super setEditing:editing animated:animated];
7308 [delegate_ updateData];
7310 [self updateNavigationItem];
7313 - (void) viewDidAppear:(BOOL)animated {
7314 [super viewDidAppear:animated];
7315 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7318 - (void) viewWillDisappear:(BOOL)animated {
7319 [super viewWillDisappear:animated];
7320 [self setEditing:NO];
7323 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7324 Section *section = nil;
7325 int index = [indexPath row];
7326 if (![self isEditing]) {
7329 section = [filtered_ objectAtIndex:index];
7331 section = [sections_ objectAtIndex:index];
7336 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7337 if ([self isEditing])
7338 return [sections_ count];
7340 return [filtered_ count] + 1;
7343 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7347 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7348 static NSString *reuseIdentifier = @"SectionCell";
7350 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7352 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7354 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7359 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7360 if ([self isEditing])
7363 Section *section = [self sectionAtIndexPath:indexPath];
7365 SectionController *controller = [[[SectionController alloc]
7366 initWithDatabase:database_
7367 source:[self source]
7368 section:[section name]
7370 [controller setDelegate:delegate_];
7372 [[self navigationController] pushViewController:controller animated:YES];
7376 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
7377 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7378 [list_ setRowHeight:46];
7379 [(UITableView *) list_ setDataSource:self];
7380 [list_ setDelegate:self];
7381 [self setView:list_];
7384 - (void) viewDidLoad {
7385 [super viewDidLoad];
7387 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7390 - (void) releaseSubviews {
7396 [super releaseSubviews];
7399 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7400 if ((self = [super init]) != nil) {
7401 database_ = database;
7402 key_ = [source key];
7406 - (void) reloadData {
7409 NSArray *packages = [database_ packages];
7411 sections_ = [NSMutableArray arrayWithCapacity:16];
7412 filtered_ = [NSMutableArray arrayWithCapacity:16];
7414 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7416 Source *source([self source]);
7419 for (Package *package in packages) {
7420 if (source != nil && [package source] != source)
7423 NSString *name([package section]);
7424 NSString *key(name == nil ? @"" : name);
7428 _profile(SectionsView$reloadData$Section)
7429 section = [sections objectForKey:key];
7430 if (section == nil) {
7431 _profile(SectionsView$reloadData$Section$Allocate)
7432 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7433 [sections setObject:section forKey:key];
7438 [section addToCount];
7440 _profile(SectionsView$reloadData$Filter)
7441 if (![package valid] || ![package visible])
7449 [sections_ addObjectsFromArray:[sections allValues]];
7451 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7453 for (Section *section in (id) sections_) {
7454 size_t count([section row]);
7458 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7459 [section setCount:count];
7460 [filtered_ addObject:section];
7463 [self updateNavigationItem];
7468 - (void) editButtonClicked {
7469 [self setEditing:![self isEditing] animated:YES];
7475 /* Changes Controller {{{ */
7476 @interface ChangesController : FilteredPackageListController {
7480 - (id) initWithDatabase:(Database *)database;
7484 @implementation ChangesController
7486 - (NSURL *) referrerURL {
7487 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/changes/", UI_]];
7490 - (NSURL *) navigationURL {
7491 return [NSURL URLWithString:@"cydia://changes"];
7494 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7495 @synchronized (database_) {
7496 if ([database_ era] != era_)
7499 NSUInteger sectionIndex([path section]);
7500 if (sectionIndex >= [sections_ count])
7502 Section *section([sections_ objectAtIndex:sectionIndex]);
7503 NSInteger row([path row]);
7504 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7507 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7508 NSString *context([alert context]);
7510 if ([context isEqualToString:@"norefresh"])
7511 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7514 - (void) setLeftBarButtonItem {
7515 if ([delegate_ updating])
7516 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7517 initWithTitle:UCLocalize("CANCEL")
7518 style:UIBarButtonItemStyleDone
7520 action:@selector(cancelButtonClicked)
7521 ] autorelease] animated:YES];
7523 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7524 initWithTitle:UCLocalize("REFRESH")
7525 style:UIBarButtonItemStylePlain
7527 action:@selector(refreshButtonClicked)
7528 ] autorelease] animated:YES];
7531 - (void) refreshButtonClicked {
7532 if ([delegate_ requestUpdate])
7533 [self setLeftBarButtonItem];
7536 - (void) cancelButtonClicked {
7537 [delegate_ cancelUpdate];
7540 - (void) upgradeButtonClicked {
7541 [delegate_ distUpgrade];
7542 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7545 - (bool) shouldYield {
7549 - (bool) shouldBlock {
7553 - (void) useFilter {
7554 @synchronized (self) {
7555 [self setFilter:[](Package *package) {
7556 return [package upgradableAndEssential:YES] || [package visible];
7559 [self setSorter:[](NSMutableArray *packages) {
7560 [packages radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7564 - (id) initWithDatabase:(Database *)database {
7565 if ((self = [super initWithDatabase:database title:UCLocalize("CHANGES")]) != nil) {
7570 - (void) viewDidLoad {
7571 [super viewDidLoad];
7572 [self setLeftBarButtonItem];
7575 - (void) viewWillAppear:(BOOL)animated {
7576 [super viewWillAppear:animated];
7577 [self setLeftBarButtonItem];
7580 - (void) reloadData {
7581 [self setLeftBarButtonItem];
7585 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
7586 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
7588 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7589 Section *ignored = nil;
7590 Section *section = nil;
7594 bool unseens = false;
7596 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7598 for (size_t offset = 0, count = [packages count]; offset != count; ++offset) {
7599 Package *package = [packages objectAtIndex:offset];
7601 BOOL uae = [package upgradableAndEssential:YES];
7605 time_t seen([package seen]);
7607 if (section == nil || last != seen) {
7611 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7614 _profile(ChangesController$reloadData$Allocate)
7615 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7616 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7617 [sections addObject:section];
7621 [section addToCount];
7622 } else if ([package ignored]) {
7623 if (ignored == nil) {
7624 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7626 [ignored addToCount];
7629 [upgradable addToCount];
7634 CFRelease(formatter);
7637 Section *last = [sections lastObject];
7638 size_t count = [last count];
7639 [packages removeObjectsInRange:NSMakeRange([packages count] - count, count)];
7640 [sections removeLastObject];
7643 if ([ignored count] != 0)
7644 [sections insertObject:ignored atIndex:0];
7646 [sections insertObject:upgradable atIndex:0];
7650 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7651 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7652 style:UIBarButtonItemStylePlain
7654 action:@selector(upgradeButtonClicked)
7655 ] autorelease]) animated:YES];
7662 /* Search Controller {{{ */
7663 @interface SearchController : FilteredPackageListController <
7666 _H<UISearchBar, 1> search_;
7671 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7672 - (void) reloadData;
7676 @implementation SearchController
7678 - (NSURL *) referrerURL {
7679 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/search?q=%@", UI_, [([search_ text] ?: @"") stringByAddingPercentEscapesIncludingReserved]]];
7682 - (NSURL *) navigationURL {
7683 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7684 return [NSURL URLWithString:@"cydia://search"];
7686 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [[search_ text] stringByAddingPercentEscapesIncludingReserved]]];
7689 - (NSArray *) termsForQuery:(NSString *)query {
7690 NSMutableArray *terms([NSMutableArray arrayWithCapacity:2]);
7691 for (NSString *component in [query componentsSeparatedByString:@" "])
7692 if ([component length] != 0)
7693 [terms addObject:component];
7698 - (void) useSearch {
7699 _H<NSArray> query([self termsForQuery:[search_ text]]);
7702 @synchronized (self) {
7703 [self setFilter:[=](Package *package) {
7704 if (![package unfiltered])
7706 if (![package matches:query])
7711 [self setSorter:[](NSMutableArray *packages) {
7712 [packages radixSortUsingSelector:@selector(rank)];
7720 - (void) usePrefix:(NSString *)prefix {
7721 _H<NSString> query(prefix);
7724 @synchronized (self) {
7725 [self setFilter:[=](Package *package) {
7726 if ([query length] == 0)
7728 if (![package unfiltered])
7730 if ([[package name] compare:query options:MatchCompareOptions_ range:NSMakeRange(0, [query length])] != NSOrderedSame)
7735 [self setSorter:nullptr];
7741 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7743 [self usePrefix:[search_ text]];
7746 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7747 [search_ resignFirstResponder];
7751 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7752 [search_ setText:@""];
7753 [self searchBarButtonClicked:searchBar];
7756 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7757 [self searchBarButtonClicked:searchBar];
7760 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7761 [self usePrefix:text];
7764 - (bool) shouldYield {
7768 - (bool) shouldBlock {
7772 - (bool) isSummarized {
7776 - (bool) showsSections {
7780 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7781 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH")])) {
7782 search_ = [[[UISearchBar alloc] init] autorelease];
7783 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7784 [search_ setDelegate:self];
7786 UITextField *textField;
7787 if ([search_ respondsToSelector:@selector(searchField)])
7788 textField = [search_ searchField];
7790 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7792 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7793 [textField setEnablesReturnKeyAutomatically:NO];
7794 [[self navigationItem] setTitleView:textField];
7797 [search_ setText:query];
7802 - (void) viewDidAppear:(BOOL)animated {
7803 [super viewDidAppear:animated];
7805 if (!searchloaded_) {
7806 searchloaded_ = YES;
7807 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7808 [search_ layoutSubviews];
7811 if ([self isSummarized])
7812 [search_ becomeFirstResponder];
7815 - (void) reloadData {
7820 - (void) didSelectPackage:(Package *)package {
7821 [search_ resignFirstResponder];
7822 [super didSelectPackage:package];
7827 /* Package Settings Controller {{{ */
7828 @interface PackageSettingsController : CyteViewController <
7829 UITableViewDataSource,
7832 _transient Database *database_;
7834 _H<Package> package_;
7835 _H<UITableView, 2> table_;
7836 _H<UISwitch> subscribedSwitch_;
7837 _H<UISwitch> ignoredSwitch_;
7838 _H<UITableViewCell> subscribedCell_;
7839 _H<UITableViewCell> ignoredCell_;
7842 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7846 @implementation PackageSettingsController
7848 - (NSURL *) navigationURL {
7849 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
7852 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7853 if (package_ == nil)
7856 if ([package_ installed] == nil)
7862 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7863 if (package_ == nil)
7866 // both sections contain just one item right now.
7870 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7874 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7876 return UCLocalize("SHOW_ALL_CHANGES_EX");
7878 return UCLocalize("IGNORE_UPGRADES_EX");
7881 - (void) onSubscribed:(id)control {
7882 bool value([control isOn]);
7883 if (package_ == nil)
7885 if ([package_ setSubscribed:value])
7886 [delegate_ updateData];
7889 - (void) _updateIgnored {
7890 const char *package([name_ UTF8String]);
7891 bool on([ignoredSwitch_ isOn]);
7893 pid_t pid(ExecFork());
7895 FILE *dpkg(popen("/usr/libexec/cydo --set-selections", "w"));
7896 fwrite(package, strlen(package), 1, dpkg);
7899 fwrite(" hold\n", 6, 1, dpkg);
7901 fwrite(" install\n", 9, 1, dpkg);
7909 - (void) onIgnored:(id)control {
7910 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7911 [invocation setTarget:self];
7912 [invocation setSelector:@selector(_updateIgnored)];
7914 [delegate_ reloadDataWithInvocation:invocation];
7917 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7918 if (package_ == nil)
7921 switch ([indexPath section]) {
7922 case 0: return subscribedCell_;
7923 case 1: return ignoredCell_;
7932 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
7933 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
7934 [self setView:view];
7936 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7937 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7938 [(UITableView *) table_ setDataSource:self];
7939 [table_ setDelegate:self];
7940 [view addSubview:table_];
7942 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7943 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7944 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7946 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7947 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7948 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7950 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7951 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7952 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7953 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7955 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7956 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7957 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7958 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7961 - (void) viewDidLoad {
7962 [super viewDidLoad];
7964 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7967 - (void) releaseSubviews {
7969 subscribedCell_ = nil;
7971 ignoredSwitch_ = nil;
7972 subscribedSwitch_ = nil;
7974 [super releaseSubviews];
7977 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7978 if ((self = [super init]) != nil) {
7979 database_ = database;
7984 - (void) reloadData {
7987 package_ = [database_ packageWithName:name_];
7989 if (package_ != nil) {
7990 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7991 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7992 } // XXX: what now, G?
7994 [table_ reloadData];
8000 /* Installed Controller {{{ */
8001 @interface InstalledController : FilteredPackageListController {
8005 - (id) initWithDatabase:(Database *)database;
8006 - (void) queueStatusDidChange;
8010 @implementation InstalledController
8012 - (NSURL *) referrerURL {
8013 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/installed/", UI_]];
8016 - (NSURL *) navigationURL {
8017 return [NSURL URLWithString:@"cydia://installed"];
8020 - (void) useRecent {
8023 @synchronized (self) {
8024 [self setFilter:[](Package *package) {
8025 return ![package uninstalled] && package->role_ < 7;
8028 [self setSorter:[](NSMutableArray *packages) {
8029 [packages radixSortUsingSelector:@selector(recent)];
8033 - (void) useFilter:(UISegmentedControl *)segmented {
8034 NSInteger selected([segmented selectedSegmentIndex]);
8036 return [self useRecent];
8037 bool simple(selected == 0);
8040 @synchronized (self) {
8041 [self setFilter:[=](Package *package) {
8042 return ![package uninstalled] && package->role_ <= (simple ? 1 : 3);
8045 [self setSorter:nullptr];
8048 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
8050 return [super sectionsForPackages:packages];
8052 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterLongStyle, kCFDateFormatterNoStyle));
8054 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
8055 Section *section(nil);
8058 for (size_t offset(0), count([packages count]); offset != count; ++offset) {
8059 Package *package([packages objectAtIndex:offset]);
8061 time_t upgraded([package upgraded]);
8062 if (upgraded < 1168364520)
8065 upgraded -= upgraded % (60 * 60 * 24);
8067 if (section == nil || upgraded != last) {
8072 continue; // XXX: name = UCLocalize("...");
8074 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:upgraded]);
8078 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
8079 [sections addObject:section];
8082 [section addToCount];
8085 CFRelease(formatter);
8089 - (id) initWithDatabase:(Database *)database {
8090 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED")]) != nil) {
8091 UISegmentedControl *segmented([[[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:UCLocalize("USER"), UCLocalize("EXPERT"), UCLocalize("RECENT"), nil]] autorelease]);
8092 [segmented setSelectedSegmentIndex:0];
8093 [segmented setSegmentedControlStyle:UISegmentedControlStyleBar];
8094 [[self navigationItem] setTitleView:segmented];
8096 [segmented addTarget:self action:@selector(modeChanged:) forEvents:UIControlEventValueChanged];
8097 [self useFilter:segmented];
8099 [self queueStatusDidChange];
8104 - (void) queueButtonClicked {
8109 - (void) queueStatusDidChange {
8112 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8113 initWithTitle:UCLocalize("QUEUE")
8114 style:UIBarButtonItemStyleDone
8116 action:@selector(queueButtonClicked)
8119 [[self navigationItem] setRightBarButtonItem:nil];
8124 - (void) modeChanged:(UISegmentedControl *)segmented {
8125 [self useFilter:segmented];
8132 /* Source Cell {{{ */
8133 @interface SourceCell : CyteTableViewCell <
8134 CyteTableViewCellDelegate,
8137 _H<Source, 1> source_;
8140 _H<NSString> origin_;
8141 _H<NSString> label_;
8142 _H<UIActivityIndicatorView> indicator_;
8145 - (void) setSource:(Source *)source;
8146 - (void) setFetch:(NSNumber *)fetch;
8150 @implementation SourceCell
8152 - (void) _setImage:(NSArray *)data {
8153 if ([url_ isEqual:[data objectAtIndex:0]]) {
8154 icon_ = [data objectAtIndex:1];
8155 [content_ setNeedsDisplay];
8159 - (void) _setSource:(NSURL *) url {
8160 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8162 if (NSData *data = [NSURLConnection
8163 sendSynchronousRequest:[NSURLRequest
8165 cachePolicy:NSURLRequestUseProtocolCachePolicy
8169 returningResponse:NULL
8172 if (UIImage *image = [UIImage imageWithData:data])
8173 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
8178 - (void) setSource:(Source *)source {
8180 [source_ setDelegate:self];
8182 [self setFetch:[NSNumber numberWithBool:[source_ fetch]]];
8184 icon_ = [UIImage imageNamed:@"unknown.png"];
8186 origin_ = [source name];
8187 label_ = [source rooturi];
8189 [content_ setNeedsDisplay];
8191 url_ = [source iconURL];
8192 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
8195 - (void) setAllSource {
8197 [indicator_ stopAnimating];
8199 icon_ = [UIImage imageNamed:@"folder.png"];
8200 origin_ = UCLocalize("ALL_SOURCES");
8201 label_ = UCLocalize("ALL_SOURCES_EX");
8202 [content_ setNeedsDisplay];
8205 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8206 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8207 UIView *content([self contentView]);
8208 CGRect bounds([content bounds]);
8210 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8211 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8212 [content_ setBackgroundColor:[UIColor whiteColor]];
8213 [content addSubview:content_];
8215 [content_ setDelegate:self];
8216 [content_ setOpaque:YES];
8218 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGraySmall] autorelease];
8219 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin];// | UIViewAutoresizingFlexibleBottomMargin];
8220 [content addSubview:indicator_];
8222 [[content_ layer] setContentsGravity:kCAGravityTopLeft];
8226 - (void) layoutSubviews {
8227 [super layoutSubviews];
8229 UIView *content([self contentView]);
8230 CGRect bounds([content bounds]);
8232 CGRect frame([indicator_ frame]);
8233 frame.origin.x = bounds.size.width - frame.size.width;
8234 frame.origin.y = Retina((bounds.size.height - frame.size.height) / 2);
8236 if (kCFCoreFoundationVersionNumber < 800)
8237 frame.origin.x -= 8;
8238 [indicator_ setFrame:frame];
8241 - (NSString *) accessibilityLabel {
8245 - (void) drawContentRect:(CGRect)rect {
8246 bool highlighted(highlighted_);
8247 float width(rect.size.width);
8251 rect.size = [(UIImage *) icon_ size];
8253 while (rect.size.width > 32 || rect.size.height > 32) {
8254 rect.size.width /= 2;
8255 rect.size.height /= 2;
8258 rect.origin.x = 26 - rect.size.width / 2;
8259 rect.origin.y = 26 - rect.size.height / 2;
8261 [icon_ drawInRect:Retina(rect)];
8264 if (highlighted && kCFCoreFoundationVersionNumber < 800)
8269 [origin_ drawAtPoint:CGPointMake(52, 8) forWidth:(width - 49) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
8273 [label_ drawAtPoint:CGPointMake(52, 29) forWidth:(width - 49) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
8276 - (void) setFetch:(NSNumber *)fetch {
8277 if ([fetch boolValue])
8278 [indicator_ startAnimating];
8280 [indicator_ stopAnimating];
8285 /* Sources Controller {{{ */
8286 @interface SourcesController : CyteViewController <
8287 UITableViewDataSource,
8290 _transient Database *database_;
8293 _H<UITableView, 2> list_;
8294 _H<NSMutableArray> sources_;
8298 _H<UIProgressHUD> hud_;
8301 NSURLConnection *trivial_bz2_;
8302 NSURLConnection *trivial_gz_;
8307 - (id) initWithDatabase:(Database *)database;
8308 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated;
8312 @implementation SourcesController
8314 - (void) _releaseConnection:(NSURLConnection *)connection {
8315 if (connection != nil) {
8316 [connection cancel];
8317 //[connection setDelegate:nil];
8318 [connection release];
8323 [self _releaseConnection:trivial_gz_];
8324 [self _releaseConnection:trivial_bz2_];
8329 - (NSURL *) navigationURL {
8330 return [NSURL URLWithString:@"cydia://sources"];
8333 - (void) viewDidAppear:(BOOL)animated {
8334 [super viewDidAppear:animated];
8335 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8338 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8342 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8344 return UCLocalize("INDIVIDUAL_SOURCES");
8348 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8351 case 1: return [sources_ count];
8356 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8357 @synchronized (database_) {
8358 if ([database_ era] != era_)
8360 if ([indexPath section] != 1)
8362 NSUInteger index([indexPath row]);
8363 if (index >= [sources_ count])
8365 return [sources_ objectAtIndex:index];
8368 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8369 static NSString *cellIdentifier = @"SourceCell";
8371 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8372 if (cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8373 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8375 Source *source([self sourceAtIndexPath:indexPath]);
8377 [cell setAllSource];
8379 [cell setSource:source];
8384 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8385 SectionsController *controller([[[SectionsController alloc]
8386 initWithDatabase:database_
8387 source:[self sourceAtIndexPath:indexPath]
8390 [controller setDelegate:delegate_];
8391 [[self navigationController] pushViewController:controller animated:YES];
8394 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8395 if ([indexPath section] != 1)
8397 Source *source = [self sourceAtIndexPath:indexPath];
8398 return [source record] != nil;
8401 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8402 _assert([indexPath section] == 1);
8403 if (editingStyle == UITableViewCellEditingStyleDelete) {
8404 Source *source = [self sourceAtIndexPath:indexPath];
8405 if (source == nil) return;
8407 [Sources_ removeObjectForKey:[source key]];
8410 [delegate_ _saveConfig];
8411 [delegate_ reloadDataWithInvocation:nil];
8415 - (void) tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath {
8416 [self updateButtonsForEditingStatusAnimated:YES];
8420 [delegate_ addTrivialSource:href_];
8423 [delegate_ syncData];
8426 - (NSString *) getWarning {
8427 NSString *href(href_);
8428 NSRange colon([href rangeOfString:@"://"]);
8429 if (colon.location != NSNotFound)
8430 href = [href substringFromIndex:(colon.location + 3)];
8431 href = [href stringByAddingPercentEscapes];
8432 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8434 NSURL *url([NSURL URLWithString:href]);
8436 NSStringEncoding encoding;
8437 NSError *error(nil);
8439 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8440 return [warning length] == 0 ? nil : warning;
8444 - (void) _endConnection:(NSURLConnection *)connection {
8445 // XXX: the memory management in this method is horribly awkward
8447 NSURLConnection **field = NULL;
8448 if (connection == trivial_bz2_)
8449 field = &trivial_bz2_;
8450 else if (connection == trivial_gz_)
8451 field = &trivial_gz_;
8452 _assert(field != NULL);
8453 [connection release];
8457 trivial_bz2_ == nil &&
8460 NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil);
8462 [delegate_ releaseNetworkActivityIndicator];
8464 [delegate_ removeProgressHUD:hud_];
8468 if (warning != nil) {
8469 UIAlertView *alert = [[[UIAlertView alloc]
8470 initWithTitle:UCLocalize("SOURCE_WARNING")
8473 cancelButtonTitle:UCLocalize("CANCEL")
8475 UCLocalize("ADD_ANYWAY"),
8479 [alert setContext:@"warning"];
8480 [alert setNumberOfRows:1];
8483 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
8489 } else if (error_ != nil) {
8490 UIAlertView *alert = [[[UIAlertView alloc]
8491 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8492 message:[error_ localizedDescription]
8494 cancelButtonTitle:UCLocalize("OK")
8495 otherButtonTitles:nil
8498 [alert setContext:@"urlerror"];
8503 UIAlertView *alert = [[[UIAlertView alloc]
8504 initWithTitle:UCLocalize("NOT_REPOSITORY")
8505 message:UCLocalize("NOT_REPOSITORY_EX")
8507 cancelButtonTitle:UCLocalize("OK")
8508 otherButtonTitles:nil
8511 [alert setContext:@"trivial"];
8521 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8522 switch ([response statusCode]) {
8528 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8529 lprintf("connection:\"%s\" didFailWithError:\"%s\"\n", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8531 [self _endConnection:connection];
8534 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8535 [self _endConnection:connection];
8538 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8539 NSURL *url([NSURL URLWithString:href]);
8541 NSMutableURLRequest *request = [NSMutableURLRequest
8543 cachePolicy:NSURLRequestUseProtocolCachePolicy
8547 [request setHTTPMethod:method];
8549 if (Machine_ != NULL)
8550 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8552 if (UniqueID_ != nil)
8553 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8555 if ([url isCydiaSecure]) {
8556 if (UniqueID_ != nil)
8557 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
8560 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8563 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8564 NSString *context([alert context]);
8566 if ([context isEqualToString:@"source"]) {
8569 NSString *href = [[alert textField] text];
8571 static RegEx href_r("(http(s?)://|file:///)[^# ]*");
8572 if (!href_r(href)) {
8573 UIAlertView *alert = [[[UIAlertView alloc]
8574 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("INVALID_URL")]
8575 message:UCLocalize("INVALID_URL_EX")
8577 cancelButtonTitle:UCLocalize("OK")
8578 otherButtonTitles:nil
8581 [alert setContext:@"badurl"];
8587 if (![href hasSuffix:@"/"])
8588 href_ = [href stringByAppendingString:@"/"];
8592 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8593 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8597 // XXX: this is stupid
8598 hud_ = [delegate_ addProgressHUD];
8599 [hud_ setText:UCLocalize("VERIFYING_URL")];
8600 [delegate_ retainNetworkActivityIndicator];
8609 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8610 } else if ([context isEqualToString:@"trivial"])
8611 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8612 else if ([context isEqualToString:@"urlerror"])
8613 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8614 else if ([context isEqualToString:@"warning"]) {
8617 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
8626 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8630 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated {
8631 BOOL editing([list_ isEditing]);
8634 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8635 initWithTitle:UCLocalize("ADD")
8636 style:UIBarButtonItemStylePlain
8638 action:@selector(addButtonClicked)
8639 ] autorelease] animated:animated];
8640 else if ([delegate_ updating])
8641 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8642 initWithTitle:UCLocalize("CANCEL")
8643 style:UIBarButtonItemStyleDone
8645 action:@selector(cancelButtonClicked)
8646 ] autorelease] animated:animated];
8648 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8649 initWithTitle:UCLocalize("REFRESH")
8650 style:UIBarButtonItemStylePlain
8652 action:@selector(refreshButtonClicked)
8653 ] autorelease] animated:animated];
8655 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8656 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8657 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8659 action:@selector(editButtonClicked)
8660 ] autorelease] animated:animated];
8664 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease];
8665 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8666 [list_ setRowHeight:53];
8667 [(UITableView *) list_ setDataSource:self];
8668 [list_ setDelegate:self];
8669 [self setView:list_];
8672 - (void) viewDidLoad {
8673 [super viewDidLoad];
8675 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8676 [self updateButtonsForEditingStatusAnimated:NO];
8679 - (void) viewWillAppear:(BOOL)animated {
8680 [super viewWillAppear:animated];
8682 [list_ setEditing:NO];
8683 [self updateButtonsForEditingStatusAnimated:NO];
8686 - (void) releaseSubviews {
8691 [super releaseSubviews];
8694 - (id) initWithDatabase:(Database *)database {
8695 if ((self = [super init]) != nil) {
8696 database_ = database;
8700 - (void) reloadData {
8702 [self updateButtonsForEditingStatusAnimated:YES];
8704 @synchronized (database_) {
8705 era_ = [database_ era];
8707 sources_ = [NSMutableArray arrayWithCapacity:16];
8708 [sources_ addObjectsFromArray:[database_ sources]];
8710 [sources_ sortUsingSelector:@selector(compareByName:)];
8713 int count([sources_ count]);
8715 for (int i = 0; i != count; i++) {
8716 if ([[sources_ objectAtIndex:i] record] == nil)
8724 - (void) showAddSourcePrompt {
8725 UIAlertView *alert = [[[UIAlertView alloc]
8726 initWithTitle:UCLocalize("ENTER_APT_URL")
8729 cancelButtonTitle:UCLocalize("CANCEL")
8731 UCLocalize("ADD_SOURCE"),
8735 [alert setContext:@"source"];
8737 [alert setNumberOfRows:1];
8738 [alert addTextFieldWithValue:@"http://" label:@""];
8740 UITextInputTraits *traits = [[alert textField] textInputTraits];
8741 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8742 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8743 [traits setKeyboardType:UIKeyboardTypeURL];
8744 // XXX: UIReturnKeyDone
8745 [traits setReturnKeyType:UIReturnKeyNext];
8750 - (void) addButtonClicked {
8751 [self showAddSourcePrompt];
8754 - (void) refreshButtonClicked {
8755 if ([delegate_ requestUpdate])
8756 [self updateButtonsForEditingStatusAnimated:YES];
8759 - (void) cancelButtonClicked {
8760 [delegate_ cancelUpdate];
8763 - (void) editButtonClicked {
8764 [list_ setEditing:![list_ isEditing] animated:YES];
8765 [self updateButtonsForEditingStatusAnimated:YES];
8771 /* Stash Controller {{{ */
8772 @interface StashController : CyteViewController {
8773 _H<UIActivityIndicatorView> spinner_;
8774 _H<UILabel> status_;
8775 _H<UILabel> caption_;
8780 @implementation StashController
8783 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8784 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8785 [self setView:view];
8787 [view setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8789 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8790 CGRect spinrect = [spinner_ frame];
8791 spinrect.origin.x = Retina([[self view] frame].size.width / 2 - spinrect.size.width / 2);
8792 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8793 [spinner_ setFrame:spinrect];
8794 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8795 [view addSubview:spinner_];
8796 [spinner_ startAnimating];
8799 captrect.size.width = [[self view] frame].size.width;
8800 captrect.size.height = 40.0f;
8801 captrect.origin.x = 0;
8802 captrect.origin.y = Retina([[self view] frame].size.height / 2 - captrect.size.height * 2);
8803 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8804 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8805 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8806 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8807 [caption_ setTextColor:[UIColor whiteColor]];
8808 [caption_ setBackgroundColor:[UIColor clearColor]];
8809 [caption_ setShadowColor:[UIColor blackColor]];
8810 [caption_ setTextAlignment:NSTextAlignmentCenter];
8811 [view addSubview:caption_];
8814 statusrect.size.width = [[self view] frame].size.width;
8815 statusrect.size.height = 30.0f;
8816 statusrect.origin.x = 0;
8817 statusrect.origin.y = Retina([[self view] frame].size.height / 2 - statusrect.size.height);
8818 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8819 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8820 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8821 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8822 [status_ setTextColor:[UIColor whiteColor]];
8823 [status_ setBackgroundColor:[UIColor clearColor]];
8824 [status_ setShadowColor:[UIColor blackColor]];
8825 [status_ setTextAlignment:NSTextAlignmentCenter];
8826 [view addSubview:status_];
8829 - (void) releaseSubviews {
8834 [super releaseSubviews];
8840 @interface CYURLCache : SDURLCache {
8845 @implementation CYURLCache
8847 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8850 else if ([event isEqualToString:@"no-cache"])
8852 else if ([event isEqualToString:@"store"])
8854 else if ([event isEqualToString:@"invalid"])
8856 else if ([event isEqualToString:@"memory"])
8858 else if ([event isEqualToString:@"disk"])
8860 else if ([event isEqualToString:@"miss"])
8863 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8867 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
8868 if (NSURLResponse *response = [cached response])
8869 if (NSString *mime = [response MIMEType])
8870 if ([mime isEqualToString:@"text/cache-manifest"]) {
8871 NSURL *url([response URL]);
8874 NSLog(@"###: %@", [url absoluteString]);
8877 @synchronized (HostConfig_) {
8878 [CachedURLs_ addObject:url];
8882 [super storeCachedResponse:cached forRequest:request];
8885 - (void) createDiskCachePath {
8886 [super createDiskCachePath];
8891 @interface Cydia : UIApplication <
8892 ConfirmationControllerDelegate,
8896 _H<UIWindow> window_;
8897 _H<CydiaTabBarController> tabbar_;
8898 _H<CyteTabBarController> emulated_;
8899 _H<AppCacheController> appcache_;
8901 _H<NSMutableArray> essential_;
8902 _H<NSMutableArray> broken_;
8904 Database *database_;
8906 _H<NSURL> starturl_;
8911 _H<StashController> stash_;
8920 @implementation Cydia
8922 - (void) lockSuspend {
8923 if (locked_++ == 0) {
8924 if ($SBSSetInterceptsMenuButtonForever != NULL)
8925 (*$SBSSetInterceptsMenuButtonForever)(true);
8927 [self setIdleTimerDisabled:YES];
8931 - (void) unlockSuspend {
8932 if (--locked_ == 0) {
8933 [self setIdleTimerDisabled:NO];
8935 if ($SBSSetInterceptsMenuButtonForever != NULL)
8936 (*$SBSSetInterceptsMenuButtonForever)(false);
8940 - (void) beginUpdate {
8941 [tabbar_ beginUpdate];
8944 - (void) cancelUpdate {
8945 [tabbar_ cancelUpdate];
8948 - (bool) requestUpdate {
8949 if (IsReachable("cydia.saurik.com")) {
8953 UIAlertView *alert = [[[UIAlertView alloc]
8954 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("REFRESH")]
8955 message:@"Host Unreachable" // XXX: Localize
8957 cancelButtonTitle:UCLocalize("OK")
8958 otherButtonTitles:nil
8961 [alert setContext:@"norefresh"];
8969 return [tabbar_ updating];
8973 if ([broken_ count] != 0) {
8974 int count = [broken_ count];
8976 UIAlertView *alert = [[[UIAlertView alloc]
8977 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8978 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8980 cancelButtonTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("FORCIBLY_CLEAR"), UCLocalize("UNSAFE")]
8982 UCLocalize("TEMPORARY_IGNORE"),
8986 [alert setContext:@"fixhalf"];
8987 [alert setNumberOfRows:2];
8989 } else if (!Ignored_ && [essential_ count] != 0) {
8990 int count = [essential_ count];
8992 UIAlertView *alert = [[[UIAlertView alloc]
8993 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8994 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8996 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8998 UCLocalize("UPGRADE_ESSENTIAL"),
8999 UCLocalize("COMPLETE_UPGRADE"),
9003 [alert setContext:@"upgrade"];
9008 - (void) returnToCydia {
9012 - (void) _saveConfig {
9013 @synchronized (database_) {
9020 NSString *error(nil);
9022 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
9024 NSError *error(nil);
9025 if (!_root([data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error]))
9026 NSLog(@"failure to save metadata data: %@", error);
9031 NSLog(@"failure to serialize metadata: %@", error);
9035 CydiaWriteSources();
9038 // Navigation controller for the queuing badge.
9039 - (UINavigationController *) queueNavigationController {
9040 NSArray *controllers = [tabbar_ viewControllers];
9041 return [controllers objectAtIndex:3];
9044 - (void) unloadData {
9045 [tabbar_ unloadData];
9048 - (void) _updateData {
9052 UINavigationController *navigation = [self queueNavigationController];
9054 id queuedelegate = nil;
9055 if ([[navigation viewControllers] count] > 0)
9056 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9058 [queuedelegate queueStatusDidChange];
9059 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9062 - (void) _refreshIfPossible:(NSDate *)update {
9063 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9065 bool recently = false;
9066 if (update != nil) {
9067 NSTimeInterval interval([update timeIntervalSinceNow]);
9068 if (interval > -(15*60))
9072 // Don't automatic refresh if:
9073 // - We already refreshed recently.
9074 // - We already auto-refreshed this launch.
9075 // - Auto-refresh is disabled.
9076 // - Cydia's server is not reachable
9077 if (recently || loaded_ || ManualRefresh || !IsReachable("cydia.saurik.com")) {
9078 // If we are cancelling, we need to make sure it knows it's already loaded.
9081 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9083 // We are going to load, so remember that.
9086 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
9092 - (void) refreshIfPossible {
9093 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
9096 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9097 _profile(reloadDataWithInvocation)
9098 @synchronized (self) {
9099 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9101 [hud setText:UCLocalize("RELOADING_DATA")];
9103 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9107 [essential_ removeAllObjects];
9108 [broken_ removeAllObjects];
9110 _profile(reloadDataWithInvocation$Essential)
9111 NSArray *packages([database_ packages]);
9112 for (Package *package in packages) {
9114 [broken_ addObject:package];
9115 if ([package upgradableAndEssential:YES] && ![package ignored]) {
9116 if ([package essential] && [package installed] != nil)
9117 [essential_ addObject:package];
9123 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9126 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9127 [changesItem setBadgeValue:badge];
9128 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9129 [self setApplicationIconBadgeNumber:changes];
9132 [changesItem setBadgeValue:nil];
9133 [changesItem setAnimatedBadge:NO];
9134 [self setApplicationIconBadgeNumber:0];
9141 [self removeProgressHUD:hud];
9148 - (void) updateData {
9152 - (void) updateDataAndLoad {
9154 if ([database_ progressDelegate] == nil)
9160 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9163 - (void) disemulate {
9164 if (emulated_ == nil)
9167 if ([window_ respondsToSelector:@selector(setRootViewController:)])
9168 [window_ setRootViewController:tabbar_];
9170 [window_ addSubview:[tabbar_ view]];
9171 [[emulated_ view] removeFromSuperview];
9175 [window_ setUserInteractionEnabled:YES];
9178 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9179 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9181 UIViewController *parent;
9182 if (emulated_ == nil)
9192 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9193 [parent presentModalViewController:navigation animated:YES];
9196 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9197 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9199 if (navigation != nil)
9200 [navigation pushViewController:progress animated:YES];
9202 [self presentModalViewController:progress force:YES];
9204 [progress invoke:invocation withTitle:title];
9208 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9209 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9212 - (void) repairWithInvocation:(NSInvocation *)invocation {
9214 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9218 - (void) repairWithSelector:(SEL)selector {
9219 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9222 - (void) reloadData {
9223 [self reloadDataWithInvocation:nil];
9224 if ([database_ progressDelegate] == nil)
9230 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9233 - (void) addSource:(NSDictionary *) source {
9234 CydiaAddSource(source);
9237 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9238 CydiaAddSource(href, distribution, sections);
9241 - (void) addTrivialSource:(NSString *)href {
9242 CydiaAddSource(href, @"./");
9245 - (void) updateValues {
9250 pkgProblemResolver *resolver = [database_ resolver];
9252 resolver->InstallProtect();
9253 if (!resolver->Resolve(true))
9258 // XXX: this is a really crappy way of doing this.
9259 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9260 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9261 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9262 if ([tabbar_ updating])
9263 [tabbar_ cancelUpdate];
9265 if (![database_ prepare])
9268 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9269 [page setDelegate:self];
9270 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9273 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9274 [tabbar_ presentModalViewController:confirm_ animated:YES];
9280 @synchronized (self) {
9285 - (void) clearPackage:(Package *)package {
9286 @synchronized (self) {
9293 - (void) installPackages:(NSArray *)packages {
9294 @synchronized (self) {
9295 for (Package *package in packages)
9302 - (void) installPackage:(Package *)package {
9303 @synchronized (self) {
9310 - (void) removePackage:(Package *)package {
9311 @synchronized (self) {
9318 - (void) distUpgrade {
9319 @synchronized (self) {
9320 if (![database_ upgrade])
9329 if (UpgradeCydia_ && Finish_ > 0) {
9331 system("su -c /usr/bin/uicache mobile");
9333 system("/usr/bin/uicache");
9340 UIProgressHUD *hud([self addProgressHUD]);
9341 [hud setText:UCLocalize("LOADING")];
9342 [self yieldToSelector:@selector(_uicache)];
9343 [self removeProgressHUD:hud];
9347 [database_ perform];
9348 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9349 [self performSelectorOnMainThread:@selector(uicache) withObject:nil waitUntilDone:YES];
9352 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9355 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9356 [self unlockSuspend];
9359 - (void) retainNetworkActivityIndicator {
9360 if (activity_++ == 0)
9361 [self setNetworkActivityIndicatorVisible:YES];
9364 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9368 - (void) releaseNetworkActivityIndicator {
9369 if (--activity_ == 0)
9370 [self setNetworkActivityIndicatorVisible:NO];
9373 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9378 - (void) cancelAndClear:(bool)clear {
9379 @synchronized (self) {
9391 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9392 NSString *context([alert context]);
9394 if ([context isEqualToString:@"conffile"]) {
9395 FILE *input = [database_ input];
9396 if (button == [alert cancelButtonIndex])
9397 fprintf(input, "N\n");
9398 else if (button == [alert firstOtherButtonIndex])
9399 fprintf(input, "Y\n");
9402 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9403 } else if ([context isEqualToString:@"fixhalf"]) {
9404 if (button == [alert cancelButtonIndex]) {
9405 @synchronized (self) {
9406 for (Package *broken in (id) broken_) {
9408 NSString *id = [broken id];
9410 system([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /bin/rm -f"
9411 " /var/lib/dpkg/info/%@.prerm"
9412 " /var/lib/dpkg/info/%@.postrm"
9413 " /var/lib/dpkg/info/%@.preinst"
9414 " /var/lib/dpkg/info/%@.postinst"
9415 " /var/lib/dpkg/info/%@.extrainst_"
9416 , id, id, id, id, id] UTF8String]);
9422 } else if (button == [alert firstOtherButtonIndex]) {
9423 [broken_ removeAllObjects];
9427 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9428 } else if ([context isEqualToString:@"upgrade"]) {
9429 if (button == [alert firstOtherButtonIndex]) {
9430 @synchronized (self) {
9431 for (Package *essential in (id) essential_)
9432 [essential install];
9437 } else if (button == [alert firstOtherButtonIndex] + 1) {
9439 } else if (button == [alert cancelButtonIndex]) {
9443 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9447 - (void) system:(NSString *)command {
9448 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9451 system([command UTF8String]);
9457 - (void) applicationWillSuspend {
9459 [super applicationWillSuspend];
9462 - (BOOL) isSafeToSuspend {
9465 NSLog(@"isSafeToSuspend: locked_ != 0");
9470 if ([tabbar_ modalViewController] != nil)
9473 // Use external process status API internally.
9474 // This is probably a really bad idea.
9475 // XXX: what is the point of this? does this solve anything at all?
9476 uint64_t status = 0;
9478 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9479 notify_get_state(notify_token, &status);
9480 notify_cancel(notify_token);
9485 NSLog(@"isSafeToSuspend: status != 0");
9491 NSLog(@"isSafeToSuspend: -> true");
9496 - (void) suspendReturningToLastApp:(BOOL)returning {
9497 if ([self isSafeToSuspend])
9498 [super suspendReturningToLastApp:returning];
9502 if ([self isSafeToSuspend])
9506 - (void) applicationSuspend {
9507 if ([self isSafeToSuspend])
9508 [super applicationSuspend];
9511 - (void) applicationSuspend:(__GSEvent *)event {
9512 if ([self isSafeToSuspend])
9513 [super applicationSuspend:event];
9516 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9517 if ([self isSafeToSuspend])
9518 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9521 - (void) _setSuspended:(BOOL)value {
9522 if ([self isSafeToSuspend])
9523 [super _setSuspended:value];
9526 - (UIProgressHUD *) addProgressHUD {
9527 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9528 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9530 [window_ setUserInteractionEnabled:NO];
9532 UIViewController *target(tabbar_);
9533 if (UIViewController *modal = [target modalViewController])
9536 [hud showInView:[target view]];
9542 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9543 [self unlockSuspend];
9545 [hud removeFromSuperview];
9546 [window_ setUserInteractionEnabled:YES];
9549 - (CyteViewController *) pageForPackage:(NSString *)name withReferrer:(NSString *)referrer {
9550 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name withReferrer:referrer] autorelease];
9553 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external withReferrer:(NSString *)referrer {
9554 NSString *scheme([[url scheme] lowercaseString]);
9555 if ([[url absoluteString] length] <= [scheme length] + 3)
9557 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9558 NSArray *components([path componentsSeparatedByString:@"/"]);
9560 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"]) {
9561 CyteViewController *controller([self pageForPackage:[components objectAtIndex:1] withReferrer:referrer]);
9562 if (controller != nil)
9563 [controller setDelegate:self];
9567 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9570 NSString *base([components objectAtIndex:0]);
9572 CyteViewController *controller = nil;
9574 if ([base isEqualToString:@"url"]) {
9575 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9576 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9577 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9578 } else if (!external && [components count] == 1) {
9579 if ([base isEqualToString:@"sources"]) {
9580 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9583 if ([base isEqualToString:@"home"]) {
9584 controller = [[[HomeController alloc] init] autorelease];
9587 if ([base isEqualToString:@"sections"]) {
9588 controller = [[[SectionsController alloc] initWithDatabase:database_ source:nil] autorelease];
9591 if ([base isEqualToString:@"search"]) {
9592 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9595 if ([base isEqualToString:@"changes"]) {
9596 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9599 if ([base isEqualToString:@"installed"]) {
9600 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9602 } else if ([components count] == 2) {
9603 NSString *argument = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9605 if ([base isEqualToString:@"package"]) {
9606 controller = [self pageForPackage:argument withReferrer:referrer];
9609 if (!external && [base isEqualToString:@"search"]) {
9610 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9613 if (!external && [base isEqualToString:@"sections"]) {
9614 if ([argument isEqualToString:@"all"] || [argument isEqualToString:@"*"])
9616 controller = [[[SectionController alloc] initWithDatabase:database_ source:nil section:argument] autorelease];
9619 if (!external && [base isEqualToString:@"sources"]) {
9620 if ([argument isEqualToString:@"add"]) {
9621 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9622 [(SourcesController *)controller showAddSourcePrompt];
9624 Source *source([database_ sourceWithKey:argument]);
9625 controller = [[[SectionsController alloc] initWithDatabase:database_ source:source] autorelease];
9629 if (!external && [base isEqualToString:@"launch"]) {
9630 [self launchApplicationWithIdentifier:argument suspended:NO];
9633 } else if (!external && [components count] == 3) {
9634 NSString *arg1 = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9635 NSString *arg2 = [[components objectAtIndex:2] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9637 if ([base isEqualToString:@"package"]) {
9638 if ([arg2 isEqualToString:@"settings"]) {
9639 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9640 } else if ([arg2 isEqualToString:@"files"]) {
9641 if (Package *package = [database_ packageWithName:arg1]) {
9642 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9643 [(FileTable *)controller setPackage:package];
9648 if ([base isEqualToString:@"sections"]) {
9649 Source *source([arg1 isEqualToString:@"*"] ? nil : [database_ sourceWithKey:arg1]);
9650 NSString *section([arg2 isEqualToString:@"*"] ? nil : arg2);
9651 controller = [[[SectionController alloc] initWithDatabase:database_ source:source section:section] autorelease];
9655 [controller setDelegate:self];
9659 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9660 CyteViewController *page([self pageForURL:url forExternal:external withReferrer:nil]);
9663 [tabbar_ setUnselectedViewController:page];
9668 - (void) applicationOpenURL:(NSURL *)url {
9669 [super applicationOpenURL:url];
9674 [self openCydiaURL:url forExternal:YES];
9677 - (void) applicationWillResignActive:(UIApplication *)application {
9678 // Stop refreshing if you get a phone call or lock the device.
9679 if ([tabbar_ updating])
9680 [tabbar_ cancelUpdate];
9682 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9683 [super applicationWillResignActive:application];
9686 - (void) saveState {
9687 [[NSDictionary dictionaryWithObjectsAndKeys:
9688 @"InterfaceState", [tabbar_ navigationURLCollection],
9689 @"LastClosed", [NSDate date],
9690 @"InterfaceIndex", [NSNumber numberWithInt:[tabbar_ selectedIndex]],
9691 nil] writeToFile:@ SavedState_ atomically:YES];
9696 - (void) applicationWillTerminate:(UIApplication *)application {
9700 - (void) applicationDidEnterBackground:(UIApplication *)application {
9701 if (kCFCoreFoundationVersionNumber < 1000 && [self isSafeToSuspend])
9702 return [self terminateWithSuccess];
9703 Backgrounded_ = [NSDate date];
9707 - (void) applicationWillEnterForeground:(UIApplication *)application {
9708 if (Backgrounded_ == nil)
9711 NSTimeInterval interval([Backgrounded_ timeIntervalSinceNow]);
9713 if (interval <= -(30*60)) {
9714 [tabbar_ setSelectedIndex:0];
9715 [[[tabbar_ viewControllers] objectAtIndex:0] popToRootViewControllerAnimated:NO];
9718 if (interval <= -(15*60)) {
9719 if (IsReachable("cydia.saurik.com")) {
9720 [tabbar_ beginUpdate];
9721 [appcache_ reloadURLWithCache:YES];
9726 - (void) setConfigurationData:(NSString *)data {
9727 static RegEx conffile_r("'(.*)' '(.*)' ([01]) ([01])");
9729 if (!conffile_r(data)) {
9730 lprintf("E:invalid conffile\n");
9734 NSString *ofile = conffile_r[1];
9735 //NSString *nfile = conffile_r[2];
9737 UIAlertView *alert = [[[UIAlertView alloc]
9738 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9739 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9741 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9743 UCLocalize("ACCEPT_NEW_COPY"),
9744 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9748 [alert setContext:@"conffile"];
9749 [alert setNumberOfRows:2];
9753 - (void) addStashController {
9755 stash_ = [[[StashController alloc] init] autorelease];
9756 [window_ addSubview:[stash_ view]];
9759 - (void) removeStashController {
9760 [[stash_ view] removeFromSuperview];
9762 [self unlockSuspend];
9766 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9767 UpdateExternalStatus(1);
9768 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/cydo /usr/libexec/cydia/free.sh"];
9769 UpdateExternalStatus(0);
9771 [self removeStashController];
9773 pid_t pid(ExecFork());
9775 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9776 perror("launchctl stop");
9782 - (void) setupViewControllers {
9783 tabbar_ = [[[CydiaTabBarController alloc] initWithDatabase:database_] autorelease];
9785 NSMutableArray *items;
9786 if (kCFCoreFoundationVersionNumber < 800) {
9787 items = [NSMutableArray arrayWithObjects:
9788 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage imageNamed:@"home.png"] tag:0] autorelease],
9789 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage imageNamed:@"install.png"] tag:0] autorelease],
9790 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage imageNamed:@"changes.png"] tag:0] autorelease],
9791 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage imageNamed:@"manage.png"] tag:0] autorelease],
9792 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage imageNamed:@"search.png"] tag:0] autorelease],
9795 items = [NSMutableArray arrayWithObjects:
9796 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage imageNamed:@"home7.png"] selectedImage:[UIImage imageNamed:@"home7s.png"]] autorelease],
9797 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage imageNamed:@"install7.png"] selectedImage:[UIImage imageNamed:@"install7s.png"]] autorelease],
9798 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage imageNamed:@"changes7.png"] selectedImage:[UIImage imageNamed:@"changes7s.png"]] autorelease],
9799 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage imageNamed:@"manage7.png"] selectedImage:[UIImage imageNamed:@"manage7s.png"]] autorelease],
9800 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage imageNamed:@"search7.png"] selectedImage:[UIImage imageNamed:@"search7s.png"]] autorelease],
9804 NSMutableArray *controllers([NSMutableArray array]);
9805 for (UITabBarItem *item in items) {
9806 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9807 [controller setTabBarItem:item];
9808 [controllers addObject:controller];
9810 [tabbar_ setViewControllers:controllers];
9812 [tabbar_ setUpdateDelegate:self];
9815 - (void) _sendMemoryWarningNotification {
9816 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: maybe 4_0?
9817 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationMemoryWarningNotification" object:[UIApplication sharedApplication]];
9819 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
9822 - (void) _sendMemoryWarningNotifications {
9824 [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO];
9830 - (void) applicationDidReceiveMemoryWarning:(UIApplication *)application {
9832 [[NSURLCache sharedURLCache] removeAllCachedResponses];
9835 - (void) applicationDidFinishLaunching:(id)unused {
9836 //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil];
9839 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9840 [self setApplicationSupportsShakeToEdit:NO];
9842 @synchronized (HostConfig_) {
9843 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9846 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9847 initWithMemoryCapacity:524288
9848 diskCapacity:10485760
9849 diskPath:Cache("SDURLCache")
9852 [CydiaWebViewController _initialize];
9854 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9856 // this would disallow http{,s} URLs from accessing this data
9857 //[WebView registerURLSchemeAsLocal:@"cydia"];
9859 Font12_ = [UIFont systemFontOfSize:12];
9860 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9861 Font14_ = [UIFont systemFontOfSize:14];
9862 Font18_ = [UIFont systemFontOfSize:18];
9863 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9864 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9866 essential_ = [NSMutableArray arrayWithCapacity:4];
9867 broken_ = [NSMutableArray arrayWithCapacity:4];
9869 // XXX: I really need this thing... like, seriously... I'm sorry
9870 appcache_ = [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] autorelease];
9871 [appcache_ reloadData];
9873 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9874 [window_ orderFront:self];
9875 [window_ makeKey:self];
9876 [window_ setHidden:NO];
9879 [self addStashController];
9880 // XXX: this would be much cleaner as a yieldToSelector:
9881 // that way the removeStashController could happen right here inline
9882 // we also could no longer require the useless stash_ field anymore
9883 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9888 int error(stat("/", &root));
9889 _assert(error != -1);
9891 #define Stash_(path) do { \
9892 struct stat folder; \
9893 int error(lstat((path), &folder)); \
9894 if (error != -1 && ( \
9895 folder.st_dev == root.st_dev && \
9896 S_ISDIR(folder.st_mode) \
9897 ) || error == -1 && ( \
9898 errno == ENOENT || \
9903 Stash_("/Applications");
9904 Stash_("/Library/Ringtones");
9905 Stash_("/Library/Wallpaper");
9906 //Stash_("/usr/bin");
9907 Stash_("/usr/include");
9908 Stash_("/usr/share");
9909 //Stash_("/var/lib");
9911 database_ = [Database sharedInstance];
9912 [database_ setDelegate:self];
9914 [window_ setUserInteractionEnabled:NO];
9915 [self setupViewControllers];
9917 CydiaLoadingViewController *loading([[[CydiaLoadingViewController alloc] init] autorelease]);
9918 UINavigationController *navigation([[[UINavigationController alloc] init] autorelease]);
9919 [navigation setViewControllers:[NSArray arrayWithObject:loading]];
9921 emulated_ = [[[CyteTabBarController alloc] init] autorelease];
9922 [emulated_ setViewControllers:[NSArray arrayWithObject:navigation]];
9923 [emulated_ setSelectedIndex:0];
9925 if ([emulated_ respondsToSelector:@selector(concealTabBarSelection)])
9926 [emulated_ concealTabBarSelection];
9928 if ([window_ respondsToSelector:@selector(setRootViewController:)])
9929 [window_ setRootViewController:emulated_];
9931 [window_ addSubview:[emulated_ view]];
9933 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9937 - (NSArray *) defaultStartPages {
9938 NSMutableArray *standard = [NSMutableArray array];
9939 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9940 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9941 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9942 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9943 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9949 if ([emulated_ modalViewController] != nil)
9950 [emulated_ dismissModalViewControllerAnimated:YES];
9951 [window_ setUserInteractionEnabled:NO];
9953 [self reloadDataWithInvocation:nil];
9954 [self refreshIfPossible];
9957 NSDictionary *state([NSDictionary dictionaryWithContentsOfFile:@ SavedState_]);
9959 int savedIndex = [[state objectForKey:@"InterfaceIndex"] intValue];
9960 NSArray *saved = [[[state objectForKey:@"InterfaceState"] mutableCopy] autorelease];
9961 int standardIndex = 0;
9962 NSArray *standard = [self defaultStartPages];
9969 NSDate *closed = [state objectForKey:@"LastClosed"];
9970 if (valid && closed != nil) {
9971 NSTimeInterval interval([closed timeIntervalSinceNow]);
9972 if (interval <= -(30*60))
9976 if (valid && [saved count] != [standard count])
9980 for (unsigned int i = 0; i < [standard count]; i++) {
9981 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9982 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9983 // but it's good enough for now.
9984 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9991 NSArray *items = nil;
9993 [tabbar_ setSelectedIndex:savedIndex];
9996 [tabbar_ setSelectedIndex:standardIndex];
10000 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
10001 NSArray *stack = [items objectAtIndex:tab];
10002 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
10003 NSMutableArray *current = [NSMutableArray array];
10005 for (unsigned int nav = 0; nav < [stack count]; nav++) {
10006 NSString *addr = [stack objectAtIndex:nav];
10007 NSURL *url = [NSURL URLWithString:addr];
10008 CyteViewController *page = [self pageForURL:url forExternal:NO withReferrer:nil];
10010 [current addObject:page];
10013 [navigation setViewControllers:current];
10016 // (Try to) show the startup URL.
10017 if (starturl_ != nil) {
10018 [self openCydiaURL:starturl_ forExternal:YES];
10023 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
10024 if (item != nil && IsWildcat_) {
10025 [sheet showFromBarButtonItem:item animated:YES];
10027 [sheet showInView:window_];
10031 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
10032 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
10033 [progress setTitle:task];
10034 [progress addProgressEvent:event];
10037 - (void) addProgressEventForTask:(NSArray *)data {
10038 CydiaProgressEvent *event([data objectAtIndex:0]);
10039 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
10040 [self addProgressEvent:event forTask:task];
10043 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
10044 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
10050 id Alloc_(id self, SEL selector) {
10051 id object = alloc_(self, selector);
10052 lprintf("[%s]A-%p\n", self->isa->name, object);
10057 id Dealloc_(id self, SEL selector) {
10058 id object = dealloc_(self, selector);
10059 lprintf("[%s]D-%p\n", self->isa->name, object);
10063 Class $NSURLConnection;
10065 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
10066 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
10068 NSURL *url([copy URL]);
10070 NSString *host([url host]);
10071 NSString *scheme([[url scheme] lowercaseString]);
10073 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
10075 @synchronized (HostConfig_) {
10076 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
10077 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
10078 [copy setHTTPShouldUsePipelining:YES];
10080 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
10081 if ([control isEqualToString:@"max-age=0"])
10082 if ([CachedURLs_ containsObject:url]) {
10084 NSLog(@"~~~: %@", url);
10087 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
10089 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
10090 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
10091 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
10095 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
10101 static CGSize $WAKWindow$screenSize(WAKWindow *self, SEL _cmd) {
10102 CGSize size([[UIScreen mainScreen] bounds].size);
10103 /*if ([$WAKWindow respondsToSelector:@selector(hasLandscapeOrientation)])
10104 if ([$WAKWindow hasLandscapeOrientation])
10105 std::swap(size.width, size.height);*/
10109 Class $NSUserDefaults;
10111 MSHook(id, NSUserDefaults$objectForKey$, NSUserDefaults *self, SEL _cmd, NSString *key) {
10112 if ([key respondsToSelector:@selector(isEqualToString:)] && [key isEqualToString:@"WebKitLocalStorageDatabasePathPreferenceKey"])
10113 return Cache("LocalStorage");
10114 return _NSUserDefaults$objectForKey$(self, _cmd, key);
10117 int main(int argc, char *argv[]) {
10118 setreugid(501, 501);
10120 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10124 UpdateExternalStatus(0);
10126 UIScreen *screen([UIScreen mainScreen]);
10127 if ([screen respondsToSelector:@selector(scale)])
10128 ScreenScale_ = [screen scale];
10132 UIDevice *device([UIDevice currentDevice]);
10133 if ([device respondsToSelector:@selector(userInterfaceIdiom)]) {
10134 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10135 if (idiom == UIUserInterfaceIdiomPad)
10139 Idiom_ = IsWildcat_ ? @"ipad" : @"iphone";
10141 RegEx pattern("([0-9]+\\.[0-9]+).*");
10143 if (pattern([device systemVersion]))
10144 Firmware_ = pattern[1];
10145 if (pattern(Cydia_))
10146 Major_ = pattern[1];
10148 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
10150 HostConfig_ = [[[NSObject alloc] init] autorelease];
10151 @synchronized (HostConfig_) {
10152 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10153 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
10154 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
10155 CachedURLs_ = [NSMutableSet setWithCapacity:32];
10158 NSString *ui(@"ui/ios");
10160 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
10161 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"/%@", Major_]];
10162 UI_ = CydiaURL(ui);
10164 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10166 /* Library Hacks {{{ */
10167 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10169 $WAKWindow = objc_getClass("WAKWindow");
10170 if ($WAKWindow != NULL)
10171 if (Method method = class_getInstanceMethod($WAKWindow, @selector(screenSize)))
10172 method_setImplementation(method, (IMP) &$WAKWindow$screenSize);
10174 $NSURLConnection = objc_getClass("NSURLConnection");
10175 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10176 if (NSURLConnection$init$ != NULL) {
10177 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10178 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10181 $NSUserDefaults = objc_getClass("NSUserDefaults");
10182 Method NSUserDefaults$objectForKey$(class_getInstanceMethod($NSUserDefaults, @selector(objectForKey:)));
10183 if (NSUserDefaults$objectForKey$ != NULL) {
10184 _NSUserDefaults$objectForKey$ = reinterpret_cast<id (*)(NSUserDefaults *, SEL, NSString *)>(method_getImplementation(NSUserDefaults$objectForKey$));
10185 method_setImplementation(NSUserDefaults$objectForKey$, reinterpret_cast<IMP>(&$NSUserDefaults$objectForKey$));
10188 /* Set Locale {{{ */
10189 Locale_ = CFLocaleCopyCurrent();
10190 Languages_ = [NSLocale preferredLanguages];
10192 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10193 //NSLog(@"%@", [Languages_ description]);
10196 if (Locale_ != NULL)
10197 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10198 else if (Languages_ != nil && [Languages_ count] != 0)
10199 lang = [[Languages_ objectAtIndex:0] UTF8String];
10201 // XXX: consider just setting to C and then falling through?
10204 if (lang != NULL) {
10205 RegEx pattern("([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?");
10206 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10209 NSLog(@"Setting Language: %s", lang);
10211 if (lang != NULL) {
10212 setenv("LANG", lang, true);
10213 std::setlocale(LC_ALL, lang);
10216 /* Index Collation {{{ */
10217 if (Class $UILocalizedIndexedCollation = objc_getClass("UILocalizedIndexedCollation")) { @try {
10218 NSBundle *bundle([NSBundle bundleForClass:$UILocalizedIndexedCollation]);
10219 NSString *path([bundle pathForResource:@"UITableViewLocalizedSectionIndex" ofType:@"plist"]);
10220 //path = @"/System/Library/Frameworks/UIKit.framework/.lproj/UITableViewLocalizedSectionIndex.plist";
10221 NSDictionary *dictionary([NSDictionary dictionaryWithContentsOfFile:path]);
10222 _H<UILocalizedIndexedCollation> collation([[[$UILocalizedIndexedCollation alloc] initWithDictionary:dictionary] autorelease]);
10224 CollationLocale_ = MSHookIvar<NSLocale *>(collation, "_locale");
10226 if (kCFCoreFoundationVersionNumber >= 800 && [[CollationLocale_ localeIdentifier] isEqualToString:@"zh@collation=stroke"]) {
10227 CollationThumbs_ = [NSArray arrayWithObjects:@"1",@"•",@"4",@"•",@"7",@"•",@"10",@"•",@"13",@"•",@"16",@"•",@"19",@"A",@"•",@"E",@"•",@"I",@"•",@"M",@"•",@"R",@"•",@"V",@"•",@"Z",@"#",nil];
10228 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})
10229 CollationOffset_.push_back(offset);
10230 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];
10231 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];
10234 CollationThumbs_ = [collation sectionIndexTitles];
10235 for (size_t index(0), end([CollationThumbs_ count]); index != end; ++index)
10236 CollationOffset_.push_back([collation sectionForSectionIndexTitleAtIndex:index]);
10238 CollationTitles_ = [collation sectionTitles];
10239 CollationStarts_ = MSHookIvar<NSArray *>(collation, "_sectionStartStrings");
10241 NSString *&transform(MSHookIvar<NSString *>(collation, "_transform"));
10242 if (&transform != NULL && transform != nil) {
10243 /*if ([collation respondsToSelector:@selector(transformedCollationStringForString:)])
10244 CollationModify_ = [=](NSString *value) { return [collation transformedCollationStringForString:value]; };*/
10245 const UChar *uid(reinterpret_cast<const UChar *>([transform cStringUsingEncoding:NSUnicodeStringEncoding]));
10246 UErrorCode code(U_ZERO_ERROR);
10247 CollationTransl_ = utrans_openU(uid, -1, UTRANS_FORWARD, NULL, 0, NULL, &code);
10248 if (!U_SUCCESS(code))
10249 NSLog(@"%s", u_errorName(code));
10253 } @catch (NSException *e) {
10257 CollationLocale_ = [[[NSLocale alloc] initWithLocaleIdentifier:@"en@collation=dictionary"] autorelease];
10259 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];
10260 for (NSInteger offset(0); offset != 28; ++offset)
10261 CollationOffset_.push_back(offset);
10263 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];
10264 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];
10267 /* Parse Arguments {{{ */
10268 bool substrate(false);
10274 for (int argi(1); argi != argc; ++argi)
10275 if (strcmp(argv[argi], "--") == 0) {
10277 argv[argi] = argv[0];
10283 for (int argi(1); argi != arge; ++argi)
10284 if (strcmp(args[argi], "--substrate") == 0)
10287 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10291 App_ = [[NSBundle mainBundle] bundlePath];
10294 Cache_ = [[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia", @"/var/mobile"] retain];
10296 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10297 alloc_ = alloc->method_imp;
10298 alloc->method_imp = (IMP) &Alloc_;*/
10300 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10301 dealloc_ = dealloc->method_imp;
10302 dealloc->method_imp = (IMP) &Dealloc_;*/
10304 void *gestalt(dlopen("/usr/lib/libMobileGestalt.dylib", RTLD_GLOBAL | RTLD_LAZY));
10305 $MGCopyAnswer = reinterpret_cast<CFStringRef (*)(CFStringRef)>(dlsym(gestalt, "MGCopyAnswer"));
10307 /* System Information {{{ */
10311 size = sizeof(maxproc);
10312 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10313 perror("sysctlbyname(\"kern.maxproc\", ?)");
10314 else if (maxproc < 64) {
10316 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10317 perror("sysctlbyname(\"kern.maxproc\", #)");
10320 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10321 char *osversion = new char[size];
10322 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10323 perror("sysctlbyname(\"kern.osversion\", ?)");
10325 System_ = [NSString stringWithUTF8String:osversion];
10327 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10328 char *machine = new char[size];
10329 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10330 perror("sysctlbyname(\"hw.machine\", ?)");
10332 Machine_ = machine;
10334 int64_t usermem(0);
10335 size = sizeof(usermem);
10336 if (sysctlbyname("hw.usermem", &usermem, &size, NULL, 0) == -1)
10339 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10340 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10341 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10343 UniqueID_ = UniqueIdentifier(device);
10345 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10346 Product_ = [info objectForKey:@"SafariProductVersion"];
10347 Safari_ = [info objectForKey:@"CFBundleVersion"];
10350 NSString *agent([NSString stringWithFormat:@"Cydia/%@ CyF/%.2f", Cydia_, kCFCoreFoundationVersionNumber]);
10352 if (RegEx match = RegEx("([0-9]+(\\.[0-9]+)+).*", Safari_))
10353 agent = [NSString stringWithFormat:@"Safari/%@ %@", match[1], agent];
10354 if (RegEx match = RegEx("([0-9]+[A-Z][0-9]+[a-z]?).*", System_))
10355 agent = [NSString stringWithFormat:@"Mobile/%@ %@", match[1], agent];
10356 if (RegEx match = RegEx("([0-9]+(\\.[0-9]+)+).*", Product_))
10357 agent = [NSString stringWithFormat:@"Version/%@ %@", match[1], agent];
10359 UserAgent_ = agent;
10361 /* Load Database {{{ */
10363 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10365 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10367 if (Metadata_ == NULL)
10368 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10370 Settings_ = [Metadata_ objectForKey:@"Settings"];
10372 Values_ = [Metadata_ objectForKey:@"Values"];
10373 Sections_ = [Metadata_ objectForKey:@"Sections"];
10374 Sources_ = [Metadata_ objectForKey:@"Sources"];
10376 Version_ = [Metadata_ objectForKey:@"Version"];
10379 if (Values_ == nil) {
10380 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10381 [Metadata_ setObject:Values_ forKey:@"Values"];
10384 if (Sections_ == nil) {
10385 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10386 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10389 if (Sources_ == nil) {
10390 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10391 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10394 if (Version_ == nil) {
10395 Version_ = [NSNumber numberWithUnsignedInt:0];
10396 [Metadata_ setObject:Version_ forKey:@"Version"];
10399 if ([Version_ unsignedIntValue] == 0) {
10400 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10401 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10402 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10403 CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./");
10405 Version_ = [NSNumber numberWithUnsignedInt:1];
10406 [Metadata_ setObject:Version_ forKey:@"Version"];
10408 [Metadata_ removeObjectForKey:@"LastUpdate"];
10413 _H<NSMutableArray> broken([NSMutableArray array]);
10414 for (NSString *key in (id) Sources_)
10415 if ([key rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"# "]].location != NSNotFound)
10416 [broken addObject:key];
10417 if ([broken count] != 0) {
10418 for (NSString *key in (id) broken)
10419 [Sources_ removeObjectForKey:key];
10424 CydiaWriteSources();
10427 mkdir("/var/mobile/Library/Cydia", 0755);
10428 MetaFile_.Open("/var/mobile/Library/Cydia/metadata.cb0");
10431 if (NSDictionary *packages = [Metadata_ objectForKey:@"Packages"]) {
10433 CFDictionaryApplyFunction((CFDictionaryRef) packages, &PackageImport, &fail);
10437 [Metadata_ removeObjectForKey:@"Packages"];
10442 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10444 #define MobileSubstrate_(name) \
10445 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10446 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10447 if (handle == NULL) \
10448 NSLog(@"%s", dlerror()); \
10451 MobileSubstrate_(Activator)
10452 MobileSubstrate_(libstatusbar)
10453 MobileSubstrate_(SimulatedKeyEvents)
10454 MobileSubstrate_(WinterBoard)
10456 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10457 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10459 if (kCFCoreFoundationVersionNumber > 1000)
10460 system("/usr/libexec/cydia/cydo /usr/libexec/cydia/setnsfpn /var/lib");
10462 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10464 if (access("/User", F_OK) != 0 || version != 6) {
10466 system("/usr/libexec/cydia/cydo /usr/libexec/cydia/firmware.sh");
10470 if (access("/tmp/cydia.chk", F_OK) == 0) {
10471 if (unlink([Cache("pkgcache.bin") UTF8String]) == -1)
10472 _assert(errno == ENOENT);
10473 if (unlink([Cache("srcpkgcache.bin") UTF8String]) == -1)
10474 _assert(errno == ENOENT);
10477 /* APT Initialization {{{ */
10478 _assert(pkgInitConfig(*_config));
10479 _assert(pkgInitSystem(*_config, _system));
10482 _config->Set("APT::Acquire::Translation", lang);
10484 // XXX: this timeout might be important :(
10485 //_config->Set("Acquire::http::Timeout", 15);
10487 _config->Set("Acquire::http::MaxParallel", usermem >= 384 * 1024 * 1024 ? 16 : 3);
10489 mkdir([Cache_ UTF8String], 0755);
10490 mkdir([Cache("archives") UTF8String], 0755);
10491 mkdir([Cache("archives/partial") UTF8String], 0755);
10492 _config->Set("Dir::Cache", [Cache_ UTF8String]);
10494 mkdir([Cache("lists") UTF8String], 0755);
10495 mkdir([Cache("lists/partial") UTF8String], 0755);
10496 mkdir([Cache("periodic") UTF8String], 0755);
10497 _config->Set("Dir::State::Lists", [Cache("lists") UTF8String]);
10499 std::string logs("/var/mobile/Library/Logs/Cydia");
10500 mkdir(logs.c_str(), 0755);
10501 _config->Set("Dir::Log::Terminal", logs + "/apt.log");
10503 _config->Set("Dir::Bin::dpkg", "/usr/libexec/cydia/cydo");
10505 /* Color Choices {{{ */
10506 space_ = CGColorSpaceCreateDeviceRGB();
10508 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10509 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10510 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10511 Folder_.Set(space_, 0x8e/255.f, 0x8e/255.f, 0x93/255.f, 1.0);
10512 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10513 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10514 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10515 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10516 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10517 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10519 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10520 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10522 /* UIKit Configuration {{{ */
10523 // XXX: I have a feeling this was important
10524 //UIKeyboardDisableAutomaticAppearance();
10527 $SBSSetInterceptsMenuButtonForever = reinterpret_cast<void (*)(bool)>(dlsym(RTLD_DEFAULT, "SBSSetInterceptsMenuButtonForever"));
10529 const char *symbol(kCFCoreFoundationVersionNumber >= 800 ? "MGGetBoolAnswer" : "GSSystemHasCapability");
10530 BOOL (*GSSystemHasCapability)(CFStringRef) = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, symbol));
10531 bool fast = GSSystemHasCapability != NULL && GSSystemHasCapability(CFSTR("armv7"));
10533 PulseInterval_ = fast ? 50000 : 500000;
10535 Colon_ = UCLocalize("COLON_DELIMITED");
10536 Elision_ = UCLocalize("ELISION");
10537 Error_ = UCLocalize("ERROR");
10538 Warning_ = UCLocalize("WARNING");
10541 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10543 CGColorSpaceRelease(space_);
10544 CFRelease(Locale_);