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 *Values_;
814 static _transient NSMutableDictionary *Sections_;
815 _H<NSMutableDictionary> Sources_;
816 static _transient NSNumber *Version_;
821 CGFloat ScreenScale_;
822 static NSString *Idiom_;
823 static _H<NSString> Firmware_;
824 static NSString *Major_;
826 static _H<NSMutableDictionary> SessionData_;
827 static _H<NSObject> HostConfig_;
828 static _H<NSMutableSet> BridgedHosts_;
829 static _H<NSMutableSet> InsecureHosts_;
830 static _H<NSMutableSet> PipelinedHosts_;
831 static _H<NSMutableSet> CachedURLs_;
833 static NSString *kCydiaProgressEventTypeError = @"Error";
834 static NSString *kCydiaProgressEventTypeInformation = @"Information";
835 static NSString *kCydiaProgressEventTypeStatus = @"Status";
836 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
839 /* Display Helpers {{{ */
840 inline float Interpolate(float begin, float end, float fraction) {
841 return (end - begin) * fraction + begin;
844 static inline double Retina(double value) {
845 value *= ScreenScale_;
846 value = round(value);
847 value /= ScreenScale_;
851 static inline CGRect Retina(CGRect value) {
852 value.origin.x *= ScreenScale_;
853 value.origin.y *= ScreenScale_;
854 value.size.width *= ScreenScale_;
855 value.size.height *= ScreenScale_;
856 value = CGRectIntegral(value);
857 value.origin.x /= ScreenScale_;
858 value.origin.y /= ScreenScale_;
859 value.size.width /= ScreenScale_;
860 value.size.height /= ScreenScale_;
864 static _finline const char *StripVersion_(const char *version) {
865 const char *colon(strchr(version, ':'));
866 return colon == NULL ? version : colon + 1;
869 NSString *LocalizeSection(NSString *section) {
870 static RegEx title_r("(.*?) \\((.*)\\)");
871 if (title_r(section)) {
872 NSString *parent(title_r[1]);
873 NSString *child(title_r[2]);
875 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
876 LocalizeSection(parent),
877 LocalizeSection(child)
881 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
884 NSString *Simplify(NSString *title) {
885 const char *data = [title UTF8String];
886 size_t size = [title lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
888 static RegEx square_r("\\[(.*)\\]");
889 if (square_r(data, size))
890 return Simplify(square_r[1]);
892 static RegEx paren_r("\\((.*)\\)");
893 if (paren_r(data, size))
894 return Simplify(paren_r[1]);
896 static RegEx title_r("(.*?) \\((.*)\\)");
897 if (title_r(data, size))
898 return Simplify(title_r[1]);
904 NSString *GetLastUpdate() {
905 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
908 return UCLocalize("NEVER_OR_UNKNOWN");
910 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
911 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
913 CFRelease(formatter);
915 return [(NSString *) formatted autorelease];
918 bool isSectionVisible(NSString *section) {
919 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
920 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
921 return hidden == nil || ![hidden boolValue];
924 static NSObject *CYIOGetValue(const char *path, NSString *property) {
925 io_registry_entry_t entry(IORegistryEntryFromPath(kIOMasterPortDefault, path));
926 if (entry == MACH_PORT_NULL)
929 CFTypeRef value(IORegistryEntryCreateCFProperty(entry, (CFStringRef) property, kCFAllocatorDefault, 0));
930 IOObjectRelease(entry);
934 return [(id) value autorelease];
937 static NSString *CYHex(NSData *data, bool reverse = false) {
941 size_t length([data length]);
942 uint8_t bytes[length];
943 [data getBytes:bytes];
945 char string[length * 2 + 1];
946 for (size_t i(0); i != length; ++i)
947 sprintf(string + i * 2, "%.2x", bytes[reverse ? length - i - 1 : i]);
949 return [NSString stringWithUTF8String:string];
954 /* Delegate Prototypes {{{ */
957 @class CydiaProgressEvent;
959 @protocol DatabaseDelegate
960 - (void) repairWithSelector:(SEL)selector;
961 - (void) setConfigurationData:(NSString *)data;
962 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
965 @class CYPackageController;
967 @protocol SourceDelegate
968 - (void) setFetch:(NSNumber *)fetch;
971 @protocol FetchDelegate
972 - (bool) isSourceCancelled;
973 - (void) startSourceFetch:(NSString *)uri;
974 - (void) stopSourceFetch:(NSString *)uri;
977 @protocol CydiaDelegate
978 - (void) returnToCydia;
980 - (void) retainNetworkActivityIndicator;
981 - (void) releaseNetworkActivityIndicator;
982 - (void) clearPackage:(Package *)package;
983 - (void) installPackage:(Package *)package;
984 - (void) installPackages:(NSArray *)packages;
985 - (void) removePackage:(Package *)package;
986 - (void) beginUpdate;
988 - (bool) requestUpdate;
989 - (void) distUpgrade;
992 - (void) _saveConfig;
994 - (void) addSource:(NSDictionary *)source;
995 - (void) addTrivialSource:(NSString *)href;
996 - (UIProgressHUD *) addProgressHUD;
997 - (void) removeProgressHUD:(UIProgressHUD *)hud;
998 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
999 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1003 /* CancelStatus {{{ */
1004 class CancelStatus :
1005 public pkgAcquireStatus
1016 virtual bool MediaChange(std::string media, std::string drive) {
1020 virtual void IMSHit(pkgAcquire::ItemDesc &desc) {
1024 virtual bool Pulse_(pkgAcquire *Owner) = 0;
1026 virtual bool Pulse(pkgAcquire *Owner) {
1027 if (pkgAcquireStatus::Pulse(Owner) && Pulse_(Owner))
1035 _finline bool WasCancelled() const {
1040 /* DelegateStatus {{{ */
1045 _transient NSObject<ProgressDelegate> *delegate_;
1053 void setDelegate(NSObject<ProgressDelegate> *delegate) {
1054 delegate_ = delegate;
1057 virtual void Fetch(pkgAcquire::ItemDesc &desc) {
1058 NSString *name([NSString stringWithUTF8String:desc.ShortDesc.c_str()]);
1059 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItemDesc:desc]);
1060 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1063 virtual void Done(pkgAcquire::ItemDesc &desc) {
1064 NSString *name([NSString stringWithUTF8String:desc.ShortDesc.c_str()]);
1065 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:Colon_, UCLocalize("DONE"), name] ofType:kCydiaProgressEventTypeStatus forItemDesc:desc]);
1066 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1069 virtual void Fail(pkgAcquire::ItemDesc &desc) {
1071 desc.Owner->Status == pkgAcquire::Item::StatIdle ||
1072 desc.Owner->Status == pkgAcquire::Item::StatDone
1076 std::string &error(desc.Owner->ErrorText);
1080 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItemDesc:desc]);
1081 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1084 virtual bool Pulse_(pkgAcquire *Owner) {
1086 double(CurrentBytes + CurrentItems) /
1087 double(TotalBytes + TotalItems)
1090 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
1091 [NSNumber numberWithDouble:percent], @"Percent",
1093 [NSNumber numberWithDouble:CurrentBytes], @"Current",
1094 [NSNumber numberWithDouble:TotalBytes], @"Total",
1095 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
1096 nil] waitUntilDone:YES];
1098 return ![delegate_ isProgressCancelled];
1101 virtual void Start() {
1102 pkgAcquireStatus::Start();
1103 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
1106 virtual void Stop() {
1107 pkgAcquireStatus::Stop();
1108 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
1109 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
1113 /* Database Interface {{{ */
1114 typedef std::map< unsigned long, _H<Source> > SourceMap;
1116 @interface Database : NSObject {
1122 pkgCacheFile cache_;
1123 pkgDepCache::Policy *policy_;
1124 pkgRecords *records_;
1125 pkgProblemResolver *resolver_;
1126 pkgAcquire *fetcher_;
1128 SPtr<pkgPackageManager> manager_;
1129 pkgSourceList *list_;
1131 SourceMap sourceMap_;
1132 _H<NSMutableArray> sourceList_;
1134 CFMutableArrayRef packages_;
1136 _transient NSObject<DatabaseDelegate> *delegate_;
1137 _transient NSObject<ProgressDelegate> *progress_;
1139 CydiaStatus status_;
1145 std::map<const char *, _H<NSString> > sections_;
1148 + (Database *) sharedInstance;
1151 - (void) _readCydia:(NSNumber *)fd;
1152 - (void) _readStatus:(NSNumber *)fd;
1153 - (void) _readOutput:(NSNumber *)fd;
1157 - (Package *) packageWithName:(NSString *)name;
1159 - (pkgCacheFile &) cache;
1160 - (pkgDepCache::Policy *) policy;
1161 - (pkgRecords *) records;
1162 - (pkgProblemResolver *) resolver;
1163 - (pkgAcquire &) fetcher;
1164 - (pkgSourceList &) list;
1165 - (NSArray *) packages;
1166 - (NSArray *) sources;
1167 - (Source *) sourceWithKey:(NSString *)key;
1168 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1176 - (void) updateWithStatus:(CancelStatus &)status;
1178 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1180 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1181 - (NSObject<ProgressDelegate> *) progressDelegate;
1183 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1184 - (void) setFetch:(bool)fetch forURI:(const char *)uri;
1185 - (void) resetFetch;
1187 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1191 /* SourceStatus {{{ */
1192 class SourceStatus :
1196 _transient NSObject<FetchDelegate> *delegate_;
1197 _transient Database *database_;
1198 std::set<std::string> fetches_;
1201 SourceStatus(NSObject<FetchDelegate> *delegate, Database *database) :
1202 delegate_(delegate),
1207 void Set(bool fetch, const std::string &uri) {
1209 if (!fetches_.insert(uri).second)
1212 if (fetches_.erase(uri) == 0)
1216 //printf("Set(%s, %s)\n", fetch ? "true" : "false", uri.c_str());
1217 [database_ setFetch:fetch forURI:uri.c_str()];
1220 _finline void Set(bool fetch, pkgAcquire::Item *item) {
1221 /*unsigned long ID(fetch ? 1 : 0);
1225 Set(fetch, item->DescURI());
1228 void Log(const char *tag, pkgAcquire::Item *item) {
1229 //printf("%s(%s) S:%u Q:%u\n", tag, item->DescURI().c_str(), item->Status, item->QueueCounter);
1232 virtual void Fetch(pkgAcquire::ItemDesc &desc) {
1233 Log("Fetch", desc.Owner);
1234 Set(true, desc.Owner);
1237 virtual void Done(pkgAcquire::ItemDesc &desc) {
1238 Log("Done", desc.Owner);
1239 Set(false, desc.Owner);
1242 virtual void Fail(pkgAcquire::ItemDesc &desc) {
1243 Log("Fail", desc.Owner);
1244 Set(false, desc.Owner);
1247 virtual bool Pulse_(pkgAcquire *Owner) {
1248 std::set<std::string> fetches;
1249 for (pkgAcquire::ItemCIterator item(Owner->ItemsBegin()); item != Owner->ItemsEnd(); ++item) {
1251 if ((*item)->QueueCounter == 0)
1253 else switch ((*item)->Status) {
1254 case pkgAcquire::Item::StatFetching:
1255 fetches.insert((*item)->DescURI());
1264 Log(fetch ? "Pulse<true>" : "Pulse<false>", *item);
1268 std::vector<std::string> stops;
1269 std::set_difference(fetches_.begin(), fetches_.end(), fetches.begin(), fetches.end(), std::back_insert_iterator<std::vector<std::string>>(stops));
1270 for (std::vector<std::string>::const_iterator stop(stops.begin()); stop != stops.end(); ++stop) {
1271 //printf("Stop(%s)\n", stop->c_str());
1275 return ![delegate_ isSourceCancelled];
1278 virtual void Stop() {
1279 pkgAcquireStatus::Stop();
1280 [database_ resetFetch];
1284 /* ProgressEvent Implementation {{{ */
1285 @implementation CydiaProgressEvent
1287 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1288 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1291 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1292 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1293 [event setPackage:package];
1297 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItemDesc:(pkgAcquire::ItemDesc &)desc {
1298 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1300 NSString *description([NSString stringWithUTF8String:desc.Description.c_str()]);
1301 NSArray *fields([description componentsSeparatedByString:@" "]);
1302 [event setItem:fields];
1304 if ([fields count] > 3) {
1305 [event setPackage:[fields objectAtIndex:2]];
1306 [event setVersion:[fields objectAtIndex:3]];
1309 [event setURL:[NSString stringWithUTF8String:desc.URI.c_str()]];
1314 + (NSArray *) _attributeKeys {
1315 return [NSArray arrayWithObjects:
1325 - (NSArray *) attributeKeys {
1326 return [[self class] _attributeKeys];
1329 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1330 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1333 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1334 if ((self = [super init]) != nil) {
1340 - (NSString *) message {
1344 - (NSString *) type {
1348 - (NSArray *) item {
1349 return (id) item_ ?: [NSNull null];
1352 - (void) setItem:(NSArray *)item {
1356 - (NSString *) package {
1357 return (id) package_ ?: [NSNull null];
1360 - (void) setPackage:(NSString *)package {
1364 - (NSString *) url {
1365 return (id) url_ ?: [NSNull null];
1368 - (void) setURL:(NSString *)url {
1372 - (void) setVersion:(NSString *)version {
1376 - (NSString *) version {
1377 return (id) version_ ?: [NSNull null];
1380 - (NSString *) compound:(NSString *)value {
1382 NSString *mode(nil); {
1383 NSString *type([self type]);
1384 if ([type isEqualToString:kCydiaProgressEventTypeError])
1385 mode = UCLocalize("ERROR");
1386 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1387 mode = UCLocalize("WARNING");
1391 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1397 - (NSString *) compoundMessage {
1398 return [self compound:[self message]];
1401 - (NSString *) compoundTitle {
1404 if (package_ == nil)
1406 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1407 title = [package name];
1411 return [self compound:title];
1417 // Cytore Definitions {{{
1418 struct PackageValue :
1421 Cytore::Offset<PackageValue> next_;
1423 uint32_t index_ : 23;
1424 uint32_t subscribed_ : 1;
1441 Cytore::Offset<PackageValue> packages_[1 << 16];
1444 static Cytore::File<MetaValue> MetaFile_;
1446 // Cytore Helper Functions {{{
1447 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1448 SplitHash nhash = { hashlittle(name, length) };
1450 PackageValue *metadata;
1452 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1453 for (;; offset = &metadata->next_) { if (offset->IsNull()) {
1454 *offset = MetaFile_.New<PackageValue>(length + 1);
1455 metadata = &MetaFile_.Get(*offset);
1457 if (metadata == NULL) {
1461 metadata = new PackageValue();
1462 memset(metadata, 0, sizeof(*metadata));
1465 memcpy(metadata->name_, name, length);
1466 metadata->name_[length] = '\0';
1467 metadata->nhash_ = nhash.u16[1];
1469 metadata = &MetaFile_.Get(*offset);
1470 if (metadata->nhash_ != nhash.u16[1])
1472 if (strncmp(metadata->name_, name, length) != 0)
1474 if (metadata->name_[length] != '\0')
1481 static void PackageImport(const void *key, const void *value, void *context) {
1482 bool &fail(*reinterpret_cast<bool *>(context));
1485 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1486 NSLog(@"failed to import package %@", key);
1490 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1491 NSDictionary *package((NSDictionary *) value);
1493 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1494 if ([subscribed boolValue] && !metadata->subscribed_)
1495 metadata->subscribed_ = true;
1497 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1498 time_t time([date timeIntervalSince1970]);
1499 if (metadata->first_ > time || metadata->first_ == 0)
1500 metadata->first_ = time;
1503 NSDate *date([package objectForKey:@"LastSeen"]);
1504 NSString *version([package objectForKey:@"LastVersion"]);
1506 if (date != nil && version != nil) {
1507 time_t time([date timeIntervalSince1970]);
1508 if (metadata->last_ < time || metadata->last_ == 0)
1509 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1510 size_t length(strlen(buffer));
1511 uint16_t vhash(hashlittle(buffer, length));
1513 size_t capped(std::min<size_t>(8, length));
1514 char *latest(buffer + length - capped);
1516 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1517 metadata->vhash_ = vhash;
1519 metadata->last_ = time;
1525 /* Source Class {{{ */
1526 @interface Source : NSObject {
1528 Database *database_;
1531 CYString depiction_;
1532 CYString description_;
1538 CYString distribution_;
1544 _H<NSString> authority_;
1546 CYString defaultIcon_;
1548 _H<NSMutableDictionary> record_;
1551 std::set<std::string> fetches_;
1552 std::set<std::string> files_;
1553 _transient NSObject<SourceDelegate> *delegate_;
1556 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(CYPool *)pool;
1558 - (NSComparisonResult) compareByName:(Source *)source;
1560 - (NSString *) depictionForPackage:(NSString *)package;
1561 - (NSString *) supportForPackage:(NSString *)package;
1563 - (metaIndex *) metaIndex;
1564 - (NSDictionary *) record;
1567 - (NSString *) rooturi;
1568 - (NSString *) distribution;
1569 - (NSString *) type;
1572 - (NSString *) host;
1574 - (NSString *) name;
1575 - (NSString *) shortDescription;
1576 - (NSString *) label;
1577 - (NSString *) origin;
1578 - (NSString *) version;
1580 - (NSString *) defaultIcon;
1581 - (NSURL *) iconURL;
1583 - (void) setFetch:(bool)fetch forURI:(const char *)uri;
1584 - (void) resetFetch;
1588 @implementation Source
1590 + (NSString *) webScriptNameForSelector:(SEL)selector {
1592 else if (selector == @selector(addSection:))
1593 return @"addSection";
1594 else if (selector == @selector(getField:))
1596 else if (selector == @selector(removeSection:))
1597 return @"removeSection";
1598 else if (selector == @selector(remove))
1604 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1605 return [self webScriptNameForSelector:selector] == nil;
1608 + (NSArray *) _attributeKeys {
1609 return [NSArray arrayWithObjects:
1620 @"shortDescription",
1627 - (NSArray *) attributeKeys {
1628 return [[self class] _attributeKeys];
1631 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1632 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1635 - (metaIndex *) metaIndex {
1639 - (void) setMetaIndex:(metaIndex *)index inPool:(CYPool *)pool {
1640 trusted_ = index->IsTrusted();
1642 uri_.set(pool, index->GetURI());
1643 distribution_.set(pool, index->GetDist());
1644 type_.set(pool, index->GetType());
1646 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1647 if (dindex != NULL) {
1648 std::string file(dindex->MetaIndexURI(""));
1649 base_.set(pool, file);
1652 _profile(Source$setMetaIndex$GetIndexes)
1653 dindex->GetIndexes(&acquire, true);
1655 _profile(Source$setMetaIndex$DescURI)
1656 for (pkgAcquire::ItemIterator item(acquire.ItemsBegin()); item != acquire.ItemsEnd(); item++) {
1657 std::string file((*item)->DescURI());
1658 files_.insert(file);
1659 if (file.length() < sizeof("Packages.bz2") || file.substr(file.length() - sizeof("Packages.bz2")) != "/Packages.bz2")
1661 file = file.substr(0, file.length() - 4);
1662 files_.insert(file);
1663 files_.insert(file + ".gz");
1664 files_.insert(file + "Index");
1669 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1672 pkgTagFile tags(&fd);
1674 pkgTagSection section;
1681 {"default-icon", &defaultIcon_},
1682 {"depiction", &depiction_},
1683 {"description", &description_},
1685 {"origin", &origin_},
1686 {"support", &support_},
1687 {"version", &version_},
1690 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1691 const char *start, *end;
1693 if (section.Find(names[i].name_, start, end)) {
1694 CYString &value(*names[i].value_);
1695 value.set(pool, start, end - start);
1701 record_ = [Sources_ objectForKey:[self key]];
1703 NSURL *url([NSURL URLWithString:uri_]);
1707 host_ = [host_ lowercaseString];
1712 authority_ = [url path];
1715 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(CYPool *)pool {
1716 if ((self = [super init]) != nil) {
1717 era_ = [database era];
1718 database_ = database;
1721 _profile(Source$initWithMetaIndex$setMetaIndex)
1722 [self setMetaIndex:index inPool:pool];
1727 - (NSString *) getField:(NSString *)name {
1728 @synchronized (database_) {
1729 if ([database_ era] != era_ || index_ == NULL)
1732 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index_));
1737 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly)) {
1742 pkgTagFile tags(&fd);
1744 pkgTagSection section;
1747 const char *start, *end;
1748 if (!section.Find([name UTF8String], start, end))
1749 return (NSString *) [NSNull null];
1751 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
1754 - (NSComparisonResult) compareByName:(Source *)source {
1755 NSString *lhs = [self name];
1756 NSString *rhs = [source name];
1758 if ([lhs length] != 0 && [rhs length] != 0) {
1759 unichar lhc = [lhs characterAtIndex:0];
1760 unichar rhc = [rhs characterAtIndex:0];
1762 if (isalpha(lhc) && !isalpha(rhc))
1763 return NSOrderedAscending;
1764 else if (!isalpha(lhc) && isalpha(rhc))
1765 return NSOrderedDescending;
1768 return [lhs compare:rhs options:LaxCompareOptions_];
1771 - (NSString *) depictionForPackage:(NSString *)package {
1772 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1775 - (NSString *) supportForPackage:(NSString *)package {
1776 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1779 - (NSArray *) sections {
1780 return record_ == nil ? (id) [NSNull null] : [record_ objectForKey:@"Sections"] ?: [NSArray array];
1783 - (void) _addSection:(NSString *)section {
1786 else if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) {
1787 if (![sections containsObject:section]) {
1788 [sections addObject:section];
1792 [record_ setObject:[NSMutableArray arrayWithObject:section] forKey:@"Sections"];
1797 - (bool) addSection:(NSString *)section {
1801 [self performSelectorOnMainThread:@selector(_addSection:) withObject:section waitUntilDone:NO];
1805 - (void) _removeSection:(NSString *)section {
1809 if (NSMutableArray *sections = [record_ objectForKey:@"Sections"])
1810 if ([sections containsObject:section]) {
1811 [sections removeObject:section];
1816 - (bool) removeSection:(NSString *)section {
1820 [self performSelectorOnMainThread:@selector(_removeSection:) withObject:section waitUntilDone:NO];
1825 [Sources_ removeObjectForKey:[self key]];
1830 bool value(record_ != nil);
1831 [self performSelectorOnMainThread:@selector(_remove) withObject:nil waitUntilDone:NO];
1835 - (NSDictionary *) record {
1843 - (NSString *) rooturi {
1847 - (NSString *) distribution {
1848 return distribution_;
1851 - (NSString *) type {
1855 - (NSString *) baseuri {
1856 return base_.empty() ? nil : (id) base_;
1859 - (NSString *) iconuri {
1860 if (NSString *base = [self baseuri])
1861 return [base stringByAppendingString:@"CydiaIcon.png"];
1866 - (NSURL *) iconURL {
1867 if (NSString *uri = [self iconuri])
1868 return [NSURL URLWithString:uri];
1872 - (NSString *) key {
1873 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1876 - (NSString *) host {
1880 - (NSString *) name {
1881 return origin_.empty() ? (id) authority_ : origin_;
1884 - (NSString *) shortDescription {
1885 return description_;
1888 - (NSString *) label {
1889 return label_.empty() ? (id) authority_ : label_;
1892 - (NSString *) origin {
1896 - (NSString *) version {
1900 - (NSString *) defaultIcon {
1901 return defaultIcon_;
1904 - (void) setDelegate:(NSObject<SourceDelegate> *)delegate {
1905 delegate_ = delegate;
1909 return !fetches_.empty();
1912 - (void) setFetch:(bool)fetch forURI:(const char *)uri {
1914 if (fetches_.erase(uri) == 0)
1916 } else if (files_.find(uri) == files_.end())
1918 else if (!fetches_.insert(uri).second)
1921 [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:[self fetch]] waitUntilDone:NO];
1924 - (void) resetFetch {
1926 [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:NO];
1931 /* CydiaOperation Class {{{ */
1932 @interface CydiaOperation : NSObject {
1933 _H<NSString> operator_;
1934 _H<NSString> value_;
1937 - (NSString *) operator;
1938 - (NSString *) value;
1942 @implementation CydiaOperation
1944 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1945 if ((self = [super init]) != nil) {
1946 operator_ = [NSString stringWithUTF8String:_operator];
1947 value_ = [NSString stringWithUTF8String:value];
1951 + (NSArray *) _attributeKeys {
1952 return [NSArray arrayWithObjects:
1958 - (NSArray *) attributeKeys {
1959 return [[self class] _attributeKeys];
1962 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1963 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1966 - (NSString *) operator {
1970 - (NSString *) value {
1976 /* CydiaClause Class {{{ */
1977 @interface CydiaClause : NSObject {
1978 _H<NSString> package_;
1979 _H<CydiaOperation> version_;
1982 - (NSString *) package;
1983 - (CydiaOperation *) version;
1987 @implementation CydiaClause
1989 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1990 if ((self = [super init]) != nil) {
1991 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1993 if (const char *version = dep.TargetVer())
1994 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1996 version_ = (id) [NSNull null];
2000 + (NSArray *) _attributeKeys {
2001 return [NSArray arrayWithObjects:
2007 - (NSArray *) attributeKeys {
2008 return [[self class] _attributeKeys];
2011 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2012 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2015 - (NSString *) package {
2019 - (CydiaOperation *) version {
2025 /* CydiaRelation Class {{{ */
2026 @interface CydiaRelation : NSObject {
2027 _H<NSString> relationship_;
2028 _H<NSMutableArray> clauses_;
2031 - (NSString *) relationship;
2032 - (NSArray *) clauses;
2036 @implementation CydiaRelation
2038 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
2039 if ((self = [super init]) != nil) {
2040 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
2041 clauses_ = [NSMutableArray arrayWithCapacity:8];
2043 pkgCache::DepIterator start;
2044 pkgCache::DepIterator end;
2045 dep.GlobOr(start, end); // ++dep
2048 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
2050 // yes, seriously. (wtf?)
2058 + (NSArray *) _attributeKeys {
2059 return [NSArray arrayWithObjects:
2065 - (NSArray *) attributeKeys {
2066 return [[self class] _attributeKeys];
2069 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2070 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2073 - (NSString *) relationship {
2074 return relationship_;
2077 - (NSArray *) clauses {
2081 - (void) addClause:(CydiaClause *)clause {
2082 [clauses_ addObject:clause];
2087 /* Package Class {{{ */
2088 struct ParsedPackage {
2092 CYString architecture_;
2095 CYString depiction_;
2102 @interface Package : NSObject {
2104 @public uint32_t role_ : 3;
2105 uint32_t essential_ : 1;
2106 uint32_t obsolete_ : 1;
2107 uint32_t ignored_ : 1;
2108 uint32_t pooled_ : 1;
2114 _transient Database *database_;
2116 pkgCache::VerIterator version_;
2117 pkgCache::PkgIterator iterator_;
2118 pkgCache::VerFileIterator file_;
2122 CYString transform_;
2125 CYString installed_;
2128 const char *section_;
2129 _transient NSString *section$_;
2133 PackageValue *metadata_;
2134 ParsedPackage *parsed_;
2136 _H<NSMutableArray> tags_;
2139 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database;
2140 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database;
2142 - (pkgCache::PkgIterator) iterator;
2145 - (NSString *) section;
2146 - (NSString *) simpleSection;
2148 - (NSString *) longSection;
2149 - (NSString *) shortSection;
2153 - (MIMEAddress *) maintainer;
2155 - (NSString *) longDescription;
2156 - (NSString *) shortDescription;
2159 - (PackageValue *) metadata;
2162 - (bool) subscribed;
2163 - (bool) setSubscribed:(bool)subscribed;
2167 - (NSString *) latest;
2168 - (NSString *) installed;
2169 - (BOOL) uninstalled;
2172 - (BOOL) upgradableAndEssential:(BOOL)essential;
2175 - (BOOL) unfiltered;
2179 - (BOOL) halfConfigured;
2180 - (BOOL) halfInstalled;
2182 - (NSString *) mode;
2185 - (NSString *) name;
2187 - (NSString *) homepage;
2188 - (NSString *) depiction;
2189 - (MIMEAddress *) author;
2191 - (NSString *) support;
2193 - (NSArray *) files;
2194 - (NSArray *) warnings;
2195 - (NSArray *) applications;
2197 - (Source *) source;
2200 - (BOOL) matches:(NSArray *)query;
2202 - (BOOL) hasTag:(NSString *)tag;
2203 - (NSString *) primaryPurpose;
2204 - (NSArray *) purposes;
2205 - (bool) isCommercial;
2207 - (void) setIndex:(size_t)index;
2209 - (CYString &) cyname;
2211 - (uint32_t) compareBySection:(NSArray *)sections;
2218 uint32_t PackageChangesRadix(Package *self, void *) {
2223 uint32_t timestamp : 30;
2224 uint32_t ignored : 1;
2225 uint32_t upgradable : 1;
2229 bool upgradable([self upgradableAndEssential:YES]);
2230 value.bits.upgradable = upgradable ? 1 : 0;
2233 value.bits.timestamp = 0;
2234 value.bits.ignored = [self ignored] ? 0 : 1;
2235 value.bits.upgradable = 1;
2237 value.bits.timestamp = [self seen] >> 2;
2238 value.bits.ignored = 0;
2239 value.bits.upgradable = 0;
2242 return _not(uint32_t) - value.key;
2245 CYString &(*PackageName)(Package *self, SEL sel);
2247 uint32_t PackagePrefixRadix(Package *self, void *context) {
2248 size_t offset(reinterpret_cast<size_t>(context));
2249 CYString &name(PackageName(self, @selector(cyname)));
2251 size_t size(name.size());
2254 char *text(name.data());
2257 if (!isdigit(text[0]))
2261 while (size != digits && isdigit(text[digits]))
2269 if (offset == 0 && zeros != 0) {
2270 memset(data, '0', zeros);
2271 memcpy(data + zeros, text, 4 - zeros);
2273 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2274 if (size <= offset - zeros)
2277 text += offset - zeros;
2278 size -= offset - zeros;
2281 memcpy(data, text, 4);
2283 memcpy(data, text, size);
2284 memset(data + size, 0, 4 - size);
2287 for (size_t i(0); i != 4; ++i)
2288 if (isalpha(data[i]))
2296 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2298 /* XXX: ntohl may be more honest */
2299 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2302 CFComparisonResult StringNameCompare(CFStringRef lhn, CFStringRef rhn, size_t length) {
2303 _profile(PackageNameCompare)
2305 return rhn == NULL ? kCFCompareEqualTo : kCFCompareLessThan;
2306 else if (rhn == NULL)
2307 return kCFCompareGreaterThan;
2309 CFIndex length(CFStringGetLength(lhn));
2311 _profile(PackageNameCompare$NumbersLast)
2312 if (length != 0 && CFStringGetLength(rhn) != 0) {
2313 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2314 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2315 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2316 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2317 return lha ? kCFCompareLessThan : kCFCompareGreaterThan;
2321 _profile(PackageNameCompare$Compare)
2322 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, (CFLocaleRef) (id) CollationLocale_);
2327 _finline CFComparisonResult StringNameCompare(NSString *lhn, NSString*rhn, size_t length) {
2328 return StringNameCompare((CFStringRef) lhn, (CFStringRef) rhn, length);
2331 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2332 CYString &lhn(PackageName(lhs, @selector(cyname)));
2333 NSString *rhn(PackageName(rhs, @selector(cyname)));
2334 return StringNameCompare(lhn, rhn, lhn.size());
2337 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *arg) {
2338 return PackageNameCompare(*lhs, *rhs, arg);
2341 struct PackageNameOrdering :
2342 std::binary_function<Package *, Package *, bool>
2344 _finline bool operator ()(Package *lhs, Package *rhs) const {
2345 return PackageNameCompare(lhs, rhs, NULL) == kCFCompareLessThan;
2349 @implementation Package
2351 - (NSString *) description {
2352 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2358 if (parsed_ != NULL)
2363 + (NSString *) webScriptNameForSelector:(SEL)selector {
2365 else if (selector == @selector(clear))
2367 else if (selector == @selector(getField:))
2369 else if (selector == @selector(getRecord))
2370 return @"getRecord";
2371 else if (selector == @selector(hasTag:))
2373 else if (selector == @selector(install))
2375 else if (selector == @selector(remove))
2381 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2382 return [self webScriptNameForSelector:selector] == nil;
2385 + (NSArray *) _attributeKeys {
2386 return [NSArray arrayWithObjects:
2407 @"shortDescription",
2420 - (NSArray *) attributeKeys {
2421 return [[self class] _attributeKeys];
2424 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2425 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2428 - (NSArray *) relations {
2429 @synchronized (database_) {
2430 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2431 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2432 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2436 - (NSString *) architecture {
2438 @synchronized (database_) {
2439 return parsed_->architecture_.empty() ? [NSNull null] : (id) parsed_->architecture_;
2442 - (NSString *) getField:(NSString *)name {
2443 @synchronized (database_) {
2444 if ([database_ era] != era_ || file_.end())
2447 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2449 const char *start, *end;
2450 if (!parser.Find([name UTF8String], start, end))
2451 return (NSString *) [NSNull null];
2453 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2456 - (NSString *) getRecord {
2457 @synchronized (database_) {
2458 if ([database_ era] != era_ || file_.end())
2461 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2463 const char *start, *end;
2464 parser.GetRec(start, end);
2466 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2470 if (parsed_ != NULL)
2472 @synchronized (database_) {
2473 if ([database_ era] != era_ || file_.end())
2476 ParsedPackage *parsed(new ParsedPackage);
2479 _profile(Package$parse)
2480 pkgRecords::Parser *parser;
2482 _profile(Package$parse$Lookup)
2483 parser = &[database_ records]->Lookup(file_);
2489 _profile(Package$parse$Find)
2494 {"architecture", &parsed->architecture_},
2495 {"icon", &parsed->icon_},
2496 {"depiction", &parsed->depiction_},
2497 {"homepage", &parsed->homepage_},
2498 {"website", &website},
2500 {"support", &parsed->support_},
2501 {"author", &parsed->author_},
2502 {"md5sum", &parsed->md5sum_},
2505 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2506 const char *start, *end;
2508 if (parser->Find(names[i].name_, start, end)) {
2509 CYString &value(*names[i].value_);
2510 _profile(Package$parse$Value)
2511 value.set(pool_, start, end - start);
2517 _profile(Package$parse$Tagline)
2518 const char *start, *end;
2519 if (parser->ShortDesc(start, end)) {
2520 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2523 while (stop != start && stop[-1] == '\r')
2525 parsed->tagline_.set(pool_, start, stop - start);
2529 _profile(Package$parse$Retain)
2530 if (parsed->homepage_.empty())
2531 parsed->homepage_ = website;
2532 if (parsed->homepage_ == parsed->depiction_)
2533 parsed->homepage_.clear();
2534 if (parsed->support_.empty())
2535 parsed->support_ = bugs;
2540 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database {
2541 if ((self = [super init]) != nil) {
2542 _profile(Package$initWithVersion)
2544 pool_ = new CYPool();
2550 database_ = database;
2551 era_ = [database era];
2555 pkgCache::PkgIterator iterator(version.ParentPkg());
2556 iterator_ = iterator;
2558 _profile(Package$initWithVersion$Version)
2559 if (!version_.end())
2560 file_ = version_.FileList();
2562 pkgCache &cache([database_ cache]);
2563 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2567 _profile(Package$initWithVersion$Cache)
2568 name_.set(NULL, iterator.Display());
2570 latest_.set(NULL, StripVersion_(version_.VerStr()));
2572 pkgCache::VerIterator current(iterator.CurrentVer());
2574 installed_.set(NULL, StripVersion_(current.VerStr()));
2577 _profile(Package$initWithVersion$Transliterate) do {
2578 if (CollationTransl_ == NULL)
2583 _profile(Package$initWithVersion$Transliterate$utf8)
2584 const uint8_t *data(reinterpret_cast<const uint8_t *>(name_.data()));
2585 for (size_t i(0), e(name_.size()); i != e; ++i)
2586 if (data[i] >= 0x80)
2591 UErrorCode code(U_ZERO_ERROR);
2594 _profile(Package$initWithVersion$Transliterate$u_strFromUTF8WithSub)
2595 CollationString_.resize(name_.size());
2596 u_strFromUTF8WithSub(&CollationString_[0], CollationString_.size(), &length, name_.data(), name_.size(), 0xfffd, NULL, &code);
2597 if (!U_SUCCESS(code))
2599 CollationString_.resize(length);
2602 _profile(Package$initWithVersion$Transliterate$utrans_trans)
2603 length = CollationString_.size();
2604 utrans_trans(CollationTransl_, reinterpret_cast<UReplaceable *>(&CollationString_), &CollationUCalls_, 0, &length, &code);
2605 if (!U_SUCCESS(code))
2607 _assert(CollationString_.size() == length);
2610 _profile(Package$initWithVersion$Transliterate$u_strToUTF8WithSub$preflight)
2611 u_strToUTF8WithSub(NULL, 0, &length, CollationString_.data(), CollationString_.size(), 0xfffd, NULL, &code);
2612 if (code == U_BUFFER_OVERFLOW_ERROR)
2613 code = U_ZERO_ERROR;
2614 else if (!U_SUCCESS(code))
2619 _profile(Package$initWithVersion$Transliterate$apr_palloc)
2620 transform = pool_->malloc<char>(length);
2622 _profile(Package$initWithVersion$Transliterate$u_strToUTF8WithSub$transform)
2623 u_strToUTF8WithSub(transform, length, NULL, CollationString_.data(), CollationString_.size(), 0xfffd, NULL, &code);
2624 if (!U_SUCCESS(code))
2628 transform_.set(NULL, transform, length);
2629 } while (false); _end
2631 _profile(Package$initWithVersion$Tags)
2632 pkgCache::TagIterator tag(iterator.TagList());
2634 tags_ = [NSMutableArray arrayWithCapacity:8];
2636 goto tag; for (; !tag.end(); ++tag) tag: {
2637 const char *name(tag.Name());
2638 NSString *string((NSString *) CYStringCreate(name));
2642 [tags_ addObject:[string autorelease]];
2644 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2645 if (strcmp(name + 6, "enduser") == 0)
2647 else if (strcmp(name + 6, "hacker") == 0)
2649 else if (strcmp(name + 6, "developer") == 0)
2651 else if (strcmp(name + 6, "cydia") == 0)
2657 if (strncmp(name, "cydia::", 7) == 0) {
2658 if (strcmp(name + 7, "essential") == 0)
2660 else if (strcmp(name + 7, "obsolete") == 0)
2667 _profile(Package$initWithVersion$Metadata)
2668 const char *mixed(iterator.Name());
2669 size_t size(strlen(mixed));
2670 static const size_t prefix(sizeof("/var/lib/dpkg/info/") - 1);
2671 char lower[prefix + size + 5 + 1];
2673 for (size_t i(0); i != size; ++i)
2674 lower[prefix + i] = mixed[i] | 0x20;
2676 if (!installed_.empty()) {
2677 memcpy(lower, "/var/lib/dpkg/info/", prefix);
2678 memcpy(lower + prefix + size, ".list", 6);
2680 if (stat(lower, &info) != -1)
2681 upgraded_ = info.st_birthtime;
2684 PackageValue *metadata(PackageFind(lower + prefix, size));
2685 metadata_ = metadata;
2687 id_.set(NULL, metadata->name_, size);
2689 const char *latest(version_.VerStr());
2690 size_t length(strlen(latest));
2692 uint16_t vhash(hashlittle(latest, length));
2694 size_t capped(std::min<size_t>(8, length));
2695 latest = latest + length - capped;
2697 if (metadata->first_ == 0)
2698 metadata->first_ = now_;
2700 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2701 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2702 metadata->vhash_ = vhash;
2703 metadata->last_ = now_;
2704 } else if (metadata->last_ == 0)
2705 metadata->last_ = metadata->first_;
2708 _profile(Package$initWithVersion$Section)
2709 section_ = version_.Section();
2712 _profile(Package$initWithVersion$Flags)
2713 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2714 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2719 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database {
2720 pkgCache::VerIterator version;
2722 _profile(Package$packageWithIterator$GetCandidateVer)
2723 version = [database policy]->GetCandidateVer(iterator);
2731 _profile(Package$packageWithIterator$Allocate)
2732 package = [Package allocWithZone:zone];
2735 _profile(Package$packageWithIterator$Initialize)
2737 initWithVersion:version
2744 _profile(Package$packageWithIterator$Autorelease)
2745 package = [package autorelease];
2751 - (pkgCache::PkgIterator) iterator {
2755 - (NSString *) section {
2756 if (section$_ == nil) {
2757 if (section_ == NULL)
2760 _profile(Package$section$mappedSectionForPointer)
2761 section$_ = [database_ mappedSectionForPointer:section_];
2766 - (NSString *) simpleSection {
2767 if (NSString *section = [self section])
2768 return Simplify(section);
2773 - (NSString *) longSection {
2774 return LocalizeSection([self section]);
2777 - (NSString *) shortSection {
2778 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2781 - (NSString *) uri {
2784 pkgIndexFile *index;
2785 pkgCache::PkgFileIterator file(file_.File());
2786 if (![database_ list].FindIndex(file, index))
2788 return [NSString stringWithUTF8String:iterator_->Path];
2789 //return [NSString stringWithUTF8String:file.Site()];
2790 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2794 - (MIMEAddress *) maintainer {
2795 @synchronized (database_) {
2796 if ([database_ era] != era_ || file_.end())
2799 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2800 const std::string &maintainer(parser->Maintainer());
2801 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2804 - (NSString *) md5sum {
2805 return parsed_ == NULL ? nil : (id) parsed_->md5sum_;
2809 @synchronized (database_) {
2810 if ([database_ era] != era_ || version_.end())
2813 return version_->InstalledSize;
2816 - (NSString *) longDescription {
2817 @synchronized (database_) {
2818 if ([database_ era] != era_ || file_.end())
2821 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2822 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2824 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2825 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2826 if ([lines count] < 2)
2829 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2830 for (size_t i(1), e([lines count]); i != e; ++i) {
2831 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2832 [trimmed addObject:trim];
2835 return [trimmed componentsJoinedByString:@"\n"];
2838 - (NSString *) shortDescription {
2839 if (parsed_ != NULL)
2840 return static_cast<NSString *>(parsed_->tagline_);
2842 @synchronized (database_) {
2843 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2845 const char *start, *end;
2846 if (!parser.ShortDesc(start, end))
2849 if (end - start > 200)
2853 if (const char *stop = reinterpret_cast<const char *>(memchr(start, '\n', end - start)))
2856 while (end != start && end[-1] == '\r')
2860 return [(id) CYStringCreate(start, end - start) autorelease];
2864 _profile(Package$index)
2865 CFStringRef name((CFStringRef) [self name]);
2866 if (CFStringGetLength(name) == 0)
2868 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2869 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2871 return toupper(character);
2875 - (PackageValue *) metadata {
2880 PackageValue *metadata([self metadata]);
2881 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2884 - (bool) subscribed {
2885 return [self metadata]->subscribed_;
2888 - (bool) setSubscribed:(bool)subscribed {
2889 PackageValue *metadata([self metadata]);
2890 if (metadata->subscribed_ == subscribed)
2892 metadata->subscribed_ = subscribed;
2900 - (NSString *) latest {
2904 - (NSString *) installed {
2908 - (BOOL) uninstalled {
2909 return installed_.empty();
2913 return !version_.end();
2916 - (BOOL) upgradableAndEssential:(BOOL)essential {
2917 _profile(Package$upgradableAndEssential)
2918 pkgCache::VerIterator current(iterator_.CurrentVer());
2920 return essential && essential_;
2922 return !version_.end() && version_ != current;
2926 - (BOOL) essential {
2931 return [database_ cache][iterator_].InstBroken();
2934 - (BOOL) unfiltered {
2935 _profile(Package$unfiltered$obsolete)
2936 if (_unlikely(obsolete_))
2940 _profile(Package$unfiltered$role)
2941 if (_unlikely(role_ > 3))
2949 if (![self unfiltered])
2954 _profile(Package$visible$section)
2955 section = [self section];
2958 _profile(Package$visible$isSectionVisible)
2959 if (!isSectionVisible(section))
2967 unsigned char current(iterator_->CurrentState);
2968 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2971 - (BOOL) halfConfigured {
2972 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2975 - (BOOL) halfInstalled {
2976 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2980 @synchronized (database_) {
2981 if ([database_ era] != era_ || iterator_.end())
2984 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2985 return state.Mode != pkgDepCache::ModeKeep;
2988 - (NSString *) mode {
2989 @synchronized (database_) {
2990 if ([database_ era] != era_ || iterator_.end())
2993 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2995 switch (state.Mode) {
2996 case pkgDepCache::ModeDelete:
2997 if ((state.iFlags & pkgDepCache::Purge) != 0)
3001 case pkgDepCache::ModeKeep:
3002 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
3003 return @"REINSTALL";
3004 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
3008 case pkgDepCache::ModeInstall:
3009 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
3010 return @"REINSTALL";
3011 else*/ switch (state.Status) {
3013 return @"DOWNGRADE";
3019 return @"NEW_INSTALL";
3030 - (NSString *) name {
3031 return name_.empty() ? id_ : name_;
3034 - (UIImage *) icon {
3035 NSString *section = [self simpleSection];
3038 if (parsed_ != NULL)
3039 if (NSString *href = parsed_->icon_)
3040 if ([href hasPrefix:@"file:///"])
3041 icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
3042 if (icon == nil) if (section != nil)
3043 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]];
3044 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
3045 if ([dicon hasPrefix:@"file:///"])
3046 icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
3048 icon = [UIImage imageNamed:@"unknown.png"];
3052 - (NSString *) homepage {
3053 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
3056 - (NSString *) depiction {
3057 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
3060 - (MIMEAddress *) author {
3061 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
3064 - (NSString *) support {
3065 return parsed_ != NULL && !parsed_->support_.empty() ? parsed_->support_ : [[self source] supportForPackage:id_];
3068 - (NSArray *) files {
3069 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
3070 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
3073 fin.open([path UTF8String]);
3078 while (std::getline(fin, line))
3079 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
3084 - (NSString *) state {
3085 @synchronized (database_) {
3086 if ([database_ era] != era_ || file_.end())
3089 switch (iterator_->CurrentState) {
3090 case pkgCache::State::NotInstalled:
3091 return @"NotInstalled";
3092 case pkgCache::State::UnPacked:
3094 case pkgCache::State::HalfConfigured:
3095 return @"HalfConfigured";
3096 case pkgCache::State::HalfInstalled:
3097 return @"HalfInstalled";
3098 case pkgCache::State::ConfigFiles:
3099 return @"ConfigFiles";
3100 case pkgCache::State::Installed:
3101 return @"Installed";
3102 case pkgCache::State::TriggersAwaited:
3103 return @"TriggersAwaited";
3104 case pkgCache::State::TriggersPending:
3105 return @"TriggersPending";
3108 return (NSString *) [NSNull null];
3111 - (NSString *) selection {
3112 @synchronized (database_) {
3113 if ([database_ era] != era_ || file_.end())
3116 switch (iterator_->SelectedState) {
3117 case pkgCache::State::Unknown:
3119 case pkgCache::State::Install:
3121 case pkgCache::State::Hold:
3123 case pkgCache::State::DeInstall:
3124 return @"DeInstall";
3125 case pkgCache::State::Purge:
3129 return (NSString *) [NSNull null];
3132 - (NSArray *) warnings {
3133 @synchronized (database_) {
3134 if ([database_ era] != era_ || file_.end())
3137 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
3138 const char *name(iterator_.Name());
3140 size_t length(strlen(name));
3141 if (length < 2) invalid:
3142 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
3143 else for (size_t i(0); i != length; ++i)
3145 /* XXX: technically this is not allowed */
3146 (name[i] < 'A' || name[i] > 'Z') &&
3147 (name[i] < 'a' || name[i] > 'z') &&
3148 (name[i] < '0' || name[i] > '9') &&
3149 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
3152 if (strcmp(name, "cydia") != 0) {
3155 bool _private = false;
3157 bool dbstash = false;
3158 bool dsstore = false;
3160 bool repository = [[self section] isEqualToString:@"Repositories"];
3162 if (NSArray *files = [self files])
3163 for (NSString *file in files)
3164 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
3166 else if (!user && [file isEqualToString:@"/User"])
3168 else if (!_private && [file isEqualToString:@"/private"])
3170 else if (!stash && [file isEqualToString:@"/var/stash"])
3172 else if (!dbstash && [file isEqualToString:@"/var/db/stash"])
3174 else if (!dsstore && [file hasSuffix:@"/.DS_Store"])
3177 /* XXX: this is not sensitive enough. only some folders are valid. */
3178 if (cydia && !repository)
3179 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
3181 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
3183 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
3185 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
3187 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/db/stash"]];
3189 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @".DS_Store"]];
3192 return [warnings count] == 0 ? nil : warnings;
3195 - (NSArray *) applications {
3196 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
3198 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
3200 static RegEx application_r("/Applications/(.*)\\.app/Info.plist");
3201 if (NSArray *files = [self files])
3202 for (NSString *file in files)
3203 if (application_r(file)) {
3204 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
3205 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
3206 if ([id isEqualToString:me])
3209 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
3211 display = application_r[1];
3213 NSString *bundle([file stringByDeletingLastPathComponent]);
3214 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
3215 // XXX: maybe this should check if this is really a string, not just for length
3216 if (icon == nil || ![icon respondsToSelector:@selector(length)] || [icon length] == 0)
3218 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
3220 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
3221 [applications addObject:application];
3223 [application addObject:id];
3224 [application addObject:display];
3225 [application addObject:url];
3228 return [applications count] == 0 ? nil : applications;
3231 - (Source *) source {
3232 if (source_ == nil) {
3233 @synchronized (database_) {
3234 if ([database_ era] != era_ || file_.end())
3235 source_ = (Source *) [NSNull null];
3237 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
3241 return source_ == (Source *) [NSNull null] ? nil : source_;
3244 - (time_t) upgraded {
3248 - (uint32_t) recent {
3249 return std::numeric_limits<uint32_t>::max() - upgraded_;
3256 - (BOOL) matches:(NSArray *)query {
3257 if (query == nil || [query count] == 0)
3266 string = [self name];
3267 length = [string length];
3270 for (NSString *term in query) {
3271 range = [string rangeOfString:term options:MatchCompareOptions_];
3272 if (range.location != NSNotFound)
3273 rank_ -= 6 * 1000000 / length;
3278 length = [string length];
3281 for (NSString *term in query) {
3282 range = [string rangeOfString:term options:MatchCompareOptions_];
3283 if (range.location != NSNotFound)
3284 rank_ -= 6 * 1000000 / length;
3288 string = [self shortDescription];
3289 length = [string length];
3290 NSUInteger stop(std::min<NSUInteger>(length, 200));
3293 for (NSString *term in query) {
3294 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
3295 if (range.location != NSNotFound)
3296 rank_ -= 2 * 100000;
3302 - (NSArray *) tags {
3306 - (BOOL) hasTag:(NSString *)tag {
3307 return tags_ == nil ? NO : [tags_ containsObject:tag];
3310 - (NSString *) primaryPurpose {
3311 for (NSString *tag in (NSArray *) tags_)
3312 if ([tag hasPrefix:@"purpose::"])
3313 return [tag substringFromIndex:9];
3317 - (NSArray *) purposes {
3318 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
3319 for (NSString *tag in (NSArray *) tags_)
3320 if ([tag hasPrefix:@"purpose::"])
3321 [purposes addObject:[tag substringFromIndex:9]];
3322 return [purposes count] == 0 ? nil : purposes;
3325 - (bool) isCommercial {
3326 return [self hasTag:@"cydia::commercial"];
3329 - (void) setIndex:(size_t)index {
3330 if (metadata_->index_ != index)
3331 metadata_->index_ = index;
3334 - (CYString &) cyname {
3335 return !transform_.empty() ? transform_ : !name_.empty() ? name_ : id_;
3338 - (uint32_t) compareBySection:(NSArray *)sections {
3339 NSString *section([self section]);
3340 for (size_t i(0), e([sections count]); i != e; ++i) {
3341 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3345 return _not(uint32_t);
3349 @synchronized (database_) {
3350 pkgProblemResolver *resolver = [database_ resolver];
3351 resolver->Clear(iterator_);
3353 pkgCacheFile &cache([database_ cache]);
3354 cache->SetReInstall(iterator_, false);
3355 cache->MarkKeep(iterator_, false);
3359 @synchronized (database_) {
3360 pkgProblemResolver *resolver = [database_ resolver];
3361 resolver->Clear(iterator_);
3362 resolver->Protect(iterator_);
3364 pkgCacheFile &cache([database_ cache]);
3365 cache->SetReInstall(iterator_, false);
3366 cache->MarkInstall(iterator_, false);
3368 pkgDepCache::StateCache &state((*cache)[iterator_]);
3369 if (!state.Install())
3370 cache->SetReInstall(iterator_, true);
3374 @synchronized (database_) {
3375 pkgProblemResolver *resolver = [database_ resolver];
3376 resolver->Clear(iterator_);
3377 resolver->Remove(iterator_);
3378 resolver->Protect(iterator_);
3380 pkgCacheFile &cache([database_ cache]);
3381 cache->SetReInstall(iterator_, false);
3382 cache->MarkDelete(iterator_, true);
3387 /* Section Class {{{ */
3388 @interface Section : NSObject {
3392 _H<NSString> localized_;
3395 - (NSComparisonResult) compareByLocalized:(Section *)section;
3396 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3397 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3398 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3400 - (NSString *) name;
3401 - (void) setName:(NSString *)name;
3407 - (void) addToCount;
3409 - (void) setCount:(size_t)count;
3410 - (NSString *) localized;
3414 @implementation Section
3416 - (NSComparisonResult) compareByLocalized:(Section *)section {
3417 NSString *lhs(localized_);
3418 NSString *rhs([section localized]);
3420 /*if ([lhs length] != 0 && [rhs length] != 0) {
3421 unichar lhc = [lhs characterAtIndex:0];
3422 unichar rhc = [rhs characterAtIndex:0];
3424 if (isalpha(lhc) && !isalpha(rhc))
3425 return NSOrderedAscending;
3426 else if (!isalpha(lhc) && isalpha(rhc))
3427 return NSOrderedDescending;
3430 return [lhs compare:rhs options:LaxCompareOptions_];
3433 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3434 if ((self = [self initWithName:name localize:NO]) != nil) {
3435 if (localized != nil)
3436 localized_ = localized;
3440 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3441 return [self initWithName:name row:0 localize:localize];
3444 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3445 if ((self = [super init]) != nil) {
3449 localized_ = LocalizeSection(name_);
3453 - (NSString *) name {
3457 - (void) setName:(NSString *)name {
3473 - (void) addToCount {
3477 - (void) setCount:(size_t)count {
3481 - (NSString *) localized {
3488 class CydiaLogCleaner :
3489 public pkgArchiveCleaner
3492 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3497 /* Database Implementation {{{ */
3498 @implementation Database
3500 + (Database *) sharedInstance {
3501 static _H<Database> instance;
3502 if (instance == nil)
3503 instance = [[[Database alloc] init] autorelease];
3511 - (void) releasePackages {
3512 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3513 CFArrayRemoveAllValues(packages_);
3517 // XXX: actually implement this thing
3519 [self releasePackages];
3520 NSRecycleZone(zone_);
3524 - (void) _readCydia:(NSNumber *)fd {
3525 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3526 std::istream is(&ib);
3529 static RegEx finish_r("finish:([^:]*)");
3531 while (std::getline(is, line)) {
3532 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3534 const char *data(line.c_str());
3535 size_t size = line.size();
3536 lprintf("C:%s\n", data);
3538 if (finish_r(data, size)) {
3539 NSString *finish = finish_r[1];
3540 int index = [Finishes_ indexOfObject:finish];
3541 if (index != INT_MAX && index > Finish_)
3551 - (void) _readStatus:(NSNumber *)fd {
3552 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3553 std::istream is(&ib);
3556 static RegEx conffile_r("status: [^ ]* : conffile-prompt : (.*?) *");
3557 static RegEx pmstatus_r("([^:]*):([^:]*):([^:]*):(.*)");
3559 while (std::getline(is, line)) {
3560 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3562 const char *data(line.c_str());
3563 size_t size(line.size());
3564 lprintf("S:%s\n", data);
3566 if (conffile_r(data, size)) {
3567 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3568 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3569 } else if (strncmp(data, "status: ", 8) == 0) {
3570 // status: <package>: {unpacked,half-configured,installed}
3571 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3572 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3573 } else if (strncmp(data, "processing: ", 12) == 0) {
3574 // processing: configure: config-test
3575 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3576 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3577 } else if (pmstatus_r(data, size)) {
3578 std::string type([pmstatus_r[1] UTF8String]);
3580 NSString *package = pmstatus_r[2];
3581 if ([package isEqualToString:@"dpkg-exec"])
3584 float percent([pmstatus_r[3] floatValue]);
3585 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3587 NSString *string = pmstatus_r[4];
3589 if (type == "pmerror") {
3590 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3591 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3592 } else if (type == "pmstatus") {
3593 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3594 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3595 } else if (type == "pmconffile")
3596 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3598 lprintf("E:unknown pmstatus\n");
3600 lprintf("E:unknown status\n");
3608 - (void) _readOutput:(NSNumber *)fd {
3609 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3610 std::istream is(&ib);
3613 while (std::getline(is, line)) {
3614 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3616 lprintf("O:%s\n", line.c_str());
3618 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3619 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3631 - (Package *) packageWithName:(NSString *)name {
3634 @synchronized (self) {
3635 if (static_cast<pkgDepCache *>(cache_) == NULL)
3637 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3638 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:NULL database:self];
3642 if ((self = [super init]) != nil) {
3649 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3651 size_t capacity(MetaFile_->active_);
3657 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3658 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3662 _assert(pipe(fds) != -1);
3665 _config->Set("APT::Keep-Fds::", cydiafd_);
3666 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3669 detachNewThreadSelector:@selector(_readCydia:)
3671 withObject:[NSNumber numberWithInt:fds[0]]
3674 _assert(pipe(fds) != -1);
3678 detachNewThreadSelector:@selector(_readStatus:)
3680 withObject:[NSNumber numberWithInt:fds[0]]
3683 _assert(pipe(fds) != -1);
3684 _assert(dup2(fds[0], 0) != -1);
3685 _assert(close(fds[0]) != -1);
3687 input_ = fdopen(fds[1], "a");
3689 _assert(pipe(fds) != -1);
3690 _assert(dup2(fds[1], 1) != -1);
3691 _assert(close(fds[1]) != -1);
3694 detachNewThreadSelector:@selector(_readOutput:)
3696 withObject:[NSNumber numberWithInt:fds[0]]
3701 - (pkgCacheFile &) cache {
3705 - (pkgDepCache::Policy *) policy {
3709 - (pkgRecords *) records {
3713 - (pkgProblemResolver *) resolver {
3717 - (pkgAcquire &) fetcher {
3721 - (pkgSourceList &) list {
3725 - (NSArray *) packages {
3726 return (NSArray *) packages_;
3729 - (NSArray *) sources {
3733 - (Source *) sourceWithKey:(NSString *)key {
3734 for (Source *source in [self sources]) {
3735 if ([[source key] isEqualToString:key])
3740 - (bool) popErrorWithTitle:(NSString *)title {
3743 while (!_error->empty()) {
3745 bool warning(!_error->PopMessage(error));
3750 size_t size(error.size());
3751 if (size == 0 || error[size - 1] != '\n')
3753 error.resize(size - 1);
3756 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3758 static RegEx no_pubkey("GPG error:.* NO_PUBKEY .*");
3759 if (warning && no_pubkey(error.c_str()))
3762 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3768 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3769 return [self popErrorWithTitle:title] || !success;
3772 - (bool) popErrorWithTitle:(NSString *)title forReadList:(pkgSourceList &)list {
3773 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3775 if ([self popErrorWithTitle:title forOperation:list.Read(SOURCES_LIST)])
3780 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3781 @synchronized (self) {
3784 [self releasePackages];
3787 [sourceList_ removeAllObjects];
3808 new (&pool_) CYPool();
3810 NSRecycleZone(zone_);
3811 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3813 int chk(creat("/tmp/cydia.chk", 0644));
3817 if (invocation != nil)
3818 [invocation invoke];
3820 NSString *title(UCLocalize("DATABASE"));
3822 list_ = new pkgSourceList();
3823 _profile(reloadDataWithInvocation$ReadMainList)
3824 if ([self popErrorWithTitle:title forReadList:*list_])
3828 _profile(reloadDataWithInvocation$Source$initWithMetaIndex)
3829 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3830 Source *object([[[Source alloc] initWithMetaIndex:*source forDatabase:self inPool:&pool_] autorelease]);
3831 [sourceList_ addObject:object];
3835 _root(_system->Lock());
3838 OpProgress progress;
3841 _profile(reloadDataWithInvocation$pkgCacheFile)
3842 opened = cache_.Open(progress, false);
3845 // XXX: what if there are errors, but Open() == true? this should be merged with popError:
3846 while (!_error->empty()) {
3848 bool warning(!_error->PopMessage(error));
3850 lprintf("cache_.Open():[%s]\n", error.c_str());
3852 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3856 else if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3857 repair = @selector(configure);
3858 //else if (error == "The package lists or status file could not be parsed or opened.")
3859 // repair = @selector(update);
3860 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3861 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3862 // else if (error == "Malformed Status line")
3863 // else if (error == "The list of sources could not be read.")
3865 if (repair != NULL) {
3867 [delegate_ repairWithSelector:repair];
3877 unlink("/tmp/cydia.chk");
3879 now_ = [[NSDate date] timeIntervalSince1970];
3881 policy_ = new pkgDepCache::Policy();
3882 records_ = new pkgRecords(cache_);
3883 resolver_ = new pkgProblemResolver(cache_);
3884 fetcher_ = new pkgAcquire(&status_);
3887 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3888 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3892 _profile(reloadDataWithInvocation$pkgApplyStatus)
3893 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3897 if (cache_->BrokenCount() != 0) {
3898 _profile(pkgApplyStatus$pkgFixBroken)
3899 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3903 if (cache_->BrokenCount() != 0) {
3904 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3908 _profile(pkgApplyStatus$pkgMinimizeUpgrade)
3909 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3914 for (Source *object in (id) sourceList_) {
3915 metaIndex *source([object metaIndex]);
3916 std::vector<pkgIndexFile *> *indices = source->GetIndexFiles();
3917 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3918 // XXX: this could be more intelligent
3919 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3920 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3922 sourceMap_[cached->ID] = object;
3927 /*std::vector<Package *> packages;
3928 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3931 _profile(reloadDataWithInvocation$packageWithIterator)
3932 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3933 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:&pool_ database:self])
3934 //packages.push_back(package);
3935 CFArrayAppendValue(packages_, CFRetain(package));
3939 /*if (packages.empty())
3940 packages_ = [[NSArray alloc] init];
3942 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3945 _profile(reloadDataWithInvocation$radix$8)
3946 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(8)];
3949 _profile(reloadDataWithInvocation$radix$4)
3950 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3953 _profile(reloadDataWithInvocation$radix$0)
3954 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3957 _profile(reloadDataWithInvocation$insertion)
3958 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3961 /*_profile(reloadDataWithInvocation$CFQSortArray)
3962 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);
3965 /*_profile(reloadDataWithInvocation$stdsort)
3966 std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3969 /*_profile(reloadDataWithInvocation$CFArraySortValues)
3970 CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3973 /*_profile(reloadDataWithInvocation$sortUsingFunction)
3974 [packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3978 size_t count(CFArrayGetCount(packages_));
3979 MetaFile_->active_ = count;
3980 for (size_t index(0); index != count; ++index)
3981 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3986 @synchronized (self) {
3988 resolver_ = new pkgProblemResolver(cache_);
3990 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3991 if (!cache_[iterator].Keep())
3992 cache_->MarkKeep(iterator, false);
3993 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3994 cache_->SetReInstall(iterator, false);
3997 - (void) configure {
3998 NSString *dpkg = [NSString stringWithFormat:@"/usr/libexec/cydo --configure -a --status-fd %u", statusfd_];
4000 system([dpkg UTF8String]);
4005 @synchronized (self) {
4006 // XXX: I don't remember this condition
4011 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
4013 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
4015 if ([self popErrorWithTitle:title])
4019 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
4021 CydiaLogCleaner cleaner;
4022 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
4029 fetcher_->Shutdown();
4031 pkgRecords records(cache_);
4033 lock_ = new FileFd();
4034 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
4036 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
4038 if ([self popErrorWithTitle:title])
4042 if ([self popErrorWithTitle:title forReadList:list])
4045 manager_ = (_system->CreatePM(cache_));
4046 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
4053 bool substrate(RestartSubstrate_);
4054 RestartSubstrate_ = false;
4056 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
4058 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
4060 if ([self popErrorWithTitle:title forReadList:list])
4062 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
4063 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
4066 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4068 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
4070 [self popErrorWithTitle:title];
4074 bool failed = false;
4075 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
4076 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
4078 if ((*item)->Status == pkgAcquire::Item::StatIdle)
4081 std::string uri = (*item)->DescURI();
4082 std::string error = (*item)->ErrorText;
4084 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
4087 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError]);
4088 [delegate_ addProgressEventOnMainThread:event forTask:title];
4091 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4099 RestartSubstrate_ = true;
4102 pkgPackageManager::OrderResult result(manager_->DoInstall(statusfd_));
4103 if ([self popErrorWithTitle:title])
4106 if (result == pkgPackageManager::Failed) {
4111 if (result != pkgPackageManager::Completed) {
4116 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
4118 if ([self popErrorWithTitle:title forReadList:list])
4120 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
4121 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
4124 if (![before isEqualToArray:after])
4129 NSString *title(UCLocalize("UPGRADE"));
4130 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
4136 [self updateWithStatus:status_];
4139 - (void) updateWithStatus:(CancelStatus &)status {
4140 NSString *title(UCLocalize("REFRESHING_DATA"));
4143 if ([self popErrorWithTitle:title forReadList:list])
4147 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
4148 if ([self popErrorWithTitle:title])
4151 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4153 bool success(ListUpdate(status, list, PulseInterval_));
4154 if (status.WasCancelled())
4157 [self popErrorWithTitle:title forOperation:success];
4158 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
4162 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4165 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
4166 delegate_ = delegate;
4169 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
4170 progress_ = delegate;
4171 status_.setDelegate(delegate);
4174 - (NSObject<ProgressDelegate> *) progressDelegate {
4178 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
4179 SourceMap::const_iterator i(sourceMap_.find(file->ID));
4180 return i == sourceMap_.end() ? nil : i->second;
4183 - (void) setFetch:(bool)fetch forURI:(const char *)uri {
4184 for (Source *source in (id) sourceList_)
4185 [source setFetch:fetch forURI:uri];
4188 - (void) resetFetch {
4189 for (Source *source in (id) sourceList_)
4190 [source resetFetch];
4193 - (NSString *) mappedSectionForPointer:(const char *)section {
4194 _H<NSString> *mapped;
4196 _profile(Database$mappedSectionForPointer$Cache)
4197 mapped = §ions_[section];
4200 if (*mapped == NULL) {
4201 size_t length(strlen(section));
4202 char spaced[length + 1];
4204 _profile(Database$mappedSectionForPointer$Replace)
4205 for (size_t index(0); index != length; ++index)
4206 spaced[index] = section[index] == '_' ? ' ' : section[index];
4207 spaced[length] = '\0';
4212 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
4213 string = [NSString stringWithUTF8String:spaced];
4216 _profile(Database$mappedSectionForPointer$Map)
4217 string = [SectionMap_ objectForKey:string] ?: string;
4227 static _H<NSMutableSet> Diversions_;
4229 @interface Diversion : NSObject {
4232 _H<NSString> format_;
4237 @implementation Diversion
4239 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
4240 if ((self = [super init]) != nil) {
4241 pattern_ = [from UTF8String];
4247 - (NSString *) divert:(NSString *)url {
4248 return !pattern_(url) ? nil : pattern_->*format_;
4251 + (NSURL *) divertURL:(NSURL *)url {
4253 NSString *href([url absoluteString]);
4255 for (Diversion *diversion in (id) Diversions_)
4256 if (NSString *diverted = [diversion divert:href]) {
4258 NSLog(@"div: %@", diverted);
4260 url = [NSURL URLWithString:diverted];
4267 - (NSString *) key {
4271 - (NSUInteger) hash {
4275 - (BOOL) isEqual:(Diversion *)object {
4276 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
4281 @interface CydiaObject : NSObject {
4282 _H<CyteWebViewController> indirect_;
4283 _transient id delegate_;
4286 - (id) initWithDelegate:(IndirectDelegate *)indirect;
4292 @interface CydiaWebViewController : CyteWebViewController {
4293 _H<CydiaObject> cydia_;
4296 + (void) addDiversion:(Diversion *)diversion;
4297 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request;
4298 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia;
4299 - (void) setDelegate:(id)delegate;
4303 /* Web Scripting {{{ */
4304 @implementation CydiaObject
4306 - (id) initWithDelegate:(IndirectDelegate *)indirect {
4307 if ((self = [super init]) != nil) {
4308 indirect_ = (CyteWebViewController *) indirect;
4312 - (void) setDelegate:(id)delegate {
4313 delegate_ = delegate;
4316 + (NSArray *) _attributeKeys {
4317 return [NSArray arrayWithObjects:
4320 @"coreFoundationVersionNumber",
4336 - (NSArray *) attributeKeys {
4337 return [[self class] _attributeKeys];
4340 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4341 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4344 - (NSString *) version {
4348 - (NSString *) build {
4352 - (NSString *) coreFoundationVersionNumber {
4353 return [NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber];
4356 - (NSString *) device {
4357 return UniqueIdentifier();
4360 - (NSString *) firmware {
4361 return [[UIDevice currentDevice] systemVersion];
4364 - (NSString *) hostname {
4365 return [[UIDevice currentDevice] name];
4368 - (NSString *) idiom {
4369 return (id) Idiom_ ?: [NSNull null];
4372 - (NSString *) mcc {
4373 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode")))
4374 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault) autorelease];
4378 - (NSString *) mnc {
4379 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberNetworkCode")))
4380 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault) autorelease];
4384 - (NSString *) operator {
4385 if (CFStringRef (*$CTRegistrationCopyOperatorName)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTRegistrationCopyOperatorName")))
4386 return [(NSString *) (*$CTRegistrationCopyOperatorName)(kCFAllocatorDefault) autorelease];
4390 - (NSString *) bbsnum {
4391 return (id) BBSNum_ ?: [NSNull null];
4394 - (NSString *) ecid {
4395 return (id) ChipID_ ?: [NSNull null];
4398 - (NSString *) serial {
4399 return SerialNumber_;
4402 - (NSString *) role {
4403 return (id) [NSNull null];
4406 - (NSString *) model {
4407 return [NSString stringWithUTF8String:Machine_];
4410 + (NSString *) webScriptNameForSelector:(SEL)selector {
4412 else if (selector == @selector(addBridgedHost:))
4413 return @"addBridgedHost";
4414 else if (selector == @selector(addInsecureHost:))
4415 return @"addInsecureHost";
4416 else if (selector == @selector(addInternalRedirect::))
4417 return @"addInternalRedirect";
4418 else if (selector == @selector(addPipelinedHost:scheme:))
4419 return @"addPipelinedHost";
4420 else if (selector == @selector(addSource:::))
4421 return @"addSource";
4422 else if (selector == @selector(addTrivialSource:))
4423 return @"addTrivialSource";
4424 else if (selector == @selector(close))
4426 else if (selector == @selector(du:))
4428 else if (selector == @selector(stringWithFormat:arguments:))
4430 else if (selector == @selector(getAllSources))
4431 return @"getAllSources";
4432 else if (selector == @selector(getApplicationInfo:value:))
4433 return @"getApplicationInfoValue";
4434 else if (selector == @selector(getKernelNumber:))
4435 return @"getKernelNumber";
4436 else if (selector == @selector(getKernelString:))
4437 return @"getKernelString";
4438 else if (selector == @selector(getInstalledPackages))
4439 return @"getInstalledPackages";
4440 else if (selector == @selector(getIORegistryEntry::))
4441 return @"getIORegistryEntry";
4442 else if (selector == @selector(getLocaleIdentifier))
4443 return @"getLocaleIdentifier";
4444 else if (selector == @selector(getPreferredLanguages))
4445 return @"getPreferredLanguages";
4446 else if (selector == @selector(getPackageById:))
4447 return @"getPackageById";
4448 else if (selector == @selector(getMetadataKeys))
4449 return @"getMetadataKeys";
4450 else if (selector == @selector(getMetadataValue:))
4451 return @"getMetadataValue";
4452 else if (selector == @selector(getSessionValue:))
4453 return @"getSessionValue";
4454 else if (selector == @selector(installPackages:))
4455 return @"installPackages";
4456 else if (selector == @selector(isReachable:))
4457 return @"isReachable";
4458 else if (selector == @selector(localizedStringForKey:value:table:))
4460 else if (selector == @selector(popViewController:))
4461 return @"popViewController";
4462 else if (selector == @selector(refreshSources))
4463 return @"refreshSources";
4464 else if (selector == @selector(registerFrame:))
4465 return @"registerFrame";
4466 else if (selector == @selector(removeButton))
4467 return @"removeButton";
4468 else if (selector == @selector(saveConfig))
4469 return @"saveConfig";
4470 else if (selector == @selector(setMetadataValue::))
4471 return @"setMetadataValue";
4472 else if (selector == @selector(setSessionValue::))
4473 return @"setSessionValue";
4474 else if (selector == @selector(substitutePackageNames:))
4475 return @"substitutePackageNames";
4476 else if (selector == @selector(scrollToBottom:))
4477 return @"scrollToBottom";
4478 else if (selector == @selector(setAllowsNavigationAction:))
4479 return @"setAllowsNavigationAction";
4480 else if (selector == @selector(setBadgeValue:))
4481 return @"setBadgeValue";
4482 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
4483 return @"setButtonImage";
4484 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
4485 return @"setButtonTitle";
4486 else if (selector == @selector(setHidesBackButton:))
4487 return @"setHidesBackButton";
4488 else if (selector == @selector(setHidesNavigationBar:))
4489 return @"setHidesNavigationBar";
4490 else if (selector == @selector(setNavigationBarStyle:))
4491 return @"setNavigationBarStyle";
4492 else if (selector == @selector(setNavigationBarTintRed:green:blue:alpha:))
4493 return @"setNavigationBarTintColor";
4494 else if (selector == @selector(setPasteboardString:))
4495 return @"setPasteboardString";
4496 else if (selector == @selector(setPasteboardURL:))
4497 return @"setPasteboardURL";
4498 else if (selector == @selector(setScrollAlwaysBounceVertical:))
4499 return @"setScrollAlwaysBounceVertical";
4500 else if (selector == @selector(setScrollIndicatorStyle:))
4501 return @"setScrollIndicatorStyle";
4502 else if (selector == @selector(setToken:))
4504 else if (selector == @selector(setViewportWidth:))
4505 return @"setViewportWidth";
4506 else if (selector == @selector(statfs:))
4508 else if (selector == @selector(supports:))
4510 else if (selector == @selector(unload))
4516 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
4517 return [self webScriptNameForSelector:selector] == nil;
4520 - (BOOL) supports:(NSString *)feature {
4521 return [feature isEqualToString:@"window.open"];
4525 [delegate_ performSelectorOnMainThread:@selector(unloadData) withObject:nil waitUntilDone:NO];
4528 - (void) setScrollAlwaysBounceVertical:(NSNumber *)value {
4529 [indirect_ performSelectorOnMainThread:@selector(setScrollAlwaysBounceVerticalNumber:) withObject:value waitUntilDone:NO];
4532 - (void) setScrollIndicatorStyle:(NSString *)style {
4533 [indirect_ performSelectorOnMainThread:@selector(setScrollIndicatorStyleWithName:) withObject:style waitUntilDone:NO];
4536 - (void) addInternalRedirect:(NSString *)from :(NSString *)to {
4537 [CydiaWebViewController performSelectorOnMainThread:@selector(addDiversion:) withObject:[[[Diversion alloc] initWithFrom:from to:to] autorelease] waitUntilDone:NO];
4540 - (NSDictionary *) getApplicationInfo:(NSString *)display value:(NSString *)key {
4542 if (SBBundlePathForDisplayIdentifier(SBSSpringBoardServerPort(), [display UTF8String], path) != 0)
4543 return (id) [NSNull null];
4544 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:[[NSString stringWithUTF8String:path] stringByAppendingString:@"/Info.plist"]]);
4546 return (id) [NSNull null];
4547 return [info objectForKey:key];
4550 - (NSNumber *) getKernelNumber:(NSString *)name {
4551 const char *string([name UTF8String]);
4554 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4555 return (id) [NSNull null];
4557 if (size != sizeof(int))
4558 return (id) [NSNull null];
4561 if (sysctlbyname(string, &value, &size, NULL, 0) == -1)
4562 return (id) [NSNull null];
4564 return [NSNumber numberWithInt:value];
4567 - (NSString *) getKernelString:(NSString *)name {
4568 const char *string([name UTF8String]);
4571 if (sysctlbyname(string, NULL, &size, NULL, 0) == -1)
4572 return (id) [NSNull null];
4574 char value[size + 1];
4575 if (sysctlbyname(string, value, &size, NULL, 0) == -1)
4576 return (id) [NSNull null];
4578 // XXX: just in case you request something ludicrous
4581 return [NSString stringWithCString:value];
4584 - (NSObject *) getIORegistryEntry:(NSString *)path :(NSString *)entry {
4585 NSObject *value(CYIOGetValue([path UTF8String], entry));
4588 if ([value isKindOfClass:[NSData class]])
4589 value = CYHex((NSData *) value);
4594 - (NSArray *) getMetadataKeys {
4595 @synchronized (Values_) {
4596 return [Values_ allKeys];
4599 - (void) registerFrame:(DOMHTMLIFrameElement *)iframe {
4600 WebFrame *frame([iframe contentFrame]);
4601 [indirect_ registerFrame:frame];
4604 - (id) getMetadataValue:(NSString *)key {
4605 @synchronized (Values_) {
4606 return [Values_ objectForKey:key];
4609 - (void) setMetadataValue:(NSString *)key :(NSString *)value {
4610 @synchronized (Values_) {
4611 if (value == nil || value == (id) [WebUndefined undefined] || value == (id) [NSNull null])
4612 [Values_ removeObjectForKey:key];
4614 [Values_ setObject:value forKey:key];
4616 [delegate_ performSelectorOnMainThread:@selector(updateValues) withObject:nil waitUntilDone:YES];
4619 - (id) getSessionValue:(NSString *)key {
4620 @synchronized (SessionData_) {
4621 return [SessionData_ objectForKey:key];
4624 - (void) setSessionValue:(NSString *)key :(NSString *)value {
4625 @synchronized (SessionData_) {
4626 if (value == (id) [WebUndefined undefined])
4627 [SessionData_ removeObjectForKey:key];
4629 [SessionData_ setObject:value forKey:key];
4632 - (void) addBridgedHost:(NSString *)host {
4633 @synchronized (HostConfig_) {
4634 [BridgedHosts_ addObject:host];
4637 - (void) addInsecureHost:(NSString *)host {
4638 @synchronized (HostConfig_) {
4639 [InsecureHosts_ addObject:host];
4642 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4643 @synchronized (HostConfig_) {
4644 if (scheme != (id) [WebUndefined undefined])
4645 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4647 [PipelinedHosts_ addObject:host];
4650 - (void) popViewController:(NSNumber *)value {
4651 if (value == (id) [WebUndefined undefined])
4652 value = [NSNumber numberWithBool:YES];
4653 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4656 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4657 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4659 for (NSString *section in sections)
4660 [array addObject:section];
4662 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4665 distribution, @"Distribution",
4667 nil] waitUntilDone:NO];
4670 - (void) addTrivialSource:(NSString *)href {
4671 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4674 - (void) refreshSources {
4675 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4678 - (void) saveConfig {
4679 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4682 - (NSArray *) getAllSources {
4683 return [[Database sharedInstance] sources];
4686 - (NSArray *) getInstalledPackages {
4687 Database *database([Database sharedInstance]);
4688 @synchronized (database) {
4689 NSArray *packages([database packages]);
4690 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4691 for (Package *package in packages)
4692 if (![package uninstalled])
4693 [installed addObject:package];
4697 - (Package *) getPackageById:(NSString *)id {
4698 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4702 return (Package *) [NSNull null];
4705 - (NSString *) getLocaleIdentifier {
4706 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4709 - (NSArray *) getPreferredLanguages {
4713 - (NSArray *) statfs:(NSString *)path {
4716 if (path == nil || statfs([path UTF8String], &stat) == -1)
4719 return [NSArray arrayWithObjects:
4720 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4721 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4722 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4726 ssize_t DiskUsage(const char *path);
4728 - (NSNumber *) du:(NSString *)path {
4729 ssize_t usage(DiskUsage([path UTF8String]));
4732 return [NSNumber numberWithUnsignedLong:usage];
4736 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4739 - (NSNumber *) isReachable:(NSString *)name {
4740 return [NSNumber numberWithBool:IsReachable([name UTF8String])];
4743 - (void) installPackages:(NSArray *)packages {
4744 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4747 - (NSString *) substitutePackageNames:(NSString *)message {
4748 NSMutableArray *words([[[message componentsSeparatedByString:@" "] mutableCopy] autorelease]);
4749 for (size_t i(0), e([words count]); i != e; ++i) {
4750 NSString *word([words objectAtIndex:i]);
4751 if (Package *package = [[Database sharedInstance] packageWithName:word])
4752 [words replaceObjectAtIndex:i withObject:[package name]];
4755 return [words componentsJoinedByString:@" "];
4758 - (void) removeButton {
4759 [indirect_ removeButton];
4762 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4763 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4766 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4767 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4770 - (void) setBadgeValue:(id)value {
4771 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4774 - (void) setAllowsNavigationAction:(NSString *)value {
4775 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4778 - (void) setHidesBackButton:(NSString *)value {
4779 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4782 - (void) setHidesNavigationBar:(NSString *)value {
4783 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4786 - (void) setNavigationBarStyle:(NSString *)value {
4787 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4790 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4791 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4792 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4793 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4796 - (void) setPasteboardString:(NSString *)value {
4797 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4800 - (void) setPasteboardURL:(NSString *)value {
4801 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4804 - (void) setToken:(NSString *)token {
4805 // XXX: the website expects this :/
4808 - (void) scrollToBottom:(NSNumber *)animated {
4809 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4812 - (void) setViewportWidth:(float)width {
4813 [indirect_ setViewportWidthOnMainThread:width];
4816 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4817 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4818 unsigned count([arguments count]);
4820 for (unsigned i(0); i != count; ++i)
4821 values[i] = [arguments objectAtIndex:i];
4822 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4825 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4826 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4828 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4830 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4836 @interface NSURL (CydiaSecure)
4839 @implementation NSURL (CydiaSecure)
4841 - (bool) isCydiaSecure {
4842 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4845 @synchronized (HostConfig_) {
4846 if ([InsecureHosts_ containsObject:[self host]])
4855 /* Cydia Browser Controller {{{ */
4856 @implementation CydiaWebViewController
4858 - (NSURL *) navigationURL {
4859 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4862 + (void) _initialize {
4863 [super _initialize];
4865 Diversions_ = [NSMutableSet setWithCapacity:0];
4868 + (void) addDiversion:(Diversion *)diversion {
4869 [Diversions_ addObject:diversion];
4872 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4873 [super webView:view didClearWindowObject:window forFrame:frame];
4874 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
4877 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia {
4878 WebDataSource *source([frame dataSource]);
4879 NSURLResponse *response([source response]);
4880 NSURL *url([response URL]);
4881 NSString *scheme([[url scheme] lowercaseString]);
4883 bool bridged(false);
4885 @synchronized (HostConfig_) {
4886 if ([scheme isEqualToString:@"file"])
4888 else if ([scheme isEqualToString:@"https"])
4889 if ([BridgedHosts_ containsObject:[url host]])
4894 [window setValue:cydia forKey:@"cydia"];
4897 - (void) _setupMail:(MFMailComposeViewController *)controller {
4898 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4900 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4901 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4904 - (NSURL *) URLWithURL:(NSURL *)url {
4905 return [Diversion divertURL:url];
4908 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4909 return [CydiaWebViewController requestWithHeaders:[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
4912 - (NSURLRequest *) webThreadWebView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4913 return [CydiaWebViewController requestWithHeaders:[super webThreadWebView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
4916 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request {
4917 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
4919 NSURL *url([copy URL]);
4920 NSString *href([url absoluteString]);
4921 NSString *host([url host]);
4923 if ([href hasPrefix:@"https://cydia.saurik.com/TSS/"]) {
4924 if (NSString *agent = [copy valueForHTTPHeaderField:@"X-User-Agent"]) {
4925 [copy setValue:agent forHTTPHeaderField:@"User-Agent"];
4926 [copy setValue:nil forHTTPHeaderField:@"X-User-Agent"];
4929 [copy setValue:nil forHTTPHeaderField:@"Referer"];
4930 [copy setValue:nil forHTTPHeaderField:@"Origin"];
4932 [copy setURL:[NSURL URLWithString:[@"http://gs.apple.com/TSS/" stringByAppendingString:[href substringFromIndex:29]]]];
4936 if ([copy valueForHTTPHeaderField:@"X-Cydia-Cf"] == nil)
4937 [copy setValue:[NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber] forHTTPHeaderField:@"X-Cydia-Cf"];
4938 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4939 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4941 bool bridged; @synchronized (HostConfig_) {
4942 bridged = [BridgedHosts_ containsObject:host];
4945 if ([url isCydiaSecure] && bridged && UniqueID_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Id"] == nil)
4946 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
4951 - (void) setDelegate:(id)delegate {
4952 [super setDelegate:delegate];
4953 [cydia_ setDelegate:delegate];
4956 - (NSString *) applicationNameForUserAgent {
4961 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4962 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
4968 @interface AppCacheController : CydiaWebViewController {
4973 @implementation AppCacheController
4975 - (void) didReceiveMemoryWarning {
4976 // XXX: this doesn't work
4979 - (bool) retainsNetworkActivityIndicator {
4987 @interface NSObject (CydiaScript)
4988 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
4991 @implementation NSObject (CydiaScript)
4993 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
4999 @implementation NSArray (CydiaScript)
5001 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5002 WebScriptObject *object([context evaluateWebScript:@"[]"]);
5003 for (size_t i(0), e([self count]); i != e; ++i)
5004 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
5010 @implementation NSDictionary (CydiaScript)
5012 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5013 WebScriptObject *object([context evaluateWebScript:@"({})"]);
5015 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
5022 /* Confirmation Controller {{{ */
5023 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
5024 if (!iterator.end())
5025 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
5026 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
5028 pkgCache::PkgIterator package(dep.TargetPkg());
5031 if (strcmp(package.Name(), "mobilesubstrate") == 0)
5038 @protocol ConfirmationControllerDelegate
5039 - (void) cancelAndClear:(bool)clear;
5040 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
5044 @interface ConfirmationController : CydiaWebViewController {
5045 _transient Database *database_;
5047 _H<UIAlertView> essential_;
5049 _H<NSDictionary> changes_;
5050 _H<NSMutableArray> issues_;
5051 _H<NSDictionary> sizes_;
5056 - (id) initWithDatabase:(Database *)database;
5060 @implementation ConfirmationController
5064 RestartSubstrate_ = true;
5065 [delegate_ confirmWithNavigationController:[self navigationController]];
5068 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
5069 NSString *context([alert context]);
5071 if ([context isEqualToString:@"remove"]) {
5072 if (button == [alert cancelButtonIndex])
5074 else if (button == [alert firstOtherButtonIndex]) {
5075 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
5078 [alert dismissWithClickedButtonIndex:-1 animated:YES];
5079 } else if ([context isEqualToString:@"unable"]) {
5080 [self dismissModalViewControllerAnimated:YES];
5081 [alert dismissWithClickedButtonIndex:-1 animated:YES];
5083 [super alertView:alert clickedButtonAtIndex:button];
5087 - (void) _doContinue {
5088 [delegate_ cancelAndClear:NO];
5089 [self dismissModalViewControllerAnimated:YES];
5092 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
5093 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
5097 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5098 [super webView:view didClearWindowObject:window forFrame:frame];
5100 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
5101 (id) changes_, @"changes",
5102 (id) issues_, @"issues",
5103 (id) sizes_, @"sizes",
5105 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
5108 - (id) initWithDatabase:(Database *)database {
5109 if ((self = [super init]) != nil) {
5110 database_ = database;
5112 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
5113 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
5114 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
5115 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
5116 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
5120 pkgCacheFile &cache([database_ cache]);
5121 NSArray *packages([database_ packages]);
5122 pkgDepCache::Policy *policy([database_ policy]);
5124 issues_ = [NSMutableArray arrayWithCapacity:4];
5126 UpgradeCydia_ = false;
5128 for (Package *package in packages) {
5129 pkgCache::PkgIterator iterator([package iterator]);
5130 NSString *name([package id]);
5132 if ([package broken]) {
5133 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
5135 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5137 reasons, @"reasons",
5140 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
5144 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
5145 pkgCache::DepIterator start;
5146 pkgCache::DepIterator end;
5147 dep.GlobOr(start, end); // ++dep
5149 if (!cache->IsImportantDep(end))
5151 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
5154 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
5156 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5157 [NSString stringWithUTF8String:start.DepType()], @"relationship",
5158 clauses, @"clauses",
5162 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
5164 pkgCache::PkgIterator target(start.TargetPkg());
5165 if (target->ProvidesList != 0)
5166 reason = @"missing";
5168 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
5170 reason = @"installed";
5171 installed = [NSString stringWithUTF8String:ver.VerStr()];
5172 } else if (!cache[target].CandidateVerIter(cache).end())
5173 reason = @"uninstalled";
5174 else if (target->ProvidesList == 0)
5175 reason = @"uninstallable";
5177 reason = @"virtual";
5180 NSDictionary *version(start.TargetVer() == 0 ? (NSDictionary *) [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
5181 [NSString stringWithUTF8String:start.CompType()], @"operator",
5182 [NSString stringWithUTF8String:start.TargetVer()], @"value",
5185 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5186 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
5187 version, @"version",
5189 installed, @"installed",
5192 // yes, seriously. (wtf?)
5200 pkgDepCache::StateCache &state(cache[iterator]);
5202 static RegEx special_r("(firmware|gsc\\..*|cy\\+.*)");
5204 if (state.NewInstall())
5205 [installs addObject:name];
5206 // XXX: else if (state.Install())
5207 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
5208 [reinstalls addObject:name];
5209 // XXX: move before previous if
5210 else if (state.Upgrade())
5211 [upgrades addObject:name];
5212 else if (state.Downgrade())
5213 [downgrades addObject:name];
5214 else if (!state.Delete())
5215 // XXX: _assert(state.Keep());
5217 else if (special_r(name))
5218 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5219 [NSNull null], @"package",
5220 [NSArray arrayWithObjects:
5221 [NSDictionary dictionaryWithObjectsAndKeys:
5222 @"Conflicts", @"relationship",
5223 [NSArray arrayWithObjects:
5224 [NSDictionary dictionaryWithObjectsAndKeys:
5226 [NSNull null], @"version",
5227 @"installed", @"reason",
5234 if ([package essential])
5236 [removes addObject:name];
5239 if ([name isEqualToString:@"cydia"])
5240 UpgradeCydia_ = true;
5242 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
5243 substrate_ |= DepSubstrate(iterator.CurrentVer());
5248 else if (Advanced_) {
5249 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
5251 essential_ = [[[UIAlertView alloc]
5252 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
5253 message:UCLocalize("REMOVING_ESSENTIALS_EX")
5255 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
5257 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
5261 [essential_ setContext:@"remove"];
5262 [essential_ setNumberOfRows:2];
5264 essential_ = [[[UIAlertView alloc]
5265 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
5266 message:UCLocalize("UNABLE_TO_COMPLY_EX")
5268 cancelButtonTitle:UCLocalize("OKAY")
5269 otherButtonTitles:nil
5272 [essential_ setContext:@"unable"];
5275 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5276 installs, @"installs",
5277 reinstalls, @"reinstalls",
5278 upgrades, @"upgrades",
5279 downgrades, @"downgrades",
5280 removes, @"removes",
5283 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5284 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
5285 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
5288 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
5292 - (UIBarButtonItem *) leftButton {
5293 return [[[UIBarButtonItem alloc]
5294 initWithTitle:UCLocalize("CANCEL")
5295 style:UIBarButtonItemStylePlain
5297 action:@selector(cancelButtonClicked)
5302 - (void) applyRightButton {
5303 if ([issues_ count] == 0 && ![self isLoading])
5304 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
5305 initWithTitle:UCLocalize("CONFIRM")
5306 style:UIBarButtonItemStyleDone
5308 action:@selector(confirmButtonClicked)
5311 [[self navigationItem] setRightBarButtonItem:nil];
5315 - (void) cancelButtonClicked {
5316 [delegate_ cancelAndClear:YES];
5317 [self dismissModalViewControllerAnimated:YES];
5321 - (void) confirmButtonClicked {
5322 if (essential_ != nil)
5332 /* Progress Data {{{ */
5333 @interface CydiaProgressData : NSObject {
5334 _transient id delegate_;
5343 _H<NSMutableArray> events_;
5344 _H<NSString> title_;
5346 _H<NSString> status_;
5347 _H<NSString> finish_;
5352 @implementation CydiaProgressData
5354 + (NSArray *) _attributeKeys {
5355 return [NSArray arrayWithObjects:
5367 - (NSArray *) attributeKeys {
5368 return [[self class] _attributeKeys];
5371 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5372 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5376 if ((self = [super init]) != nil) {
5377 events_ = [NSMutableArray arrayWithCapacity:32];
5385 - (void) setDelegate:(id)delegate {
5386 delegate_ = delegate;
5389 - (void) setPercent:(float)value {
5393 - (NSNumber *) percent {
5394 return [NSNumber numberWithFloat:percent_];
5397 - (void) setCurrent:(float)value {
5401 - (NSNumber *) current {
5402 return [NSNumber numberWithFloat:current_];
5405 - (void) setTotal:(float)value {
5409 - (NSNumber *) total {
5410 return [NSNumber numberWithFloat:total_];
5413 - (void) setSpeed:(float)value {
5417 - (NSNumber *) speed {
5418 return [NSNumber numberWithFloat:speed_];
5421 - (NSArray *) events {
5425 - (void) removeAllEvents {
5426 [events_ removeAllObjects];
5429 - (void) addEvent:(CydiaProgressEvent *)event {
5430 [events_ addObject:event];
5433 - (void) setTitle:(NSString *)text {
5437 - (NSString *) title {
5441 - (void) setFinish:(NSString *)text {
5445 - (NSString *) finish {
5446 return (id) finish_ ?: [NSNull null];
5449 - (void) setRunning:(bool)running {
5453 - (NSNumber *) running {
5454 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5459 /* Progress Controller {{{ */
5460 @interface ProgressController : CydiaWebViewController <
5463 _transient Database *database_;
5464 _H<CydiaProgressData, 1> progress_;
5468 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5470 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5472 - (void) setTitle:(NSString *)title;
5473 - (void) setCancellable:(bool)cancellable;
5477 @implementation ProgressController
5480 [database_ setProgressDelegate:nil];
5484 - (UIBarButtonItem *) leftButton {
5485 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5486 initWithTitle:UCLocalize("CANCEL")
5487 style:UIBarButtonItemStylePlain
5489 action:@selector(cancel)
5490 ] autorelease] : nil;
5493 - (void) updateCancel {
5494 [super applyLeftButton];
5497 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5498 if ((self = [super init]) != nil) {
5499 database_ = database;
5500 delegate_ = delegate;
5502 [database_ setProgressDelegate:self];
5504 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5505 [progress_ setDelegate:self];
5507 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5509 [scroller_ setBackgroundColor:[UIColor blackColor]];
5511 [[self navigationItem] setHidesBackButton:YES];
5513 [self updateCancel];
5517 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5518 [super webView:view didClearWindowObject:window forFrame:frame];
5519 [window setValue:progress_ forKey:@"cydiaProgress"];
5522 - (void) updateProgress {
5523 [self dispatchEvent:@"CydiaProgressUpdate"];
5526 - (void) viewWillAppear:(BOOL)animated {
5527 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5528 [super viewWillAppear:animated];
5531 - (void) reloadSpringBoard {
5532 if (kCFCoreFoundationVersionNumber > 700) { // XXX: iOS 6.x
5533 system("/bin/launchctl stop com.apple.backboardd");
5535 system("/usr/bin/killall backboardd SpringBoard sbreload");
5539 pid_t pid(ExecFork());
5544 pid_t pid(ExecFork());
5546 execl("/usr/libexec/cydia/cydo", "cydo", "/usr/bin/sbreload", NULL);
5556 system("/usr/bin/killall backboardd SpringBoard sbreload");
5560 UpdateExternalStatus(0);
5563 [delegate_ saveState];
5567 [delegate_ returnToCydia];
5571 [delegate_ terminateWithSuccess];
5572 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5573 [delegate_ suspendWithAnimation:YES];
5575 [delegate_ suspend];*/
5587 UIProgressHUD *hud([delegate_ addProgressHUD]);
5588 [hud setText:UCLocalize("LOADING")];
5589 [self performSelector:@selector(reloadSpringBoard) withObject:nil afterDelay:0.5];
5595 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5596 SBReboot(SBSSpringBoardServerPort());
5598 reboot2(RB_AUTOBOOT);
5605 - (void) setTitle:(NSString *)title {
5606 [progress_ setTitle:title];
5607 [self updateProgress];
5610 - (UIBarButtonItem *) rightButton {
5611 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5612 initWithTitle:UCLocalize("CLOSE")
5613 style:UIBarButtonItemStylePlain
5615 action:@selector(close)
5619 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5620 UpdateExternalStatus(1);
5622 [progress_ setRunning:true];
5623 [self setTitle:title];
5624 // implicit updateProgress
5626 SHA1SumValue notifyconf; {
5628 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5631 MMap mmap(file, MMap::ReadOnly);
5633 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5634 notifyconf = sha1.Result();
5638 SHA1SumValue springlist; {
5640 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5643 MMap mmap(file, MMap::ReadOnly);
5645 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5646 springlist = sha1.Result();
5650 if (invocation != nil) {
5651 [invocation yieldToSelector:@selector(invoke)];
5652 [self setTitle:@"COMPLETE"];
5657 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5660 MMap mmap(file, MMap::ReadOnly);
5662 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5663 if (!(notifyconf == sha1.Result()))
5670 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5673 MMap mmap(file, MMap::ReadOnly);
5675 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5676 if (!(springlist == sha1.Result()))
5682 if (RestartSubstrate_)
5686 RestartSubstrate_ = false;
5689 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5690 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5691 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5692 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5693 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5696 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5698 [progress_ setRunning:false];
5699 [self updateProgress];
5701 [self applyRightButton];
5704 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5705 [progress_ addEvent:event];
5706 [self updateProgress];
5709 - (bool) isProgressCancelled {
5710 return cancel_ == 2;
5715 [self updateCancel];
5718 - (void) setCancellable:(bool)cancellable {
5719 unsigned cancel(cancel_);
5723 else if (cancel_ == 0)
5726 if (cancel != cancel_)
5727 [self updateCancel];
5730 - (void) setProgressCancellable:(NSNumber *)cancellable {
5731 [self setCancellable:[cancellable boolValue]];
5734 - (void) setProgressPercent:(NSNumber *)percent {
5735 [progress_ setPercent:[percent floatValue]];
5736 [self updateProgress];
5739 - (void) setProgressStatus:(NSDictionary *)status {
5740 if (status == nil) {
5741 [progress_ setCurrent:0];
5742 [progress_ setTotal:0];
5743 [progress_ setSpeed:0];
5745 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5747 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5748 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5749 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5752 [self updateProgress];
5758 /* Package Cell {{{ */
5759 @interface PackageCell : CyteTableViewCell <
5760 CyteTableViewCellDelegate
5764 _H<NSString> description_;
5766 _H<NSString> source_;
5768 _H<UIImage> placard_;
5772 - (PackageCell *) init;
5773 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5775 - (void) drawContentRect:(CGRect)rect;
5779 @implementation PackageCell
5781 - (PackageCell *) init {
5782 CGRect frame(CGRectMake(0, 0, 320, 74));
5783 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5784 UIView *content([self contentView]);
5785 CGRect bounds([content bounds]);
5787 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5788 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5789 [content addSubview:content_];
5791 [content_ setDelegate:self];
5792 [content_ setOpaque:YES];
5796 - (NSString *) accessibilityLabel {
5800 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5801 summarized_ = summary;
5811 [content_ setBackgroundColor:[UIColor whiteColor]];
5815 Source *source = [package source];
5817 icon_ = [package icon];
5819 if (NSString *name = [package name])
5820 name_ = [NSString stringWithString:name];
5822 if (NSString *description = [package shortDescription])
5823 description_ = [NSString stringWithString:description];
5825 commercial_ = [package isCommercial];
5827 NSString *label = nil;
5828 bool trusted = false;
5830 if (source != nil) {
5831 label = [source label];
5832 trusted = [source trusted];
5833 } else if ([[package id] isEqualToString:@"firmware"])
5834 label = UCLocalize("APPLE");
5836 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5838 NSString *from(label);
5840 NSString *section = [package simpleSection];
5841 if (section != nil && ![section isEqualToString:label]) {
5842 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5843 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5846 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5848 if (NSString *purpose = [package primaryPurpose])
5849 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5854 if (NSString *mode = [package mode]) {
5855 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5856 color = RemovingColor_;
5857 placard = @"removing";
5859 color = InstallingColor_;
5860 placard = @"installing";
5863 color = [UIColor whiteColor];
5865 if ([package installed] != nil)
5866 placard = @"installed";
5871 [content_ setBackgroundColor:color];
5874 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5877 [self setNeedsDisplay];
5878 [content_ setNeedsDisplay];
5881 - (void) drawSummaryContentRect:(CGRect)rect {
5882 bool highlighted(highlighted_);
5883 float width([self bounds].size.width);
5887 rect.size = [(UIImage *) icon_ size];
5889 while (rect.size.width > 16 || rect.size.height > 16) {
5890 rect.size.width /= 2;
5891 rect.size.height /= 2;
5894 rect.origin.x = 19 - rect.size.width / 2;
5895 rect.origin.y = 19 - rect.size.height / 2;
5897 [icon_ drawInRect:Retina(rect)];
5900 if (badge_ != nil) {
5902 rect.size = [(UIImage *) badge_ size];
5904 rect.size.width /= 4;
5905 rect.size.height /= 4;
5907 rect.origin.x = 25 - rect.size.width / 2;
5908 rect.origin.y = 25 - rect.size.height / 2;
5910 [badge_ drawInRect:Retina(rect)];
5913 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5917 UISetColor(commercial_ ? Purple_ : Black_);
5918 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
5920 if (placard_ != nil)
5921 [placard_ drawAtPoint:CGPointMake(width - 52, 11)];
5924 - (void) drawNormalContentRect:(CGRect)rect {
5925 bool highlighted(highlighted_);
5926 float width([self bounds].size.width);
5930 rect.size = [(UIImage *) icon_ size];
5932 while (rect.size.width > 32 || rect.size.height > 32) {
5933 rect.size.width /= 2;
5934 rect.size.height /= 2;
5937 rect.origin.x = 25 - rect.size.width / 2;
5938 rect.origin.y = 25 - rect.size.height / 2;
5940 [icon_ drawInRect:Retina(rect)];
5943 if (badge_ != nil) {
5945 rect.size = [(UIImage *) badge_ size];
5947 rect.size.width /= 2;
5948 rect.size.height /= 2;
5950 rect.origin.x = 36 - rect.size.width / 2;
5951 rect.origin.y = 36 - rect.size.height / 2;
5953 [badge_ drawInRect:Retina(rect)];
5956 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5960 UISetColor(commercial_ ? Purple_ : Black_);
5961 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
5962 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
5965 UISetColor(commercial_ ? Purplish_ : Gray_);
5966 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:NSLineBreakByTruncatingTail];
5968 if (placard_ != nil)
5969 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5972 - (void) drawContentRect:(CGRect)rect {
5974 [self drawSummaryContentRect:rect];
5976 [self drawNormalContentRect:rect];
5981 /* Section Cell {{{ */
5982 @interface SectionCell : CyteTableViewCell <
5983 CyteTableViewCellDelegate
5985 _H<NSString> basic_;
5986 _H<NSString> section_;
5988 _H<NSString> count_;
5990 _H<UISwitch> switch_;
5994 - (void) setSection:(Section *)section editing:(BOOL)editing;
5998 @implementation SectionCell
6000 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
6001 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
6002 icon_ = [UIImage imageNamed:@"folder.png"];
6003 // XXX: this initial frame is wrong, but is fixed later
6004 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
6005 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
6007 UIView *content([self contentView]);
6008 CGRect bounds([content bounds]);
6010 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
6011 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6012 [content addSubview:content_];
6013 [content_ setBackgroundColor:[UIColor whiteColor]];
6015 [content_ setDelegate:self];
6019 - (void) onSwitch:(id)sender {
6020 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
6021 if (metadata == nil) {
6022 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
6023 [Sections_ setObject:metadata forKey:basic_];
6026 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
6030 - (void) setSection:(Section *)section editing:(BOOL)editing {
6031 if (editing != editing_) {
6033 [switch_ removeFromSuperview];
6035 [self addSubview:switch_];
6044 if (section == nil) {
6045 name_ = UCLocalize("ALL_PACKAGES");
6048 basic_ = [section name];
6049 section_ = [section localized];
6051 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
6052 count_ = [NSString stringWithFormat:@"%zd", [section count]];
6055 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
6058 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
6059 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
6061 [content_ setNeedsDisplay];
6064 - (void) setFrame:(CGRect)frame {
6065 [super setFrame:frame];
6067 CGRect rect([switch_ frame]);
6068 [switch_ setFrame:CGRectMake(frame.size.width - rect.size.width - 9, 9, rect.size.width, rect.size.height)];
6071 - (NSString *) accessibilityLabel {
6075 - (void) drawContentRect:(CGRect)rect {
6076 bool highlighted(highlighted_ && !editing_);
6078 [icon_ drawInRect:CGRectMake(7, 7, 32, 32)];
6080 if (highlighted && kCFCoreFoundationVersionNumber < 800)
6083 float width(rect.size.width);
6085 width -= 9 + [switch_ frame].size.width;
6089 [name_ drawAtPoint:CGPointMake(48, 12) forWidth:(width - 58) withFont:Font18_ lineBreakMode:NSLineBreakByTruncatingTail];
6091 CGSize size = [count_ sizeWithFont:Font14_];
6093 UISetColor(Folder_);
6095 [count_ drawAtPoint:CGPointMake(Retina(10 + (30 - size.width) / 2), 18) withFont:Font12Bold_];
6101 /* File Table {{{ */
6102 @interface FileTable : CyteViewController <
6103 UITableViewDataSource,
6106 _transient Database *database_;
6107 _H<Package> package_;
6109 _H<NSMutableArray> files_;
6110 _H<UITableView, 2> list_;
6113 - (id) initWithDatabase:(Database *)database;
6114 - (void) setPackage:(Package *)package;
6118 @implementation FileTable
6120 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6121 return files_ == nil ? 0 : [files_ count];
6124 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6128 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6129 static NSString *reuseIdentifier = @"Cell";
6131 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6133 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6134 [cell setFont:[UIFont systemFontOfSize:16]];
6136 [cell setText:[files_ objectAtIndex:indexPath.row]];
6137 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
6142 - (NSURL *) navigationURL {
6143 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
6147 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
6148 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6149 [list_ setRowHeight:24.0f];
6150 [(UITableView *) list_ setDataSource:self];
6151 [list_ setDelegate:self];
6152 [self setView:list_];
6155 - (void) viewDidLoad {
6156 [super viewDidLoad];
6158 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
6161 - (void) releaseSubviews {
6167 [super releaseSubviews];
6170 - (id) initWithDatabase:(Database *)database {
6171 if ((self = [super init]) != nil) {
6172 database_ = database;
6176 - (void) setPackage:(Package *)package {
6180 files_ = [NSMutableArray arrayWithCapacity:32];
6182 if (package != nil) {
6184 name_ = [package id];
6186 if (NSArray *files = [package files])
6187 [files_ addObjectsFromArray:files];
6189 if ([files_ count] != 0) {
6190 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
6191 [files_ removeObjectAtIndex:0];
6192 [files_ sortUsingSelector:@selector(compareByPath:)];
6194 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
6195 [stack addObject:@"/"];
6197 for (int i(0), e([files_ count]); i != e; ++i) {
6198 NSString *file = [files_ objectAtIndex:i];
6199 while (![file hasPrefix:[stack lastObject]])
6200 [stack removeLastObject];
6201 NSString *directory = [stack lastObject];
6202 [stack addObject:[file stringByAppendingString:@"/"]];
6203 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
6204 ([stack count] - 2) * 3, "",
6205 [file substringFromIndex:[directory length]]
6214 - (void) reloadData {
6217 [self setPackage:[database_ packageWithName:name_]];
6222 /* Package Controller {{{ */
6223 @interface CYPackageController : CydiaWebViewController <
6224 UIActionSheetDelegate
6226 _transient Database *database_;
6227 _H<Package> package_;
6230 std::vector<std::pair<_H<NSString>, _H<NSString>>> buttons_;
6231 _H<UIBarButtonItem> button_;
6234 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer;
6238 @implementation CYPackageController
6240 - (NSURL *) navigationURL {
6241 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
6244 - (void) _clickButtonWithName:(NSString *)name {
6245 if ([name isEqualToString:@"CLEAR"])
6246 [delegate_ clearPackage:package_];
6247 else if ([name isEqualToString:@"INSTALL"])
6248 [delegate_ installPackage:package_];
6249 else if ([name isEqualToString:@"REINSTALL"])
6250 [delegate_ installPackage:package_];
6251 else if ([name isEqualToString:@"REMOVE"])
6252 [delegate_ removePackage:package_];
6253 else if ([name isEqualToString:@"UPGRADE"])
6254 [delegate_ installPackage:package_];
6255 else _assert(false);
6258 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
6259 NSString *context([sheet context]);
6261 if ([context isEqualToString:@"modify"]) {
6262 if (button != [sheet cancelButtonIndex]) {
6264 [self performSelector:@selector(_clickButtonWithName:) withObject:buttons_[button].first afterDelay:0];
6266 [self _clickButtonWithName:buttons_[button].first];
6269 [sheet dismissWithClickedButtonIndex:button animated:YES];
6273 - (bool) _allowJavaScriptPanel {
6278 - (void) _customButtonClicked {
6279 size_t count(buttons_.size());
6284 [self _clickButtonWithName:buttons_[0].first];
6286 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
6287 for (const auto &button : buttons_)
6288 [buttons addObject:button.second];
6290 UIActionSheet *sheet = [[[UIActionSheet alloc]
6293 cancelButtonTitle:nil
6294 destructiveButtonTitle:nil
6295 otherButtonTitles:nil
6298 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
6300 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
6301 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
6303 [sheet setContext:@"modify"];
6305 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
6309 - (void) reloadButtonClicked {
6310 if (commercial_ && function_ == nil && [package_ uninstalled])
6312 [self customButtonClicked];
6315 - (void) applyLoadingTitle {
6316 // Don't show "Loading" as the title. Ever.
6319 - (UIBarButtonItem *) rightButton {
6324 - (void) setPageColor:(UIColor *)color {
6325 return [super setPageColor:nil];
6328 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer {
6329 if ((self = [super init]) != nil) {
6330 database_ = database;
6331 name_ = name == nil ? @"" : [NSString stringWithString:name];
6332 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]] withReferrer:referrer];
6336 - (void) reloadData {
6339 package_ = [database_ packageWithName:name_];
6343 if (package_ != nil) {
6344 [(Package *) package_ parse];
6346 commercial_ = [package_ isCommercial];
6348 if ([package_ mode] != nil)
6349 buttons_.push_back(std::make_pair(@"CLEAR", UCLocalize("CLEAR")));
6350 if ([package_ source] == nil);
6351 else if ([package_ upgradableAndEssential:NO])
6352 buttons_.push_back(std::make_pair(@"UPGRADE", UCLocalize("UPGRADE")));
6353 else if ([package_ uninstalled])
6354 buttons_.push_back(std::make_pair(@"INSTALL", UCLocalize("INSTALL")));
6356 buttons_.push_back(std::make_pair(@"REINSTALL", UCLocalize("REINSTALL")));
6357 if (![package_ uninstalled])
6358 buttons_.push_back(std::make_pair(@"REMOVE", UCLocalize("REMOVE")));
6362 switch (buttons_.size()) {
6363 case 0: title = nil; break;
6364 case 1: title = buttons_[0].second; break;
6365 default: title = UCLocalize("MODIFY"); break;
6368 button_ = [[[UIBarButtonItem alloc]
6370 style:UIBarButtonItemStylePlain
6372 action:@selector(customButtonClicked)
6376 - (bool) isLoading {
6377 return commercial_ ? [super isLoading] : false;
6383 /* Package List Controller {{{ */
6384 @interface PackageListController : CyteViewController <
6385 UITableViewDataSource,
6388 _transient Database *database_;
6390 _H<NSArray> packages_;
6391 _H<NSArray> sections_;
6392 _H<UITableView, 2> list_;
6394 _H<NSArray> thumbs_;
6395 std::vector<NSInteger> offset_;
6397 _H<NSString> title_;
6398 unsigned reloading_;
6401 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6402 - (void) setDelegate:(id)delegate;
6403 - (void) resetCursor;
6406 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages;
6410 @implementation PackageListController
6412 - (NSURL *) referrerURL {
6413 return [self navigationURL];
6416 - (bool) isSummarized {
6420 - (bool) showsSections {
6424 - (void) deselectWithAnimation:(BOOL)animated {
6425 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6428 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6429 CGRect base = [[self view] bounds];
6430 base.size.height -= bounds.size.height;
6431 base.origin = [list_ frame].origin;
6433 [UIView beginAnimations:nil context:NULL];
6434 [UIView setAnimationBeginsFromCurrentState:YES];
6435 [UIView setAnimationCurve:curve];
6436 [UIView setAnimationDuration:duration];
6437 [list_ setFrame:base];
6438 [UIView commitAnimations];
6441 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6442 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6445 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6446 [self resizeForKeyboardBounds:bounds duration:0];
6449 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6450 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6451 *curve = UIViewAnimationCurveEaseInOut;
6453 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6455 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6458 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6461 - (void) keyboardWillShow:(NSNotification *)notification {
6464 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6465 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6467 NSTimeInterval duration;
6468 UIViewAnimationCurve curve;
6469 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6471 CGRect kbframe = CGRectMake(Retina(center.x - bounds.size.width / 2), Retina(center.y - bounds.size.height / 2), bounds.size.width, bounds.size.height);
6472 UIViewController *base = self;
6473 while ([base parentOrPresentingViewController] != nil)
6474 base = [base parentOrPresentingViewController];
6475 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6476 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6478 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6479 intersection.size.height += CYStatusBarHeight();
6481 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6484 - (void) keyboardWillHide:(NSNotification *)notification {
6485 NSTimeInterval duration;
6486 UIViewAnimationCurve curve;
6487 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6489 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6492 - (void) viewWillAppear:(BOOL)animated {
6493 [super viewWillAppear:animated];
6495 [self resizeForKeyboardBounds:CGRectZero];
6496 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6497 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6500 - (void) viewWillDisappear:(BOOL)animated {
6501 [super viewWillDisappear:animated];
6503 [self resizeForKeyboardBounds:CGRectZero];
6504 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6505 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6508 - (void) viewDidAppear:(BOOL)animated {
6509 [super viewDidAppear:animated];
6510 [self deselectWithAnimation:animated];
6513 - (void) didSelectPackage:(Package *)package {
6514 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[[self referrerURL] absoluteString]] autorelease]);
6515 [view setDelegate:delegate_];
6516 [[self navigationController] pushViewController:view animated:YES];
6519 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6520 NSInteger count([sections_ count]);
6521 return count == 0 ? 1 : count;
6524 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6525 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6527 return [[sections_ objectAtIndex:section] name];
6530 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6531 if ([sections_ count] == 0)
6533 return [[sections_ objectAtIndex:section] count];
6536 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6537 @synchronized (database_) {
6538 if ([database_ era] != era_)
6541 Section *section([sections_ objectAtIndex:[path section]]);
6542 NSInteger row([path row]);
6543 Package *package([packages_ objectAtIndex:([section row] + row)]);
6544 return [[package retain] autorelease];
6547 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6548 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6550 cell = [[[PackageCell alloc] init] autorelease];
6552 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6553 [cell setPackage:package asSummary:[self isSummarized]];
6557 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6558 Package *package([self packageAtIndexPath:path]);
6559 package = [database_ packageWithName:[package id]];
6560 [self didSelectPackage:package];
6563 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6567 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6568 return offset_[index];
6571 - (void) updateHeight {
6572 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6575 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6576 if ((self = [super init]) != nil) {
6577 database_ = database;
6578 title_ = [title copy];
6579 [[self navigationItem] setTitle:title_];
6584 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
6585 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
6586 [self setView:view];
6588 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6589 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6590 [view addSubview:list_];
6592 // XXX: is 20 the most optimal number here?
6593 [list_ setSectionIndexMinimumDisplayRowCount:20];
6595 [(UITableView *) list_ setDataSource:self];
6596 [list_ setDelegate:self];
6598 [self updateHeight];
6601 - (void) releaseSubviews {
6610 [super releaseSubviews];
6613 - (void) setDelegate:(id)delegate {
6614 delegate_ = delegate;
6617 - (bool) shouldYield {
6621 - (bool) shouldBlock {
6625 - (NSMutableArray *) _reloadPackages {
6626 @synchronized (database_) {
6627 era_ = [database_ era];
6628 NSArray *packages([database_ packages]);
6630 return [NSMutableArray arrayWithArray:packages];
6633 - (void) _reloadData {
6634 if (reloading_ != 0) {
6639 NSMutableArray *packages;
6642 if ([self shouldYield]) {
6646 if (![self shouldBlock])
6649 hud = [delegate_ addProgressHUD];
6650 [hud setText:UCLocalize("LOADING")];
6654 packages = [self yieldToSelector:@selector(_reloadPackages)];
6657 [delegate_ removeProgressHUD:hud];
6658 } while (reloading_ == 2);
6660 packages = [self _reloadPackages];
6663 @synchronized (database_) {
6664 if (era_ != [database_ era])
6671 packages_ = packages;
6673 if ([self showsSections])
6674 sections_ = [self sectionsForPackages:packages];
6676 Section *section([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6677 [section setCount:[packages_ count]];
6678 sections_ = [NSArray arrayWithObject:section];
6681 [self updateHeight];
6683 _profile(PackageTable$reloadData$List)
6684 [(UITableView *) list_ setDataSource:self];
6692 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
6693 Section *prefix([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6694 size_t end([packages count]);
6696 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
6697 Section *section(prefix);
6699 thumbs_ = CollationThumbs_;
6700 offset_ = CollationOffset_;
6703 size_t offsets([CollationStarts_ count]);
6705 NSString *start([CollationStarts_ objectAtIndex:offset]);
6706 size_t length([start length]);
6708 for (size_t index(0); index != end; ++index) {
6710 Package *package([packages objectAtIndex:index]);
6711 NSString *name(PackageName(package, @selector(cyname)));
6713 //while ([start compare:name options:NSNumericSearch range:NSMakeRange(0, length) locale:CollationLocale_] != NSOrderedDescending) {
6714 while (StringNameCompare(start, name, length) != kCFCompareGreaterThan) {
6715 NSString *title([CollationTitles_ objectAtIndex:offset]);
6716 section = [[[Section alloc] initWithName:title row:index localize:NO] autorelease];
6717 [sections addObject:section];
6719 start = ++offset == offsets ? nil : [CollationStarts_ objectAtIndex:offset];
6722 length = [start length];
6726 [section addToCount];
6729 for (; offset != offsets; ++offset) {
6730 NSString *title([CollationTitles_ objectAtIndex:offset]);
6731 Section *section([[[Section alloc] initWithName:title row:end localize:NO] autorelease]);
6732 [sections addObject:section];
6735 if ([prefix count] != 0) {
6736 Section *suffix([sections lastObject]);
6737 [prefix setName:[suffix name]];
6738 [suffix setName:nil];
6739 [sections insertObject:prefix atIndex:(offsets - 1)];
6745 - (void) reloadData {
6748 if ([self shouldYield])
6749 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6754 - (void) resetCursor {
6755 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6758 - (void) clearData {
6759 [self updateHeight];
6761 [list_ setDataSource:nil];
6769 /* Filtered Package List Controller {{{ */
6770 typedef Function<bool, Package *> PackageFilter;
6771 typedef Function<void, NSMutableArray *> PackageSorter;
6772 @interface FilteredPackageListController : PackageListController {
6773 PackageFilter filter_;
6774 PackageSorter sorter_;
6777 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter;
6779 - (void) setFilter:(PackageFilter)filter;
6780 - (void) setSorter:(PackageSorter)sorter;
6784 @implementation FilteredPackageListController
6786 - (void) setFilter:(PackageFilter)filter {
6787 @synchronized (self) {
6791 - (void) setSorter:(PackageSorter)sorter {
6792 @synchronized (self) {
6796 - (NSMutableArray *) _reloadPackages {
6797 @synchronized (database_) {
6798 era_ = [database_ era];
6800 NSArray *packages([database_ packages]);
6801 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6803 PackageFilter filter;
6804 PackageSorter sorter;
6806 @synchronized (self) {
6811 _profile(PackageTable$reloadData$Filter)
6812 for (Package *package in packages)
6813 if ([package valid] && filter(package))
6814 [filtered addObject:package];
6822 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter {
6823 if ((self = [super initWithDatabase:database title:title]) != nil) {
6824 [self setFilter:filter];
6831 /* Home Controller {{{ */
6832 @interface HomeController : CydiaWebViewController {
6833 CFRunLoopRef runloop_;
6834 SCNetworkReachabilityRef reachability_;
6839 @implementation HomeController
6841 static void HomeControllerReachabilityCallback(SCNetworkReachabilityRef reachability, SCNetworkReachabilityFlags flags, void *info) {
6842 [(HomeController *) info dispatchEvent:@"CydiaReachabilityCallback"];
6846 if ((self = [super init]) != nil) {
6847 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6850 reachability_ = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "cydia.saurik.com");
6851 if (reachability_ != NULL) {
6852 SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
6853 SCNetworkReachabilitySetCallback(reachability_, HomeControllerReachabilityCallback, &context);
6855 CFRunLoopRef runloop(CFRunLoopGetCurrent());
6856 if (SCNetworkReachabilityScheduleWithRunLoop(reachability_, runloop, kCFRunLoopDefaultMode))
6863 if (reachability_ != NULL && runloop_ != NULL)
6864 SCNetworkReachabilityUnscheduleFromRunLoop(reachability_, runloop_, kCFRunLoopDefaultMode);
6868 - (NSURL *) navigationURL {
6869 return [NSURL URLWithString:@"cydia://home"];
6872 - (void) aboutButtonClicked {
6873 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6875 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6876 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6877 [alert setCancelButtonIndex:0];
6880 @"Copyright \u00a9 2008-2014\n"
6883 "Jay Freeman (saurik)\n"
6884 "saurik@saurik.com\n"
6885 "http://www.saurik.com/"
6891 - (UIBarButtonItem *) leftButton {
6892 return [[[UIBarButtonItem alloc]
6893 initWithTitle:UCLocalize("ABOUT")
6894 style:UIBarButtonItemStylePlain
6896 action:@selector(aboutButtonClicked)
6903 /* Cydia Navigation Controller Interface {{{ */
6904 @interface UINavigationController (Cydia)
6906 - (NSArray *) navigationURLCollection;
6907 - (void) unloadData;
6912 /* Cydia Tab Bar Controller {{{ */
6913 @interface CydiaTabBarController : CyteTabBarController <
6914 UITabBarControllerDelegate,
6917 _transient Database *database_;
6919 _H<UIActivityIndicatorView> indicator_;
6922 // XXX: ok, "updatedelegate_"?...
6923 _transient NSObject<CydiaDelegate> *updatedelegate_;
6926 - (NSArray *) navigationURLCollection;
6927 - (void) beginUpdate;
6932 @implementation CydiaTabBarController
6934 - (NSArray *) navigationURLCollection {
6935 NSMutableArray *items([NSMutableArray array]);
6937 // XXX: Should this deal with transient view controllers?
6938 for (id navigation in [self viewControllers]) {
6939 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6941 [items addObject:stack];
6947 - (id) initWithDatabase:(Database *)database {
6948 if ((self = [super init]) != nil) {
6949 database_ = database;
6950 [self setDelegate:self];
6952 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteTiny] autorelease];
6953 [indicator_ setOrigin:CGPointMake(kCFCoreFoundationVersionNumber >= 800 ? 2 : 4, 2)];
6955 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6959 - (void) setUpdate:(NSDate *)date {
6963 - (void) beginUpdate {
6967 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
6968 UITabBarItem *item([controller tabBarItem]);
6970 [item setBadgeValue:@""];
6971 UIView *badge(MSHookIvar<UIView *>([item view], "_badge"));
6973 [indicator_ startAnimating];
6974 [badge addSubview:indicator_];
6976 [updatedelegate_ retainNetworkActivityIndicator];
6980 detachNewThreadSelector:@selector(performUpdate)
6986 - (void) performUpdate {
6987 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
6989 SourceStatus status(self, database_);
6990 [database_ updateWithStatus:status];
6993 performSelectorOnMainThread:@selector(completeUpdate)
7001 - (void) stopUpdateWithSelector:(SEL)selector {
7003 [updatedelegate_ releaseNetworkActivityIndicator];
7005 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
7006 [[controller tabBarItem] setBadgeValue:nil];
7008 [indicator_ removeFromSuperview];
7009 [indicator_ stopAnimating];
7011 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
7014 - (void) completeUpdate {
7017 [self stopUpdateWithSelector:@selector(reloadData)];
7020 - (void) cancelUpdate {
7021 [self stopUpdateWithSelector:@selector(updateDataAndLoad)];
7024 - (void) cancelPressed {
7025 [self cancelUpdate];
7032 - (bool) isSourceCancelled {
7036 - (void) startSourceFetch:(NSString *)uri {
7039 - (void) stopSourceFetch:(NSString *)uri {
7042 - (void) setUpdateDelegate:(id)delegate {
7043 updatedelegate_ = delegate;
7049 /* Cydia Navigation Controller Implementation {{{ */
7050 @implementation UINavigationController (Cydia)
7052 - (NSArray *) navigationURLCollection {
7053 NSMutableArray *stack([NSMutableArray array]);
7055 for (CyteViewController *controller in [self viewControllers]) {
7056 NSString *url = [[controller navigationURL] absoluteString];
7058 [stack addObject:url];
7064 - (void) reloadData {
7067 UIViewController *visible([self visibleViewController]);
7069 [visible reloadData];
7071 // on the iPad, this view controller is ALSO visible. :(
7073 if (UIViewController *modal = [self modalViewController])
7074 if ([modal modalPresentationStyle] == UIModalPresentationFormSheet)
7075 if (UIViewController *top = [self topViewController])
7080 - (void) unloadData {
7081 for (CyteViewController *page in [self viewControllers])
7090 /* Cydia:// Protocol {{{ */
7091 @interface CydiaURLProtocol : NSURLProtocol {
7096 @implementation CydiaURLProtocol
7098 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7099 NSURL *url([request URL]);
7103 NSString *scheme([[url scheme] lowercaseString]);
7104 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7106 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7112 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7116 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7117 id<NSURLProtocolClient> client([self client]);
7119 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7121 NSData *data(UIImagePNGRepresentation(icon));
7123 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7124 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7125 [client URLProtocol:self didLoadData:data];
7126 [client URLProtocolDidFinishLoading:self];
7130 - (void) startLoading {
7131 id<NSURLProtocolClient> client([self client]);
7132 NSURLRequest *request([self request]);
7134 NSURL *url([request URL]);
7135 NSString *href([url absoluteString]);
7136 NSString *scheme([[url scheme] lowercaseString]);
7140 if ([scheme isEqualToString:@"cydia"])
7141 path = [href substringFromIndex:8];
7142 else if ([scheme isEqualToString:@"about"])
7143 path = [href substringFromIndex:12];
7144 else _assert(false);
7146 NSRange slash([path rangeOfString:@"/"]);
7149 if (slash.location == NSNotFound) {
7153 command = [path substringToIndex:slash.location];
7154 path = [path substringFromIndex:(slash.location + 1)];
7157 Database *database([Database sharedInstance]);
7159 if ([command isEqualToString:@"package-icon"]) {
7162 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7163 Package *package([database packageWithName:path]);
7167 UIImage *icon([package icon]);
7168 [self _returnPNGWithImage:icon forRequest:request];
7169 } else if ([command isEqualToString:@"uikit-image"]) {
7172 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7173 UIImage *icon(_UIImageWithName(path));
7174 [self _returnPNGWithImage:icon forRequest:request];
7175 } else if ([command isEqualToString:@"section-icon"]) {
7178 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7179 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7181 icon = [UIImage imageNamed:@"unknown.png"];
7182 [self _returnPNGWithImage:icon forRequest:request];
7184 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7188 - (void) stopLoading {
7194 /* Section Controller {{{ */
7195 @interface SectionController : FilteredPackageListController {
7197 _H<NSString> section_;
7200 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section;
7204 @implementation SectionController
7206 - (NSURL *) referrerURL {
7207 NSString *name(section_);
7208 name = name ?: @"*";
7209 NSString *key(key_);
7211 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sections/%@/%@", UI_, [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7214 - (NSURL *) navigationURL {
7215 NSString *name(section_);
7216 name = name ?: @"*";
7217 NSString *key(key_);
7219 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@/%@", [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7222 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section {
7225 title = UCLocalize("ALL_PACKAGES");
7226 else if (![section isEqual:@""])
7227 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(section) value:nil table:@"Sections"];
7229 title = UCLocalize("NO_SECTION");
7231 if ((self = [super initWithDatabase:database title:title]) != nil) {
7232 key_ = [source key];
7237 - (void) reloadData {
7238 Source *source([database_ sourceWithKey:key_]);
7239 _H<NSString> name(section_);
7241 [self setFilter:[=](Package *package) {
7242 NSString *section([package section]);
7246 section == nil && [name length] == 0 ||
7247 [name isEqualToString:section]
7250 [package source] == source
7251 ) && [package visible];
7259 /* Sections Controller {{{ */
7260 @interface SectionsController : CyteViewController <
7261 UITableViewDataSource,
7264 _transient Database *database_;
7266 _H<NSMutableArray> sections_;
7267 _H<NSMutableArray> filtered_;
7268 _H<UITableView, 2> list_;
7271 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7272 - (void) editButtonClicked;
7276 @implementation SectionsController
7278 - (NSURL *) navigationURL {
7279 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
7282 - (Source *) source {
7285 return [database_ sourceWithKey:key_];
7288 - (void) updateNavigationItem {
7289 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7290 if ([sections_ count] == 0) {
7291 [[self navigationItem] setRightBarButtonItem:nil];
7293 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7294 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7296 action:@selector(editButtonClicked)
7297 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7301 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7302 [super setEditing:editing animated:animated];
7307 [delegate_ updateData];
7309 [self updateNavigationItem];
7312 - (void) viewDidAppear:(BOOL)animated {
7313 [super viewDidAppear:animated];
7314 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7317 - (void) viewWillDisappear:(BOOL)animated {
7318 [super viewWillDisappear:animated];
7319 [self setEditing:NO];
7322 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7323 Section *section = nil;
7324 int index = [indexPath row];
7325 if (![self isEditing]) {
7328 section = [filtered_ objectAtIndex:index];
7330 section = [sections_ objectAtIndex:index];
7335 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7336 if ([self isEditing])
7337 return [sections_ count];
7339 return [filtered_ count] + 1;
7342 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7346 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7347 static NSString *reuseIdentifier = @"SectionCell";
7349 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7351 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7353 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7358 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7359 if ([self isEditing])
7362 Section *section = [self sectionAtIndexPath:indexPath];
7364 SectionController *controller = [[[SectionController alloc]
7365 initWithDatabase:database_
7366 source:[self source]
7367 section:[section name]
7369 [controller setDelegate:delegate_];
7371 [[self navigationController] pushViewController:controller animated:YES];
7375 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
7376 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7377 [list_ setRowHeight:46];
7378 [(UITableView *) list_ setDataSource:self];
7379 [list_ setDelegate:self];
7380 [self setView:list_];
7383 - (void) viewDidLoad {
7384 [super viewDidLoad];
7386 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7389 - (void) releaseSubviews {
7395 [super releaseSubviews];
7398 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7399 if ((self = [super init]) != nil) {
7400 database_ = database;
7401 key_ = [source key];
7405 - (void) reloadData {
7408 NSArray *packages = [database_ packages];
7410 sections_ = [NSMutableArray arrayWithCapacity:16];
7411 filtered_ = [NSMutableArray arrayWithCapacity:16];
7413 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7415 Source *source([self source]);
7418 for (Package *package in packages) {
7419 if (source != nil && [package source] != source)
7422 NSString *name([package section]);
7423 NSString *key(name == nil ? @"" : name);
7427 _profile(SectionsView$reloadData$Section)
7428 section = [sections objectForKey:key];
7429 if (section == nil) {
7430 _profile(SectionsView$reloadData$Section$Allocate)
7431 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7432 [sections setObject:section forKey:key];
7437 [section addToCount];
7439 _profile(SectionsView$reloadData$Filter)
7440 if (![package valid] || ![package visible])
7448 [sections_ addObjectsFromArray:[sections allValues]];
7450 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7452 for (Section *section in (id) sections_) {
7453 size_t count([section row]);
7457 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7458 [section setCount:count];
7459 [filtered_ addObject:section];
7462 [self updateNavigationItem];
7467 - (void) editButtonClicked {
7468 [self setEditing:![self isEditing] animated:YES];
7474 /* Changes Controller {{{ */
7475 @interface ChangesController : FilteredPackageListController {
7479 - (id) initWithDatabase:(Database *)database;
7483 @implementation ChangesController
7485 - (NSURL *) referrerURL {
7486 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/changes/", UI_]];
7489 - (NSURL *) navigationURL {
7490 return [NSURL URLWithString:@"cydia://changes"];
7493 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7494 @synchronized (database_) {
7495 if ([database_ era] != era_)
7498 NSUInteger sectionIndex([path section]);
7499 if (sectionIndex >= [sections_ count])
7501 Section *section([sections_ objectAtIndex:sectionIndex]);
7502 NSInteger row([path row]);
7503 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7506 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7507 NSString *context([alert context]);
7509 if ([context isEqualToString:@"norefresh"])
7510 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7513 - (void) setLeftBarButtonItem {
7514 if ([delegate_ updating])
7515 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7516 initWithTitle:UCLocalize("CANCEL")
7517 style:UIBarButtonItemStyleDone
7519 action:@selector(cancelButtonClicked)
7520 ] autorelease] animated:YES];
7522 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7523 initWithTitle:UCLocalize("REFRESH")
7524 style:UIBarButtonItemStylePlain
7526 action:@selector(refreshButtonClicked)
7527 ] autorelease] animated:YES];
7530 - (void) refreshButtonClicked {
7531 if ([delegate_ requestUpdate])
7532 [self setLeftBarButtonItem];
7535 - (void) cancelButtonClicked {
7536 [delegate_ cancelUpdate];
7539 - (void) upgradeButtonClicked {
7540 [delegate_ distUpgrade];
7541 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7544 - (bool) shouldYield {
7548 - (bool) shouldBlock {
7552 - (void) useFilter {
7553 @synchronized (self) {
7554 [self setFilter:[](Package *package) {
7555 return [package upgradableAndEssential:YES] || [package visible];
7558 [self setSorter:[](NSMutableArray *packages) {
7559 [packages radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7563 - (id) initWithDatabase:(Database *)database {
7564 if ((self = [super initWithDatabase:database title:UCLocalize("CHANGES")]) != nil) {
7569 - (void) viewDidLoad {
7570 [super viewDidLoad];
7571 [self setLeftBarButtonItem];
7574 - (void) viewWillAppear:(BOOL)animated {
7575 [super viewWillAppear:animated];
7576 [self setLeftBarButtonItem];
7579 - (void) reloadData {
7580 [self setLeftBarButtonItem];
7584 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
7585 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
7587 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7588 Section *ignored = nil;
7589 Section *section = nil;
7593 bool unseens = false;
7595 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7597 for (size_t offset = 0, count = [packages count]; offset != count; ++offset) {
7598 Package *package = [packages objectAtIndex:offset];
7600 BOOL uae = [package upgradableAndEssential:YES];
7604 time_t seen([package seen]);
7606 if (section == nil || last != seen) {
7610 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7613 _profile(ChangesController$reloadData$Allocate)
7614 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7615 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7616 [sections addObject:section];
7620 [section addToCount];
7621 } else if ([package ignored]) {
7622 if (ignored == nil) {
7623 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7625 [ignored addToCount];
7628 [upgradable addToCount];
7633 CFRelease(formatter);
7636 Section *last = [sections lastObject];
7637 size_t count = [last count];
7638 [packages removeObjectsInRange:NSMakeRange([packages count] - count, count)];
7639 [sections removeLastObject];
7642 if ([ignored count] != 0)
7643 [sections insertObject:ignored atIndex:0];
7645 [sections insertObject:upgradable atIndex:0];
7649 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7650 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7651 style:UIBarButtonItemStylePlain
7653 action:@selector(upgradeButtonClicked)
7654 ] autorelease]) animated:YES];
7661 /* Search Controller {{{ */
7662 @interface SearchController : FilteredPackageListController <
7665 _H<UISearchBar, 1> search_;
7670 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7671 - (void) reloadData;
7675 @implementation SearchController
7677 - (NSURL *) referrerURL {
7678 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/search?q=%@", UI_, [([search_ text] ?: @"") stringByAddingPercentEscapesIncludingReserved]]];
7681 - (NSURL *) navigationURL {
7682 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7683 return [NSURL URLWithString:@"cydia://search"];
7685 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [[search_ text] stringByAddingPercentEscapesIncludingReserved]]];
7688 - (NSArray *) termsForQuery:(NSString *)query {
7689 NSMutableArray *terms([NSMutableArray arrayWithCapacity:2]);
7690 for (NSString *component in [query componentsSeparatedByString:@" "])
7691 if ([component length] != 0)
7692 [terms addObject:component];
7697 - (void) useSearch {
7698 _H<NSArray> query([self termsForQuery:[search_ text]]);
7701 @synchronized (self) {
7702 [self setFilter:[=](Package *package) {
7703 if (![package unfiltered])
7705 if (![package matches:query])
7710 [self setSorter:[](NSMutableArray *packages) {
7711 [packages radixSortUsingSelector:@selector(rank)];
7719 - (void) usePrefix:(NSString *)prefix {
7720 _H<NSString> query(prefix);
7723 @synchronized (self) {
7724 [self setFilter:[=](Package *package) {
7725 if ([query length] == 0)
7727 if (![package unfiltered])
7729 if ([[package name] compare:query options:MatchCompareOptions_ range:NSMakeRange(0, [query length])] != NSOrderedSame)
7734 [self setSorter:nullptr];
7740 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7742 [self usePrefix:[search_ text]];
7745 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7746 [search_ resignFirstResponder];
7750 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7751 [search_ setText:@""];
7752 [self searchBarButtonClicked:searchBar];
7755 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7756 [self searchBarButtonClicked:searchBar];
7759 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7760 [self usePrefix:text];
7763 - (bool) shouldYield {
7767 - (bool) shouldBlock {
7771 - (bool) isSummarized {
7775 - (bool) showsSections {
7779 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7780 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH")])) {
7781 search_ = [[[UISearchBar alloc] init] autorelease];
7782 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7783 [search_ setDelegate:self];
7785 UITextField *textField;
7786 if ([search_ respondsToSelector:@selector(searchField)])
7787 textField = [search_ searchField];
7789 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7791 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7792 [textField setEnablesReturnKeyAutomatically:NO];
7793 [[self navigationItem] setTitleView:textField];
7796 [search_ setText:query];
7801 - (void) viewDidAppear:(BOOL)animated {
7802 [super viewDidAppear:animated];
7804 if (!searchloaded_) {
7805 searchloaded_ = YES;
7806 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7807 [search_ layoutSubviews];
7810 if ([self isSummarized])
7811 [search_ becomeFirstResponder];
7814 - (void) reloadData {
7819 - (void) didSelectPackage:(Package *)package {
7820 [search_ resignFirstResponder];
7821 [super didSelectPackage:package];
7826 /* Package Settings Controller {{{ */
7827 @interface PackageSettingsController : CyteViewController <
7828 UITableViewDataSource,
7831 _transient Database *database_;
7833 _H<Package> package_;
7834 _H<UITableView, 2> table_;
7835 _H<UISwitch> subscribedSwitch_;
7836 _H<UISwitch> ignoredSwitch_;
7837 _H<UITableViewCell> subscribedCell_;
7838 _H<UITableViewCell> ignoredCell_;
7841 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7845 @implementation PackageSettingsController
7847 - (NSURL *) navigationURL {
7848 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
7851 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7852 if (package_ == nil)
7855 if ([package_ installed] == nil)
7861 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7862 if (package_ == nil)
7865 // both sections contain just one item right now.
7869 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7873 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7875 return UCLocalize("SHOW_ALL_CHANGES_EX");
7877 return UCLocalize("IGNORE_UPGRADES_EX");
7880 - (void) onSubscribed:(id)control {
7881 bool value([control isOn]);
7882 if (package_ == nil)
7884 if ([package_ setSubscribed:value])
7885 [delegate_ updateData];
7888 - (void) _updateIgnored {
7889 const char *package([name_ UTF8String]);
7890 bool on([ignoredSwitch_ isOn]);
7892 pid_t pid(ExecFork());
7894 FILE *dpkg(popen("/usr/libexec/cydo --set-selections", "w"));
7895 fwrite(package, strlen(package), 1, dpkg);
7898 fwrite(" hold\n", 6, 1, dpkg);
7900 fwrite(" install\n", 9, 1, dpkg);
7908 - (void) onIgnored:(id)control {
7909 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7910 [invocation setTarget:self];
7911 [invocation setSelector:@selector(_updateIgnored)];
7913 [delegate_ reloadDataWithInvocation:invocation];
7916 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7917 if (package_ == nil)
7920 switch ([indexPath section]) {
7921 case 0: return subscribedCell_;
7922 case 1: return ignoredCell_;
7931 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
7932 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
7933 [self setView:view];
7935 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7936 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7937 [(UITableView *) table_ setDataSource:self];
7938 [table_ setDelegate:self];
7939 [view addSubview:table_];
7941 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7942 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7943 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7945 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7946 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7947 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7949 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7950 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7951 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7952 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7954 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7955 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7956 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7957 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7960 - (void) viewDidLoad {
7961 [super viewDidLoad];
7963 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7966 - (void) releaseSubviews {
7968 subscribedCell_ = nil;
7970 ignoredSwitch_ = nil;
7971 subscribedSwitch_ = nil;
7973 [super releaseSubviews];
7976 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7977 if ((self = [super init]) != nil) {
7978 database_ = database;
7983 - (void) reloadData {
7986 package_ = [database_ packageWithName:name_];
7988 if (package_ != nil) {
7989 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7990 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7991 } // XXX: what now, G?
7993 [table_ reloadData];
7999 /* Installed Controller {{{ */
8000 @interface InstalledController : FilteredPackageListController {
8004 - (id) initWithDatabase:(Database *)database;
8005 - (void) queueStatusDidChange;
8009 @implementation InstalledController
8011 - (NSURL *) referrerURL {
8012 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/installed/", UI_]];
8015 - (NSURL *) navigationURL {
8016 return [NSURL URLWithString:@"cydia://installed"];
8019 - (void) useRecent {
8022 @synchronized (self) {
8023 [self setFilter:[](Package *package) {
8024 return ![package uninstalled] && package->role_ < 7;
8027 [self setSorter:[](NSMutableArray *packages) {
8028 [packages radixSortUsingSelector:@selector(recent)];
8032 - (void) useFilter:(UISegmentedControl *)segmented {
8033 NSInteger selected([segmented selectedSegmentIndex]);
8035 return [self useRecent];
8036 bool simple(selected == 0);
8039 @synchronized (self) {
8040 [self setFilter:[=](Package *package) {
8041 return ![package uninstalled] && package->role_ <= (simple ? 1 : 3);
8044 [self setSorter:nullptr];
8047 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
8049 return [super sectionsForPackages:packages];
8051 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterLongStyle, kCFDateFormatterNoStyle));
8053 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
8054 Section *section(nil);
8057 for (size_t offset(0), count([packages count]); offset != count; ++offset) {
8058 Package *package([packages objectAtIndex:offset]);
8060 time_t upgraded([package upgraded]);
8061 if (upgraded < 1168364520)
8064 upgraded -= upgraded % (60 * 60 * 24);
8066 if (section == nil || upgraded != last) {
8071 continue; // XXX: name = UCLocalize("...");
8073 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:upgraded]);
8077 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
8078 [sections addObject:section];
8081 [section addToCount];
8084 CFRelease(formatter);
8088 - (id) initWithDatabase:(Database *)database {
8089 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED")]) != nil) {
8090 UISegmentedControl *segmented([[[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:UCLocalize("USER"), UCLocalize("EXPERT"), UCLocalize("RECENT"), nil]] autorelease]);
8091 [segmented setSelectedSegmentIndex:0];
8092 [segmented setSegmentedControlStyle:UISegmentedControlStyleBar];
8093 [[self navigationItem] setTitleView:segmented];
8095 [segmented addTarget:self action:@selector(modeChanged:) forEvents:UIControlEventValueChanged];
8096 [self useFilter:segmented];
8098 [self queueStatusDidChange];
8103 - (void) queueButtonClicked {
8108 - (void) queueStatusDidChange {
8111 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8112 initWithTitle:UCLocalize("QUEUE")
8113 style:UIBarButtonItemStyleDone
8115 action:@selector(queueButtonClicked)
8118 [[self navigationItem] setRightBarButtonItem:nil];
8123 - (void) modeChanged:(UISegmentedControl *)segmented {
8124 [self useFilter:segmented];
8131 /* Source Cell {{{ */
8132 @interface SourceCell : CyteTableViewCell <
8133 CyteTableViewCellDelegate,
8136 _H<Source, 1> source_;
8139 _H<NSString> origin_;
8140 _H<NSString> label_;
8141 _H<UIActivityIndicatorView> indicator_;
8144 - (void) setSource:(Source *)source;
8145 - (void) setFetch:(NSNumber *)fetch;
8149 @implementation SourceCell
8151 - (void) _setImage:(NSArray *)data {
8152 if ([url_ isEqual:[data objectAtIndex:0]]) {
8153 icon_ = [data objectAtIndex:1];
8154 [content_ setNeedsDisplay];
8158 - (void) _setSource:(NSURL *) url {
8159 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8161 if (NSData *data = [NSURLConnection
8162 sendSynchronousRequest:[NSURLRequest
8164 cachePolicy:NSURLRequestUseProtocolCachePolicy
8168 returningResponse:NULL
8171 if (UIImage *image = [UIImage imageWithData:data])
8172 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
8177 - (void) setSource:(Source *)source {
8179 [source_ setDelegate:self];
8181 [self setFetch:[NSNumber numberWithBool:[source_ fetch]]];
8183 icon_ = [UIImage imageNamed:@"unknown.png"];
8185 origin_ = [source name];
8186 label_ = [source rooturi];
8188 [content_ setNeedsDisplay];
8190 url_ = [source iconURL];
8191 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
8194 - (void) setAllSource {
8196 [indicator_ stopAnimating];
8198 icon_ = [UIImage imageNamed:@"folder.png"];
8199 origin_ = UCLocalize("ALL_SOURCES");
8200 label_ = UCLocalize("ALL_SOURCES_EX");
8201 [content_ setNeedsDisplay];
8204 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8205 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8206 UIView *content([self contentView]);
8207 CGRect bounds([content bounds]);
8209 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8210 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8211 [content_ setBackgroundColor:[UIColor whiteColor]];
8212 [content addSubview:content_];
8214 [content_ setDelegate:self];
8215 [content_ setOpaque:YES];
8217 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGraySmall] autorelease];
8218 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin];// | UIViewAutoresizingFlexibleBottomMargin];
8219 [content addSubview:indicator_];
8221 [[content_ layer] setContentsGravity:kCAGravityTopLeft];
8225 - (void) layoutSubviews {
8226 [super layoutSubviews];
8228 UIView *content([self contentView]);
8229 CGRect bounds([content bounds]);
8231 CGRect frame([indicator_ frame]);
8232 frame.origin.x = bounds.size.width - frame.size.width;
8233 frame.origin.y = Retina((bounds.size.height - frame.size.height) / 2);
8235 if (kCFCoreFoundationVersionNumber < 800)
8236 frame.origin.x -= 8;
8237 [indicator_ setFrame:frame];
8240 - (NSString *) accessibilityLabel {
8244 - (void) drawContentRect:(CGRect)rect {
8245 bool highlighted(highlighted_);
8246 float width(rect.size.width);
8250 rect.size = [(UIImage *) icon_ size];
8252 while (rect.size.width > 32 || rect.size.height > 32) {
8253 rect.size.width /= 2;
8254 rect.size.height /= 2;
8257 rect.origin.x = 26 - rect.size.width / 2;
8258 rect.origin.y = 26 - rect.size.height / 2;
8260 [icon_ drawInRect:Retina(rect)];
8263 if (highlighted && kCFCoreFoundationVersionNumber < 800)
8268 [origin_ drawAtPoint:CGPointMake(52, 8) forWidth:(width - 49) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
8272 [label_ drawAtPoint:CGPointMake(52, 29) forWidth:(width - 49) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
8275 - (void) setFetch:(NSNumber *)fetch {
8276 if ([fetch boolValue])
8277 [indicator_ startAnimating];
8279 [indicator_ stopAnimating];
8284 /* Sources Controller {{{ */
8285 @interface SourcesController : CyteViewController <
8286 UITableViewDataSource,
8289 _transient Database *database_;
8292 _H<UITableView, 2> list_;
8293 _H<NSMutableArray> sources_;
8297 _H<UIProgressHUD> hud_;
8300 NSURLConnection *trivial_bz2_;
8301 NSURLConnection *trivial_gz_;
8306 - (id) initWithDatabase:(Database *)database;
8307 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated;
8311 @implementation SourcesController
8313 - (void) _releaseConnection:(NSURLConnection *)connection {
8314 if (connection != nil) {
8315 [connection cancel];
8316 //[connection setDelegate:nil];
8317 [connection release];
8322 [self _releaseConnection:trivial_gz_];
8323 [self _releaseConnection:trivial_bz2_];
8328 - (NSURL *) navigationURL {
8329 return [NSURL URLWithString:@"cydia://sources"];
8332 - (void) viewDidAppear:(BOOL)animated {
8333 [super viewDidAppear:animated];
8334 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8337 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8341 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8343 return UCLocalize("INDIVIDUAL_SOURCES");
8347 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8350 case 1: return [sources_ count];
8355 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8356 @synchronized (database_) {
8357 if ([database_ era] != era_)
8359 if ([indexPath section] != 1)
8361 NSUInteger index([indexPath row]);
8362 if (index >= [sources_ count])
8364 return [sources_ objectAtIndex:index];
8367 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8368 static NSString *cellIdentifier = @"SourceCell";
8370 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8371 if (cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8372 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8374 Source *source([self sourceAtIndexPath:indexPath]);
8376 [cell setAllSource];
8378 [cell setSource:source];
8383 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8384 SectionsController *controller([[[SectionsController alloc]
8385 initWithDatabase:database_
8386 source:[self sourceAtIndexPath:indexPath]
8389 [controller setDelegate:delegate_];
8390 [[self navigationController] pushViewController:controller animated:YES];
8393 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8394 if ([indexPath section] != 1)
8396 Source *source = [self sourceAtIndexPath:indexPath];
8397 return [source record] != nil;
8400 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8401 _assert([indexPath section] == 1);
8402 if (editingStyle == UITableViewCellEditingStyleDelete) {
8403 Source *source = [self sourceAtIndexPath:indexPath];
8404 if (source == nil) return;
8406 [Sources_ removeObjectForKey:[source key]];
8409 [delegate_ _saveConfig];
8410 [delegate_ reloadDataWithInvocation:nil];
8414 - (void) tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath {
8415 [self updateButtonsForEditingStatusAnimated:YES];
8419 [delegate_ addTrivialSource:href_];
8422 [delegate_ syncData];
8425 - (NSString *) getWarning {
8426 NSString *href(href_);
8427 NSRange colon([href rangeOfString:@"://"]);
8428 if (colon.location != NSNotFound)
8429 href = [href substringFromIndex:(colon.location + 3)];
8430 href = [href stringByAddingPercentEscapes];
8431 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8433 NSURL *url([NSURL URLWithString:href]);
8435 NSStringEncoding encoding;
8436 NSError *error(nil);
8438 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8439 return [warning length] == 0 ? nil : warning;
8443 - (void) _endConnection:(NSURLConnection *)connection {
8444 // XXX: the memory management in this method is horribly awkward
8446 NSURLConnection **field = NULL;
8447 if (connection == trivial_bz2_)
8448 field = &trivial_bz2_;
8449 else if (connection == trivial_gz_)
8450 field = &trivial_gz_;
8451 _assert(field != NULL);
8452 [connection release];
8456 trivial_bz2_ == nil &&
8459 NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil);
8461 [delegate_ releaseNetworkActivityIndicator];
8463 [delegate_ removeProgressHUD:hud_];
8467 if (warning != nil) {
8468 UIAlertView *alert = [[[UIAlertView alloc]
8469 initWithTitle:UCLocalize("SOURCE_WARNING")
8472 cancelButtonTitle:UCLocalize("CANCEL")
8474 UCLocalize("ADD_ANYWAY"),
8478 [alert setContext:@"warning"];
8479 [alert setNumberOfRows:1];
8482 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
8488 } else if (error_ != nil) {
8489 UIAlertView *alert = [[[UIAlertView alloc]
8490 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8491 message:[error_ localizedDescription]
8493 cancelButtonTitle:UCLocalize("OK")
8494 otherButtonTitles:nil
8497 [alert setContext:@"urlerror"];
8502 UIAlertView *alert = [[[UIAlertView alloc]
8503 initWithTitle:UCLocalize("NOT_REPOSITORY")
8504 message:UCLocalize("NOT_REPOSITORY_EX")
8506 cancelButtonTitle:UCLocalize("OK")
8507 otherButtonTitles:nil
8510 [alert setContext:@"trivial"];
8520 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8521 switch ([response statusCode]) {
8527 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8528 lprintf("connection:\"%s\" didFailWithError:\"%s\"\n", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8530 [self _endConnection:connection];
8533 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8534 [self _endConnection:connection];
8537 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8538 NSURL *url([NSURL URLWithString:href]);
8540 NSMutableURLRequest *request = [NSMutableURLRequest
8542 cachePolicy:NSURLRequestUseProtocolCachePolicy
8546 [request setHTTPMethod:method];
8548 if (Machine_ != NULL)
8549 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8551 if (UniqueID_ != nil)
8552 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8554 if ([url isCydiaSecure]) {
8555 if (UniqueID_ != nil)
8556 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
8559 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8562 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8563 NSString *context([alert context]);
8565 if ([context isEqualToString:@"source"]) {
8568 NSString *href = [[alert textField] text];
8570 static RegEx href_r("(http(s?)://|file:///)[^# ]*");
8571 if (!href_r(href)) {
8572 UIAlertView *alert = [[[UIAlertView alloc]
8573 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("INVALID_URL")]
8574 message:UCLocalize("INVALID_URL_EX")
8576 cancelButtonTitle:UCLocalize("OK")
8577 otherButtonTitles:nil
8580 [alert setContext:@"badurl"];
8586 if (![href hasSuffix:@"/"])
8587 href_ = [href stringByAppendingString:@"/"];
8591 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8592 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8596 // XXX: this is stupid
8597 hud_ = [delegate_ addProgressHUD];
8598 [hud_ setText:UCLocalize("VERIFYING_URL")];
8599 [delegate_ retainNetworkActivityIndicator];
8608 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8609 } else if ([context isEqualToString:@"trivial"])
8610 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8611 else if ([context isEqualToString:@"urlerror"])
8612 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8613 else if ([context isEqualToString:@"warning"]) {
8616 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
8625 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8629 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated {
8630 BOOL editing([list_ isEditing]);
8633 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8634 initWithTitle:UCLocalize("ADD")
8635 style:UIBarButtonItemStylePlain
8637 action:@selector(addButtonClicked)
8638 ] autorelease] animated:animated];
8639 else if ([delegate_ updating])
8640 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8641 initWithTitle:UCLocalize("CANCEL")
8642 style:UIBarButtonItemStyleDone
8644 action:@selector(cancelButtonClicked)
8645 ] autorelease] animated:animated];
8647 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8648 initWithTitle:UCLocalize("REFRESH")
8649 style:UIBarButtonItemStylePlain
8651 action:@selector(refreshButtonClicked)
8652 ] autorelease] animated:animated];
8654 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8655 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8656 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8658 action:@selector(editButtonClicked)
8659 ] autorelease] animated:animated];
8663 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease];
8664 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8665 [list_ setRowHeight:53];
8666 [(UITableView *) list_ setDataSource:self];
8667 [list_ setDelegate:self];
8668 [self setView:list_];
8671 - (void) viewDidLoad {
8672 [super viewDidLoad];
8674 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8675 [self updateButtonsForEditingStatusAnimated:NO];
8678 - (void) viewWillAppear:(BOOL)animated {
8679 [super viewWillAppear:animated];
8681 [list_ setEditing:NO];
8682 [self updateButtonsForEditingStatusAnimated:NO];
8685 - (void) releaseSubviews {
8690 [super releaseSubviews];
8693 - (id) initWithDatabase:(Database *)database {
8694 if ((self = [super init]) != nil) {
8695 database_ = database;
8699 - (void) reloadData {
8701 [self updateButtonsForEditingStatusAnimated:YES];
8703 @synchronized (database_) {
8704 era_ = [database_ era];
8706 sources_ = [NSMutableArray arrayWithCapacity:16];
8707 [sources_ addObjectsFromArray:[database_ sources]];
8709 [sources_ sortUsingSelector:@selector(compareByName:)];
8712 int count([sources_ count]);
8714 for (int i = 0; i != count; i++) {
8715 if ([[sources_ objectAtIndex:i] record] == nil)
8723 - (void) showAddSourcePrompt {
8724 UIAlertView *alert = [[[UIAlertView alloc]
8725 initWithTitle:UCLocalize("ENTER_APT_URL")
8728 cancelButtonTitle:UCLocalize("CANCEL")
8730 UCLocalize("ADD_SOURCE"),
8734 [alert setContext:@"source"];
8736 [alert setNumberOfRows:1];
8737 [alert addTextFieldWithValue:@"http://" label:@""];
8739 UITextInputTraits *traits = [[alert textField] textInputTraits];
8740 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8741 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8742 [traits setKeyboardType:UIKeyboardTypeURL];
8743 // XXX: UIReturnKeyDone
8744 [traits setReturnKeyType:UIReturnKeyNext];
8749 - (void) addButtonClicked {
8750 [self showAddSourcePrompt];
8753 - (void) refreshButtonClicked {
8754 if ([delegate_ requestUpdate])
8755 [self updateButtonsForEditingStatusAnimated:YES];
8758 - (void) cancelButtonClicked {
8759 [delegate_ cancelUpdate];
8762 - (void) editButtonClicked {
8763 [list_ setEditing:![list_ isEditing] animated:YES];
8764 [self updateButtonsForEditingStatusAnimated:YES];
8770 /* Stash Controller {{{ */
8771 @interface StashController : CyteViewController {
8772 _H<UIActivityIndicatorView> spinner_;
8773 _H<UILabel> status_;
8774 _H<UILabel> caption_;
8779 @implementation StashController
8782 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8783 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8784 [self setView:view];
8786 [view setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8788 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8789 CGRect spinrect = [spinner_ frame];
8790 spinrect.origin.x = Retina([[self view] frame].size.width / 2 - spinrect.size.width / 2);
8791 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8792 [spinner_ setFrame:spinrect];
8793 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8794 [view addSubview:spinner_];
8795 [spinner_ startAnimating];
8798 captrect.size.width = [[self view] frame].size.width;
8799 captrect.size.height = 40.0f;
8800 captrect.origin.x = 0;
8801 captrect.origin.y = Retina([[self view] frame].size.height / 2 - captrect.size.height * 2);
8802 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8803 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8804 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8805 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8806 [caption_ setTextColor:[UIColor whiteColor]];
8807 [caption_ setBackgroundColor:[UIColor clearColor]];
8808 [caption_ setShadowColor:[UIColor blackColor]];
8809 [caption_ setTextAlignment:NSTextAlignmentCenter];
8810 [view addSubview:caption_];
8813 statusrect.size.width = [[self view] frame].size.width;
8814 statusrect.size.height = 30.0f;
8815 statusrect.origin.x = 0;
8816 statusrect.origin.y = Retina([[self view] frame].size.height / 2 - statusrect.size.height);
8817 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8818 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8819 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8820 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8821 [status_ setTextColor:[UIColor whiteColor]];
8822 [status_ setBackgroundColor:[UIColor clearColor]];
8823 [status_ setShadowColor:[UIColor blackColor]];
8824 [status_ setTextAlignment:NSTextAlignmentCenter];
8825 [view addSubview:status_];
8828 - (void) releaseSubviews {
8833 [super releaseSubviews];
8839 @interface CYURLCache : SDURLCache {
8844 @implementation CYURLCache
8846 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8849 else if ([event isEqualToString:@"no-cache"])
8851 else if ([event isEqualToString:@"store"])
8853 else if ([event isEqualToString:@"invalid"])
8855 else if ([event isEqualToString:@"memory"])
8857 else if ([event isEqualToString:@"disk"])
8859 else if ([event isEqualToString:@"miss"])
8862 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8866 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
8867 if (NSURLResponse *response = [cached response])
8868 if (NSString *mime = [response MIMEType])
8869 if ([mime isEqualToString:@"text/cache-manifest"]) {
8870 NSURL *url([response URL]);
8873 NSLog(@"###: %@", [url absoluteString]);
8876 @synchronized (HostConfig_) {
8877 [CachedURLs_ addObject:url];
8881 [super storeCachedResponse:cached forRequest:request];
8884 - (void) createDiskCachePath {
8885 [super createDiskCachePath];
8890 @interface Cydia : UIApplication <
8891 ConfirmationControllerDelegate,
8895 _H<UIWindow> window_;
8896 _H<CydiaTabBarController> tabbar_;
8897 _H<CyteTabBarController> emulated_;
8898 _H<AppCacheController> appcache_;
8900 _H<NSMutableArray> essential_;
8901 _H<NSMutableArray> broken_;
8903 Database *database_;
8905 _H<NSURL> starturl_;
8910 _H<StashController> stash_;
8919 @implementation Cydia
8921 - (void) lockSuspend {
8922 if (locked_++ == 0) {
8923 if ($SBSSetInterceptsMenuButtonForever != NULL)
8924 (*$SBSSetInterceptsMenuButtonForever)(true);
8926 [self setIdleTimerDisabled:YES];
8930 - (void) unlockSuspend {
8931 if (--locked_ == 0) {
8932 [self setIdleTimerDisabled:NO];
8934 if ($SBSSetInterceptsMenuButtonForever != NULL)
8935 (*$SBSSetInterceptsMenuButtonForever)(false);
8939 - (void) beginUpdate {
8940 [tabbar_ beginUpdate];
8943 - (void) cancelUpdate {
8944 [tabbar_ cancelUpdate];
8947 - (bool) requestUpdate {
8948 if (IsReachable("cydia.saurik.com")) {
8952 UIAlertView *alert = [[[UIAlertView alloc]
8953 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("REFRESH")]
8954 message:@"Host Unreachable" // XXX: Localize
8956 cancelButtonTitle:UCLocalize("OK")
8957 otherButtonTitles:nil
8960 [alert setContext:@"norefresh"];
8968 return [tabbar_ updating];
8972 if ([broken_ count] != 0) {
8973 int count = [broken_ count];
8975 UIAlertView *alert = [[[UIAlertView alloc]
8976 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8977 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8979 cancelButtonTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("FORCIBLY_CLEAR"), UCLocalize("UNSAFE")]
8981 UCLocalize("TEMPORARY_IGNORE"),
8985 [alert setContext:@"fixhalf"];
8986 [alert setNumberOfRows:2];
8988 } else if (!Ignored_ && [essential_ count] != 0) {
8989 int count = [essential_ count];
8991 UIAlertView *alert = [[[UIAlertView alloc]
8992 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8993 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8995 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8997 UCLocalize("UPGRADE_ESSENTIAL"),
8998 UCLocalize("COMPLETE_UPGRADE"),
9002 [alert setContext:@"upgrade"];
9007 - (void) returnToCydia {
9011 - (void) _saveConfig {
9012 @synchronized (database_) {
9019 NSString *error(nil);
9021 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
9023 NSError *error(nil);
9024 if (!_root([data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error]))
9025 NSLog(@"failure to save metadata data: %@", error);
9030 NSLog(@"failure to serialize metadata: %@", error);
9034 CydiaWriteSources();
9037 // Navigation controller for the queuing badge.
9038 - (UINavigationController *) queueNavigationController {
9039 NSArray *controllers = [tabbar_ viewControllers];
9040 return [controllers objectAtIndex:3];
9043 - (void) unloadData {
9044 [tabbar_ unloadData];
9047 - (void) _updateData {
9051 UINavigationController *navigation = [self queueNavigationController];
9053 id queuedelegate = nil;
9054 if ([[navigation viewControllers] count] > 0)
9055 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9057 [queuedelegate queueStatusDidChange];
9058 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9061 - (void) _refreshIfPossible:(NSDate *)update {
9062 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9064 bool recently = false;
9065 if (update != nil) {
9066 NSTimeInterval interval([update timeIntervalSinceNow]);
9067 if (interval > -(15*60))
9071 // Don't automatic refresh if:
9072 // - We already refreshed recently.
9073 // - We already auto-refreshed this launch.
9074 // - Auto-refresh is disabled.
9075 // - Cydia's server is not reachable
9076 if (recently || loaded_ || ManualRefresh || !IsReachable("cydia.saurik.com")) {
9077 // If we are cancelling, we need to make sure it knows it's already loaded.
9080 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9082 // We are going to load, so remember that.
9085 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
9091 - (void) refreshIfPossible {
9092 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
9095 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9096 _profile(reloadDataWithInvocation)
9097 @synchronized (self) {
9098 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9100 [hud setText:UCLocalize("RELOADING_DATA")];
9102 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9106 [essential_ removeAllObjects];
9107 [broken_ removeAllObjects];
9109 _profile(reloadDataWithInvocation$Essential)
9110 NSArray *packages([database_ packages]);
9111 for (Package *package in packages) {
9113 [broken_ addObject:package];
9114 if ([package upgradableAndEssential:YES] && ![package ignored]) {
9115 if ([package essential] && [package installed] != nil)
9116 [essential_ addObject:package];
9122 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9125 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9126 [changesItem setBadgeValue:badge];
9127 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9128 [self setApplicationIconBadgeNumber:changes];
9131 [changesItem setBadgeValue:nil];
9132 [changesItem setAnimatedBadge:NO];
9133 [self setApplicationIconBadgeNumber:0];
9140 [self removeProgressHUD:hud];
9147 - (void) updateData {
9151 - (void) updateDataAndLoad {
9153 if ([database_ progressDelegate] == nil)
9159 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9162 - (void) disemulate {
9163 if (emulated_ == nil)
9166 if ([window_ respondsToSelector:@selector(setRootViewController:)])
9167 [window_ setRootViewController:tabbar_];
9169 [window_ addSubview:[tabbar_ view]];
9170 [[emulated_ view] removeFromSuperview];
9174 [window_ setUserInteractionEnabled:YES];
9177 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9178 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9180 UIViewController *parent;
9181 if (emulated_ == nil)
9191 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9192 [parent presentModalViewController:navigation animated:YES];
9195 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9196 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9198 if (navigation != nil)
9199 [navigation pushViewController:progress animated:YES];
9201 [self presentModalViewController:progress force:YES];
9203 [progress invoke:invocation withTitle:title];
9207 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9208 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9211 - (void) repairWithInvocation:(NSInvocation *)invocation {
9213 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9217 - (void) repairWithSelector:(SEL)selector {
9218 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9221 - (void) reloadData {
9222 [self reloadDataWithInvocation:nil];
9223 if ([database_ progressDelegate] == nil)
9229 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9232 - (void) addSource:(NSDictionary *) source {
9233 CydiaAddSource(source);
9236 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9237 CydiaAddSource(href, distribution, sections);
9240 - (void) addTrivialSource:(NSString *)href {
9241 CydiaAddSource(href, @"./");
9244 - (void) updateValues {
9249 pkgProblemResolver *resolver = [database_ resolver];
9251 resolver->InstallProtect();
9252 if (!resolver->Resolve(true))
9257 // XXX: this is a really crappy way of doing this.
9258 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9259 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9260 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9261 if ([tabbar_ updating])
9262 [tabbar_ cancelUpdate];
9264 if (![database_ prepare])
9267 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9268 [page setDelegate:self];
9269 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9272 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9273 [tabbar_ presentModalViewController:confirm_ animated:YES];
9279 @synchronized (self) {
9284 - (void) clearPackage:(Package *)package {
9285 @synchronized (self) {
9292 - (void) installPackages:(NSArray *)packages {
9293 @synchronized (self) {
9294 for (Package *package in packages)
9301 - (void) installPackage:(Package *)package {
9302 @synchronized (self) {
9309 - (void) removePackage:(Package *)package {
9310 @synchronized (self) {
9317 - (void) distUpgrade {
9318 @synchronized (self) {
9319 if (![database_ upgrade])
9328 if (UpgradeCydia_ && Finish_ > 0) {
9330 system("su -c /usr/bin/uicache mobile");
9332 system("/usr/bin/uicache");
9339 UIProgressHUD *hud([self addProgressHUD]);
9340 [hud setText:UCLocalize("LOADING")];
9341 [self yieldToSelector:@selector(_uicache)];
9342 [self removeProgressHUD:hud];
9346 [database_ perform];
9347 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9348 [self performSelectorOnMainThread:@selector(uicache) withObject:nil waitUntilDone:YES];
9351 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9354 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9355 [self unlockSuspend];
9358 - (void) retainNetworkActivityIndicator {
9359 if (activity_++ == 0)
9360 [self setNetworkActivityIndicatorVisible:YES];
9363 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9367 - (void) releaseNetworkActivityIndicator {
9368 if (--activity_ == 0)
9369 [self setNetworkActivityIndicatorVisible:NO];
9372 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9377 - (void) cancelAndClear:(bool)clear {
9378 @synchronized (self) {
9390 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9391 NSString *context([alert context]);
9393 if ([context isEqualToString:@"conffile"]) {
9394 FILE *input = [database_ input];
9395 if (button == [alert cancelButtonIndex])
9396 fprintf(input, "N\n");
9397 else if (button == [alert firstOtherButtonIndex])
9398 fprintf(input, "Y\n");
9401 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9402 } else if ([context isEqualToString:@"fixhalf"]) {
9403 if (button == [alert cancelButtonIndex]) {
9404 @synchronized (self) {
9405 for (Package *broken in (id) broken_) {
9407 NSString *id = [broken id];
9409 system([[NSString stringWithFormat:@"/usr/libexec/cydia/cydo /bin/rm -f"
9410 " /var/lib/dpkg/info/%@.prerm"
9411 " /var/lib/dpkg/info/%@.postrm"
9412 " /var/lib/dpkg/info/%@.preinst"
9413 " /var/lib/dpkg/info/%@.postinst"
9414 " /var/lib/dpkg/info/%@.extrainst_"
9415 , id, id, id, id, id] UTF8String]);
9421 } else if (button == [alert firstOtherButtonIndex]) {
9422 [broken_ removeAllObjects];
9426 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9427 } else if ([context isEqualToString:@"upgrade"]) {
9428 if (button == [alert firstOtherButtonIndex]) {
9429 @synchronized (self) {
9430 for (Package *essential in (id) essential_)
9431 [essential install];
9436 } else if (button == [alert firstOtherButtonIndex] + 1) {
9438 } else if (button == [alert cancelButtonIndex]) {
9442 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9446 - (void) system:(NSString *)command {
9447 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9450 system([command UTF8String]);
9456 - (void) applicationWillSuspend {
9458 [super applicationWillSuspend];
9461 - (BOOL) isSafeToSuspend {
9464 NSLog(@"isSafeToSuspend: locked_ != 0");
9469 if ([tabbar_ modalViewController] != nil)
9472 // Use external process status API internally.
9473 // This is probably a really bad idea.
9474 // XXX: what is the point of this? does this solve anything at all?
9475 uint64_t status = 0;
9477 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9478 notify_get_state(notify_token, &status);
9479 notify_cancel(notify_token);
9484 NSLog(@"isSafeToSuspend: status != 0");
9490 NSLog(@"isSafeToSuspend: -> true");
9495 - (void) suspendReturningToLastApp:(BOOL)returning {
9496 if ([self isSafeToSuspend])
9497 [super suspendReturningToLastApp:returning];
9501 if ([self isSafeToSuspend])
9505 - (void) applicationSuspend {
9506 if ([self isSafeToSuspend])
9507 [super applicationSuspend];
9510 - (void) applicationSuspend:(__GSEvent *)event {
9511 if ([self isSafeToSuspend])
9512 [super applicationSuspend:event];
9515 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9516 if ([self isSafeToSuspend])
9517 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9520 - (void) _setSuspended:(BOOL)value {
9521 if ([self isSafeToSuspend])
9522 [super _setSuspended:value];
9525 - (UIProgressHUD *) addProgressHUD {
9526 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9527 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9529 [window_ setUserInteractionEnabled:NO];
9531 UIViewController *target(tabbar_);
9532 if (UIViewController *modal = [target modalViewController])
9535 [hud showInView:[target view]];
9541 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9542 [self unlockSuspend];
9544 [hud removeFromSuperview];
9545 [window_ setUserInteractionEnabled:YES];
9548 - (CyteViewController *) pageForPackage:(NSString *)name withReferrer:(NSString *)referrer {
9549 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name withReferrer:referrer] autorelease];
9552 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external withReferrer:(NSString *)referrer {
9553 NSString *scheme([[url scheme] lowercaseString]);
9554 if ([[url absoluteString] length] <= [scheme length] + 3)
9556 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9557 NSArray *components([path componentsSeparatedByString:@"/"]);
9559 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"]) {
9560 CyteViewController *controller([self pageForPackage:[components objectAtIndex:1] withReferrer:referrer]);
9561 if (controller != nil)
9562 [controller setDelegate:self];
9566 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9569 NSString *base([components objectAtIndex:0]);
9571 CyteViewController *controller = nil;
9573 if ([base isEqualToString:@"url"]) {
9574 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9575 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9576 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9577 } else if (!external && [components count] == 1) {
9578 if ([base isEqualToString:@"sources"]) {
9579 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9582 if ([base isEqualToString:@"home"]) {
9583 controller = [[[HomeController alloc] init] autorelease];
9586 if ([base isEqualToString:@"sections"]) {
9587 controller = [[[SectionsController alloc] initWithDatabase:database_ source:nil] autorelease];
9590 if ([base isEqualToString:@"search"]) {
9591 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9594 if ([base isEqualToString:@"changes"]) {
9595 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9598 if ([base isEqualToString:@"installed"]) {
9599 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9601 } else if ([components count] == 2) {
9602 NSString *argument = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9604 if ([base isEqualToString:@"package"]) {
9605 controller = [self pageForPackage:argument withReferrer:referrer];
9608 if (!external && [base isEqualToString:@"search"]) {
9609 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9612 if (!external && [base isEqualToString:@"sections"]) {
9613 if ([argument isEqualToString:@"all"] || [argument isEqualToString:@"*"])
9615 controller = [[[SectionController alloc] initWithDatabase:database_ source:nil section:argument] autorelease];
9618 if (!external && [base isEqualToString:@"sources"]) {
9619 if ([argument isEqualToString:@"add"]) {
9620 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9621 [(SourcesController *)controller showAddSourcePrompt];
9623 Source *source([database_ sourceWithKey:argument]);
9624 controller = [[[SectionsController alloc] initWithDatabase:database_ source:source] autorelease];
9628 if (!external && [base isEqualToString:@"launch"]) {
9629 [self launchApplicationWithIdentifier:argument suspended:NO];
9632 } else if (!external && [components count] == 3) {
9633 NSString *arg1 = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9634 NSString *arg2 = [[components objectAtIndex:2] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9636 if ([base isEqualToString:@"package"]) {
9637 if ([arg2 isEqualToString:@"settings"]) {
9638 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9639 } else if ([arg2 isEqualToString:@"files"]) {
9640 if (Package *package = [database_ packageWithName:arg1]) {
9641 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9642 [(FileTable *)controller setPackage:package];
9647 if ([base isEqualToString:@"sections"]) {
9648 Source *source([arg1 isEqualToString:@"*"] ? nil : [database_ sourceWithKey:arg1]);
9649 NSString *section([arg2 isEqualToString:@"*"] ? nil : arg2);
9650 controller = [[[SectionController alloc] initWithDatabase:database_ source:source section:section] autorelease];
9654 [controller setDelegate:self];
9658 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9659 CyteViewController *page([self pageForURL:url forExternal:external withReferrer:nil]);
9662 [tabbar_ setUnselectedViewController:page];
9667 - (void) applicationOpenURL:(NSURL *)url {
9668 [super applicationOpenURL:url];
9673 [self openCydiaURL:url forExternal:YES];
9676 - (void) applicationWillResignActive:(UIApplication *)application {
9677 // Stop refreshing if you get a phone call or lock the device.
9678 if ([tabbar_ updating])
9679 [tabbar_ cancelUpdate];
9681 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9682 [super applicationWillResignActive:application];
9685 - (void) saveState {
9686 [[NSDictionary dictionaryWithObjectsAndKeys:
9687 @"InterfaceState", [tabbar_ navigationURLCollection],
9688 @"LastClosed", [NSDate date],
9689 @"InterfaceIndex", [NSNumber numberWithInt:[tabbar_ selectedIndex]],
9690 nil] writeToFile:@ SavedState_ atomically:YES];
9695 - (void) applicationWillTerminate:(UIApplication *)application {
9699 - (void) applicationDidEnterBackground:(UIApplication *)application {
9700 if (kCFCoreFoundationVersionNumber < 1000 && [self isSafeToSuspend])
9701 return [self terminateWithSuccess];
9702 Backgrounded_ = [NSDate date];
9706 - (void) applicationWillEnterForeground:(UIApplication *)application {
9707 if (Backgrounded_ == nil)
9710 NSTimeInterval interval([Backgrounded_ timeIntervalSinceNow]);
9712 if (interval <= -(30*60)) {
9713 [tabbar_ setSelectedIndex:0];
9714 [[[tabbar_ viewControllers] objectAtIndex:0] popToRootViewControllerAnimated:NO];
9717 if (interval <= -(15*60)) {
9718 if (IsReachable("cydia.saurik.com")) {
9719 [tabbar_ beginUpdate];
9720 [appcache_ reloadURLWithCache:YES];
9725 - (void) setConfigurationData:(NSString *)data {
9726 static RegEx conffile_r("'(.*)' '(.*)' ([01]) ([01])");
9728 if (!conffile_r(data)) {
9729 lprintf("E:invalid conffile\n");
9733 NSString *ofile = conffile_r[1];
9734 //NSString *nfile = conffile_r[2];
9736 UIAlertView *alert = [[[UIAlertView alloc]
9737 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9738 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9740 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9742 UCLocalize("ACCEPT_NEW_COPY"),
9743 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9747 [alert setContext:@"conffile"];
9748 [alert setNumberOfRows:2];
9752 - (void) addStashController {
9754 stash_ = [[[StashController alloc] init] autorelease];
9755 [window_ addSubview:[stash_ view]];
9758 - (void) removeStashController {
9759 [[stash_ view] removeFromSuperview];
9761 [self unlockSuspend];
9765 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9766 UpdateExternalStatus(1);
9767 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/cydo /usr/libexec/cydia/free.sh"];
9768 UpdateExternalStatus(0);
9770 [self removeStashController];
9772 pid_t pid(ExecFork());
9774 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9775 perror("launchctl stop");
9781 - (void) setupViewControllers {
9782 tabbar_ = [[[CydiaTabBarController alloc] initWithDatabase:database_] autorelease];
9784 NSMutableArray *items;
9785 if (kCFCoreFoundationVersionNumber < 800) {
9786 items = [NSMutableArray arrayWithObjects:
9787 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage imageNamed:@"home.png"] tag:0] autorelease],
9788 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage imageNamed:@"install.png"] tag:0] autorelease],
9789 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage imageNamed:@"changes.png"] tag:0] autorelease],
9790 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage imageNamed:@"manage.png"] tag:0] autorelease],
9791 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage imageNamed:@"search.png"] tag:0] autorelease],
9794 items = [NSMutableArray arrayWithObjects:
9795 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage imageNamed:@"home7.png"] selectedImage:[UIImage imageNamed:@"home7s.png"]] autorelease],
9796 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage imageNamed:@"install7.png"] selectedImage:[UIImage imageNamed:@"install7s.png"]] autorelease],
9797 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage imageNamed:@"changes7.png"] selectedImage:[UIImage imageNamed:@"changes7s.png"]] autorelease],
9798 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage imageNamed:@"manage7.png"] selectedImage:[UIImage imageNamed:@"manage7s.png"]] autorelease],
9799 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage imageNamed:@"search7.png"] selectedImage:[UIImage imageNamed:@"search7s.png"]] autorelease],
9803 NSMutableArray *controllers([NSMutableArray array]);
9804 for (UITabBarItem *item in items) {
9805 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9806 [controller setTabBarItem:item];
9807 [controllers addObject:controller];
9809 [tabbar_ setViewControllers:controllers];
9811 [tabbar_ setUpdateDelegate:self];
9814 - (void) _sendMemoryWarningNotification {
9815 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: maybe 4_0?
9816 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationMemoryWarningNotification" object:[UIApplication sharedApplication]];
9818 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
9821 - (void) _sendMemoryWarningNotifications {
9823 [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO];
9829 - (void) applicationDidReceiveMemoryWarning:(UIApplication *)application {
9831 [[NSURLCache sharedURLCache] removeAllCachedResponses];
9834 - (void) applicationDidFinishLaunching:(id)unused {
9835 //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil];
9838 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9839 [self setApplicationSupportsShakeToEdit:NO];
9841 @synchronized (HostConfig_) {
9842 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9845 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9846 initWithMemoryCapacity:524288
9847 diskCapacity:10485760
9848 diskPath:Cache("SDURLCache")
9851 [CydiaWebViewController _initialize];
9853 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9855 // this would disallow http{,s} URLs from accessing this data
9856 //[WebView registerURLSchemeAsLocal:@"cydia"];
9858 Font12_ = [UIFont systemFontOfSize:12];
9859 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9860 Font14_ = [UIFont systemFontOfSize:14];
9861 Font18_ = [UIFont systemFontOfSize:18];
9862 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9863 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9865 essential_ = [NSMutableArray arrayWithCapacity:4];
9866 broken_ = [NSMutableArray arrayWithCapacity:4];
9868 // XXX: I really need this thing... like, seriously... I'm sorry
9869 appcache_ = [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] autorelease];
9870 [appcache_ reloadData];
9872 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9873 [window_ orderFront:self];
9874 [window_ makeKey:self];
9875 [window_ setHidden:NO];
9878 [self addStashController];
9879 // XXX: this would be much cleaner as a yieldToSelector:
9880 // that way the removeStashController could happen right here inline
9881 // we also could no longer require the useless stash_ field anymore
9882 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9887 int error(stat("/", &root));
9888 _assert(error != -1);
9890 #define Stash_(path) do { \
9891 struct stat folder; \
9892 int error(lstat((path), &folder)); \
9893 if (error != -1 && ( \
9894 folder.st_dev == root.st_dev && \
9895 S_ISDIR(folder.st_mode) \
9896 ) || error == -1 && ( \
9897 errno == ENOENT || \
9902 Stash_("/Applications");
9903 Stash_("/Library/Ringtones");
9904 Stash_("/Library/Wallpaper");
9905 //Stash_("/usr/bin");
9906 Stash_("/usr/include");
9907 Stash_("/usr/share");
9908 //Stash_("/var/lib");
9910 database_ = [Database sharedInstance];
9911 [database_ setDelegate:self];
9913 [window_ setUserInteractionEnabled:NO];
9914 [self setupViewControllers];
9916 CydiaLoadingViewController *loading([[[CydiaLoadingViewController alloc] init] autorelease]);
9917 UINavigationController *navigation([[[UINavigationController alloc] init] autorelease]);
9918 [navigation setViewControllers:[NSArray arrayWithObject:loading]];
9920 emulated_ = [[[CyteTabBarController alloc] init] autorelease];
9921 [emulated_ setViewControllers:[NSArray arrayWithObject:navigation]];
9922 [emulated_ setSelectedIndex:0];
9924 if ([emulated_ respondsToSelector:@selector(concealTabBarSelection)])
9925 [emulated_ concealTabBarSelection];
9927 if ([window_ respondsToSelector:@selector(setRootViewController:)])
9928 [window_ setRootViewController:emulated_];
9930 [window_ addSubview:[emulated_ view]];
9932 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9936 - (NSArray *) defaultStartPages {
9937 NSMutableArray *standard = [NSMutableArray array];
9938 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9939 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9940 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9941 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9942 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9948 if ([emulated_ modalViewController] != nil)
9949 [emulated_ dismissModalViewControllerAnimated:YES];
9950 [window_ setUserInteractionEnabled:NO];
9952 [self reloadDataWithInvocation:nil];
9953 [self refreshIfPossible];
9956 NSDictionary *state([NSDictionary dictionaryWithContentsOfFile:@ SavedState_]);
9958 int savedIndex = [[state objectForKey:@"InterfaceIndex"] intValue];
9959 NSArray *saved = [[[state objectForKey:@"InterfaceState"] mutableCopy] autorelease];
9960 int standardIndex = 0;
9961 NSArray *standard = [self defaultStartPages];
9968 NSDate *closed = [state objectForKey:@"LastClosed"];
9969 if (valid && closed != nil) {
9970 NSTimeInterval interval([closed timeIntervalSinceNow]);
9971 if (interval <= -(30*60))
9975 if (valid && [saved count] != [standard count])
9979 for (unsigned int i = 0; i < [standard count]; i++) {
9980 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
9981 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
9982 // but it's good enough for now.
9983 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
9990 NSArray *items = nil;
9992 [tabbar_ setSelectedIndex:savedIndex];
9995 [tabbar_ setSelectedIndex:standardIndex];
9999 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
10000 NSArray *stack = [items objectAtIndex:tab];
10001 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
10002 NSMutableArray *current = [NSMutableArray array];
10004 for (unsigned int nav = 0; nav < [stack count]; nav++) {
10005 NSString *addr = [stack objectAtIndex:nav];
10006 NSURL *url = [NSURL URLWithString:addr];
10007 CyteViewController *page = [self pageForURL:url forExternal:NO withReferrer:nil];
10009 [current addObject:page];
10012 [navigation setViewControllers:current];
10015 // (Try to) show the startup URL.
10016 if (starturl_ != nil) {
10017 [self openCydiaURL:starturl_ forExternal:YES];
10022 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
10023 if (item != nil && IsWildcat_) {
10024 [sheet showFromBarButtonItem:item animated:YES];
10026 [sheet showInView:window_];
10030 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
10031 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
10032 [progress setTitle:task];
10033 [progress addProgressEvent:event];
10036 - (void) addProgressEventForTask:(NSArray *)data {
10037 CydiaProgressEvent *event([data objectAtIndex:0]);
10038 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
10039 [self addProgressEvent:event forTask:task];
10042 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
10043 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
10049 id Alloc_(id self, SEL selector) {
10050 id object = alloc_(self, selector);
10051 lprintf("[%s]A-%p\n", self->isa->name, object);
10056 id Dealloc_(id self, SEL selector) {
10057 id object = dealloc_(self, selector);
10058 lprintf("[%s]D-%p\n", self->isa->name, object);
10062 Class $NSURLConnection;
10064 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
10065 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
10067 NSURL *url([copy URL]);
10069 NSString *host([url host]);
10070 NSString *scheme([[url scheme] lowercaseString]);
10072 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
10074 @synchronized (HostConfig_) {
10075 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
10076 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
10077 [copy setHTTPShouldUsePipelining:YES];
10079 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
10080 if ([control isEqualToString:@"max-age=0"])
10081 if ([CachedURLs_ containsObject:url]) {
10083 NSLog(@"~~~: %@", url);
10086 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
10088 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
10089 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
10090 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
10094 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
10100 static CGSize $WAKWindow$screenSize(WAKWindow *self, SEL _cmd) {
10101 CGSize size([[UIScreen mainScreen] bounds].size);
10102 /*if ([$WAKWindow respondsToSelector:@selector(hasLandscapeOrientation)])
10103 if ([$WAKWindow hasLandscapeOrientation])
10104 std::swap(size.width, size.height);*/
10108 Class $NSUserDefaults;
10110 MSHook(id, NSUserDefaults$objectForKey$, NSUserDefaults *self, SEL _cmd, NSString *key) {
10111 if ([key respondsToSelector:@selector(isEqualToString:)] && [key isEqualToString:@"WebKitLocalStorageDatabasePathPreferenceKey"])
10112 return Cache("LocalStorage");
10113 return _NSUserDefaults$objectForKey$(self, _cmd, key);
10116 int main(int argc, char *argv[]) {
10117 setreugid(501, 501);
10119 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10123 UpdateExternalStatus(0);
10125 UIScreen *screen([UIScreen mainScreen]);
10126 if ([screen respondsToSelector:@selector(scale)])
10127 ScreenScale_ = [screen scale];
10131 UIDevice *device([UIDevice currentDevice]);
10132 if ([device respondsToSelector:@selector(userInterfaceIdiom)]) {
10133 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10134 if (idiom == UIUserInterfaceIdiomPad)
10138 Idiom_ = IsWildcat_ ? @"ipad" : @"iphone";
10140 RegEx pattern("([0-9]+\\.[0-9]+).*");
10142 if (pattern([device systemVersion]))
10143 Firmware_ = pattern[1];
10144 if (pattern(Cydia_))
10145 Major_ = pattern[1];
10147 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
10149 HostConfig_ = [[[NSObject alloc] init] autorelease];
10150 @synchronized (HostConfig_) {
10151 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10152 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
10153 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
10154 CachedURLs_ = [NSMutableSet setWithCapacity:32];
10157 NSString *ui(@"ui/ios");
10159 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
10160 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"/%@", Major_]];
10161 UI_ = CydiaURL(ui);
10163 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10165 /* Library Hacks {{{ */
10166 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10168 $WAKWindow = objc_getClass("WAKWindow");
10169 if ($WAKWindow != NULL)
10170 if (Method method = class_getInstanceMethod($WAKWindow, @selector(screenSize)))
10171 method_setImplementation(method, (IMP) &$WAKWindow$screenSize);
10173 $NSURLConnection = objc_getClass("NSURLConnection");
10174 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10175 if (NSURLConnection$init$ != NULL) {
10176 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10177 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10180 $NSUserDefaults = objc_getClass("NSUserDefaults");
10181 Method NSUserDefaults$objectForKey$(class_getInstanceMethod($NSUserDefaults, @selector(objectForKey:)));
10182 if (NSUserDefaults$objectForKey$ != NULL) {
10183 _NSUserDefaults$objectForKey$ = reinterpret_cast<id (*)(NSUserDefaults *, SEL, NSString *)>(method_getImplementation(NSUserDefaults$objectForKey$));
10184 method_setImplementation(NSUserDefaults$objectForKey$, reinterpret_cast<IMP>(&$NSUserDefaults$objectForKey$));
10187 /* Set Locale {{{ */
10188 Locale_ = CFLocaleCopyCurrent();
10189 Languages_ = [NSLocale preferredLanguages];
10191 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10192 //NSLog(@"%@", [Languages_ description]);
10195 if (Locale_ != NULL)
10196 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10197 else if (Languages_ != nil && [Languages_ count] != 0)
10198 lang = [[Languages_ objectAtIndex:0] UTF8String];
10200 // XXX: consider just setting to C and then falling through?
10203 if (lang != NULL) {
10204 RegEx pattern("([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?");
10205 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10208 NSLog(@"Setting Language: %s", lang);
10210 if (lang != NULL) {
10211 setenv("LANG", lang, true);
10212 std::setlocale(LC_ALL, lang);
10215 /* Index Collation {{{ */
10216 if (Class $UILocalizedIndexedCollation = objc_getClass("UILocalizedIndexedCollation")) { @try {
10217 NSBundle *bundle([NSBundle bundleForClass:$UILocalizedIndexedCollation]);
10218 NSString *path([bundle pathForResource:@"UITableViewLocalizedSectionIndex" ofType:@"plist"]);
10219 //path = @"/System/Library/Frameworks/UIKit.framework/.lproj/UITableViewLocalizedSectionIndex.plist";
10220 NSDictionary *dictionary([NSDictionary dictionaryWithContentsOfFile:path]);
10221 _H<UILocalizedIndexedCollation> collation([[[$UILocalizedIndexedCollation alloc] initWithDictionary:dictionary] autorelease]);
10223 CollationLocale_ = MSHookIvar<NSLocale *>(collation, "_locale");
10225 if (kCFCoreFoundationVersionNumber >= 800 && [[CollationLocale_ localeIdentifier] isEqualToString:@"zh@collation=stroke"]) {
10226 CollationThumbs_ = [NSArray arrayWithObjects:@"1",@"•",@"4",@"•",@"7",@"•",@"10",@"•",@"13",@"•",@"16",@"•",@"19",@"A",@"•",@"E",@"•",@"I",@"•",@"M",@"•",@"R",@"•",@"V",@"•",@"Z",@"#",nil];
10227 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})
10228 CollationOffset_.push_back(offset);
10229 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];
10230 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];
10233 CollationThumbs_ = [collation sectionIndexTitles];
10234 for (size_t index(0), end([CollationThumbs_ count]); index != end; ++index)
10235 CollationOffset_.push_back([collation sectionForSectionIndexTitleAtIndex:index]);
10237 CollationTitles_ = [collation sectionTitles];
10238 CollationStarts_ = MSHookIvar<NSArray *>(collation, "_sectionStartStrings");
10240 NSString *&transform(MSHookIvar<NSString *>(collation, "_transform"));
10241 if (&transform != NULL && transform != nil) {
10242 /*if ([collation respondsToSelector:@selector(transformedCollationStringForString:)])
10243 CollationModify_ = [=](NSString *value) { return [collation transformedCollationStringForString:value]; };*/
10244 const UChar *uid(reinterpret_cast<const UChar *>([transform cStringUsingEncoding:NSUnicodeStringEncoding]));
10245 UErrorCode code(U_ZERO_ERROR);
10246 CollationTransl_ = utrans_openU(uid, -1, UTRANS_FORWARD, NULL, 0, NULL, &code);
10247 if (!U_SUCCESS(code))
10248 NSLog(@"%s", u_errorName(code));
10252 } @catch (NSException *e) {
10256 CollationLocale_ = [[[NSLocale alloc] initWithLocaleIdentifier:@"en@collation=dictionary"] autorelease];
10258 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];
10259 for (NSInteger offset(0); offset != 28; ++offset)
10260 CollationOffset_.push_back(offset);
10262 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];
10263 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];
10266 /* Parse Arguments {{{ */
10267 bool substrate(false);
10273 for (int argi(1); argi != argc; ++argi)
10274 if (strcmp(argv[argi], "--") == 0) {
10276 argv[argi] = argv[0];
10282 for (int argi(1); argi != arge; ++argi)
10283 if (strcmp(args[argi], "--substrate") == 0)
10286 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10290 App_ = [[NSBundle mainBundle] bundlePath];
10293 Cache_ = [[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia", @"/var/mobile"] retain];
10295 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10296 alloc_ = alloc->method_imp;
10297 alloc->method_imp = (IMP) &Alloc_;*/
10299 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10300 dealloc_ = dealloc->method_imp;
10301 dealloc->method_imp = (IMP) &Dealloc_;*/
10303 void *gestalt(dlopen("/usr/lib/libMobileGestalt.dylib", RTLD_GLOBAL | RTLD_LAZY));
10304 $MGCopyAnswer = reinterpret_cast<CFStringRef (*)(CFStringRef)>(dlsym(gestalt, "MGCopyAnswer"));
10306 /* System Information {{{ */
10310 size = sizeof(maxproc);
10311 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10312 perror("sysctlbyname(\"kern.maxproc\", ?)");
10313 else if (maxproc < 64) {
10315 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10316 perror("sysctlbyname(\"kern.maxproc\", #)");
10319 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10320 char *osversion = new char[size];
10321 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10322 perror("sysctlbyname(\"kern.osversion\", ?)");
10324 System_ = [NSString stringWithUTF8String:osversion];
10326 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10327 char *machine = new char[size];
10328 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10329 perror("sysctlbyname(\"hw.machine\", ?)");
10331 Machine_ = machine;
10333 int64_t usermem(0);
10334 size = sizeof(usermem);
10335 if (sysctlbyname("hw.usermem", &usermem, &size, NULL, 0) == -1)
10338 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10339 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10340 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10342 UniqueID_ = UniqueIdentifier(device);
10344 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10345 Product_ = [info objectForKey:@"SafariProductVersion"];
10346 Safari_ = [info objectForKey:@"CFBundleVersion"];
10349 NSString *agent([NSString stringWithFormat:@"Cydia/%@ CyF/%.2f", Cydia_, kCFCoreFoundationVersionNumber]);
10351 if (RegEx match = RegEx("([0-9]+(\\.[0-9]+)+).*", Safari_))
10352 agent = [NSString stringWithFormat:@"Safari/%@ %@", match[1], agent];
10353 if (RegEx match = RegEx("([0-9]+[A-Z][0-9]+[a-z]?).*", System_))
10354 agent = [NSString stringWithFormat:@"Mobile/%@ %@", match[1], agent];
10355 if (RegEx match = RegEx("([0-9]+(\\.[0-9]+)+).*", Product_))
10356 agent = [NSString stringWithFormat:@"Version/%@ %@", match[1], agent];
10358 UserAgent_ = agent;
10360 /* Load Database {{{ */
10362 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10364 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10366 if (Metadata_ == NULL)
10367 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10369 Values_ = [Metadata_ objectForKey:@"Values"];
10370 Sections_ = [Metadata_ objectForKey:@"Sections"];
10371 Sources_ = [Metadata_ objectForKey:@"Sources"];
10373 Version_ = [Metadata_ objectForKey:@"Version"];
10376 if (Values_ == nil) {
10377 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10378 [Metadata_ setObject:Values_ forKey:@"Values"];
10381 if (Sections_ == nil) {
10382 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10383 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10386 if (Sources_ == nil) {
10387 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10388 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10391 if (Version_ == nil) {
10392 Version_ = [NSNumber numberWithUnsignedInt:0];
10393 [Metadata_ setObject:Version_ forKey:@"Version"];
10396 if ([Version_ unsignedIntValue] == 0) {
10397 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10398 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10399 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10400 CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./");
10402 Version_ = [NSNumber numberWithUnsignedInt:1];
10403 [Metadata_ setObject:Version_ forKey:@"Version"];
10405 [Metadata_ removeObjectForKey:@"LastUpdate"];
10410 _H<NSMutableArray> broken([NSMutableArray array]);
10411 for (NSString *key in (id) Sources_)
10412 if ([key rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"# "]].location != NSNotFound)
10413 [broken addObject:key];
10414 if ([broken count] != 0) {
10415 for (NSString *key in (id) broken)
10416 [Sources_ removeObjectForKey:key];
10421 CydiaWriteSources();
10424 mkdir("/var/mobile/Library/Cydia", 0755);
10425 MetaFile_.Open("/var/mobile/Library/Cydia/metadata.cb0");
10428 if (NSDictionary *packages = [Metadata_ objectForKey:@"Packages"]) {
10430 CFDictionaryApplyFunction((CFDictionaryRef) packages, &PackageImport, &fail);
10434 [Metadata_ removeObjectForKey:@"Packages"];
10439 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10441 #define MobileSubstrate_(name) \
10442 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10443 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10444 if (handle == NULL) \
10445 NSLog(@"%s", dlerror()); \
10448 MobileSubstrate_(Activator)
10449 MobileSubstrate_(libstatusbar)
10450 MobileSubstrate_(SimulatedKeyEvents)
10451 MobileSubstrate_(WinterBoard)
10453 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10454 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10456 if (kCFCoreFoundationVersionNumber > 1000)
10457 system("/usr/libexec/cydia/cydo /usr/libexec/cydia/setnsfpn /var/lib");
10459 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10461 if (access("/User", F_OK) != 0 || version != 6) {
10463 system("/usr/libexec/cydia/cydo /usr/libexec/cydia/firmware.sh");
10467 if (access("/tmp/cydia.chk", F_OK) == 0) {
10468 if (unlink([Cache("pkgcache.bin") UTF8String]) == -1)
10469 _assert(errno == ENOENT);
10470 if (unlink([Cache("srcpkgcache.bin") UTF8String]) == -1)
10471 _assert(errno == ENOENT);
10474 /* APT Initialization {{{ */
10475 _assert(pkgInitConfig(*_config));
10476 _assert(pkgInitSystem(*_config, _system));
10479 _config->Set("APT::Acquire::Translation", lang);
10481 // XXX: this timeout might be important :(
10482 //_config->Set("Acquire::http::Timeout", 15);
10484 _config->Set("Acquire::http::MaxParallel", usermem >= 384 * 1024 * 1024 ? 16 : 3);
10486 mkdir([Cache_ UTF8String], 0755);
10487 mkdir([Cache("archives") UTF8String], 0755);
10488 mkdir([Cache("archives/partial") UTF8String], 0755);
10489 _config->Set("Dir::Cache", [Cache_ UTF8String]);
10491 mkdir([Cache("lists") UTF8String], 0755);
10492 mkdir([Cache("lists/partial") UTF8String], 0755);
10493 mkdir([Cache("periodic") UTF8String], 0755);
10494 _config->Set("Dir::State::Lists", [Cache("lists") UTF8String]);
10496 std::string logs("/var/mobile/Library/Logs/Cydia");
10497 mkdir(logs.c_str(), 0755);
10498 _config->Set("Dir::Log::Terminal", logs + "/apt.log");
10500 _config->Set("Dir::Bin::dpkg", "/usr/libexec/cydia/cydo");
10502 /* Color Choices {{{ */
10503 space_ = CGColorSpaceCreateDeviceRGB();
10505 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10506 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10507 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10508 Folder_.Set(space_, 0x8e/255.f, 0x8e/255.f, 0x93/255.f, 1.0);
10509 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10510 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10511 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10512 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10513 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10514 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10516 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10517 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10519 /* UIKit Configuration {{{ */
10520 // XXX: I have a feeling this was important
10521 //UIKeyboardDisableAutomaticAppearance();
10524 $SBSSetInterceptsMenuButtonForever = reinterpret_cast<void (*)(bool)>(dlsym(RTLD_DEFAULT, "SBSSetInterceptsMenuButtonForever"));
10526 const char *symbol(kCFCoreFoundationVersionNumber >= 800 ? "MGGetBoolAnswer" : "GSSystemHasCapability");
10527 BOOL (*GSSystemHasCapability)(CFStringRef) = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, symbol));
10528 bool fast = GSSystemHasCapability != NULL && GSSystemHasCapability(CFSTR("armv7"));
10530 PulseInterval_ = fast ? 50000 : 500000;
10532 Colon_ = UCLocalize("COLON_DELIMITED");
10533 Elision_ = UCLocalize("ELISION");
10534 Error_ = UCLocalize("ERROR");
10535 Warning_ = UCLocalize("WARNING");
10538 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10540 CGColorSpaceRelease(space_);
10541 CFRelease(Locale_);