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> Token_;
750 static _H<NSString> UniqueID_;
751 static _H<NSString> UserAgent_;
752 static _H<NSString> Product_;
753 static _H<NSString> Safari_;
755 static _H<NSLocale> CollationLocale_;
756 static _H<NSArray> CollationThumbs_;
757 static std::vector<NSInteger> CollationOffset_;
758 static _H<NSArray> CollationTitles_;
759 static _H<NSArray> CollationStarts_;
760 static UTransliterator *CollationTransl_;
761 //static Function<NSString *, NSString *> CollationModify_;
763 typedef std::basic_string<UChar> ustring;
764 static ustring CollationString_;
766 #define CUC const ustring &str(*reinterpret_cast<const ustring *>(rep))
767 #define UC ustring &str(*reinterpret_cast<ustring *>(rep))
768 static struct UReplaceableCallbacks CollationUCalls_ = {
769 .length = [](const UReplaceable *rep) -> int32_t { CUC;
773 .charAt = [](const UReplaceable *rep, int32_t offset) -> UChar { CUC;
774 //fprintf(stderr, "charAt(%d) : %d\n", offset, str.size());
775 if (offset >= str.size())
780 .char32At = [](const UReplaceable *rep, int32_t offset) -> UChar32 { CUC;
781 //fprintf(stderr, "char32At(%d) : %d\n", offset, str.size());
782 if (offset >= str.size())
785 U16_GET(str.data(), 0, offset, str.size(), c);
789 .replace = [](UReplaceable *rep, int32_t start, int32_t limit, const UChar *text, int32_t length) -> void { UC;
790 //fprintf(stderr, "replace(%d, %d, %d) : %d\n", start, limit, length, str.size());
791 str.replace(start, limit - start, text, length);
794 .extract = [](UReplaceable *rep, int32_t start, int32_t limit, UChar *dst) -> void { UC;
795 //fprintf(stderr, "extract(%d, %d) : %d\n", start, limit, str.size());
796 str.copy(dst, limit - start, start);
799 .copy = [](UReplaceable *rep, int32_t start, int32_t limit, int32_t dest) -> void { UC;
800 //fprintf(stderr, "copy(%d, %d, %d) : %d\n", start, limit, dest, str.size());
801 str.replace(dest, 0, str, start, limit - start);
805 static CFLocaleRef Locale_;
806 static NSArray *Languages_;
807 static CGColorSpaceRef space_;
809 static NSDictionary *SectionMap_;
810 static NSMutableDictionary *Metadata_;
811 static _transient NSMutableDictionary *Settings_;
812 static _transient NSMutableDictionary *Packages_;
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> TokenHosts_;
830 static _H<NSMutableSet> InsecureHosts_;
831 static _H<NSMutableSet> PipelinedHosts_;
832 static _H<NSMutableSet> CachedURLs_;
834 static NSString *kCydiaProgressEventTypeError = @"Error";
835 static NSString *kCydiaProgressEventTypeInformation = @"Information";
836 static NSString *kCydiaProgressEventTypeStatus = @"Status";
837 static NSString *kCydiaProgressEventTypeWarning = @"Warning";
840 /* Display Helpers {{{ */
841 inline float Interpolate(float begin, float end, float fraction) {
842 return (end - begin) * fraction + begin;
845 static inline double Retina(double value) {
846 value *= ScreenScale_;
847 value = round(value);
848 value /= ScreenScale_;
852 static inline CGRect Retina(CGRect value) {
853 value.origin.x *= ScreenScale_;
854 value.origin.y *= ScreenScale_;
855 value.size.width *= ScreenScale_;
856 value.size.height *= ScreenScale_;
857 value = CGRectIntegral(value);
858 value.origin.x /= ScreenScale_;
859 value.origin.y /= ScreenScale_;
860 value.size.width /= ScreenScale_;
861 value.size.height /= ScreenScale_;
865 static _finline const char *StripVersion_(const char *version) {
866 const char *colon(strchr(version, ':'));
867 return colon == NULL ? version : colon + 1;
870 NSString *LocalizeSection(NSString *section) {
871 static RegEx title_r("(.*?) \\((.*)\\)");
872 if (title_r(section)) {
873 NSString *parent(title_r[1]);
874 NSString *child(title_r[2]);
876 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
877 LocalizeSection(parent),
878 LocalizeSection(child)
882 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
885 NSString *Simplify(NSString *title) {
886 const char *data = [title UTF8String];
887 size_t size = [title lengthOfBytesUsingEncoding:NSUTF8StringEncoding];
889 static RegEx square_r("\\[(.*)\\]");
890 if (square_r(data, size))
891 return Simplify(square_r[1]);
893 static RegEx paren_r("\\((.*)\\)");
894 if (paren_r(data, size))
895 return Simplify(paren_r[1]);
897 static RegEx title_r("(.*?) \\((.*)\\)");
898 if (title_r(data, size))
899 return Simplify(title_r[1]);
905 NSString *GetLastUpdate() {
906 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
909 return UCLocalize("NEVER_OR_UNKNOWN");
911 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
912 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
914 CFRelease(formatter);
916 return [(NSString *) formatted autorelease];
919 bool isSectionVisible(NSString *section) {
920 NSDictionary *metadata([Sections_ objectForKey:(section ?: @"")]);
921 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
922 return hidden == nil || ![hidden boolValue];
925 static NSObject *CYIOGetValue(const char *path, NSString *property) {
926 io_registry_entry_t entry(IORegistryEntryFromPath(kIOMasterPortDefault, path));
927 if (entry == MACH_PORT_NULL)
930 CFTypeRef value(IORegistryEntryCreateCFProperty(entry, (CFStringRef) property, kCFAllocatorDefault, 0));
931 IOObjectRelease(entry);
935 return [(id) value autorelease];
938 static NSString *CYHex(NSData *data, bool reverse = false) {
942 size_t length([data length]);
943 uint8_t bytes[length];
944 [data getBytes:bytes];
946 char string[length * 2 + 1];
947 for (size_t i(0); i != length; ++i)
948 sprintf(string + i * 2, "%.2x", bytes[reverse ? length - i - 1 : i]);
950 return [NSString stringWithUTF8String:string];
955 /* Delegate Prototypes {{{ */
958 @class CydiaProgressEvent;
960 @protocol DatabaseDelegate
961 - (void) repairWithSelector:(SEL)selector;
962 - (void) setConfigurationData:(NSString *)data;
963 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task;
966 @class CYPackageController;
968 @protocol SourceDelegate
969 - (void) setFetch:(NSNumber *)fetch;
972 @protocol FetchDelegate
973 - (bool) isSourceCancelled;
974 - (void) startSourceFetch:(NSString *)uri;
975 - (void) stopSourceFetch:(NSString *)uri;
978 @protocol CydiaDelegate
979 - (void) returnToCydia;
981 - (void) retainNetworkActivityIndicator;
982 - (void) releaseNetworkActivityIndicator;
983 - (void) clearPackage:(Package *)package;
984 - (void) installPackage:(Package *)package;
985 - (void) installPackages:(NSArray *)packages;
986 - (void) removePackage:(Package *)package;
987 - (void) beginUpdate;
989 - (bool) requestUpdate;
990 - (void) distUpgrade;
993 - (void) _saveConfig;
995 - (void) addSource:(NSDictionary *)source;
996 - (void) addTrivialSource:(NSString *)href;
997 - (UIProgressHUD *) addProgressHUD;
998 - (void) removeProgressHUD:(UIProgressHUD *)hud;
999 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
1000 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1004 /* CancelStatus {{{ */
1005 class CancelStatus :
1006 public pkgAcquireStatus
1017 virtual bool MediaChange(std::string media, std::string drive) {
1021 virtual void IMSHit(pkgAcquire::ItemDesc &desc) {
1025 virtual bool Pulse_(pkgAcquire *Owner) = 0;
1027 virtual bool Pulse(pkgAcquire *Owner) {
1028 if (pkgAcquireStatus::Pulse(Owner) && Pulse_(Owner))
1036 _finline bool WasCancelled() const {
1041 /* DelegateStatus {{{ */
1046 _transient NSObject<ProgressDelegate> *delegate_;
1054 void setDelegate(NSObject<ProgressDelegate> *delegate) {
1055 delegate_ = delegate;
1058 virtual void Fetch(pkgAcquire::ItemDesc &desc) {
1059 NSString *name([NSString stringWithUTF8String:desc.ShortDesc.c_str()]);
1060 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), name] ofType:kCydiaProgressEventTypeStatus forItemDesc:desc]);
1061 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1064 virtual void Done(pkgAcquire::ItemDesc &desc) {
1065 NSString *name([NSString stringWithUTF8String:desc.ShortDesc.c_str()]);
1066 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithFormat:Colon_, UCLocalize("DONE"), name] ofType:kCydiaProgressEventTypeStatus forItemDesc:desc]);
1067 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1070 virtual void Fail(pkgAcquire::ItemDesc &desc) {
1072 desc.Owner->Status == pkgAcquire::Item::StatIdle ||
1073 desc.Owner->Status == pkgAcquire::Item::StatDone
1077 std::string &error(desc.Owner->ErrorText);
1081 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError forItemDesc:desc]);
1082 [delegate_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
1085 virtual bool Pulse_(pkgAcquire *Owner) {
1087 double(CurrentBytes + CurrentItems) /
1088 double(TotalBytes + TotalItems)
1091 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:[NSDictionary dictionaryWithObjectsAndKeys:
1092 [NSNumber numberWithDouble:percent], @"Percent",
1094 [NSNumber numberWithDouble:CurrentBytes], @"Current",
1095 [NSNumber numberWithDouble:TotalBytes], @"Total",
1096 [NSNumber numberWithDouble:CurrentCPS], @"Speed",
1097 nil] waitUntilDone:YES];
1099 return ![delegate_ isProgressCancelled];
1102 virtual void Start() {
1103 pkgAcquireStatus::Start();
1104 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:YES] waitUntilDone:YES];
1107 virtual void Stop() {
1108 pkgAcquireStatus::Stop();
1109 [delegate_ performSelectorOnMainThread:@selector(setProgressCancellable:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:YES];
1110 [delegate_ performSelectorOnMainThread:@selector(setProgressStatus:) withObject:nil waitUntilDone:YES];
1114 /* Database Interface {{{ */
1115 typedef std::map< unsigned long, _H<Source> > SourceMap;
1117 @interface Database : NSObject {
1123 pkgCacheFile cache_;
1124 pkgDepCache::Policy *policy_;
1125 pkgRecords *records_;
1126 pkgProblemResolver *resolver_;
1127 pkgAcquire *fetcher_;
1129 SPtr<pkgPackageManager> manager_;
1130 pkgSourceList *list_;
1132 SourceMap sourceMap_;
1133 _H<NSMutableArray> sourceList_;
1135 CFMutableArrayRef packages_;
1137 _transient NSObject<DatabaseDelegate> *delegate_;
1138 _transient NSObject<ProgressDelegate> *progress_;
1140 CydiaStatus status_;
1146 std::map<const char *, _H<NSString> > sections_;
1149 + (Database *) sharedInstance;
1152 - (void) _readCydia:(NSNumber *)fd;
1153 - (void) _readStatus:(NSNumber *)fd;
1154 - (void) _readOutput:(NSNumber *)fd;
1158 - (Package *) packageWithName:(NSString *)name;
1160 - (pkgCacheFile &) cache;
1161 - (pkgDepCache::Policy *) policy;
1162 - (pkgRecords *) records;
1163 - (pkgProblemResolver *) resolver;
1164 - (pkgAcquire &) fetcher;
1165 - (pkgSourceList &) list;
1166 - (NSArray *) packages;
1167 - (NSArray *) sources;
1168 - (Source *) sourceWithKey:(NSString *)key;
1169 - (void) reloadDataWithInvocation:(NSInvocation *)invocation;
1177 - (void) updateWithStatus:(CancelStatus &)status;
1179 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate;
1181 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate;
1182 - (NSObject<ProgressDelegate> *) progressDelegate;
1184 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1185 - (void) setFetch:(bool)fetch forURI:(const char *)uri;
1186 - (void) resetFetch;
1188 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1192 /* SourceStatus {{{ */
1193 class SourceStatus :
1197 _transient NSObject<FetchDelegate> *delegate_;
1198 _transient Database *database_;
1199 std::set<std::string> fetches_;
1202 SourceStatus(NSObject<FetchDelegate> *delegate, Database *database) :
1203 delegate_(delegate),
1208 void Set(bool fetch, const std::string &uri) {
1210 if (!fetches_.insert(uri).second)
1213 if (fetches_.erase(uri) == 0)
1217 //printf("Set(%s, %s)\n", fetch ? "true" : "false", uri.c_str());
1218 [database_ setFetch:fetch forURI:uri.c_str()];
1221 _finline void Set(bool fetch, pkgAcquire::Item *item) {
1222 /*unsigned long ID(fetch ? 1 : 0);
1226 Set(fetch, item->DescURI());
1229 void Log(const char *tag, pkgAcquire::Item *item) {
1230 //printf("%s(%s) S:%u Q:%u\n", tag, item->DescURI().c_str(), item->Status, item->QueueCounter);
1233 virtual void Fetch(pkgAcquire::ItemDesc &desc) {
1234 Log("Fetch", desc.Owner);
1235 Set(true, desc.Owner);
1238 virtual void Done(pkgAcquire::ItemDesc &desc) {
1239 Log("Done", desc.Owner);
1240 Set(false, desc.Owner);
1243 virtual void Fail(pkgAcquire::ItemDesc &desc) {
1244 Log("Fail", desc.Owner);
1245 Set(false, desc.Owner);
1248 virtual bool Pulse_(pkgAcquire *Owner) {
1249 std::set<std::string> fetches;
1250 for (pkgAcquire::ItemCIterator item(Owner->ItemsBegin()); item != Owner->ItemsEnd(); ++item) {
1252 if ((*item)->QueueCounter == 0)
1254 else switch ((*item)->Status) {
1255 case pkgAcquire::Item::StatFetching:
1256 fetches.insert((*item)->DescURI());
1265 Log(fetch ? "Pulse<true>" : "Pulse<false>", *item);
1269 std::vector<std::string> stops;
1270 std::set_difference(fetches_.begin(), fetches_.end(), fetches.begin(), fetches.end(), std::back_insert_iterator<std::vector<std::string>>(stops));
1271 for (std::vector<std::string>::const_iterator stop(stops.begin()); stop != stops.end(); ++stop) {
1272 //printf("Stop(%s)\n", stop->c_str());
1276 return ![delegate_ isSourceCancelled];
1279 virtual void Stop() {
1280 pkgAcquireStatus::Stop();
1281 [database_ resetFetch];
1285 /* ProgressEvent Implementation {{{ */
1286 @implementation CydiaProgressEvent
1288 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type {
1289 return [[[CydiaProgressEvent alloc] initWithMessage:message ofType:type] autorelease];
1292 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forPackage:(NSString *)package {
1293 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1294 [event setPackage:package];
1298 + (CydiaProgressEvent *) eventWithMessage:(NSString *)message ofType:(NSString *)type forItemDesc:(pkgAcquire::ItemDesc &)desc {
1299 CydiaProgressEvent *event([self eventWithMessage:message ofType:type]);
1301 NSString *description([NSString stringWithUTF8String:desc.Description.c_str()]);
1302 NSArray *fields([description componentsSeparatedByString:@" "]);
1303 [event setItem:fields];
1305 if ([fields count] > 3) {
1306 [event setPackage:[fields objectAtIndex:2]];
1307 [event setVersion:[fields objectAtIndex:3]];
1310 [event setURL:[NSString stringWithUTF8String:desc.URI.c_str()]];
1315 + (NSArray *) _attributeKeys {
1316 return [NSArray arrayWithObjects:
1326 - (NSArray *) attributeKeys {
1327 return [[self class] _attributeKeys];
1330 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1331 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1334 - (id) initWithMessage:(NSString *)message ofType:(NSString *)type {
1335 if ((self = [super init]) != nil) {
1341 - (NSString *) message {
1345 - (NSString *) type {
1349 - (NSArray *) item {
1350 return (id) item_ ?: [NSNull null];
1353 - (void) setItem:(NSArray *)item {
1357 - (NSString *) package {
1358 return (id) package_ ?: [NSNull null];
1361 - (void) setPackage:(NSString *)package {
1365 - (NSString *) url {
1366 return (id) url_ ?: [NSNull null];
1369 - (void) setURL:(NSString *)url {
1373 - (void) setVersion:(NSString *)version {
1377 - (NSString *) version {
1378 return (id) version_ ?: [NSNull null];
1381 - (NSString *) compound:(NSString *)value {
1383 NSString *mode(nil); {
1384 NSString *type([self type]);
1385 if ([type isEqualToString:kCydiaProgressEventTypeError])
1386 mode = UCLocalize("ERROR");
1387 else if ([type isEqualToString:kCydiaProgressEventTypeWarning])
1388 mode = UCLocalize("WARNING");
1392 value = [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), mode, value];
1398 - (NSString *) compoundMessage {
1399 return [self compound:[self message]];
1402 - (NSString *) compoundTitle {
1405 if (package_ == nil)
1407 else if (Package *package = [[Database sharedInstance] packageWithName:package_])
1408 title = [package name];
1412 return [self compound:title];
1418 // Cytore Definitions {{{
1419 struct PackageValue :
1422 Cytore::Offset<PackageValue> next_;
1424 uint32_t index_ : 23;
1425 uint32_t subscribed_ : 1;
1442 Cytore::Offset<PackageValue> packages_[1 << 16];
1445 static Cytore::File<MetaValue> MetaFile_;
1447 // Cytore Helper Functions {{{
1448 static PackageValue *PackageFind(const char *name, size_t length, bool *fail = NULL) {
1449 SplitHash nhash = { hashlittle(name, length) };
1451 PackageValue *metadata;
1453 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1454 for (;; offset = &metadata->next_) { if (offset->IsNull()) {
1455 *offset = MetaFile_.New<PackageValue>(length + 1);
1456 metadata = &MetaFile_.Get(*offset);
1458 if (metadata == NULL) {
1462 metadata = new PackageValue();
1463 memset(metadata, 0, sizeof(*metadata));
1466 memcpy(metadata->name_, name, length);
1467 metadata->name_[length] = '\0';
1468 metadata->nhash_ = nhash.u16[1];
1470 metadata = &MetaFile_.Get(*offset);
1471 if (metadata->nhash_ != nhash.u16[1])
1473 if (strncmp(metadata->name_, name, length) != 0)
1475 if (metadata->name_[length] != '\0')
1482 static void PackageImport(const void *key, const void *value, void *context) {
1483 bool &fail(*reinterpret_cast<bool *>(context));
1486 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1487 NSLog(@"failed to import package %@", key);
1491 PackageValue *metadata(PackageFind(buffer, strlen(buffer), &fail));
1492 NSDictionary *package((NSDictionary *) value);
1494 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1495 if ([subscribed boolValue] && !metadata->subscribed_)
1496 metadata->subscribed_ = true;
1498 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1499 time_t time([date timeIntervalSince1970]);
1500 if (metadata->first_ > time || metadata->first_ == 0)
1501 metadata->first_ = time;
1504 NSDate *date([package objectForKey:@"LastSeen"]);
1505 NSString *version([package objectForKey:@"LastVersion"]);
1507 if (date != nil && version != nil) {
1508 time_t time([date timeIntervalSince1970]);
1509 if (metadata->last_ < time || metadata->last_ == 0)
1510 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1511 size_t length(strlen(buffer));
1512 uint16_t vhash(hashlittle(buffer, length));
1514 size_t capped(std::min<size_t>(8, length));
1515 char *latest(buffer + length - capped);
1517 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1518 metadata->vhash_ = vhash;
1520 metadata->last_ = time;
1526 /* Source Class {{{ */
1527 @interface Source : NSObject {
1529 Database *database_;
1532 CYString depiction_;
1533 CYString description_;
1539 CYString distribution_;
1545 _H<NSString> authority_;
1547 CYString defaultIcon_;
1549 _H<NSMutableDictionary> record_;
1552 std::set<std::string> fetches_;
1553 std::set<std::string> files_;
1554 _transient NSObject<SourceDelegate> *delegate_;
1557 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(CYPool *)pool;
1559 - (NSComparisonResult) compareByName:(Source *)source;
1561 - (NSString *) depictionForPackage:(NSString *)package;
1562 - (NSString *) supportForPackage:(NSString *)package;
1564 - (metaIndex *) metaIndex;
1565 - (NSDictionary *) record;
1568 - (NSString *) rooturi;
1569 - (NSString *) distribution;
1570 - (NSString *) type;
1573 - (NSString *) host;
1575 - (NSString *) name;
1576 - (NSString *) shortDescription;
1577 - (NSString *) label;
1578 - (NSString *) origin;
1579 - (NSString *) version;
1581 - (NSString *) defaultIcon;
1582 - (NSURL *) iconURL;
1584 - (void) setFetch:(bool)fetch forURI:(const char *)uri;
1585 - (void) resetFetch;
1589 @implementation Source
1591 + (NSString *) webScriptNameForSelector:(SEL)selector {
1593 else if (selector == @selector(addSection:))
1594 return @"addSection";
1595 else if (selector == @selector(getField:))
1597 else if (selector == @selector(removeSection:))
1598 return @"removeSection";
1599 else if (selector == @selector(remove))
1605 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
1606 return [self webScriptNameForSelector:selector] == nil;
1609 + (NSArray *) _attributeKeys {
1610 return [NSArray arrayWithObjects:
1621 @"shortDescription",
1628 - (NSArray *) attributeKeys {
1629 return [[self class] _attributeKeys];
1632 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1633 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1636 - (metaIndex *) metaIndex {
1640 - (void) setMetaIndex:(metaIndex *)index inPool:(CYPool *)pool {
1641 trusted_ = index->IsTrusted();
1643 uri_.set(pool, index->GetURI());
1644 distribution_.set(pool, index->GetDist());
1645 type_.set(pool, index->GetType());
1647 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1648 if (dindex != NULL) {
1649 std::string file(dindex->MetaIndexURI(""));
1650 base_.set(pool, file);
1653 _profile(Source$setMetaIndex$GetIndexes)
1654 dindex->GetIndexes(&acquire, true);
1656 _profile(Source$setMetaIndex$DescURI)
1657 for (pkgAcquire::ItemIterator item(acquire.ItemsBegin()); item != acquire.ItemsEnd(); item++) {
1658 std::string file((*item)->DescURI());
1659 files_.insert(file);
1660 if (file.length() < sizeof("Packages.bz2") || file.substr(file.length() - sizeof("Packages.bz2")) != "/Packages.bz2")
1662 file = file.substr(0, file.length() - 4);
1663 files_.insert(file);
1664 files_.insert(file + ".gz");
1665 files_.insert(file + "Index");
1670 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1673 pkgTagFile tags(&fd);
1675 pkgTagSection section;
1682 {"default-icon", &defaultIcon_},
1683 {"depiction", &depiction_},
1684 {"description", &description_},
1686 {"origin", &origin_},
1687 {"support", &support_},
1688 {"version", &version_},
1691 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1692 const char *start, *end;
1694 if (section.Find(names[i].name_, start, end)) {
1695 CYString &value(*names[i].value_);
1696 value.set(pool, start, end - start);
1702 record_ = [Sources_ objectForKey:[self key]];
1704 NSURL *url([NSURL URLWithString:uri_]);
1708 host_ = [host_ lowercaseString];
1713 authority_ = [url path];
1716 - (Source *) initWithMetaIndex:(metaIndex *)index forDatabase:(Database *)database inPool:(CYPool *)pool {
1717 if ((self = [super init]) != nil) {
1718 era_ = [database era];
1719 database_ = database;
1722 _profile(Source$initWithMetaIndex$setMetaIndex)
1723 [self setMetaIndex:index inPool:pool];
1728 - (NSString *) getField:(NSString *)name {
1729 @synchronized (database_) {
1730 if ([database_ era] != era_ || index_ == NULL)
1733 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index_));
1738 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly)) {
1743 pkgTagFile tags(&fd);
1745 pkgTagSection section;
1748 const char *start, *end;
1749 if (!section.Find([name UTF8String], start, end))
1750 return (NSString *) [NSNull null];
1752 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
1755 - (NSComparisonResult) compareByName:(Source *)source {
1756 NSString *lhs = [self name];
1757 NSString *rhs = [source name];
1759 if ([lhs length] != 0 && [rhs length] != 0) {
1760 unichar lhc = [lhs characterAtIndex:0];
1761 unichar rhc = [rhs characterAtIndex:0];
1763 if (isalpha(lhc) && !isalpha(rhc))
1764 return NSOrderedAscending;
1765 else if (!isalpha(lhc) && isalpha(rhc))
1766 return NSOrderedDescending;
1769 return [lhs compare:rhs options:LaxCompareOptions_];
1772 - (NSString *) depictionForPackage:(NSString *)package {
1773 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1776 - (NSString *) supportForPackage:(NSString *)package {
1777 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1780 - (NSArray *) sections {
1781 return record_ == nil ? (id) [NSNull null] : [record_ objectForKey:@"Sections"] ?: [NSArray array];
1784 - (void) _addSection:(NSString *)section {
1787 else if (NSMutableArray *sections = [record_ objectForKey:@"Sections"]) {
1788 if (![sections containsObject:section]) {
1789 [sections addObject:section];
1793 [record_ setObject:[NSMutableArray arrayWithObject:section] forKey:@"Sections"];
1798 - (bool) addSection:(NSString *)section {
1802 [self performSelectorOnMainThread:@selector(_addSection:) withObject:section waitUntilDone:NO];
1806 - (void) _removeSection:(NSString *)section {
1810 if (NSMutableArray *sections = [record_ objectForKey:@"Sections"])
1811 if ([sections containsObject:section]) {
1812 [sections removeObject:section];
1817 - (bool) removeSection:(NSString *)section {
1821 [self performSelectorOnMainThread:@selector(_removeSection:) withObject:section waitUntilDone:NO];
1826 [Sources_ removeObjectForKey:[self key]];
1831 bool value(record_ != nil);
1832 [self performSelectorOnMainThread:@selector(_remove) withObject:nil waitUntilDone:NO];
1836 - (NSDictionary *) record {
1844 - (NSString *) rooturi {
1848 - (NSString *) distribution {
1849 return distribution_;
1852 - (NSString *) type {
1856 - (NSString *) baseuri {
1857 return base_.empty() ? nil : (id) base_;
1860 - (NSString *) iconuri {
1861 if (NSString *base = [self baseuri])
1862 return [base stringByAppendingString:@"CydiaIcon.png"];
1867 - (NSURL *) iconURL {
1868 if (NSString *uri = [self iconuri])
1869 return [NSURL URLWithString:uri];
1873 - (NSString *) key {
1874 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1877 - (NSString *) host {
1881 - (NSString *) name {
1882 return origin_.empty() ? (id) authority_ : origin_;
1885 - (NSString *) shortDescription {
1886 return description_;
1889 - (NSString *) label {
1890 return label_.empty() ? (id) authority_ : label_;
1893 - (NSString *) origin {
1897 - (NSString *) version {
1901 - (NSString *) defaultIcon {
1902 return defaultIcon_;
1905 - (void) setDelegate:(NSObject<SourceDelegate> *)delegate {
1906 delegate_ = delegate;
1910 return !fetches_.empty();
1913 - (void) setFetch:(bool)fetch forURI:(const char *)uri {
1915 if (fetches_.erase(uri) == 0)
1917 } else if (files_.find(uri) == files_.end())
1919 else if (!fetches_.insert(uri).second)
1922 [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:[self fetch]] waitUntilDone:NO];
1925 - (void) resetFetch {
1927 [delegate_ performSelectorOnMainThread:@selector(setFetch:) withObject:[NSNumber numberWithBool:NO] waitUntilDone:NO];
1932 /* CydiaOperation Class {{{ */
1933 @interface CydiaOperation : NSObject {
1934 _H<NSString> operator_;
1935 _H<NSString> value_;
1938 - (NSString *) operator;
1939 - (NSString *) value;
1943 @implementation CydiaOperation
1945 - (id) initWithOperator:(const char *)_operator value:(const char *)value {
1946 if ((self = [super init]) != nil) {
1947 operator_ = [NSString stringWithUTF8String:_operator];
1948 value_ = [NSString stringWithUTF8String:value];
1952 + (NSArray *) _attributeKeys {
1953 return [NSArray arrayWithObjects:
1959 - (NSArray *) attributeKeys {
1960 return [[self class] _attributeKeys];
1963 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1964 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1967 - (NSString *) operator {
1971 - (NSString *) value {
1977 /* CydiaClause Class {{{ */
1978 @interface CydiaClause : NSObject {
1979 _H<NSString> package_;
1980 _H<CydiaOperation> version_;
1983 - (NSString *) package;
1984 - (CydiaOperation *) version;
1988 @implementation CydiaClause
1990 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
1991 if ((self = [super init]) != nil) {
1992 package_ = [NSString stringWithUTF8String:dep.TargetPkg().Name()];
1994 if (const char *version = dep.TargetVer())
1995 version_ = [[[CydiaOperation alloc] initWithOperator:dep.CompType() value:version] autorelease];
1997 version_ = (id) [NSNull null];
2001 + (NSArray *) _attributeKeys {
2002 return [NSArray arrayWithObjects:
2008 - (NSArray *) attributeKeys {
2009 return [[self class] _attributeKeys];
2012 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2013 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2016 - (NSString *) package {
2020 - (CydiaOperation *) version {
2026 /* CydiaRelation Class {{{ */
2027 @interface CydiaRelation : NSObject {
2028 _H<NSString> relationship_;
2029 _H<NSMutableArray> clauses_;
2032 - (NSString *) relationship;
2033 - (NSArray *) clauses;
2037 @implementation CydiaRelation
2039 - (id) initWithIterator:(pkgCache::DepIterator &)dep {
2040 if ((self = [super init]) != nil) {
2041 relationship_ = [NSString stringWithUTF8String:dep.DepType()];
2042 clauses_ = [NSMutableArray arrayWithCapacity:8];
2044 pkgCache::DepIterator start;
2045 pkgCache::DepIterator end;
2046 dep.GlobOr(start, end); // ++dep
2049 [clauses_ addObject:[[[CydiaClause alloc] initWithIterator:start] autorelease]];
2051 // yes, seriously. (wtf?)
2059 + (NSArray *) _attributeKeys {
2060 return [NSArray arrayWithObjects:
2066 - (NSArray *) attributeKeys {
2067 return [[self class] _attributeKeys];
2070 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2071 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2074 - (NSString *) relationship {
2075 return relationship_;
2078 - (NSArray *) clauses {
2082 - (void) addClause:(CydiaClause *)clause {
2083 [clauses_ addObject:clause];
2088 /* Package Class {{{ */
2089 struct ParsedPackage {
2093 CYString architecture_;
2096 CYString depiction_;
2103 @interface Package : NSObject {
2105 @public uint32_t role_ : 3;
2106 uint32_t essential_ : 1;
2107 uint32_t obsolete_ : 1;
2108 uint32_t ignored_ : 1;
2109 uint32_t pooled_ : 1;
2115 _transient Database *database_;
2117 pkgCache::VerIterator version_;
2118 pkgCache::PkgIterator iterator_;
2119 pkgCache::VerFileIterator file_;
2123 CYString transform_;
2126 CYString installed_;
2129 const char *section_;
2130 _transient NSString *section$_;
2134 PackageValue *metadata_;
2135 ParsedPackage *parsed_;
2137 _H<NSMutableArray> tags_;
2140 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database;
2141 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database;
2143 - (pkgCache::PkgIterator) iterator;
2146 - (NSString *) section;
2147 - (NSString *) simpleSection;
2149 - (NSString *) longSection;
2150 - (NSString *) shortSection;
2154 - (MIMEAddress *) maintainer;
2156 - (NSString *) longDescription;
2157 - (NSString *) shortDescription;
2160 - (PackageValue *) metadata;
2163 - (bool) subscribed;
2164 - (bool) setSubscribed:(bool)subscribed;
2168 - (NSString *) latest;
2169 - (NSString *) installed;
2170 - (BOOL) uninstalled;
2173 - (BOOL) upgradableAndEssential:(BOOL)essential;
2176 - (BOOL) unfiltered;
2180 - (BOOL) halfConfigured;
2181 - (BOOL) halfInstalled;
2183 - (NSString *) mode;
2186 - (NSString *) name;
2188 - (NSString *) homepage;
2189 - (NSString *) depiction;
2190 - (MIMEAddress *) author;
2192 - (NSString *) support;
2194 - (NSArray *) files;
2195 - (NSArray *) warnings;
2196 - (NSArray *) applications;
2198 - (Source *) source;
2201 - (BOOL) matches:(NSArray *)query;
2203 - (BOOL) hasTag:(NSString *)tag;
2204 - (NSString *) primaryPurpose;
2205 - (NSArray *) purposes;
2206 - (bool) isCommercial;
2208 - (void) setIndex:(size_t)index;
2210 - (CYString &) cyname;
2212 - (uint32_t) compareBySection:(NSArray *)sections;
2219 uint32_t PackageChangesRadix(Package *self, void *) {
2224 uint32_t timestamp : 30;
2225 uint32_t ignored : 1;
2226 uint32_t upgradable : 1;
2230 bool upgradable([self upgradableAndEssential:YES]);
2231 value.bits.upgradable = upgradable ? 1 : 0;
2234 value.bits.timestamp = 0;
2235 value.bits.ignored = [self ignored] ? 0 : 1;
2236 value.bits.upgradable = 1;
2238 value.bits.timestamp = [self seen] >> 2;
2239 value.bits.ignored = 0;
2240 value.bits.upgradable = 0;
2243 return _not(uint32_t) - value.key;
2246 CYString &(*PackageName)(Package *self, SEL sel);
2248 uint32_t PackagePrefixRadix(Package *self, void *context) {
2249 size_t offset(reinterpret_cast<size_t>(context));
2250 CYString &name(PackageName(self, @selector(cyname)));
2252 size_t size(name.size());
2255 char *text(name.data());
2258 if (!isdigit(text[0]))
2262 while (size != digits && isdigit(text[digits]))
2270 if (offset == 0 && zeros != 0) {
2271 memset(data, '0', zeros);
2272 memcpy(data + zeros, text, 4 - zeros);
2274 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2275 if (size <= offset - zeros)
2278 text += offset - zeros;
2279 size -= offset - zeros;
2282 memcpy(data, text, 4);
2284 memcpy(data, text, size);
2285 memset(data + size, 0, 4 - size);
2288 for (size_t i(0); i != 4; ++i)
2289 if (isalpha(data[i]))
2297 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2299 /* XXX: ntohl may be more honest */
2300 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2303 CFComparisonResult StringNameCompare(CFStringRef lhn, CFStringRef rhn, size_t length) {
2304 _profile(PackageNameCompare)
2306 return rhn == NULL ? kCFCompareEqualTo : kCFCompareLessThan;
2307 else if (rhn == NULL)
2308 return kCFCompareGreaterThan;
2310 CFIndex length(CFStringGetLength(lhn));
2312 _profile(PackageNameCompare$NumbersLast)
2313 if (length != 0 && CFStringGetLength(rhn) != 0) {
2314 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2315 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2316 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2317 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2318 return lha ? kCFCompareLessThan : kCFCompareGreaterThan;
2322 _profile(PackageNameCompare$Compare)
2323 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, (CFLocaleRef) (id) CollationLocale_);
2328 _finline CFComparisonResult StringNameCompare(NSString *lhn, NSString*rhn, size_t length) {
2329 return StringNameCompare((CFStringRef) lhn, (CFStringRef) rhn, length);
2332 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2333 CYString &lhn(PackageName(lhs, @selector(cyname)));
2334 NSString *rhn(PackageName(rhs, @selector(cyname)));
2335 return StringNameCompare(lhn, rhn, lhn.size());
2338 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *arg) {
2339 return PackageNameCompare(*lhs, *rhs, arg);
2342 struct PackageNameOrdering :
2343 std::binary_function<Package *, Package *, bool>
2345 _finline bool operator ()(Package *lhs, Package *rhs) const {
2346 return PackageNameCompare(lhs, rhs, NULL) == kCFCompareLessThan;
2350 @implementation Package
2352 - (NSString *) description {
2353 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2359 if (parsed_ != NULL)
2364 + (NSString *) webScriptNameForSelector:(SEL)selector {
2366 else if (selector == @selector(clear))
2368 else if (selector == @selector(getField:))
2370 else if (selector == @selector(getRecord))
2371 return @"getRecord";
2372 else if (selector == @selector(hasTag:))
2374 else if (selector == @selector(install))
2376 else if (selector == @selector(remove))
2382 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2383 return [self webScriptNameForSelector:selector] == nil;
2386 + (NSArray *) _attributeKeys {
2387 return [NSArray arrayWithObjects:
2408 @"shortDescription",
2421 - (NSArray *) attributeKeys {
2422 return [[self class] _attributeKeys];
2425 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2426 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2429 - (NSArray *) relations {
2430 @synchronized (database_) {
2431 NSMutableArray *relations([NSMutableArray arrayWithCapacity:16]);
2432 for (pkgCache::DepIterator dep(version_.DependsList()); !dep.end(); ++dep)
2433 [relations addObject:[[[CydiaRelation alloc] initWithIterator:dep] autorelease]];
2437 - (NSString *) architecture {
2439 @synchronized (database_) {
2440 return parsed_->architecture_.empty() ? [NSNull null] : (id) parsed_->architecture_;
2443 - (NSString *) getField:(NSString *)name {
2444 @synchronized (database_) {
2445 if ([database_ era] != era_ || file_.end())
2448 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2450 const char *start, *end;
2451 if (!parser.Find([name UTF8String], start, end))
2452 return (NSString *) [NSNull null];
2454 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2457 - (NSString *) getRecord {
2458 @synchronized (database_) {
2459 if ([database_ era] != era_ || file_.end())
2462 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2464 const char *start, *end;
2465 parser.GetRec(start, end);
2467 return [NSString stringWithString:[(NSString *) CYStringCreate(start, end - start) autorelease]];
2471 if (parsed_ != NULL)
2473 @synchronized (database_) {
2474 if ([database_ era] != era_ || file_.end())
2477 ParsedPackage *parsed(new ParsedPackage);
2480 _profile(Package$parse)
2481 pkgRecords::Parser *parser;
2483 _profile(Package$parse$Lookup)
2484 parser = &[database_ records]->Lookup(file_);
2490 _profile(Package$parse$Find)
2495 {"architecture", &parsed->architecture_},
2496 {"icon", &parsed->icon_},
2497 {"depiction", &parsed->depiction_},
2498 {"homepage", &parsed->homepage_},
2499 {"website", &website},
2501 {"support", &parsed->support_},
2502 {"author", &parsed->author_},
2503 {"md5sum", &parsed->md5sum_},
2506 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2507 const char *start, *end;
2509 if (parser->Find(names[i].name_, start, end)) {
2510 CYString &value(*names[i].value_);
2511 _profile(Package$parse$Value)
2512 value.set(pool_, start, end - start);
2518 _profile(Package$parse$Tagline)
2519 const char *start, *end;
2520 if (parser->ShortDesc(start, end)) {
2521 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2524 while (stop != start && stop[-1] == '\r')
2526 parsed->tagline_.set(pool_, start, stop - start);
2530 _profile(Package$parse$Retain)
2531 if (parsed->homepage_.empty())
2532 parsed->homepage_ = website;
2533 if (parsed->homepage_ == parsed->depiction_)
2534 parsed->homepage_.clear();
2535 if (parsed->support_.empty())
2536 parsed->support_ = bugs;
2541 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database {
2542 if ((self = [super init]) != nil) {
2543 _profile(Package$initWithVersion)
2545 pool_ = new CYPool();
2551 database_ = database;
2552 era_ = [database era];
2556 pkgCache::PkgIterator iterator(version.ParentPkg());
2557 iterator_ = iterator;
2559 _profile(Package$initWithVersion$Version)
2560 if (!version_.end())
2561 file_ = version_.FileList();
2563 pkgCache &cache([database_ cache]);
2564 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2568 _profile(Package$initWithVersion$Cache)
2569 name_.set(NULL, iterator.Display());
2571 latest_.set(NULL, StripVersion_(version_.VerStr()));
2573 pkgCache::VerIterator current(iterator.CurrentVer());
2575 installed_.set(NULL, StripVersion_(current.VerStr()));
2578 _profile(Package$initWithVersion$Transliterate) do {
2579 if (CollationTransl_ == NULL)
2584 _profile(Package$initWithVersion$Transliterate$utf8)
2585 const uint8_t *data(reinterpret_cast<const uint8_t *>(name_.data()));
2586 for (size_t i(0), e(name_.size()); i != e; ++i)
2587 if (data[i] >= 0x80)
2592 UErrorCode code(U_ZERO_ERROR);
2595 _profile(Package$initWithVersion$Transliterate$u_strFromUTF8WithSub)
2596 CollationString_.resize(name_.size());
2597 u_strFromUTF8WithSub(&CollationString_[0], CollationString_.size(), &length, name_.data(), name_.size(), 0xfffd, NULL, &code);
2598 if (!U_SUCCESS(code))
2600 CollationString_.resize(length);
2603 _profile(Package$initWithVersion$Transliterate$utrans_trans)
2604 length = CollationString_.size();
2605 utrans_trans(CollationTransl_, reinterpret_cast<UReplaceable *>(&CollationString_), &CollationUCalls_, 0, &length, &code);
2606 if (!U_SUCCESS(code))
2608 _assert(CollationString_.size() == length);
2611 _profile(Package$initWithVersion$Transliterate$u_strToUTF8WithSub$preflight)
2612 u_strToUTF8WithSub(NULL, 0, &length, CollationString_.data(), CollationString_.size(), 0xfffd, NULL, &code);
2613 if (code == U_BUFFER_OVERFLOW_ERROR)
2614 code = U_ZERO_ERROR;
2615 else if (!U_SUCCESS(code))
2620 _profile(Package$initWithVersion$Transliterate$apr_palloc)
2621 transform = pool_->malloc<char>(length);
2623 _profile(Package$initWithVersion$Transliterate$u_strToUTF8WithSub$transform)
2624 u_strToUTF8WithSub(transform, length, NULL, CollationString_.data(), CollationString_.size(), 0xfffd, NULL, &code);
2625 if (!U_SUCCESS(code))
2629 transform_.set(NULL, transform, length);
2630 } while (false); _end
2632 _profile(Package$initWithVersion$Tags)
2633 pkgCache::TagIterator tag(iterator.TagList());
2635 tags_ = [NSMutableArray arrayWithCapacity:8];
2637 goto tag; for (; !tag.end(); ++tag) tag: {
2638 const char *name(tag.Name());
2639 NSString *string((NSString *) CYStringCreate(name));
2643 [tags_ addObject:[string autorelease]];
2645 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2646 if (strcmp(name + 6, "enduser") == 0)
2648 else if (strcmp(name + 6, "hacker") == 0)
2650 else if (strcmp(name + 6, "developer") == 0)
2652 else if (strcmp(name + 6, "cydia") == 0)
2658 if (strncmp(name, "cydia::", 7) == 0) {
2659 if (strcmp(name + 7, "essential") == 0)
2661 else if (strcmp(name + 7, "obsolete") == 0)
2668 _profile(Package$initWithVersion$Metadata)
2669 const char *mixed(iterator.Name());
2670 size_t size(strlen(mixed));
2671 static const size_t prefix(sizeof("/var/lib/dpkg/info/") - 1);
2672 char lower[prefix + size + 5 + 1];
2674 for (size_t i(0); i != size; ++i)
2675 lower[prefix + i] = mixed[i] | 0x20;
2677 if (!installed_.empty()) {
2678 memcpy(lower, "/var/lib/dpkg/info/", prefix);
2679 memcpy(lower + prefix + size, ".list", 6);
2681 if (stat(lower, &info) != -1)
2682 upgraded_ = info.st_birthtime;
2685 PackageValue *metadata(PackageFind(lower + prefix, size));
2686 metadata_ = metadata;
2688 id_.set(NULL, metadata->name_, size);
2690 const char *latest(version_.VerStr());
2691 size_t length(strlen(latest));
2693 uint16_t vhash(hashlittle(latest, length));
2695 size_t capped(std::min<size_t>(8, length));
2696 latest = latest + length - capped;
2698 if (metadata->first_ == 0)
2699 metadata->first_ = now_;
2701 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2702 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2703 metadata->vhash_ = vhash;
2704 metadata->last_ = now_;
2705 } else if (metadata->last_ == 0)
2706 metadata->last_ = metadata->first_;
2709 _profile(Package$initWithVersion$Section)
2710 section_ = version_.Section();
2713 _profile(Package$initWithVersion$Flags)
2714 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2715 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2720 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(CYPool *)pool database:(Database *)database {
2721 pkgCache::VerIterator version;
2723 _profile(Package$packageWithIterator$GetCandidateVer)
2724 version = [database policy]->GetCandidateVer(iterator);
2732 _profile(Package$packageWithIterator$Allocate)
2733 package = [Package allocWithZone:zone];
2736 _profile(Package$packageWithIterator$Initialize)
2738 initWithVersion:version
2745 _profile(Package$packageWithIterator$Autorelease)
2746 package = [package autorelease];
2752 - (pkgCache::PkgIterator) iterator {
2756 - (NSString *) section {
2757 if (section$_ == nil) {
2758 if (section_ == NULL)
2761 _profile(Package$section$mappedSectionForPointer)
2762 section$_ = [database_ mappedSectionForPointer:section_];
2767 - (NSString *) simpleSection {
2768 if (NSString *section = [self section])
2769 return Simplify(section);
2774 - (NSString *) longSection {
2775 return LocalizeSection([self section]);
2778 - (NSString *) shortSection {
2779 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2782 - (NSString *) uri {
2785 pkgIndexFile *index;
2786 pkgCache::PkgFileIterator file(file_.File());
2787 if (![database_ list].FindIndex(file, index))
2789 return [NSString stringWithUTF8String:iterator_->Path];
2790 //return [NSString stringWithUTF8String:file.Site()];
2791 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2795 - (MIMEAddress *) maintainer {
2796 @synchronized (database_) {
2797 if ([database_ era] != era_ || file_.end())
2800 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2801 const std::string &maintainer(parser->Maintainer());
2802 return maintainer.empty() ? nil : [MIMEAddress addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2805 - (NSString *) md5sum {
2806 return parsed_ == NULL ? nil : (id) parsed_->md5sum_;
2810 @synchronized (database_) {
2811 if ([database_ era] != era_ || version_.end())
2814 return version_->InstalledSize;
2817 - (NSString *) longDescription {
2818 @synchronized (database_) {
2819 if ([database_ era] != era_ || file_.end())
2822 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2823 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2825 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2826 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2827 if ([lines count] < 2)
2830 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2831 for (size_t i(1), e([lines count]); i != e; ++i) {
2832 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2833 [trimmed addObject:trim];
2836 return [trimmed componentsJoinedByString:@"\n"];
2839 - (NSString *) shortDescription {
2840 if (parsed_ != NULL)
2841 return static_cast<NSString *>(parsed_->tagline_);
2843 @synchronized (database_) {
2844 pkgRecords::Parser &parser([database_ records]->Lookup(file_));
2846 const char *start, *end;
2847 if (!parser.ShortDesc(start, end))
2850 if (end - start > 200)
2854 if (const char *stop = reinterpret_cast<const char *>(memchr(start, '\n', end - start)))
2857 while (end != start && end[-1] == '\r')
2861 return [(id) CYStringCreate(start, end - start) autorelease];
2865 _profile(Package$index)
2866 CFStringRef name((CFStringRef) [self name]);
2867 if (CFStringGetLength(name) == 0)
2869 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2870 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2872 return toupper(character);
2876 - (PackageValue *) metadata {
2881 PackageValue *metadata([self metadata]);
2882 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2885 - (bool) subscribed {
2886 return [self metadata]->subscribed_;
2889 - (bool) setSubscribed:(bool)subscribed {
2890 PackageValue *metadata([self metadata]);
2891 if (metadata->subscribed_ == subscribed)
2893 metadata->subscribed_ = subscribed;
2901 - (NSString *) latest {
2905 - (NSString *) installed {
2909 - (BOOL) uninstalled {
2910 return installed_.empty();
2914 return !version_.end();
2917 - (BOOL) upgradableAndEssential:(BOOL)essential {
2918 _profile(Package$upgradableAndEssential)
2919 pkgCache::VerIterator current(iterator_.CurrentVer());
2921 return essential && essential_;
2923 return !version_.end() && version_ != current;
2927 - (BOOL) essential {
2932 return [database_ cache][iterator_].InstBroken();
2935 - (BOOL) unfiltered {
2936 _profile(Package$unfiltered$obsolete)
2937 if (_unlikely(obsolete_))
2941 _profile(Package$unfiltered$role)
2942 if (_unlikely(role_ > 3))
2950 if (![self unfiltered])
2955 _profile(Package$visible$section)
2956 section = [self section];
2959 _profile(Package$visible$isSectionVisible)
2960 if (!isSectionVisible(section))
2968 unsigned char current(iterator_->CurrentState);
2969 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2972 - (BOOL) halfConfigured {
2973 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2976 - (BOOL) halfInstalled {
2977 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2981 @synchronized (database_) {
2982 if ([database_ era] != era_ || iterator_.end())
2985 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2986 return state.Mode != pkgDepCache::ModeKeep;
2989 - (NSString *) mode {
2990 @synchronized (database_) {
2991 if ([database_ era] != era_ || iterator_.end())
2994 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2996 switch (state.Mode) {
2997 case pkgDepCache::ModeDelete:
2998 if ((state.iFlags & pkgDepCache::Purge) != 0)
3002 case pkgDepCache::ModeKeep:
3003 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
3004 return @"REINSTALL";
3005 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
3009 case pkgDepCache::ModeInstall:
3010 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
3011 return @"REINSTALL";
3012 else*/ switch (state.Status) {
3014 return @"DOWNGRADE";
3020 return @"NEW_INSTALL";
3031 - (NSString *) name {
3032 return name_.empty() ? id_ : name_;
3035 - (UIImage *) icon {
3036 NSString *section = [self simpleSection];
3039 if (parsed_ != NULL)
3040 if (NSString *href = parsed_->icon_)
3041 if ([href hasPrefix:@"file:///"])
3042 icon = [UIImage imageAtPath:[[href substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
3043 if (icon == nil) if (section != nil)
3044 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [section stringByReplacingOccurrencesOfString:@" " withString:@"_"]]];
3045 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
3046 if ([dicon hasPrefix:@"file:///"])
3047 icon = [UIImage imageAtPath:[[dicon substringFromIndex:7] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];
3049 icon = [UIImage imageNamed:@"unknown.png"];
3053 - (NSString *) homepage {
3054 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
3057 - (NSString *) depiction {
3058 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
3061 - (MIMEAddress *) author {
3062 return parsed_ == NULL || parsed_->author_.empty() ? nil : [MIMEAddress addressWithString:parsed_->author_];
3065 - (NSString *) support {
3066 return parsed_ != NULL && !parsed_->support_.empty() ? parsed_->support_ : [[self source] supportForPackage:id_];
3069 - (NSArray *) files {
3070 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
3071 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
3074 fin.open([path UTF8String]);
3079 while (std::getline(fin, line))
3080 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
3085 - (NSString *) state {
3086 @synchronized (database_) {
3087 if ([database_ era] != era_ || file_.end())
3090 switch (iterator_->CurrentState) {
3091 case pkgCache::State::NotInstalled:
3092 return @"NotInstalled";
3093 case pkgCache::State::UnPacked:
3095 case pkgCache::State::HalfConfigured:
3096 return @"HalfConfigured";
3097 case pkgCache::State::HalfInstalled:
3098 return @"HalfInstalled";
3099 case pkgCache::State::ConfigFiles:
3100 return @"ConfigFiles";
3101 case pkgCache::State::Installed:
3102 return @"Installed";
3103 case pkgCache::State::TriggersAwaited:
3104 return @"TriggersAwaited";
3105 case pkgCache::State::TriggersPending:
3106 return @"TriggersPending";
3109 return (NSString *) [NSNull null];
3112 - (NSString *) selection {
3113 @synchronized (database_) {
3114 if ([database_ era] != era_ || file_.end())
3117 switch (iterator_->SelectedState) {
3118 case pkgCache::State::Unknown:
3120 case pkgCache::State::Install:
3122 case pkgCache::State::Hold:
3124 case pkgCache::State::DeInstall:
3125 return @"DeInstall";
3126 case pkgCache::State::Purge:
3130 return (NSString *) [NSNull null];
3133 - (NSArray *) warnings {
3134 @synchronized (database_) {
3135 if ([database_ era] != era_ || file_.end())
3138 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
3139 const char *name(iterator_.Name());
3141 size_t length(strlen(name));
3142 if (length < 2) invalid:
3143 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
3144 else for (size_t i(0); i != length; ++i)
3146 /* XXX: technically this is not allowed */
3147 (name[i] < 'A' || name[i] > 'Z') &&
3148 (name[i] < 'a' || name[i] > 'z') &&
3149 (name[i] < '0' || name[i] > '9') &&
3150 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
3153 if (strcmp(name, "cydia") != 0) {
3156 bool _private = false;
3158 bool dbstash = false;
3159 bool dsstore = false;
3161 bool repository = [[self section] isEqualToString:@"Repositories"];
3163 if (NSArray *files = [self files])
3164 for (NSString *file in files)
3165 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
3167 else if (!user && [file isEqualToString:@"/User"])
3169 else if (!_private && [file isEqualToString:@"/private"])
3171 else if (!stash && [file isEqualToString:@"/var/stash"])
3173 else if (!dbstash && [file isEqualToString:@"/var/db/stash"])
3175 else if (!dsstore && [file hasSuffix:@"/.DS_Store"])
3178 /* XXX: this is not sensitive enough. only some folders are valid. */
3179 if (cydia && !repository)
3180 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
3182 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
3184 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
3186 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
3188 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/db/stash"]];
3190 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @".DS_Store"]];
3193 return [warnings count] == 0 ? nil : warnings;
3196 - (NSArray *) applications {
3197 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
3199 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
3201 static RegEx application_r("/Applications/(.*)\\.app/Info.plist");
3202 if (NSArray *files = [self files])
3203 for (NSString *file in files)
3204 if (application_r(file)) {
3205 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
3206 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
3207 if ([id isEqualToString:me])
3210 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
3212 display = application_r[1];
3214 NSString *bundle([file stringByDeletingLastPathComponent]);
3215 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
3216 // XXX: maybe this should check if this is really a string, not just for length
3217 if (icon == nil || ![icon respondsToSelector:@selector(length)] || [icon length] == 0)
3219 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
3221 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
3222 [applications addObject:application];
3224 [application addObject:id];
3225 [application addObject:display];
3226 [application addObject:url];
3229 return [applications count] == 0 ? nil : applications;
3232 - (Source *) source {
3233 if (source_ == nil) {
3234 @synchronized (database_) {
3235 if ([database_ era] != era_ || file_.end())
3236 source_ = (Source *) [NSNull null];
3238 source_ = [database_ getSource:file_.File()] ?: (Source *) [NSNull null];
3242 return source_ == (Source *) [NSNull null] ? nil : source_;
3245 - (time_t) upgraded {
3249 - (uint32_t) recent {
3250 return std::numeric_limits<uint32_t>::max() - upgraded_;
3257 - (BOOL) matches:(NSArray *)query {
3258 if (query == nil || [query count] == 0)
3267 string = [self name];
3268 length = [string length];
3271 for (NSString *term in query) {
3272 range = [string rangeOfString:term options:MatchCompareOptions_];
3273 if (range.location != NSNotFound)
3274 rank_ -= 6 * 1000000 / length;
3279 length = [string length];
3282 for (NSString *term in query) {
3283 range = [string rangeOfString:term options:MatchCompareOptions_];
3284 if (range.location != NSNotFound)
3285 rank_ -= 6 * 1000000 / length;
3289 string = [self shortDescription];
3290 length = [string length];
3291 NSUInteger stop(std::min<NSUInteger>(length, 200));
3294 for (NSString *term in query) {
3295 range = [string rangeOfString:term options:MatchCompareOptions_ range:NSMakeRange(0, stop)];
3296 if (range.location != NSNotFound)
3297 rank_ -= 2 * 100000;
3303 - (NSArray *) tags {
3307 - (BOOL) hasTag:(NSString *)tag {
3308 return tags_ == nil ? NO : [tags_ containsObject:tag];
3311 - (NSString *) primaryPurpose {
3312 for (NSString *tag in (NSArray *) tags_)
3313 if ([tag hasPrefix:@"purpose::"])
3314 return [tag substringFromIndex:9];
3318 - (NSArray *) purposes {
3319 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
3320 for (NSString *tag in (NSArray *) tags_)
3321 if ([tag hasPrefix:@"purpose::"])
3322 [purposes addObject:[tag substringFromIndex:9]];
3323 return [purposes count] == 0 ? nil : purposes;
3326 - (bool) isCommercial {
3327 return [self hasTag:@"cydia::commercial"];
3330 - (void) setIndex:(size_t)index {
3331 if (metadata_->index_ != index)
3332 metadata_->index_ = index;
3335 - (CYString &) cyname {
3336 return !transform_.empty() ? transform_ : !name_.empty() ? name_ : id_;
3339 - (uint32_t) compareBySection:(NSArray *)sections {
3340 NSString *section([self section]);
3341 for (size_t i(0), e([sections count]); i != e; ++i) {
3342 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
3346 return _not(uint32_t);
3350 @synchronized (database_) {
3351 pkgProblemResolver *resolver = [database_ resolver];
3352 resolver->Clear(iterator_);
3354 pkgCacheFile &cache([database_ cache]);
3355 cache->SetReInstall(iterator_, false);
3356 cache->MarkKeep(iterator_, false);
3360 @synchronized (database_) {
3361 pkgProblemResolver *resolver = [database_ resolver];
3362 resolver->Clear(iterator_);
3363 resolver->Protect(iterator_);
3365 pkgCacheFile &cache([database_ cache]);
3366 cache->SetReInstall(iterator_, false);
3367 cache->MarkInstall(iterator_, false);
3369 pkgDepCache::StateCache &state((*cache)[iterator_]);
3370 if (!state.Install())
3371 cache->SetReInstall(iterator_, true);
3375 @synchronized (database_) {
3376 pkgProblemResolver *resolver = [database_ resolver];
3377 resolver->Clear(iterator_);
3378 resolver->Remove(iterator_);
3379 resolver->Protect(iterator_);
3381 pkgCacheFile &cache([database_ cache]);
3382 cache->SetReInstall(iterator_, false);
3383 cache->MarkDelete(iterator_, true);
3388 /* Section Class {{{ */
3389 @interface Section : NSObject {
3393 _H<NSString> localized_;
3396 - (NSComparisonResult) compareByLocalized:(Section *)section;
3397 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
3398 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
3399 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
3401 - (NSString *) name;
3402 - (void) setName:(NSString *)name;
3408 - (void) addToCount;
3410 - (void) setCount:(size_t)count;
3411 - (NSString *) localized;
3415 @implementation Section
3417 - (NSComparisonResult) compareByLocalized:(Section *)section {
3418 NSString *lhs(localized_);
3419 NSString *rhs([section localized]);
3421 /*if ([lhs length] != 0 && [rhs length] != 0) {
3422 unichar lhc = [lhs characterAtIndex:0];
3423 unichar rhc = [rhs characterAtIndex:0];
3425 if (isalpha(lhc) && !isalpha(rhc))
3426 return NSOrderedAscending;
3427 else if (!isalpha(lhc) && isalpha(rhc))
3428 return NSOrderedDescending;
3431 return [lhs compare:rhs options:LaxCompareOptions_];
3434 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
3435 if ((self = [self initWithName:name localize:NO]) != nil) {
3436 if (localized != nil)
3437 localized_ = localized;
3441 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
3442 return [self initWithName:name row:0 localize:localize];
3445 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
3446 if ((self = [super init]) != nil) {
3450 localized_ = LocalizeSection(name_);
3454 - (NSString *) name {
3458 - (void) setName:(NSString *)name {
3474 - (void) addToCount {
3478 - (void) setCount:(size_t)count {
3482 - (NSString *) localized {
3489 class CydiaLogCleaner :
3490 public pkgArchiveCleaner
3493 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3498 /* Database Implementation {{{ */
3499 @implementation Database
3501 + (Database *) sharedInstance {
3502 static _H<Database> instance;
3503 if (instance == nil)
3504 instance = [[[Database alloc] init] autorelease];
3512 - (void) releasePackages {
3513 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3514 CFArrayRemoveAllValues(packages_);
3518 // XXX: actually implement this thing
3520 [self releasePackages];
3521 NSRecycleZone(zone_);
3525 - (void) _readCydia:(NSNumber *)fd {
3526 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3527 std::istream is(&ib);
3530 static RegEx finish_r("finish:([^:]*)");
3532 while (std::getline(is, line)) {
3533 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3535 const char *data(line.c_str());
3536 size_t size = line.size();
3537 lprintf("C:%s\n", data);
3539 if (finish_r(data, size)) {
3540 NSString *finish = finish_r[1];
3541 int index = [Finishes_ indexOfObject:finish];
3542 if (index != INT_MAX && index > Finish_)
3552 - (void) _readStatus:(NSNumber *)fd {
3553 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3554 std::istream is(&ib);
3557 static RegEx conffile_r("status: [^ ]* : conffile-prompt : (.*?) *");
3558 static RegEx pmstatus_r("([^:]*):([^:]*):([^:]*):(.*)");
3560 while (std::getline(is, line)) {
3561 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3563 const char *data(line.c_str());
3564 size_t size(line.size());
3565 lprintf("S:%s\n", data);
3567 if (conffile_r(data, size)) {
3568 // status: /fail : conffile-prompt : '/fail' '/fail.dpkg-new' 1 1
3569 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:conffile_r[1] waitUntilDone:YES];
3570 } else if (strncmp(data, "status: ", 8) == 0) {
3571 // status: <package>: {unpacked,half-configured,installed}
3572 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 8)] ofType:kCydiaProgressEventTypeStatus]);
3573 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3574 } else if (strncmp(data, "processing: ", 12) == 0) {
3575 // processing: configure: config-test
3576 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:(data + 12)] ofType:kCydiaProgressEventTypeStatus]);
3577 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3578 } else if (pmstatus_r(data, size)) {
3579 std::string type([pmstatus_r[1] UTF8String]);
3581 NSString *package = pmstatus_r[2];
3582 if ([package isEqualToString:@"dpkg-exec"])
3585 float percent([pmstatus_r[3] floatValue]);
3586 [progress_ performSelectorOnMainThread:@selector(setProgressPercent:) withObject:[NSNumber numberWithFloat:(percent / 100)] waitUntilDone:YES];
3588 NSString *string = pmstatus_r[4];
3590 if (type == "pmerror") {
3591 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeError forPackage:package]);
3592 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3593 } else if (type == "pmstatus") {
3594 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:string ofType:kCydiaProgressEventTypeStatus forPackage:package]);
3595 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3596 } else if (type == "pmconffile")
3597 [delegate_ performSelectorOnMainThread:@selector(setConfigurationData:) withObject:string waitUntilDone:YES];
3599 lprintf("E:unknown pmstatus\n");
3601 lprintf("E:unknown status\n");
3609 - (void) _readOutput:(NSNumber *)fd {
3610 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3611 std::istream is(&ib);
3614 while (std::getline(is, line)) {
3615 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
3617 lprintf("O:%s\n", line.c_str());
3619 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:line.c_str()] ofType:kCydiaProgressEventTypeInformation]);
3620 [progress_ performSelectorOnMainThread:@selector(addProgressEvent:) withObject:event waitUntilDone:YES];
3632 - (Package *) packageWithName:(NSString *)name {
3635 @synchronized (self) {
3636 if (static_cast<pkgDepCache *>(cache_) == NULL)
3638 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3639 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:NULL database:self];
3643 if ((self = [super init]) != nil) {
3650 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3652 size_t capacity(MetaFile_->active_);
3658 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3659 sourceList_ = [NSMutableArray arrayWithCapacity:16];
3663 _assert(pipe(fds) != -1);
3666 _config->Set("APT::Keep-Fds::", cydiafd_);
3667 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3670 detachNewThreadSelector:@selector(_readCydia:)
3672 withObject:[NSNumber numberWithInt:fds[0]]
3675 _assert(pipe(fds) != -1);
3679 detachNewThreadSelector:@selector(_readStatus:)
3681 withObject:[NSNumber numberWithInt:fds[0]]
3684 _assert(pipe(fds) != -1);
3685 _assert(dup2(fds[0], 0) != -1);
3686 _assert(close(fds[0]) != -1);
3688 input_ = fdopen(fds[1], "a");
3690 _assert(pipe(fds) != -1);
3691 _assert(dup2(fds[1], 1) != -1);
3692 _assert(close(fds[1]) != -1);
3695 detachNewThreadSelector:@selector(_readOutput:)
3697 withObject:[NSNumber numberWithInt:fds[0]]
3702 - (pkgCacheFile &) cache {
3706 - (pkgDepCache::Policy *) policy {
3710 - (pkgRecords *) records {
3714 - (pkgProblemResolver *) resolver {
3718 - (pkgAcquire &) fetcher {
3722 - (pkgSourceList &) list {
3726 - (NSArray *) packages {
3727 return (NSArray *) packages_;
3730 - (NSArray *) sources {
3734 - (Source *) sourceWithKey:(NSString *)key {
3735 for (Source *source in [self sources]) {
3736 if ([[source key] isEqualToString:key])
3741 - (bool) popErrorWithTitle:(NSString *)title {
3744 while (!_error->empty()) {
3746 bool warning(!_error->PopMessage(error));
3751 size_t size(error.size());
3752 if (size == 0 || error[size - 1] != '\n')
3754 error.resize(size - 1);
3757 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3759 static RegEx no_pubkey("GPG error:.* NO_PUBKEY .*");
3760 if (warning && no_pubkey(error.c_str()))
3763 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3769 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3770 return [self popErrorWithTitle:title] || !success;
3773 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
3774 @synchronized (self) {
3777 [self releasePackages];
3780 [sourceList_ removeAllObjects];
3801 new (&pool_) CYPool();
3803 NSRecycleZone(zone_);
3804 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3806 int chk(creat("/tmp/cydia.chk", 0644));
3810 if (invocation != nil)
3811 [invocation invoke];
3813 NSString *title(UCLocalize("DATABASE"));
3815 list_ = new pkgSourceList();
3816 _profile(reloadDataWithInvocation$ReadMainList)
3817 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3821 _profile(reloadDataWithInvocation$Source$initWithMetaIndex)
3822 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3823 Source *object([[[Source alloc] initWithMetaIndex:*source forDatabase:self inPool:&pool_] autorelease]);
3824 [sourceList_ addObject:object];
3828 _root(_system->Lock());
3831 OpProgress progress;
3834 _profile(reloadDataWithInvocation$pkgCacheFile)
3835 opened = cache_.Open(progress, false);
3838 // XXX: what if there are errors, but Open() == true? this should be merged with popError:
3839 while (!_error->empty()) {
3841 bool warning(!_error->PopMessage(error));
3843 lprintf("cache_.Open():[%s]\n", error.c_str());
3845 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:(warning ? kCydiaProgressEventTypeWarning : kCydiaProgressEventTypeError)] forTask:title];
3849 else if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3850 repair = @selector(configure);
3851 //else if (error == "The package lists or status file could not be parsed or opened.")
3852 // repair = @selector(update);
3853 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3854 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3855 // else if (error == "Malformed Status line")
3856 // else if (error == "The list of sources could not be read.")
3858 if (repair != NULL) {
3860 [delegate_ repairWithSelector:repair];
3870 unlink("/tmp/cydia.chk");
3872 now_ = [[NSDate date] timeIntervalSince1970];
3874 policy_ = new pkgDepCache::Policy();
3875 records_ = new pkgRecords(cache_);
3876 resolver_ = new pkgProblemResolver(cache_);
3877 fetcher_ = new pkgAcquire(&status_);
3880 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3881 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("COUNTS_NONZERO_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3885 _profile(reloadDataWithInvocation$pkgApplyStatus)
3886 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3890 if (cache_->BrokenCount() != 0) {
3891 _profile(pkgApplyStatus$pkgFixBroken)
3892 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3896 if (cache_->BrokenCount() != 0) {
3897 [delegate_ addProgressEventOnMainThread:[CydiaProgressEvent eventWithMessage:UCLocalize("STILL_BROKEN_EX") ofType:kCydiaProgressEventTypeError] forTask:title];
3901 _profile(pkgApplyStatus$pkgMinimizeUpgrade)
3902 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3907 for (Source *object in (id) sourceList_) {
3908 metaIndex *source([object metaIndex]);
3909 std::vector<pkgIndexFile *> *indices = source->GetIndexFiles();
3910 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3911 // XXX: this could be more intelligent
3912 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3913 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3915 sourceMap_[cached->ID] = object;
3920 /*std::vector<Package *> packages;
3921 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3924 _profile(reloadDataWithInvocation$packageWithIterator)
3925 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3926 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:&pool_ database:self])
3927 //packages.push_back(package);
3928 CFArrayAppendValue(packages_, CFRetain(package));
3932 /*if (packages.empty())
3933 packages_ = [[NSArray alloc] init];
3935 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3938 _profile(reloadDataWithInvocation$radix$8)
3939 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(8)];
3942 _profile(reloadDataWithInvocation$radix$4)
3943 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3946 _profile(reloadDataWithInvocation$radix$0)
3947 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3950 _profile(reloadDataWithInvocation$insertion)
3951 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3954 /*_profile(reloadDataWithInvocation$CFQSortArray)
3955 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);
3958 /*_profile(reloadDataWithInvocation$stdsort)
3959 std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3962 /*_profile(reloadDataWithInvocation$CFArraySortValues)
3963 CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3966 /*_profile(reloadDataWithInvocation$sortUsingFunction)
3967 [packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3971 size_t count(CFArrayGetCount(packages_));
3972 MetaFile_->active_ = count;
3973 for (size_t index(0); index != count; ++index)
3974 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3979 @synchronized (self) {
3981 resolver_ = new pkgProblemResolver(cache_);
3983 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator)
3984 if (!cache_[iterator].Keep())
3985 cache_->MarkKeep(iterator, false);
3986 else if ((cache_[iterator].iFlags & pkgDepCache::ReInstall) != 0)
3987 cache_->SetReInstall(iterator, false);
3990 - (void) configure {
3991 NSString *dpkg = [NSString stringWithFormat:@"/usr/libexec/cydo --configure -a --status-fd %u", statusfd_];
3993 system([dpkg UTF8String]);
3998 @synchronized (self) {
3999 // XXX: I don't remember this condition
4004 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
4006 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
4008 if ([self popErrorWithTitle:title])
4012 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
4014 CydiaLogCleaner cleaner;
4015 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
4022 fetcher_->Shutdown();
4024 pkgRecords records(cache_);
4026 lock_ = new FileFd();
4027 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
4029 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
4031 if ([self popErrorWithTitle:title])
4035 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
4038 manager_ = (_system->CreatePM(cache_));
4039 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
4046 bool substrate(RestartSubstrate_);
4047 RestartSubstrate_ = false;
4049 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
4051 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
4053 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
4055 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
4056 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
4059 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4061 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
4063 [self popErrorWithTitle:title];
4067 bool failed = false;
4068 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
4069 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
4071 if ((*item)->Status == pkgAcquire::Item::StatIdle)
4074 std::string uri = (*item)->DescURI();
4075 std::string error = (*item)->ErrorText;
4077 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
4080 CydiaProgressEvent *event([CydiaProgressEvent eventWithMessage:[NSString stringWithUTF8String:error.c_str()] ofType:kCydiaProgressEventTypeError]);
4081 [delegate_ addProgressEventOnMainThread:event forTask:title];
4084 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4092 RestartSubstrate_ = true;
4095 pkgPackageManager::OrderResult result(manager_->DoInstall(statusfd_));
4096 if ([self popErrorWithTitle:title])
4099 if (result == pkgPackageManager::Failed) {
4104 if (result != pkgPackageManager::Completed) {
4109 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
4111 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
4113 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
4114 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
4117 if (![before isEqualToArray:after])
4122 NSString *title(UCLocalize("UPGRADE"));
4123 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
4129 [self updateWithStatus:status_];
4132 - (void) updateWithStatus:(CancelStatus &)status {
4133 NSString *title(UCLocalize("REFRESHING_DATA"));
4136 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
4140 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
4141 if ([self popErrorWithTitle:title])
4144 [delegate_ performSelectorOnMainThread:@selector(retainNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4146 bool success(ListUpdate(status, list, PulseInterval_));
4147 if (status.WasCancelled())
4150 [self popErrorWithTitle:title forOperation:success];
4151 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
4155 [delegate_ performSelectorOnMainThread:@selector(releaseNetworkActivityIndicator) withObject:nil waitUntilDone:YES];
4158 - (void) setDelegate:(NSObject<DatabaseDelegate> *)delegate {
4159 delegate_ = delegate;
4162 - (void) setProgressDelegate:(NSObject<ProgressDelegate> *)delegate {
4163 progress_ = delegate;
4164 status_.setDelegate(delegate);
4167 - (NSObject<ProgressDelegate> *) progressDelegate {
4171 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
4172 SourceMap::const_iterator i(sourceMap_.find(file->ID));
4173 return i == sourceMap_.end() ? nil : i->second;
4176 - (void) setFetch:(bool)fetch forURI:(const char *)uri {
4177 for (Source *source in (id) sourceList_)
4178 [source setFetch:fetch forURI:uri];
4181 - (void) resetFetch {
4182 for (Source *source in (id) sourceList_)
4183 [source resetFetch];
4186 - (NSString *) mappedSectionForPointer:(const char *)section {
4187 _H<NSString> *mapped;
4189 _profile(Database$mappedSectionForPointer$Cache)
4190 mapped = §ions_[section];
4193 if (*mapped == NULL) {
4194 size_t length(strlen(section));
4195 char spaced[length + 1];
4197 _profile(Database$mappedSectionForPointer$Replace)
4198 for (size_t index(0); index != length; ++index)
4199 spaced[index] = section[index] == '_' ? ' ' : section[index];
4200 spaced[length] = '\0';
4205 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
4206 string = [NSString stringWithUTF8String:spaced];
4209 _profile(Database$mappedSectionForPointer$Map)
4210 string = [SectionMap_ objectForKey:string] ?: string;
4220 static _H<NSMutableSet> Diversions_;
4222 @interface Diversion : NSObject {
4225 _H<NSString> format_;
4230 @implementation Diversion
4232 - (id) initWithFrom:(NSString *)from to:(NSString *)to {
4233 if ((self = [super init]) != nil) {
4234 pattern_ = [from UTF8String];
4240 - (NSString *) divert:(NSString *)url {
4241 return !pattern_(url) ? nil : pattern_->*format_;
4244 + (NSURL *) divertURL:(NSURL *)url {
4246 NSString *href([url absoluteString]);
4248 for (Diversion *diversion in (id) Diversions_)
4249 if (NSString *diverted = [diversion divert:href]) {
4251 NSLog(@"div: %@", diverted);
4253 url = [NSURL URLWithString:diverted];
4260 - (NSString *) key {
4264 - (NSUInteger) hash {
4268 - (BOOL) isEqual:(Diversion *)object {
4269 return self == object || [self class] == [object class] && [key_ isEqual:[object key]];
4274 @interface CydiaObject : NSObject {
4275 _H<CyteWebViewController> indirect_;
4276 _transient id delegate_;
4279 - (id) initWithDelegate:(IndirectDelegate *)indirect;
4285 @interface CydiaWebViewController : CyteWebViewController {
4286 _H<CydiaObject> cydia_;
4289 + (void) addDiversion:(Diversion *)diversion;
4290 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request;
4291 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia;
4292 - (void) setDelegate:(id)delegate;
4296 /* Web Scripting {{{ */
4297 @implementation CydiaObject
4299 - (id) initWithDelegate:(IndirectDelegate *)indirect {
4300 if ((self = [super init]) != nil) {
4301 indirect_ = (CyteWebViewController *) indirect;
4305 - (void) setDelegate:(id)delegate {
4306 delegate_ = delegate;
4309 + (NSArray *) _attributeKeys {
4310 return [NSArray arrayWithObjects:
4313 @"coreFoundationVersionNumber",
4330 - (NSArray *) attributeKeys {
4331 return [[self class] _attributeKeys];
4334 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
4335 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
4338 - (NSString *) version {
4342 - (NSString *) build {
4346 - (NSString *) coreFoundationVersionNumber {
4347 return [NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber];
4350 - (NSString *) device {
4351 return UniqueIdentifier();
4354 - (NSString *) firmware {
4355 return [[UIDevice currentDevice] systemVersion];
4358 - (NSString *) hostname {
4359 return [[UIDevice currentDevice] name];
4362 - (NSString *) idiom {
4363 return (id) Idiom_ ?: [NSNull null];
4366 - (NSString *) mcc {
4367 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode")))
4368 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault) autorelease];
4372 - (NSString *) mnc {
4373 if (CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberNetworkCode")))
4374 return [(NSString *) (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault) autorelease];
4378 - (NSString *) operator {
4379 if (CFStringRef (*$CTRegistrationCopyOperatorName)(CFAllocatorRef) = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTRegistrationCopyOperatorName")))
4380 return [(NSString *) (*$CTRegistrationCopyOperatorName)(kCFAllocatorDefault) autorelease];
4384 - (NSString *) bbsnum {
4385 return (id) BBSNum_ ?: [NSNull null];
4388 - (NSString *) ecid {
4389 return (id) ChipID_ ?: [NSNull null];
4392 - (NSString *) serial {
4393 return SerialNumber_;
4396 - (NSString *) role {
4397 return (id) [NSNull null];
4400 - (NSString *) model {
4401 return [NSString stringWithUTF8String:Machine_];
4404 - (NSString *) token {
4405 return (id) Token_ ?: [NSNull null];
4408 + (NSString *) webScriptNameForSelector:(SEL)selector {
4410 else if (selector == @selector(addBridgedHost:))
4411 return @"addBridgedHost";
4412 else if (selector == @selector(addInsecureHost:))
4413 return @"addInsecureHost";
4414 else if (selector == @selector(addInternalRedirect::))
4415 return @"addInternalRedirect";
4416 else if (selector == @selector(addPipelinedHost:scheme:))
4417 return @"addPipelinedHost";
4418 else if (selector == @selector(addSource:::))
4419 return @"addSource";
4420 else if (selector == @selector(addTokenHost:))
4421 return @"addTokenHost";
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) addTokenHost:(NSString *)host {
4643 @synchronized (HostConfig_) {
4644 [TokenHosts_ addObject:host];
4647 - (void) addPipelinedHost:(NSString *)host scheme:(NSString *)scheme {
4648 @synchronized (HostConfig_) {
4649 if (scheme != (id) [WebUndefined undefined])
4650 host = [NSString stringWithFormat:@"%@:%@", [scheme lowercaseString], host];
4652 [PipelinedHosts_ addObject:host];
4655 - (void) popViewController:(NSNumber *)value {
4656 if (value == (id) [WebUndefined undefined])
4657 value = [NSNumber numberWithBool:YES];
4658 [indirect_ performSelectorOnMainThread:@selector(popViewControllerWithNumber:) withObject:value waitUntilDone:NO];
4661 - (void) addSource:(NSString *)href :(NSString *)distribution :(WebScriptObject *)sections {
4662 NSMutableArray *array([NSMutableArray arrayWithCapacity:[sections count]]);
4664 for (NSString *section in sections)
4665 [array addObject:section];
4667 [delegate_ performSelectorOnMainThread:@selector(addSource:) withObject:[NSMutableDictionary dictionaryWithObjectsAndKeys:
4670 distribution, @"Distribution",
4672 nil] waitUntilDone:NO];
4675 - (void) addTrivialSource:(NSString *)href {
4676 [delegate_ performSelectorOnMainThread:@selector(addTrivialSource:) withObject:href waitUntilDone:NO];
4679 - (void) refreshSources {
4680 [delegate_ performSelectorOnMainThread:@selector(syncData) withObject:nil waitUntilDone:NO];
4683 - (void) saveConfig {
4684 [delegate_ performSelectorOnMainThread:@selector(_saveConfig) withObject:nil waitUntilDone:NO];
4687 - (NSArray *) getAllSources {
4688 return [[Database sharedInstance] sources];
4691 - (NSArray *) getInstalledPackages {
4692 Database *database([Database sharedInstance]);
4693 @synchronized (database) {
4694 NSArray *packages([database packages]);
4695 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
4696 for (Package *package in packages)
4697 if (![package uninstalled])
4698 [installed addObject:package];
4702 - (Package *) getPackageById:(NSString *)id {
4703 if (Package *package = [[Database sharedInstance] packageWithName:id]) {
4707 return (Package *) [NSNull null];
4710 - (NSString *) getLocaleIdentifier {
4711 return Locale_ == NULL ? (NSString *) [NSNull null] : (NSString *) CFLocaleGetIdentifier(Locale_);
4714 - (NSArray *) getPreferredLanguages {
4718 - (NSArray *) statfs:(NSString *)path {
4721 if (path == nil || statfs([path UTF8String], &stat) == -1)
4724 return [NSArray arrayWithObjects:
4725 [NSNumber numberWithUnsignedLong:stat.f_bsize],
4726 [NSNumber numberWithUnsignedLong:stat.f_blocks],
4727 [NSNumber numberWithUnsignedLong:stat.f_bfree],
4731 ssize_t DiskUsage(const char *path);
4733 - (NSNumber *) du:(NSString *)path {
4734 ssize_t usage(DiskUsage([path UTF8String]));
4737 return [NSNumber numberWithUnsignedLong:usage];
4741 [indirect_ performSelectorOnMainThread:@selector(close) withObject:nil waitUntilDone:NO];
4744 - (NSNumber *) isReachable:(NSString *)name {
4745 return [NSNumber numberWithBool:IsReachable([name UTF8String])];
4748 - (void) installPackages:(NSArray *)packages {
4749 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
4752 - (NSString *) substitutePackageNames:(NSString *)message {
4753 NSMutableArray *words([[[message componentsSeparatedByString:@" "] mutableCopy] autorelease]);
4754 for (size_t i(0), e([words count]); i != e; ++i) {
4755 NSString *word([words objectAtIndex:i]);
4756 if (Package *package = [[Database sharedInstance] packageWithName:word])
4757 [words replaceObjectAtIndex:i withObject:[package name]];
4760 return [words componentsJoinedByString:@" "];
4763 - (void) removeButton {
4764 [indirect_ removeButton];
4767 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4768 [indirect_ setButtonImage:button withStyle:style toFunction:function];
4771 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
4772 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
4775 - (void) setBadgeValue:(id)value {
4776 [indirect_ performSelectorOnMainThread:@selector(setBadgeValue:) withObject:value waitUntilDone:NO];
4779 - (void) setAllowsNavigationAction:(NSString *)value {
4780 [indirect_ performSelectorOnMainThread:@selector(setAllowsNavigationActionByNumber:) withObject:value waitUntilDone:NO];
4783 - (void) setHidesBackButton:(NSString *)value {
4784 [indirect_ performSelectorOnMainThread:@selector(setHidesBackButtonByNumber:) withObject:value waitUntilDone:NO];
4787 - (void) setHidesNavigationBar:(NSString *)value {
4788 [indirect_ performSelectorOnMainThread:@selector(setHidesNavigationBarByNumber:) withObject:value waitUntilDone:NO];
4791 - (void) setNavigationBarStyle:(NSString *)value {
4792 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarStyle:) withObject:value waitUntilDone:NO];
4795 - (void) setNavigationBarTintRed:(NSNumber *)red green:(NSNumber *)green blue:(NSNumber *)blue alpha:(NSNumber *)alpha {
4796 float opacity(alpha == (id) [WebUndefined undefined] ? 1 : [alpha floatValue]);
4797 UIColor *color([UIColor colorWithRed:[red floatValue] green:[green floatValue] blue:[blue floatValue] alpha:opacity]);
4798 [indirect_ performSelectorOnMainThread:@selector(setNavigationBarTintColor:) withObject:color waitUntilDone:NO];
4801 - (void) setPasteboardString:(NSString *)value {
4802 [[objc_getClass("UIPasteboard") generalPasteboard] setString:value];
4805 - (void) setPasteboardURL:(NSString *)value {
4806 [[objc_getClass("UIPasteboard") generalPasteboard] setURL:[NSURL URLWithString:value]];
4809 - (void) _setToken:(NSString *)token {
4813 [Metadata_ removeObjectForKey:@"Token"];
4815 [Metadata_ setObject:Token_ forKey:@"Token"];
4820 - (void) setToken:(NSString *)token {
4821 [self performSelectorOnMainThread:@selector(_setToken:) withObject:token waitUntilDone:NO];
4824 - (void) scrollToBottom:(NSNumber *)animated {
4825 [indirect_ performSelectorOnMainThread:@selector(scrollToBottomAnimated:) withObject:animated waitUntilDone:NO];
4828 - (void) setViewportWidth:(float)width {
4829 [indirect_ setViewportWidthOnMainThread:width];
4832 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
4833 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
4834 unsigned count([arguments count]);
4836 for (unsigned i(0); i != count; ++i)
4837 values[i] = [arguments objectAtIndex:i];
4838 return [[[NSString alloc] initWithFormat:format arguments:reinterpret_cast<va_list>(values)] autorelease];
4841 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
4842 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
4844 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
4846 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
4852 @interface NSURL (CydiaSecure)
4855 @implementation NSURL (CydiaSecure)
4857 - (bool) isCydiaSecure {
4858 if ([[[self scheme] lowercaseString] isEqualToString:@"https"])
4861 @synchronized (HostConfig_) {
4862 if ([InsecureHosts_ containsObject:[self host]])
4871 /* Cydia Browser Controller {{{ */
4872 @implementation CydiaWebViewController
4874 - (NSURL *) navigationURL {
4875 return request_ == nil ? nil : [NSURL URLWithString:[NSString stringWithFormat:@"cydia://url/%@", [[request_ URL] absoluteString]]];
4878 + (void) _initialize {
4879 [super _initialize];
4881 Diversions_ = [NSMutableSet setWithCapacity:0];
4884 + (void) addDiversion:(Diversion *)diversion {
4885 [Diversions_ addObject:diversion];
4888 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4889 [super webView:view didClearWindowObject:window forFrame:frame];
4890 [CydiaWebViewController didClearWindowObject:window forFrame:frame withCydia:cydia_];
4893 + (void) didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame withCydia:(CydiaObject *)cydia {
4894 WebDataSource *source([frame dataSource]);
4895 NSURLResponse *response([source response]);
4896 NSURL *url([response URL]);
4897 NSString *scheme([[url scheme] lowercaseString]);
4899 bool bridged(false);
4901 @synchronized (HostConfig_) {
4902 if ([scheme isEqualToString:@"file"])
4904 else if ([scheme isEqualToString:@"https"])
4905 if ([BridgedHosts_ containsObject:[url host]])
4910 [window setValue:cydia forKey:@"cydia"];
4913 - (void) _setupMail:(MFMailComposeViewController *)controller {
4914 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/cydia.log"] mimeType:@"text/plain" fileName:@"cydia.log"];
4916 system("/usr/bin/dpkg -l >/tmp/dpkgl.log");
4917 [controller addAttachmentData:[NSData dataWithContentsOfFile:@"/tmp/dpkgl.log"] mimeType:@"text/plain" fileName:@"dpkgl.log"];
4920 - (NSURL *) URLWithURL:(NSURL *)url {
4921 return [Diversion divertURL:url];
4924 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4925 return [CydiaWebViewController requestWithHeaders:[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
4928 - (NSURLRequest *) webThreadWebView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4929 return [CydiaWebViewController requestWithHeaders:[super webThreadWebView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source]];
4932 + (NSURLRequest *) requestWithHeaders:(NSURLRequest *)request {
4933 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
4935 NSURL *url([copy URL]);
4936 NSString *href([url absoluteString]);
4937 NSString *host([url host]);
4939 if ([href hasPrefix:@"https://cydia.saurik.com/TSS/"]) {
4940 if (NSString *agent = [copy valueForHTTPHeaderField:@"X-User-Agent"]) {
4941 [copy setValue:agent forHTTPHeaderField:@"User-Agent"];
4942 [copy setValue:nil forHTTPHeaderField:@"X-User-Agent"];
4945 [copy setValue:nil forHTTPHeaderField:@"Referer"];
4946 [copy setValue:nil forHTTPHeaderField:@"Origin"];
4948 [copy setURL:[NSURL URLWithString:[@"http://gs.apple.com/TSS/" stringByAppendingString:[href substringFromIndex:29]]]];
4952 if ([copy valueForHTTPHeaderField:@"X-Cydia-Cf"] == nil)
4953 [copy setValue:[NSString stringWithFormat:@"%.2f", kCFCoreFoundationVersionNumber] forHTTPHeaderField:@"X-Cydia-Cf"];
4954 if (Machine_ != NULL && [copy valueForHTTPHeaderField:@"X-Machine"] == nil)
4955 [copy setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4960 @synchronized (HostConfig_) {
4961 bridged = [BridgedHosts_ containsObject:host];
4962 token = [TokenHosts_ containsObject:host];
4965 if ([url isCydiaSecure]) {
4967 if (UniqueID_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Id"] == nil)
4968 [copy setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
4970 if (Token_ != nil && [copy valueForHTTPHeaderField:@"X-Cydia-Token"] == nil)
4971 [copy setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4978 - (void) setDelegate:(id)delegate {
4979 [super setDelegate:delegate];
4980 [cydia_ setDelegate:delegate];
4983 - (NSString *) applicationNameForUserAgent {
4988 if ((self = [super initWithWidth:0 ofClass:[CydiaWebViewController class]]) != nil) {
4989 cydia_ = [[[CydiaObject alloc] initWithDelegate:indirect_] autorelease];
4995 @interface AppCacheController : CydiaWebViewController {
5000 @implementation AppCacheController
5002 - (void) didReceiveMemoryWarning {
5003 // XXX: this doesn't work
5006 - (bool) retainsNetworkActivityIndicator {
5014 @interface NSObject (CydiaScript)
5015 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context;
5018 @implementation NSObject (CydiaScript)
5020 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5026 @implementation NSArray (CydiaScript)
5028 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5029 WebScriptObject *object([context evaluateWebScript:@"[]"]);
5030 for (size_t i(0), e([self count]); i != e; ++i)
5031 [object setWebScriptValueAtIndex:i value:[[self objectAtIndex:i] Cydia$webScriptObjectInContext:context]];
5037 @implementation NSDictionary (CydiaScript)
5039 - (id) Cydia$webScriptObjectInContext:(WebScriptObject *)context {
5040 WebScriptObject *object([context evaluateWebScript:@"({})"]);
5042 [object setValue:[[self objectForKey:i] Cydia$webScriptObjectInContext:context] forKey:i];
5049 /* Confirmation Controller {{{ */
5050 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
5051 if (!iterator.end())
5052 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
5053 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
5055 pkgCache::PkgIterator package(dep.TargetPkg());
5058 if (strcmp(package.Name(), "mobilesubstrate") == 0)
5065 @protocol ConfirmationControllerDelegate
5066 - (void) cancelAndClear:(bool)clear;
5067 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
5071 @interface ConfirmationController : CydiaWebViewController {
5072 _transient Database *database_;
5074 _H<UIAlertView> essential_;
5076 _H<NSDictionary> changes_;
5077 _H<NSMutableArray> issues_;
5078 _H<NSDictionary> sizes_;
5083 - (id) initWithDatabase:(Database *)database;
5087 @implementation ConfirmationController
5091 RestartSubstrate_ = true;
5092 [delegate_ confirmWithNavigationController:[self navigationController]];
5095 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
5096 NSString *context([alert context]);
5098 if ([context isEqualToString:@"remove"]) {
5099 if (button == [alert cancelButtonIndex])
5101 else if (button == [alert firstOtherButtonIndex]) {
5102 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
5105 [alert dismissWithClickedButtonIndex:-1 animated:YES];
5106 } else if ([context isEqualToString:@"unable"]) {
5107 [self dismissModalViewControllerAnimated:YES];
5108 [alert dismissWithClickedButtonIndex:-1 animated:YES];
5110 [super alertView:alert clickedButtonAtIndex:button];
5114 - (void) _doContinue {
5115 [delegate_ cancelAndClear:NO];
5116 [self dismissModalViewControllerAnimated:YES];
5119 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
5120 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
5124 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5125 [super webView:view didClearWindowObject:window forFrame:frame];
5127 [window setValue:[[NSDictionary dictionaryWithObjectsAndKeys:
5128 (id) changes_, @"changes",
5129 (id) issues_, @"issues",
5130 (id) sizes_, @"sizes",
5132 nil] Cydia$webScriptObjectInContext:window] forKey:@"cydiaConfirm"];
5135 - (id) initWithDatabase:(Database *)database {
5136 if ((self = [super init]) != nil) {
5137 database_ = database;
5139 NSMutableArray *installs([NSMutableArray arrayWithCapacity:16]);
5140 NSMutableArray *reinstalls([NSMutableArray arrayWithCapacity:16]);
5141 NSMutableArray *upgrades([NSMutableArray arrayWithCapacity:16]);
5142 NSMutableArray *downgrades([NSMutableArray arrayWithCapacity:16]);
5143 NSMutableArray *removes([NSMutableArray arrayWithCapacity:16]);
5147 pkgCacheFile &cache([database_ cache]);
5148 NSArray *packages([database_ packages]);
5149 pkgDepCache::Policy *policy([database_ policy]);
5151 issues_ = [NSMutableArray arrayWithCapacity:4];
5153 UpgradeCydia_ = false;
5155 for (Package *package in packages) {
5156 pkgCache::PkgIterator iterator([package iterator]);
5157 NSString *name([package id]);
5159 if ([package broken]) {
5160 NSMutableArray *reasons([NSMutableArray arrayWithCapacity:4]);
5162 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5164 reasons, @"reasons",
5167 pkgCache::VerIterator ver(cache[iterator].InstVerIter(cache));
5171 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
5172 pkgCache::DepIterator start;
5173 pkgCache::DepIterator end;
5174 dep.GlobOr(start, end); // ++dep
5176 if (!cache->IsImportantDep(end))
5178 if ((cache[end] & pkgDepCache::DepGInstall) != 0)
5181 NSMutableArray *clauses([NSMutableArray arrayWithCapacity:4]);
5183 [reasons addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5184 [NSString stringWithUTF8String:start.DepType()], @"relationship",
5185 clauses, @"clauses",
5189 NSString *reason, *installed((NSString *) [WebUndefined undefined]);
5191 pkgCache::PkgIterator target(start.TargetPkg());
5192 if (target->ProvidesList != 0)
5193 reason = @"missing";
5195 pkgCache::VerIterator ver(cache[target].InstVerIter(cache));
5197 reason = @"installed";
5198 installed = [NSString stringWithUTF8String:ver.VerStr()];
5199 } else if (!cache[target].CandidateVerIter(cache).end())
5200 reason = @"uninstalled";
5201 else if (target->ProvidesList == 0)
5202 reason = @"uninstallable";
5204 reason = @"virtual";
5207 NSDictionary *version(start.TargetVer() == 0 ? (NSDictionary *) [NSNull null] : [NSDictionary dictionaryWithObjectsAndKeys:
5208 [NSString stringWithUTF8String:start.CompType()], @"operator",
5209 [NSString stringWithUTF8String:start.TargetVer()], @"value",
5212 [clauses addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5213 [NSString stringWithUTF8String:start.TargetPkg().Name()], @"package",
5214 version, @"version",
5216 installed, @"installed",
5219 // yes, seriously. (wtf?)
5227 pkgDepCache::StateCache &state(cache[iterator]);
5229 static RegEx special_r("(firmware|gsc\\..*|cy\\+.*)");
5231 if (state.NewInstall())
5232 [installs addObject:name];
5233 // XXX: else if (state.Install())
5234 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
5235 [reinstalls addObject:name];
5236 // XXX: move before previous if
5237 else if (state.Upgrade())
5238 [upgrades addObject:name];
5239 else if (state.Downgrade())
5240 [downgrades addObject:name];
5241 else if (!state.Delete())
5242 // XXX: _assert(state.Keep());
5244 else if (special_r(name))
5245 [issues_ addObject:[NSDictionary dictionaryWithObjectsAndKeys:
5246 [NSNull null], @"package",
5247 [NSArray arrayWithObjects:
5248 [NSDictionary dictionaryWithObjectsAndKeys:
5249 @"Conflicts", @"relationship",
5250 [NSArray arrayWithObjects:
5251 [NSDictionary dictionaryWithObjectsAndKeys:
5253 [NSNull null], @"version",
5254 @"installed", @"reason",
5261 if ([package essential])
5263 [removes addObject:name];
5266 if ([name isEqualToString:@"cydia"])
5267 UpgradeCydia_ = true;
5269 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
5270 substrate_ |= DepSubstrate(iterator.CurrentVer());
5275 else if (Advanced_) {
5276 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
5278 essential_ = [[[UIAlertView alloc]
5279 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
5280 message:UCLocalize("REMOVING_ESSENTIALS_EX")
5282 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
5284 [NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")],
5288 [essential_ setContext:@"remove"];
5289 [essential_ setNumberOfRows:2];
5291 essential_ = [[[UIAlertView alloc]
5292 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
5293 message:UCLocalize("UNABLE_TO_COMPLY_EX")
5295 cancelButtonTitle:UCLocalize("OKAY")
5296 otherButtonTitles:nil
5299 [essential_ setContext:@"unable"];
5302 changes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5303 installs, @"installs",
5304 reinstalls, @"reinstalls",
5305 upgrades, @"upgrades",
5306 downgrades, @"downgrades",
5307 removes, @"removes",
5310 sizes_ = [NSDictionary dictionaryWithObjectsAndKeys:
5311 [NSNumber numberWithInteger:[database_ fetcher].FetchNeeded()], @"downloading",
5312 [NSNumber numberWithInteger:[database_ fetcher].PartialPresent()], @"resuming",
5315 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/confirm/", UI_]]];
5319 - (UIBarButtonItem *) leftButton {
5320 return [[[UIBarButtonItem alloc]
5321 initWithTitle:UCLocalize("CANCEL")
5322 style:UIBarButtonItemStylePlain
5324 action:@selector(cancelButtonClicked)
5329 - (void) applyRightButton {
5330 if ([issues_ count] == 0 && ![self isLoading])
5331 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
5332 initWithTitle:UCLocalize("CONFIRM")
5333 style:UIBarButtonItemStyleDone
5335 action:@selector(confirmButtonClicked)
5338 [[self navigationItem] setRightBarButtonItem:nil];
5342 - (void) cancelButtonClicked {
5343 [delegate_ cancelAndClear:YES];
5344 [self dismissModalViewControllerAnimated:YES];
5348 - (void) confirmButtonClicked {
5349 if (essential_ != nil)
5359 /* Progress Data {{{ */
5360 @interface CydiaProgressData : NSObject {
5361 _transient id delegate_;
5370 _H<NSMutableArray> events_;
5371 _H<NSString> title_;
5373 _H<NSString> status_;
5374 _H<NSString> finish_;
5379 @implementation CydiaProgressData
5381 + (NSArray *) _attributeKeys {
5382 return [NSArray arrayWithObjects:
5394 - (NSArray *) attributeKeys {
5395 return [[self class] _attributeKeys];
5398 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
5399 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
5403 if ((self = [super init]) != nil) {
5404 events_ = [NSMutableArray arrayWithCapacity:32];
5412 - (void) setDelegate:(id)delegate {
5413 delegate_ = delegate;
5416 - (void) setPercent:(float)value {
5420 - (NSNumber *) percent {
5421 return [NSNumber numberWithFloat:percent_];
5424 - (void) setCurrent:(float)value {
5428 - (NSNumber *) current {
5429 return [NSNumber numberWithFloat:current_];
5432 - (void) setTotal:(float)value {
5436 - (NSNumber *) total {
5437 return [NSNumber numberWithFloat:total_];
5440 - (void) setSpeed:(float)value {
5444 - (NSNumber *) speed {
5445 return [NSNumber numberWithFloat:speed_];
5448 - (NSArray *) events {
5452 - (void) removeAllEvents {
5453 [events_ removeAllObjects];
5456 - (void) addEvent:(CydiaProgressEvent *)event {
5457 [events_ addObject:event];
5460 - (void) setTitle:(NSString *)text {
5464 - (NSString *) title {
5468 - (void) setFinish:(NSString *)text {
5472 - (NSString *) finish {
5473 return (id) finish_ ?: [NSNull null];
5476 - (void) setRunning:(bool)running {
5480 - (NSNumber *) running {
5481 return running_ ? (NSNumber *) kCFBooleanTrue : (NSNumber *) kCFBooleanFalse;
5486 /* Progress Controller {{{ */
5487 @interface ProgressController : CydiaWebViewController <
5490 _transient Database *database_;
5491 _H<CydiaProgressData, 1> progress_;
5495 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
5497 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title;
5499 - (void) setTitle:(NSString *)title;
5500 - (void) setCancellable:(bool)cancellable;
5504 @implementation ProgressController
5507 [database_ setProgressDelegate:nil];
5511 - (UIBarButtonItem *) leftButton {
5512 return cancel_ == 1 ? [[[UIBarButtonItem alloc]
5513 initWithTitle:UCLocalize("CANCEL")
5514 style:UIBarButtonItemStylePlain
5516 action:@selector(cancel)
5517 ] autorelease] : nil;
5520 - (void) updateCancel {
5521 [super applyLeftButton];
5524 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
5525 if ((self = [super init]) != nil) {
5526 database_ = database;
5527 delegate_ = delegate;
5529 [database_ setProgressDelegate:self];
5531 progress_ = [[[CydiaProgressData alloc] init] autorelease];
5532 [progress_ setDelegate:self];
5534 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/progress/", UI_]]];
5536 [scroller_ setBackgroundColor:[UIColor blackColor]];
5538 [[self navigationItem] setHidesBackButton:YES];
5540 [self updateCancel];
5544 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5545 [super webView:view didClearWindowObject:window forFrame:frame];
5546 [window setValue:progress_ forKey:@"cydiaProgress"];
5549 - (void) updateProgress {
5550 [self dispatchEvent:@"CydiaProgressUpdate"];
5553 - (void) viewWillAppear:(BOOL)animated {
5554 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
5555 [super viewWillAppear:animated];
5558 - (void) reloadSpringBoard {
5559 if (kCFCoreFoundationVersionNumber > 700) { // XXX: iOS 6.x
5560 system("/bin/launchctl stop com.apple.backboardd");
5562 system("/usr/bin/killall backboardd SpringBoard sbreload");
5566 pid_t pid(ExecFork());
5571 pid_t pid(ExecFork());
5573 execl("/usr/libexec/cydia/cydo", "cydo", "/usr/bin/sbreload", NULL);
5583 system("/usr/bin/killall backboardd SpringBoard sbreload");
5587 UpdateExternalStatus(0);
5590 [delegate_ saveState];
5594 [delegate_ returnToCydia];
5598 [delegate_ terminateWithSuccess];
5599 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
5600 [delegate_ suspendWithAnimation:YES];
5602 [delegate_ suspend];*/
5614 UIProgressHUD *hud([delegate_ addProgressHUD]);
5615 [hud setText:UCLocalize("LOADING")];
5616 [self performSelector:@selector(reloadSpringBoard) withObject:nil afterDelay:0.5];
5622 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
5623 SBReboot(SBSSpringBoardServerPort());
5625 reboot2(RB_AUTOBOOT);
5632 - (void) setTitle:(NSString *)title {
5633 [progress_ setTitle:title];
5634 [self updateProgress];
5637 - (UIBarButtonItem *) rightButton {
5638 return [[progress_ running] boolValue] ? [super rightButton] : [[[UIBarButtonItem alloc]
5639 initWithTitle:UCLocalize("CLOSE")
5640 style:UIBarButtonItemStylePlain
5642 action:@selector(close)
5646 - (void) invoke:(NSInvocation *)invocation withTitle:(NSString *)title {
5647 UpdateExternalStatus(1);
5649 [progress_ setRunning:true];
5650 [self setTitle:title];
5651 // implicit updateProgress
5653 SHA1SumValue notifyconf; {
5655 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5658 MMap mmap(file, MMap::ReadOnly);
5660 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5661 notifyconf = sha1.Result();
5665 SHA1SumValue springlist; {
5667 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5670 MMap mmap(file, MMap::ReadOnly);
5672 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5673 springlist = sha1.Result();
5677 if (invocation != nil) {
5678 [invocation yieldToSelector:@selector(invoke)];
5679 [self setTitle:@"COMPLETE"];
5684 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
5687 MMap mmap(file, MMap::ReadOnly);
5689 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5690 if (!(notifyconf == sha1.Result()))
5697 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
5700 MMap mmap(file, MMap::ReadOnly);
5702 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
5703 if (!(springlist == sha1.Result()))
5709 if (RestartSubstrate_)
5713 RestartSubstrate_ = false;
5716 case 0: [progress_ setFinish:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
5717 case 1: [progress_ setFinish:UCLocalize("CLOSE_CYDIA")]; break;
5718 case 2: [progress_ setFinish:UCLocalize("RESTART_SPRINGBOARD")]; break;
5719 case 3: [progress_ setFinish:UCLocalize("RELOAD_SPRINGBOARD")]; break;
5720 case 4: [progress_ setFinish:UCLocalize("REBOOT_DEVICE")]; break;
5723 UpdateExternalStatus(Finish_ == 0 ? 0 : 2);
5725 [progress_ setRunning:false];
5726 [self updateProgress];
5728 [self applyRightButton];
5731 - (void) addProgressEvent:(CydiaProgressEvent *)event {
5732 [progress_ addEvent:event];
5733 [self updateProgress];
5736 - (bool) isProgressCancelled {
5737 return cancel_ == 2;
5742 [self updateCancel];
5745 - (void) setCancellable:(bool)cancellable {
5746 unsigned cancel(cancel_);
5750 else if (cancel_ == 0)
5753 if (cancel != cancel_)
5754 [self updateCancel];
5757 - (void) setProgressCancellable:(NSNumber *)cancellable {
5758 [self setCancellable:[cancellable boolValue]];
5761 - (void) setProgressPercent:(NSNumber *)percent {
5762 [progress_ setPercent:[percent floatValue]];
5763 [self updateProgress];
5766 - (void) setProgressStatus:(NSDictionary *)status {
5767 if (status == nil) {
5768 [progress_ setCurrent:0];
5769 [progress_ setTotal:0];
5770 [progress_ setSpeed:0];
5772 [progress_ setPercent:[[status objectForKey:@"Percent"] floatValue]];
5774 [progress_ setCurrent:[[status objectForKey:@"Current"] floatValue]];
5775 [progress_ setTotal:[[status objectForKey:@"Total"] floatValue]];
5776 [progress_ setSpeed:[[status objectForKey:@"Speed"] floatValue]];
5779 [self updateProgress];
5785 /* Package Cell {{{ */
5786 @interface PackageCell : CyteTableViewCell <
5787 CyteTableViewCellDelegate
5791 _H<NSString> description_;
5793 _H<NSString> source_;
5795 _H<UIImage> placard_;
5799 - (PackageCell *) init;
5800 - (void) setPackage:(Package *)package asSummary:(bool)summary;
5802 - (void) drawContentRect:(CGRect)rect;
5806 @implementation PackageCell
5808 - (PackageCell *) init {
5809 CGRect frame(CGRectMake(0, 0, 320, 74));
5810 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
5811 UIView *content([self contentView]);
5812 CGRect bounds([content bounds]);
5814 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
5815 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5816 [content addSubview:content_];
5818 [content_ setDelegate:self];
5819 [content_ setOpaque:YES];
5823 - (NSString *) accessibilityLabel {
5827 - (void) setPackage:(Package *)package asSummary:(bool)summary {
5828 summarized_ = summary;
5838 [content_ setBackgroundColor:[UIColor whiteColor]];
5842 Source *source = [package source];
5844 icon_ = [package icon];
5846 if (NSString *name = [package name])
5847 name_ = [NSString stringWithString:name];
5849 if (NSString *description = [package shortDescription])
5850 description_ = [NSString stringWithString:description];
5852 commercial_ = [package isCommercial];
5854 NSString *label = nil;
5855 bool trusted = false;
5857 if (source != nil) {
5858 label = [source label];
5859 trusted = [source trusted];
5860 } else if ([[package id] isEqualToString:@"firmware"])
5861 label = UCLocalize("APPLE");
5863 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5865 NSString *from(label);
5867 NSString *section = [package simpleSection];
5868 if (section != nil && ![section isEqualToString:label]) {
5869 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5870 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5873 source_ = [NSString stringWithFormat:UCLocalize("FROM"), from];
5875 if (NSString *purpose = [package primaryPurpose])
5876 badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]];
5881 if (NSString *mode = [package mode]) {
5882 if ([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]) {
5883 color = RemovingColor_;
5884 placard = @"removing";
5886 color = InstallingColor_;
5887 placard = @"installing";
5890 color = [UIColor whiteColor];
5892 if ([package installed] != nil)
5893 placard = @"installed";
5898 [content_ setBackgroundColor:color];
5901 placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/%@.png", App_, placard]];
5904 [self setNeedsDisplay];
5905 [content_ setNeedsDisplay];
5908 - (void) drawSummaryContentRect:(CGRect)rect {
5909 bool highlighted(highlighted_);
5910 float width([self bounds].size.width);
5914 rect.size = [(UIImage *) icon_ size];
5916 while (rect.size.width > 16 || rect.size.height > 16) {
5917 rect.size.width /= 2;
5918 rect.size.height /= 2;
5921 rect.origin.x = 19 - rect.size.width / 2;
5922 rect.origin.y = 19 - rect.size.height / 2;
5924 [icon_ drawInRect:Retina(rect)];
5927 if (badge_ != nil) {
5929 rect.size = [(UIImage *) badge_ size];
5931 rect.size.width /= 4;
5932 rect.size.height /= 4;
5934 rect.origin.x = 25 - rect.size.width / 2;
5935 rect.origin.y = 25 - rect.size.height / 2;
5937 [badge_ drawInRect:Retina(rect)];
5940 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5944 UISetColor(commercial_ ? Purple_ : Black_);
5945 [name_ drawAtPoint:CGPointMake(36, 8) forWidth:(width - (placard_ == nil ? 68 : 94)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
5947 if (placard_ != nil)
5948 [placard_ drawAtPoint:CGPointMake(width - 52, 11)];
5951 - (void) drawNormalContentRect:(CGRect)rect {
5952 bool highlighted(highlighted_);
5953 float width([self bounds].size.width);
5957 rect.size = [(UIImage *) icon_ size];
5959 while (rect.size.width > 32 || rect.size.height > 32) {
5960 rect.size.width /= 2;
5961 rect.size.height /= 2;
5964 rect.origin.x = 25 - rect.size.width / 2;
5965 rect.origin.y = 25 - rect.size.height / 2;
5967 [icon_ drawInRect:Retina(rect)];
5970 if (badge_ != nil) {
5972 rect.size = [(UIImage *) badge_ size];
5974 rect.size.width /= 2;
5975 rect.size.height /= 2;
5977 rect.origin.x = 36 - rect.size.width / 2;
5978 rect.origin.y = 36 - rect.size.height / 2;
5980 [badge_ drawInRect:Retina(rect)];
5983 if (highlighted && kCFCoreFoundationVersionNumber < 800)
5987 UISetColor(commercial_ ? Purple_ : Black_);
5988 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
5989 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
5992 UISetColor(commercial_ ? Purplish_ : Gray_);
5993 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:NSLineBreakByTruncatingTail];
5995 if (placard_ != nil)
5996 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5999 - (void) drawContentRect:(CGRect)rect {
6001 [self drawSummaryContentRect:rect];
6003 [self drawNormalContentRect:rect];
6008 /* Section Cell {{{ */
6009 @interface SectionCell : CyteTableViewCell <
6010 CyteTableViewCellDelegate
6012 _H<NSString> basic_;
6013 _H<NSString> section_;
6015 _H<NSString> count_;
6017 _H<UISwitch> switch_;
6021 - (void) setSection:(Section *)section editing:(BOOL)editing;
6025 @implementation SectionCell
6027 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
6028 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
6029 icon_ = [UIImage imageNamed:@"folder.png"];
6030 // XXX: this initial frame is wrong, but is fixed later
6031 switch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)] autorelease];
6032 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
6034 UIView *content([self contentView]);
6035 CGRect bounds([content bounds]);
6037 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
6038 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6039 [content addSubview:content_];
6040 [content_ setBackgroundColor:[UIColor whiteColor]];
6042 [content_ setDelegate:self];
6046 - (void) onSwitch:(id)sender {
6047 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
6048 if (metadata == nil) {
6049 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
6050 [Sections_ setObject:metadata forKey:basic_];
6053 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
6057 - (void) setSection:(Section *)section editing:(BOOL)editing {
6058 if (editing != editing_) {
6060 [switch_ removeFromSuperview];
6062 [self addSubview:switch_];
6071 if (section == nil) {
6072 name_ = UCLocalize("ALL_PACKAGES");
6075 basic_ = [section name];
6076 section_ = [section localized];
6078 name_ = section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : (NSString *) section_;
6079 count_ = [NSString stringWithFormat:@"%zd", [section count]];
6082 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
6085 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
6086 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
6088 [content_ setNeedsDisplay];
6091 - (void) setFrame:(CGRect)frame {
6092 [super setFrame:frame];
6094 CGRect rect([switch_ frame]);
6095 [switch_ setFrame:CGRectMake(frame.size.width - rect.size.width - 9, 9, rect.size.width, rect.size.height)];
6098 - (NSString *) accessibilityLabel {
6102 - (void) drawContentRect:(CGRect)rect {
6103 bool highlighted(highlighted_ && !editing_);
6105 [icon_ drawInRect:CGRectMake(7, 7, 32, 32)];
6107 if (highlighted && kCFCoreFoundationVersionNumber < 800)
6110 float width(rect.size.width);
6112 width -= 9 + [switch_ frame].size.width;
6116 [name_ drawAtPoint:CGPointMake(48, 12) forWidth:(width - 58) withFont:Font18_ lineBreakMode:NSLineBreakByTruncatingTail];
6118 CGSize size = [count_ sizeWithFont:Font14_];
6120 UISetColor(Folder_);
6122 [count_ drawAtPoint:CGPointMake(Retina(10 + (30 - size.width) / 2), 18) withFont:Font12Bold_];
6128 /* File Table {{{ */
6129 @interface FileTable : CyteViewController <
6130 UITableViewDataSource,
6133 _transient Database *database_;
6134 _H<Package> package_;
6136 _H<NSMutableArray> files_;
6137 _H<UITableView, 2> list_;
6140 - (id) initWithDatabase:(Database *)database;
6141 - (void) setPackage:(Package *)package;
6145 @implementation FileTable
6147 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6148 return files_ == nil ? 0 : [files_ count];
6151 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6155 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6156 static NSString *reuseIdentifier = @"Cell";
6158 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6160 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6161 [cell setFont:[UIFont systemFontOfSize:16]];
6163 [cell setText:[files_ objectAtIndex:indexPath.row]];
6164 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
6169 - (NSURL *) navigationURL {
6170 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/files", [package_ id]]];
6174 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
6175 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6176 [list_ setRowHeight:24.0f];
6177 [(UITableView *) list_ setDataSource:self];
6178 [list_ setDelegate:self];
6179 [self setView:list_];
6182 - (void) viewDidLoad {
6183 [super viewDidLoad];
6185 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
6188 - (void) releaseSubviews {
6194 [super releaseSubviews];
6197 - (id) initWithDatabase:(Database *)database {
6198 if ((self = [super init]) != nil) {
6199 database_ = database;
6203 - (void) setPackage:(Package *)package {
6207 files_ = [NSMutableArray arrayWithCapacity:32];
6209 if (package != nil) {
6211 name_ = [package id];
6213 if (NSArray *files = [package files])
6214 [files_ addObjectsFromArray:files];
6216 if ([files_ count] != 0) {
6217 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
6218 [files_ removeObjectAtIndex:0];
6219 [files_ sortUsingSelector:@selector(compareByPath:)];
6221 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
6222 [stack addObject:@"/"];
6224 for (int i(0), e([files_ count]); i != e; ++i) {
6225 NSString *file = [files_ objectAtIndex:i];
6226 while (![file hasPrefix:[stack lastObject]])
6227 [stack removeLastObject];
6228 NSString *directory = [stack lastObject];
6229 [stack addObject:[file stringByAppendingString:@"/"]];
6230 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
6231 ([stack count] - 2) * 3, "",
6232 [file substringFromIndex:[directory length]]
6241 - (void) reloadData {
6244 [self setPackage:[database_ packageWithName:name_]];
6249 /* Package Controller {{{ */
6250 @interface CYPackageController : CydiaWebViewController <
6251 UIActionSheetDelegate
6253 _transient Database *database_;
6254 _H<Package> package_;
6257 std::vector<std::pair<_H<NSString>, _H<NSString>>> buttons_;
6258 _H<UIBarButtonItem> button_;
6261 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer;
6265 @implementation CYPackageController
6267 - (NSURL *) navigationURL {
6268 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@", (id) name_]];
6271 - (void) _clickButtonWithName:(NSString *)name {
6272 if ([name isEqualToString:@"CLEAR"])
6273 [delegate_ clearPackage:package_];
6274 else if ([name isEqualToString:@"INSTALL"])
6275 [delegate_ installPackage:package_];
6276 else if ([name isEqualToString:@"REINSTALL"])
6277 [delegate_ installPackage:package_];
6278 else if ([name isEqualToString:@"REMOVE"])
6279 [delegate_ removePackage:package_];
6280 else if ([name isEqualToString:@"UPGRADE"])
6281 [delegate_ installPackage:package_];
6282 else _assert(false);
6285 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
6286 NSString *context([sheet context]);
6288 if ([context isEqualToString:@"modify"]) {
6289 if (button != [sheet cancelButtonIndex]) {
6291 [self performSelector:@selector(_clickButtonWithName:) withObject:buttons_[button].first afterDelay:0];
6293 [self _clickButtonWithName:buttons_[button].first];
6296 [sheet dismissWithClickedButtonIndex:button animated:YES];
6300 - (bool) _allowJavaScriptPanel {
6305 - (void) _customButtonClicked {
6306 size_t count(buttons_.size());
6311 [self _clickButtonWithName:buttons_[0].first];
6313 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
6314 for (const auto &button : buttons_)
6315 [buttons addObject:button.second];
6317 UIActionSheet *sheet = [[[UIActionSheet alloc]
6320 cancelButtonTitle:nil
6321 destructiveButtonTitle:nil
6322 otherButtonTitles:nil
6325 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
6327 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
6328 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
6330 [sheet setContext:@"modify"];
6332 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
6336 - (void) reloadButtonClicked {
6337 if (commercial_ && function_ == nil && [package_ uninstalled])
6339 [self customButtonClicked];
6342 - (void) applyLoadingTitle {
6343 // Don't show "Loading" as the title. Ever.
6346 - (UIBarButtonItem *) rightButton {
6351 - (void) setPageColor:(UIColor *)color {
6352 return [super setPageColor:nil];
6355 - (id) initWithDatabase:(Database *)database forPackage:(NSString *)name withReferrer:(NSString *)referrer {
6356 if ((self = [super init]) != nil) {
6357 database_ = database;
6358 name_ = name == nil ? @"" : [NSString stringWithString:name];
6359 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/package/%@", UI_, (id) name_]] withReferrer:referrer];
6363 - (void) reloadData {
6366 package_ = [database_ packageWithName:name_];
6370 if (package_ != nil) {
6371 [(Package *) package_ parse];
6373 commercial_ = [package_ isCommercial];
6375 if ([package_ mode] != nil)
6376 buttons_.push_back(std::make_pair(@"CLEAR", UCLocalize("CLEAR")));
6377 if ([package_ source] == nil);
6378 else if ([package_ upgradableAndEssential:NO])
6379 buttons_.push_back(std::make_pair(@"UPGRADE", UCLocalize("UPGRADE")));
6380 else if ([package_ uninstalled])
6381 buttons_.push_back(std::make_pair(@"INSTALL", UCLocalize("INSTALL")));
6383 buttons_.push_back(std::make_pair(@"REINSTALL", UCLocalize("REINSTALL")));
6384 if (![package_ uninstalled])
6385 buttons_.push_back(std::make_pair(@"REMOVE", UCLocalize("REMOVE")));
6389 switch (buttons_.size()) {
6390 case 0: title = nil; break;
6391 case 1: title = buttons_[0].second; break;
6392 default: title = UCLocalize("MODIFY"); break;
6395 button_ = [[[UIBarButtonItem alloc]
6397 style:UIBarButtonItemStylePlain
6399 action:@selector(customButtonClicked)
6403 - (bool) isLoading {
6404 return commercial_ ? [super isLoading] : false;
6410 /* Package List Controller {{{ */
6411 @interface PackageListController : CyteViewController <
6412 UITableViewDataSource,
6415 _transient Database *database_;
6417 _H<NSArray> packages_;
6418 _H<NSArray> sections_;
6419 _H<UITableView, 2> list_;
6421 _H<NSArray> thumbs_;
6422 std::vector<NSInteger> offset_;
6424 _H<NSString> title_;
6425 unsigned reloading_;
6428 - (id) initWithDatabase:(Database *)database title:(NSString *)title;
6429 - (void) setDelegate:(id)delegate;
6430 - (void) resetCursor;
6433 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages;
6437 @implementation PackageListController
6439 - (NSURL *) referrerURL {
6440 return [self navigationURL];
6443 - (bool) isSummarized {
6447 - (bool) showsSections {
6451 - (void) deselectWithAnimation:(BOOL)animated {
6452 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6455 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration curve:(UIViewAnimationCurve)curve {
6456 CGRect base = [[self view] bounds];
6457 base.size.height -= bounds.size.height;
6458 base.origin = [list_ frame].origin;
6460 [UIView beginAnimations:nil context:NULL];
6461 [UIView setAnimationBeginsFromCurrentState:YES];
6462 [UIView setAnimationCurve:curve];
6463 [UIView setAnimationDuration:duration];
6464 [list_ setFrame:base];
6465 [UIView commitAnimations];
6468 - (void) resizeForKeyboardBounds:(CGRect)bounds duration:(NSTimeInterval)duration {
6469 [self resizeForKeyboardBounds:bounds duration:duration curve:UIViewAnimationCurveLinear];
6472 - (void) resizeForKeyboardBounds:(CGRect)bounds {
6473 [self resizeForKeyboardBounds:bounds duration:0];
6476 - (void) getKeyboardCurve:(UIViewAnimationCurve *)curve duration:(NSTimeInterval *)duration forNotification:(NSNotification *)notification {
6477 if (&UIKeyboardAnimationCurveUserInfoKey == NULL)
6478 *curve = UIViewAnimationCurveEaseInOut;
6480 [[[notification userInfo] objectForKey:UIKeyboardAnimationCurveUserInfoKey] getValue:curve];
6482 if (&UIKeyboardAnimationDurationUserInfoKey == NULL)
6485 [[[notification userInfo] objectForKey:UIKeyboardAnimationDurationUserInfoKey] getValue:duration];
6488 - (void) keyboardWillShow:(NSNotification *)notification {
6491 [[[notification userInfo] objectForKey:UIKeyboardBoundsUserInfoKey] getValue:&bounds];
6492 [[[notification userInfo] objectForKey:UIKeyboardCenterEndUserInfoKey] getValue:¢er];
6494 NSTimeInterval duration;
6495 UIViewAnimationCurve curve;
6496 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6498 CGRect kbframe = CGRectMake(Retina(center.x - bounds.size.width / 2), Retina(center.y - bounds.size.height / 2), bounds.size.width, bounds.size.height);
6499 UIViewController *base = self;
6500 while ([base parentOrPresentingViewController] != nil)
6501 base = [base parentOrPresentingViewController];
6502 CGRect viewframe = [[base view] convertRect:[list_ frame] fromView:[list_ superview]];
6503 CGRect intersection = CGRectIntersection(viewframe, kbframe);
6505 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6506 intersection.size.height += CYStatusBarHeight();
6508 [self resizeForKeyboardBounds:intersection duration:duration curve:curve];
6511 - (void) keyboardWillHide:(NSNotification *)notification {
6512 NSTimeInterval duration;
6513 UIViewAnimationCurve curve;
6514 [self getKeyboardCurve:&curve duration:&duration forNotification:notification];
6516 [self resizeForKeyboardBounds:CGRectZero duration:duration curve:curve];
6519 - (void) viewWillAppear:(BOOL)animated {
6520 [super viewWillAppear:animated];
6522 [self resizeForKeyboardBounds:CGRectZero];
6523 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
6524 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
6527 - (void) viewWillDisappear:(BOOL)animated {
6528 [super viewWillDisappear:animated];
6530 [self resizeForKeyboardBounds:CGRectZero];
6531 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillShowNotification object:nil];
6532 [[NSNotificationCenter defaultCenter] removeObserver:self name:UIKeyboardWillHideNotification object:nil];
6535 - (void) viewDidAppear:(BOOL)animated {
6536 [super viewDidAppear:animated];
6537 [self deselectWithAnimation:animated];
6540 - (void) didSelectPackage:(Package *)package {
6541 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_ forPackage:[package id] withReferrer:[[self referrerURL] absoluteString]] autorelease]);
6542 [view setDelegate:delegate_];
6543 [[self navigationController] pushViewController:view animated:YES];
6546 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6547 NSInteger count([sections_ count]);
6548 return count == 0 ? 1 : count;
6551 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6552 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
6554 return [[sections_ objectAtIndex:section] name];
6557 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6558 if ([sections_ count] == 0)
6560 return [[sections_ objectAtIndex:section] count];
6563 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6564 @synchronized (database_) {
6565 if ([database_ era] != era_)
6568 Section *section([sections_ objectAtIndex:[path section]]);
6569 NSInteger row([path row]);
6570 Package *package([packages_ objectAtIndex:([section row] + row)]);
6571 return [[package retain] autorelease];
6574 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6575 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6577 cell = [[[PackageCell alloc] init] autorelease];
6579 Package *package([database_ packageWithName:[[self packageAtIndexPath:path] id]]);
6580 [cell setPackage:package asSummary:[self isSummarized]];
6584 - (void) tableView:(UITableView *)table didSelectRowAtIndexPath:(NSIndexPath *)path {
6585 Package *package([self packageAtIndexPath:path]);
6586 package = [database_ packageWithName:[package id]];
6587 [self didSelectPackage:package];
6590 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
6594 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
6595 return offset_[index];
6598 - (void) updateHeight {
6599 [list_ setRowHeight:([self isSummarized] ? 38 : 73)];
6602 - (id) initWithDatabase:(Database *)database title:(NSString *)title {
6603 if ((self = [super init]) != nil) {
6604 database_ = database;
6605 title_ = [title copy];
6606 [[self navigationItem] setTitle:title_];
6611 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
6612 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
6613 [self setView:view];
6615 list_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain] autorelease];
6616 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6617 [view addSubview:list_];
6619 // XXX: is 20 the most optimal number here?
6620 [list_ setSectionIndexMinimumDisplayRowCount:20];
6622 [(UITableView *) list_ setDataSource:self];
6623 [list_ setDelegate:self];
6625 [self updateHeight];
6628 - (void) releaseSubviews {
6637 [super releaseSubviews];
6640 - (void) setDelegate:(id)delegate {
6641 delegate_ = delegate;
6644 - (bool) shouldYield {
6648 - (bool) shouldBlock {
6652 - (NSMutableArray *) _reloadPackages {
6653 @synchronized (database_) {
6654 era_ = [database_ era];
6655 NSArray *packages([database_ packages]);
6657 return [NSMutableArray arrayWithArray:packages];
6660 - (void) _reloadData {
6661 if (reloading_ != 0) {
6666 NSMutableArray *packages;
6669 if ([self shouldYield]) {
6673 if (![self shouldBlock])
6676 hud = [delegate_ addProgressHUD];
6677 [hud setText:UCLocalize("LOADING")];
6681 packages = [self yieldToSelector:@selector(_reloadPackages)];
6684 [delegate_ removeProgressHUD:hud];
6685 } while (reloading_ == 2);
6687 packages = [self _reloadPackages];
6690 @synchronized (database_) {
6691 if (era_ != [database_ era])
6698 packages_ = packages;
6700 if ([self showsSections])
6701 sections_ = [self sectionsForPackages:packages];
6703 Section *section([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6704 [section setCount:[packages_ count]];
6705 sections_ = [NSArray arrayWithObject:section];
6708 [self updateHeight];
6710 _profile(PackageTable$reloadData$List)
6711 [(UITableView *) list_ setDataSource:self];
6719 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
6720 Section *prefix([[[Section alloc] initWithName:nil row:0 localize:NO] autorelease]);
6721 size_t end([packages count]);
6723 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
6724 Section *section(prefix);
6726 thumbs_ = CollationThumbs_;
6727 offset_ = CollationOffset_;
6730 size_t offsets([CollationStarts_ count]);
6732 NSString *start([CollationStarts_ objectAtIndex:offset]);
6733 size_t length([start length]);
6735 for (size_t index(0); index != end; ++index) {
6737 Package *package([packages objectAtIndex:index]);
6738 NSString *name(PackageName(package, @selector(cyname)));
6740 //while ([start compare:name options:NSNumericSearch range:NSMakeRange(0, length) locale:CollationLocale_] != NSOrderedDescending) {
6741 while (StringNameCompare(start, name, length) != kCFCompareGreaterThan) {
6742 NSString *title([CollationTitles_ objectAtIndex:offset]);
6743 section = [[[Section alloc] initWithName:title row:index localize:NO] autorelease];
6744 [sections addObject:section];
6746 start = ++offset == offsets ? nil : [CollationStarts_ objectAtIndex:offset];
6749 length = [start length];
6753 [section addToCount];
6756 for (; offset != offsets; ++offset) {
6757 NSString *title([CollationTitles_ objectAtIndex:offset]);
6758 Section *section([[[Section alloc] initWithName:title row:end localize:NO] autorelease]);
6759 [sections addObject:section];
6762 if ([prefix count] != 0) {
6763 Section *suffix([sections lastObject]);
6764 [prefix setName:[suffix name]];
6765 [suffix setName:nil];
6766 [sections insertObject:prefix atIndex:(offsets - 1)];
6772 - (void) reloadData {
6775 if ([self shouldYield])
6776 [self performSelector:@selector(_reloadData) withObject:nil afterDelay:0];
6781 - (void) resetCursor {
6782 [list_ scrollRectToVisible:CGRectMake(0, 0, 1, 1) animated:NO];
6785 - (void) clearData {
6786 [self updateHeight];
6788 [list_ setDataSource:nil];
6796 /* Filtered Package List Controller {{{ */
6797 typedef Function<bool, Package *> PackageFilter;
6798 typedef Function<void, NSMutableArray *> PackageSorter;
6799 @interface FilteredPackageListController : PackageListController {
6800 PackageFilter filter_;
6801 PackageSorter sorter_;
6804 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter;
6806 - (void) setFilter:(PackageFilter)filter;
6807 - (void) setSorter:(PackageSorter)sorter;
6811 @implementation FilteredPackageListController
6813 - (void) setFilter:(PackageFilter)filter {
6814 @synchronized (self) {
6818 - (void) setSorter:(PackageSorter)sorter {
6819 @synchronized (self) {
6823 - (NSMutableArray *) _reloadPackages {
6824 @synchronized (database_) {
6825 era_ = [database_ era];
6827 NSArray *packages([database_ packages]);
6828 NSMutableArray *filtered([NSMutableArray arrayWithCapacity:[packages count]]);
6830 PackageFilter filter;
6831 PackageSorter sorter;
6833 @synchronized (self) {
6838 _profile(PackageTable$reloadData$Filter)
6839 for (Package *package in packages)
6840 if ([package valid] && filter(package))
6841 [filtered addObject:package];
6849 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(PackageFilter)filter {
6850 if ((self = [super initWithDatabase:database title:title]) != nil) {
6851 [self setFilter:filter];
6858 /* Home Controller {{{ */
6859 @interface HomeController : CydiaWebViewController {
6860 CFRunLoopRef runloop_;
6861 SCNetworkReachabilityRef reachability_;
6866 @implementation HomeController
6868 static void HomeControllerReachabilityCallback(SCNetworkReachabilityRef reachability, SCNetworkReachabilityFlags flags, void *info) {
6869 [(HomeController *) info dispatchEvent:@"CydiaReachabilityCallback"];
6873 if ((self = [super init]) != nil) {
6874 [self setURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/home/", UI_]]];
6877 reachability_ = SCNetworkReachabilityCreateWithName(kCFAllocatorDefault, "cydia.saurik.com");
6878 if (reachability_ != NULL) {
6879 SCNetworkReachabilityContext context = {0, self, NULL, NULL, NULL};
6880 SCNetworkReachabilitySetCallback(reachability_, HomeControllerReachabilityCallback, &context);
6882 CFRunLoopRef runloop(CFRunLoopGetCurrent());
6883 if (SCNetworkReachabilityScheduleWithRunLoop(reachability_, runloop, kCFRunLoopDefaultMode))
6890 if (reachability_ != NULL && runloop_ != NULL)
6891 SCNetworkReachabilityUnscheduleFromRunLoop(reachability_, runloop_, kCFRunLoopDefaultMode);
6895 - (NSURL *) navigationURL {
6896 return [NSURL URLWithString:@"cydia://home"];
6899 - (void) aboutButtonClicked {
6900 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
6902 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
6903 [alert addButtonWithTitle:UCLocalize("CLOSE")];
6904 [alert setCancelButtonIndex:0];
6907 @"Copyright \u00a9 2008-2014\n"
6910 "Jay Freeman (saurik)\n"
6911 "saurik@saurik.com\n"
6912 "http://www.saurik.com/"
6918 - (UIBarButtonItem *) leftButton {
6919 return [[[UIBarButtonItem alloc]
6920 initWithTitle:UCLocalize("ABOUT")
6921 style:UIBarButtonItemStylePlain
6923 action:@selector(aboutButtonClicked)
6930 /* Cydia Navigation Controller Interface {{{ */
6931 @interface UINavigationController (Cydia)
6933 - (NSArray *) navigationURLCollection;
6934 - (void) unloadData;
6939 /* Cydia Tab Bar Controller {{{ */
6940 @interface CydiaTabBarController : CyteTabBarController <
6941 UITabBarControllerDelegate,
6944 _transient Database *database_;
6946 _H<UIActivityIndicatorView> indicator_;
6949 // XXX: ok, "updatedelegate_"?...
6950 _transient NSObject<CydiaDelegate> *updatedelegate_;
6953 - (NSArray *) navigationURLCollection;
6954 - (void) beginUpdate;
6959 @implementation CydiaTabBarController
6961 - (NSArray *) navigationURLCollection {
6962 NSMutableArray *items([NSMutableArray array]);
6964 // XXX: Should this deal with transient view controllers?
6965 for (id navigation in [self viewControllers]) {
6966 NSArray *stack = [navigation performSelector:@selector(navigationURLCollection)];
6968 [items addObject:stack];
6974 - (id) initWithDatabase:(Database *)database {
6975 if ((self = [super init]) != nil) {
6976 database_ = database;
6977 [self setDelegate:self];
6979 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteTiny] autorelease];
6980 [indicator_ setOrigin:CGPointMake(kCFCoreFoundationVersionNumber >= 800 ? 2 : 4, 2)];
6982 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6986 - (void) setUpdate:(NSDate *)date {
6990 - (void) beginUpdate {
6994 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
6995 UITabBarItem *item([controller tabBarItem]);
6997 [item setBadgeValue:@""];
6998 UIView *badge(MSHookIvar<UIView *>([item view], "_badge"));
7000 [indicator_ startAnimating];
7001 [badge addSubview:indicator_];
7003 [updatedelegate_ retainNetworkActivityIndicator];
7007 detachNewThreadSelector:@selector(performUpdate)
7013 - (void) performUpdate {
7014 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
7016 SourceStatus status(self, database_);
7017 [database_ updateWithStatus:status];
7020 performSelectorOnMainThread:@selector(completeUpdate)
7028 - (void) stopUpdateWithSelector:(SEL)selector {
7030 [updatedelegate_ releaseNetworkActivityIndicator];
7032 UIViewController *controller([[self viewControllers] objectAtIndex:1]);
7033 [[controller tabBarItem] setBadgeValue:nil];
7035 [indicator_ removeFromSuperview];
7036 [indicator_ stopAnimating];
7038 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
7041 - (void) completeUpdate {
7044 [self stopUpdateWithSelector:@selector(reloadData)];
7047 - (void) cancelUpdate {
7048 [self stopUpdateWithSelector:@selector(updateDataAndLoad)];
7051 - (void) cancelPressed {
7052 [self cancelUpdate];
7059 - (bool) isSourceCancelled {
7063 - (void) startSourceFetch:(NSString *)uri {
7066 - (void) stopSourceFetch:(NSString *)uri {
7069 - (void) setUpdateDelegate:(id)delegate {
7070 updatedelegate_ = delegate;
7076 /* Cydia Navigation Controller Implementation {{{ */
7077 @implementation UINavigationController (Cydia)
7079 - (NSArray *) navigationURLCollection {
7080 NSMutableArray *stack([NSMutableArray array]);
7082 for (CyteViewController *controller in [self viewControllers]) {
7083 NSString *url = [[controller navigationURL] absoluteString];
7085 [stack addObject:url];
7091 - (void) reloadData {
7094 UIViewController *visible([self visibleViewController]);
7096 [visible reloadData];
7098 // on the iPad, this view controller is ALSO visible. :(
7100 if (UIViewController *modal = [self modalViewController])
7101 if ([modal modalPresentationStyle] == UIModalPresentationFormSheet)
7102 if (UIViewController *top = [self topViewController])
7107 - (void) unloadData {
7108 for (CyteViewController *page in [self viewControllers])
7117 /* Cydia:// Protocol {{{ */
7118 @interface CydiaURLProtocol : NSURLProtocol {
7123 @implementation CydiaURLProtocol
7125 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
7126 NSURL *url([request URL]);
7130 NSString *scheme([[url scheme] lowercaseString]);
7131 if (scheme != nil && [scheme isEqualToString:@"cydia"])
7133 if ([[url absoluteString] hasPrefix:@"about:cydia-"])
7139 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
7143 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
7144 id<NSURLProtocolClient> client([self client]);
7146 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
7148 NSData *data(UIImagePNGRepresentation(icon));
7150 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
7151 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
7152 [client URLProtocol:self didLoadData:data];
7153 [client URLProtocolDidFinishLoading:self];
7157 - (void) startLoading {
7158 id<NSURLProtocolClient> client([self client]);
7159 NSURLRequest *request([self request]);
7161 NSURL *url([request URL]);
7162 NSString *href([url absoluteString]);
7163 NSString *scheme([[url scheme] lowercaseString]);
7167 if ([scheme isEqualToString:@"cydia"])
7168 path = [href substringFromIndex:8];
7169 else if ([scheme isEqualToString:@"about"])
7170 path = [href substringFromIndex:12];
7171 else _assert(false);
7173 NSRange slash([path rangeOfString:@"/"]);
7176 if (slash.location == NSNotFound) {
7180 command = [path substringToIndex:slash.location];
7181 path = [path substringFromIndex:(slash.location + 1)];
7184 Database *database([Database sharedInstance]);
7186 if ([command isEqualToString:@"package-icon"]) {
7189 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7190 Package *package([database packageWithName:path]);
7194 UIImage *icon([package icon]);
7195 [self _returnPNGWithImage:icon forRequest:request];
7196 } else if ([command isEqualToString:@"uikit-image"]) {
7199 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7200 UIImage *icon(_UIImageWithName(path));
7201 [self _returnPNGWithImage:icon forRequest:request];
7202 } else if ([command isEqualToString:@"section-icon"]) {
7205 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
7206 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, [path stringByReplacingOccurrencesOfString:@" " withString:@"_"]]]);
7208 icon = [UIImage imageNamed:@"unknown.png"];
7209 [self _returnPNGWithImage:icon forRequest:request];
7211 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
7215 - (void) stopLoading {
7221 /* Section Controller {{{ */
7222 @interface SectionController : FilteredPackageListController {
7224 _H<NSString> section_;
7227 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section;
7231 @implementation SectionController
7233 - (NSURL *) referrerURL {
7234 NSString *name(section_);
7235 name = name ?: @"*";
7236 NSString *key(key_);
7238 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/sections/%@/%@", UI_, [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7241 - (NSURL *) navigationURL {
7242 NSString *name(section_);
7243 name = name ?: @"*";
7244 NSString *key(key_);
7246 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sections/%@/%@", [key stringByAddingPercentEscapesIncludingReserved], [name stringByAddingPercentEscapesIncludingReserved]]];
7249 - (id) initWithDatabase:(Database *)database source:(Source *)source section:(NSString *)section {
7252 title = UCLocalize("ALL_PACKAGES");
7253 else if (![section isEqual:@""])
7254 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(section) value:nil table:@"Sections"];
7256 title = UCLocalize("NO_SECTION");
7258 if ((self = [super initWithDatabase:database title:title]) != nil) {
7259 key_ = [source key];
7264 - (void) reloadData {
7265 Source *source([database_ sourceWithKey:key_]);
7266 _H<NSString> name(section_);
7268 [self setFilter:[=](Package *package) {
7269 NSString *section([package section]);
7273 section == nil && [name length] == 0 ||
7274 [name isEqualToString:section]
7277 [package source] == source
7278 ) && [package visible];
7286 /* Sections Controller {{{ */
7287 @interface SectionsController : CyteViewController <
7288 UITableViewDataSource,
7291 _transient Database *database_;
7293 _H<NSMutableArray> sections_;
7294 _H<NSMutableArray> filtered_;
7295 _H<UITableView, 2> list_;
7298 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7299 - (void) editButtonClicked;
7303 @implementation SectionsController
7305 - (NSURL *) navigationURL {
7306 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://sources/%@", [key_ stringByAddingPercentEscapesIncludingReserved]]];
7309 - (Source *) source {
7312 return [database_ sourceWithKey:key_];
7315 - (void) updateNavigationItem {
7316 [[self navigationItem] setTitle:[self isEditing] ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
7317 if ([sections_ count] == 0) {
7318 [[self navigationItem] setRightBarButtonItem:nil];
7320 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
7321 initWithBarButtonSystemItem:([self isEditing] ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
7323 action:@selector(editButtonClicked)
7324 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
7328 - (void) setEditing:(BOOL)editing animated:(BOOL)animated {
7329 [super setEditing:editing animated:animated];
7334 [delegate_ updateData];
7336 [self updateNavigationItem];
7339 - (void) viewDidAppear:(BOOL)animated {
7340 [super viewDidAppear:animated];
7341 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7344 - (void) viewWillDisappear:(BOOL)animated {
7345 [super viewWillDisappear:animated];
7346 [self setEditing:NO];
7349 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
7350 Section *section = nil;
7351 int index = [indexPath row];
7352 if (![self isEditing]) {
7355 section = [filtered_ objectAtIndex:index];
7357 section = [sections_ objectAtIndex:index];
7362 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7363 if ([self isEditing])
7364 return [sections_ count];
7366 return [filtered_ count] + 1;
7369 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
7373 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7374 static NSString *reuseIdentifier = @"SectionCell";
7376 SectionCell *cell = (SectionCell *)[tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
7378 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
7380 [cell setSection:[self sectionAtIndexPath:indexPath] editing:[self isEditing]];
7385 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7386 if ([self isEditing])
7389 Section *section = [self sectionAtIndexPath:indexPath];
7391 SectionController *controller = [[[SectionController alloc]
7392 initWithDatabase:database_
7393 source:[self source]
7394 section:[section name]
7396 [controller setDelegate:delegate_];
7398 [[self navigationController] pushViewController:controller animated:YES];
7402 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease];
7403 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7404 [list_ setRowHeight:46];
7405 [(UITableView *) list_ setDataSource:self];
7406 [list_ setDelegate:self];
7407 [self setView:list_];
7410 - (void) viewDidLoad {
7411 [super viewDidLoad];
7413 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
7416 - (void) releaseSubviews {
7422 [super releaseSubviews];
7425 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7426 if ((self = [super init]) != nil) {
7427 database_ = database;
7428 key_ = [source key];
7432 - (void) reloadData {
7435 NSArray *packages = [database_ packages];
7437 sections_ = [NSMutableArray arrayWithCapacity:16];
7438 filtered_ = [NSMutableArray arrayWithCapacity:16];
7440 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
7442 Source *source([self source]);
7445 for (Package *package in packages) {
7446 if (source != nil && [package source] != source)
7449 NSString *name([package section]);
7450 NSString *key(name == nil ? @"" : name);
7454 _profile(SectionsView$reloadData$Section)
7455 section = [sections objectForKey:key];
7456 if (section == nil) {
7457 _profile(SectionsView$reloadData$Section$Allocate)
7458 section = [[[Section alloc] initWithName:key localize:YES] autorelease];
7459 [sections setObject:section forKey:key];
7464 [section addToCount];
7466 _profile(SectionsView$reloadData$Filter)
7467 if (![package valid] || ![package visible])
7475 [sections_ addObjectsFromArray:[sections allValues]];
7477 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
7479 for (Section *section in (id) sections_) {
7480 size_t count([section row]);
7484 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
7485 [section setCount:count];
7486 [filtered_ addObject:section];
7489 [self updateNavigationItem];
7494 - (void) editButtonClicked {
7495 [self setEditing:![self isEditing] animated:YES];
7501 /* Changes Controller {{{ */
7502 @interface ChangesController : FilteredPackageListController {
7506 - (id) initWithDatabase:(Database *)database;
7510 @implementation ChangesController
7512 - (NSURL *) referrerURL {
7513 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/changes/", UI_]];
7516 - (NSURL *) navigationURL {
7517 return [NSURL URLWithString:@"cydia://changes"];
7520 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
7521 @synchronized (database_) {
7522 if ([database_ era] != era_)
7525 NSUInteger sectionIndex([path section]);
7526 if (sectionIndex >= [sections_ count])
7528 Section *section([sections_ objectAtIndex:sectionIndex]);
7529 NSInteger row([path row]);
7530 return [[[packages_ objectAtIndex:([section row] + row)] retain] autorelease];
7533 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7534 NSString *context([alert context]);
7536 if ([context isEqualToString:@"norefresh"])
7537 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7540 - (void) setLeftBarButtonItem {
7541 if ([delegate_ updating])
7542 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7543 initWithTitle:UCLocalize("CANCEL")
7544 style:UIBarButtonItemStyleDone
7546 action:@selector(cancelButtonClicked)
7547 ] autorelease] animated:YES];
7549 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7550 initWithTitle:UCLocalize("REFRESH")
7551 style:UIBarButtonItemStylePlain
7553 action:@selector(refreshButtonClicked)
7554 ] autorelease] animated:YES];
7557 - (void) refreshButtonClicked {
7558 if ([delegate_ requestUpdate])
7559 [self setLeftBarButtonItem];
7562 - (void) cancelButtonClicked {
7563 [delegate_ cancelUpdate];
7566 - (void) upgradeButtonClicked {
7567 [delegate_ distUpgrade];
7568 [[self navigationItem] setRightBarButtonItem:nil animated:YES];
7571 - (bool) shouldYield {
7575 - (bool) shouldBlock {
7579 - (void) useFilter {
7580 @synchronized (self) {
7581 [self setFilter:[](Package *package) {
7582 return [package upgradableAndEssential:YES] || [package visible];
7585 [self setSorter:[](NSMutableArray *packages) {
7586 [packages radixSortUsingFunction:reinterpret_cast<MenesRadixSortFunction>(&PackageChangesRadix) withContext:NULL];
7590 - (id) initWithDatabase:(Database *)database {
7591 if ((self = [super initWithDatabase:database title:UCLocalize("CHANGES")]) != nil) {
7596 - (void) viewDidLoad {
7597 [super viewDidLoad];
7598 [self setLeftBarButtonItem];
7601 - (void) viewWillAppear:(BOOL)animated {
7602 [super viewWillAppear:animated];
7603 [self setLeftBarButtonItem];
7606 - (void) reloadData {
7607 [self setLeftBarButtonItem];
7611 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
7612 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
7614 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
7615 Section *ignored = nil;
7616 Section *section = nil;
7620 bool unseens = false;
7622 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7624 for (size_t offset = 0, count = [packages count]; offset != count; ++offset) {
7625 Package *package = [packages objectAtIndex:offset];
7627 BOOL uae = [package upgradableAndEssential:YES];
7631 time_t seen([package seen]);
7633 if (section == nil || last != seen) {
7637 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7640 _profile(ChangesController$reloadData$Allocate)
7641 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7642 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7643 [sections addObject:section];
7647 [section addToCount];
7648 } else if ([package ignored]) {
7649 if (ignored == nil) {
7650 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7652 [ignored addToCount];
7655 [upgradable addToCount];
7660 CFRelease(formatter);
7663 Section *last = [sections lastObject];
7664 size_t count = [last count];
7665 [packages removeObjectsInRange:NSMakeRange([packages count] - count, count)];
7666 [sections removeLastObject];
7669 if ([ignored count] != 0)
7670 [sections insertObject:ignored atIndex:0];
7672 [sections insertObject:upgradable atIndex:0];
7676 [[self navigationItem] setRightBarButtonItem:(upgrades_ == 0 ? nil : [[[UIBarButtonItem alloc]
7677 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7678 style:UIBarButtonItemStylePlain
7680 action:@selector(upgradeButtonClicked)
7681 ] autorelease]) animated:YES];
7688 /* Search Controller {{{ */
7689 @interface SearchController : FilteredPackageListController <
7692 _H<UISearchBar, 1> search_;
7697 - (id) initWithDatabase:(Database *)database query:(NSString *)query;
7698 - (void) reloadData;
7702 @implementation SearchController
7704 - (NSURL *) referrerURL {
7705 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/search?q=%@", UI_, [([search_ text] ?: @"") stringByAddingPercentEscapesIncludingReserved]]];
7708 - (NSURL *) navigationURL {
7709 if ([search_ text] == nil || [[search_ text] isEqualToString:@""])
7710 return [NSURL URLWithString:@"cydia://search"];
7712 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://search/%@", [[search_ text] stringByAddingPercentEscapesIncludingReserved]]];
7715 - (NSArray *) termsForQuery:(NSString *)query {
7716 NSMutableArray *terms([NSMutableArray arrayWithCapacity:2]);
7717 for (NSString *component in [query componentsSeparatedByString:@" "])
7718 if ([component length] != 0)
7719 [terms addObject:component];
7724 - (void) useSearch {
7725 _H<NSArray> query([self termsForQuery:[search_ text]]);
7728 @synchronized (self) {
7729 [self setFilter:[=](Package *package) {
7730 if (![package unfiltered])
7732 if (![package matches:query])
7737 [self setSorter:[](NSMutableArray *packages) {
7738 [packages radixSortUsingSelector:@selector(rank)];
7746 - (void) usePrefix:(NSString *)prefix {
7747 _H<NSString> query(prefix);
7750 @synchronized (self) {
7751 [self setFilter:[=](Package *package) {
7752 if ([query length] == 0)
7754 if (![package unfiltered])
7756 if ([[package name] compare:query options:MatchCompareOptions_ range:NSMakeRange(0, [query length])] != NSOrderedSame)
7761 [self setSorter:nullptr];
7767 - (void) searchBarTextDidBeginEditing:(UISearchBar *)searchBar {
7769 [self usePrefix:[search_ text]];
7772 - (void) searchBarButtonClicked:(UISearchBar *)searchBar {
7773 [search_ resignFirstResponder];
7777 - (void) searchBarCancelButtonClicked:(UISearchBar *)searchBar {
7778 [search_ setText:@""];
7779 [self searchBarButtonClicked:searchBar];
7782 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7783 [self searchBarButtonClicked:searchBar];
7786 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7787 [self usePrefix:text];
7790 - (bool) shouldYield {
7794 - (bool) shouldBlock {
7798 - (bool) isSummarized {
7802 - (bool) showsSections {
7806 - (id) initWithDatabase:(Database *)database query:(NSString *)query {
7807 if ((self = [super initWithDatabase:database title:UCLocalize("SEARCH")])) {
7808 search_ = [[[UISearchBar alloc] init] autorelease];
7809 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7810 [search_ setDelegate:self];
7812 UITextField *textField;
7813 if ([search_ respondsToSelector:@selector(searchField)])
7814 textField = [search_ searchField];
7816 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7818 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7819 [textField setEnablesReturnKeyAutomatically:NO];
7820 [[self navigationItem] setTitleView:textField];
7823 [search_ setText:query];
7828 - (void) viewDidAppear:(BOOL)animated {
7829 [super viewDidAppear:animated];
7831 if (!searchloaded_) {
7832 searchloaded_ = YES;
7833 [search_ setFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7834 [search_ layoutSubviews];
7837 if ([self isSummarized])
7838 [search_ becomeFirstResponder];
7841 - (void) reloadData {
7846 - (void) didSelectPackage:(Package *)package {
7847 [search_ resignFirstResponder];
7848 [super didSelectPackage:package];
7853 /* Package Settings Controller {{{ */
7854 @interface PackageSettingsController : CyteViewController <
7855 UITableViewDataSource,
7858 _transient Database *database_;
7860 _H<Package> package_;
7861 _H<UITableView, 2> table_;
7862 _H<UISwitch> subscribedSwitch_;
7863 _H<UISwitch> ignoredSwitch_;
7864 _H<UITableViewCell> subscribedCell_;
7865 _H<UITableViewCell> ignoredCell_;
7868 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7872 @implementation PackageSettingsController
7874 - (NSURL *) navigationURL {
7875 return [NSURL URLWithString:[NSString stringWithFormat:@"cydia://package/%@/settings", (id) name_]];
7878 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7879 if (package_ == nil)
7882 if ([package_ installed] == nil)
7888 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7889 if (package_ == nil)
7892 // both sections contain just one item right now.
7896 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7900 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7902 return UCLocalize("SHOW_ALL_CHANGES_EX");
7904 return UCLocalize("IGNORE_UPGRADES_EX");
7907 - (void) onSubscribed:(id)control {
7908 bool value([control isOn]);
7909 if (package_ == nil)
7911 if ([package_ setSubscribed:value])
7912 [delegate_ updateData];
7915 - (void) _updateIgnored {
7916 const char *package([name_ UTF8String]);
7917 bool on([ignoredSwitch_ isOn]);
7919 pid_t pid(ExecFork());
7921 FILE *dpkg(popen("/usr/libexec/cydo --set-selections", "w"));
7922 fwrite(package, strlen(package), 1, dpkg);
7925 fwrite(" hold\n", 6, 1, dpkg);
7927 fwrite(" install\n", 9, 1, dpkg);
7935 - (void) onIgnored:(id)control {
7936 NSInvocation *invocation([NSInvocation invocationWithMethodSignature:[self methodSignatureForSelector:@selector(_updateIgnored)]]);
7937 [invocation setTarget:self];
7938 [invocation setSelector:@selector(_updateIgnored)];
7940 [delegate_ reloadDataWithInvocation:invocation];
7943 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7944 if (package_ == nil)
7947 switch ([indexPath section]) {
7948 case 0: return subscribedCell_;
7949 case 1: return ignoredCell_;
7958 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
7959 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
7960 [self setView:view];
7962 table_ = [[[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped] autorelease];
7963 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7964 [(UITableView *) table_ setDataSource:self];
7965 [table_ setDelegate:self];
7966 [view addSubview:table_];
7968 subscribedSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7969 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7970 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7972 ignoredSwitch_ = [[[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)] autorelease];
7973 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7974 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7976 subscribedCell_ = [[[UITableViewCell alloc] init] autorelease];
7977 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7978 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7979 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7981 ignoredCell_ = [[[UITableViewCell alloc] init] autorelease];
7982 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7983 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7984 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7987 - (void) viewDidLoad {
7988 [super viewDidLoad];
7990 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7993 - (void) releaseSubviews {
7995 subscribedCell_ = nil;
7997 ignoredSwitch_ = nil;
7998 subscribedSwitch_ = nil;
8000 [super releaseSubviews];
8003 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
8004 if ((self = [super init]) != nil) {
8005 database_ = database;
8010 - (void) reloadData {
8013 package_ = [database_ packageWithName:name_];
8015 if (package_ != nil) {
8016 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
8017 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
8018 } // XXX: what now, G?
8020 [table_ reloadData];
8026 /* Installed Controller {{{ */
8027 @interface InstalledController : FilteredPackageListController {
8031 - (id) initWithDatabase:(Database *)database;
8032 - (void) queueStatusDidChange;
8036 @implementation InstalledController
8038 - (NSURL *) referrerURL {
8039 return [NSURL URLWithString:[NSString stringWithFormat:@"%@/#!/installed/", UI_]];
8042 - (NSURL *) navigationURL {
8043 return [NSURL URLWithString:@"cydia://installed"];
8046 - (void) useRecent {
8049 @synchronized (self) {
8050 [self setFilter:[](Package *package) {
8051 return ![package uninstalled] && package->role_ < 7;
8054 [self setSorter:[](NSMutableArray *packages) {
8055 [packages radixSortUsingSelector:@selector(recent)];
8059 - (void) useFilter:(UISegmentedControl *)segmented {
8060 NSInteger selected([segmented selectedSegmentIndex]);
8062 return [self useRecent];
8063 bool simple(selected == 0);
8066 @synchronized (self) {
8067 [self setFilter:[=](Package *package) {
8068 return ![package uninstalled] && package->role_ <= (simple ? 1 : 3);
8071 [self setSorter:nullptr];
8074 - (NSArray *) sectionsForPackages:(NSMutableArray *)packages {
8076 return [super sectionsForPackages:packages];
8078 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterLongStyle, kCFDateFormatterNoStyle));
8080 NSMutableArray *sections([NSMutableArray arrayWithCapacity:16]);
8081 Section *section(nil);
8084 for (size_t offset(0), count([packages count]); offset != count; ++offset) {
8085 Package *package([packages objectAtIndex:offset]);
8087 time_t upgraded([package upgraded]);
8088 if (upgraded < 1168364520)
8091 upgraded -= upgraded % (60 * 60 * 24);
8093 if (section == nil || upgraded != last) {
8098 continue; // XXX: name = UCLocalize("...");
8100 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:upgraded]);
8104 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
8105 [sections addObject:section];
8108 [section addToCount];
8111 CFRelease(formatter);
8115 - (id) initWithDatabase:(Database *)database {
8116 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED")]) != nil) {
8117 UISegmentedControl *segmented([[[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:UCLocalize("USER"), UCLocalize("EXPERT"), UCLocalize("RECENT"), nil]] autorelease]);
8118 [segmented setSelectedSegmentIndex:0];
8119 [segmented setSegmentedControlStyle:UISegmentedControlStyleBar];
8120 [[self navigationItem] setTitleView:segmented];
8122 [segmented addTarget:self action:@selector(modeChanged:) forEvents:UIControlEventValueChanged];
8123 [self useFilter:segmented];
8125 [self queueStatusDidChange];
8130 - (void) queueButtonClicked {
8135 - (void) queueStatusDidChange {
8138 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8139 initWithTitle:UCLocalize("QUEUE")
8140 style:UIBarButtonItemStyleDone
8142 action:@selector(queueButtonClicked)
8145 [[self navigationItem] setRightBarButtonItem:nil];
8150 - (void) modeChanged:(UISegmentedControl *)segmented {
8151 [self useFilter:segmented];
8158 /* Source Cell {{{ */
8159 @interface SourceCell : CyteTableViewCell <
8160 CyteTableViewCellDelegate,
8163 _H<Source, 1> source_;
8166 _H<NSString> origin_;
8167 _H<NSString> label_;
8168 _H<UIActivityIndicatorView> indicator_;
8171 - (void) setSource:(Source *)source;
8172 - (void) setFetch:(NSNumber *)fetch;
8176 @implementation SourceCell
8178 - (void) _setImage:(NSArray *)data {
8179 if ([url_ isEqual:[data objectAtIndex:0]]) {
8180 icon_ = [data objectAtIndex:1];
8181 [content_ setNeedsDisplay];
8185 - (void) _setSource:(NSURL *) url {
8186 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
8188 if (NSData *data = [NSURLConnection
8189 sendSynchronousRequest:[NSURLRequest
8191 cachePolicy:NSURLRequestUseProtocolCachePolicy
8195 returningResponse:NULL
8198 if (UIImage *image = [UIImage imageWithData:data])
8199 [self performSelectorOnMainThread:@selector(_setImage:) withObject:[NSArray arrayWithObjects:url, image, nil] waitUntilDone:NO];
8204 - (void) setSource:(Source *)source {
8206 [source_ setDelegate:self];
8208 [self setFetch:[NSNumber numberWithBool:[source_ fetch]]];
8210 icon_ = [UIImage imageNamed:@"unknown.png"];
8212 origin_ = [source name];
8213 label_ = [source rooturi];
8215 [content_ setNeedsDisplay];
8217 url_ = [source iconURL];
8218 [NSThread detachNewThreadSelector:@selector(_setSource:) toTarget:self withObject:url_];
8221 - (void) setAllSource {
8223 [indicator_ stopAnimating];
8225 icon_ = [UIImage imageNamed:@"folder.png"];
8226 origin_ = UCLocalize("ALL_SOURCES");
8227 label_ = UCLocalize("ALL_SOURCES_EX");
8228 [content_ setNeedsDisplay];
8231 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
8232 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
8233 UIView *content([self contentView]);
8234 CGRect bounds([content bounds]);
8236 content_ = [[[CyteTableViewCellContentView alloc] initWithFrame:bounds] autorelease];
8237 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8238 [content_ setBackgroundColor:[UIColor whiteColor]];
8239 [content addSubview:content_];
8241 [content_ setDelegate:self];
8242 [content_ setOpaque:YES];
8244 indicator_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGraySmall] autorelease];
8245 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin];// | UIViewAutoresizingFlexibleBottomMargin];
8246 [content addSubview:indicator_];
8248 [[content_ layer] setContentsGravity:kCAGravityTopLeft];
8252 - (void) layoutSubviews {
8253 [super layoutSubviews];
8255 UIView *content([self contentView]);
8256 CGRect bounds([content bounds]);
8258 CGRect frame([indicator_ frame]);
8259 frame.origin.x = bounds.size.width - frame.size.width;
8260 frame.origin.y = Retina((bounds.size.height - frame.size.height) / 2);
8262 if (kCFCoreFoundationVersionNumber < 800)
8263 frame.origin.x -= 8;
8264 [indicator_ setFrame:frame];
8267 - (NSString *) accessibilityLabel {
8271 - (void) drawContentRect:(CGRect)rect {
8272 bool highlighted(highlighted_);
8273 float width(rect.size.width);
8277 rect.size = [(UIImage *) icon_ size];
8279 while (rect.size.width > 32 || rect.size.height > 32) {
8280 rect.size.width /= 2;
8281 rect.size.height /= 2;
8284 rect.origin.x = 26 - rect.size.width / 2;
8285 rect.origin.y = 26 - rect.size.height / 2;
8287 [icon_ drawInRect:Retina(rect)];
8290 if (highlighted && kCFCoreFoundationVersionNumber < 800)
8295 [origin_ drawAtPoint:CGPointMake(52, 8) forWidth:(width - 49) withFont:Font18Bold_ lineBreakMode:NSLineBreakByTruncatingTail];
8299 [label_ drawAtPoint:CGPointMake(52, 29) forWidth:(width - 49) withFont:Font12_ lineBreakMode:NSLineBreakByTruncatingTail];
8302 - (void) setFetch:(NSNumber *)fetch {
8303 if ([fetch boolValue])
8304 [indicator_ startAnimating];
8306 [indicator_ stopAnimating];
8311 /* Sources Controller {{{ */
8312 @interface SourcesController : CyteViewController <
8313 UITableViewDataSource,
8316 _transient Database *database_;
8319 _H<UITableView, 2> list_;
8320 _H<NSMutableArray> sources_;
8324 _H<UIProgressHUD> hud_;
8327 NSURLConnection *trivial_bz2_;
8328 NSURLConnection *trivial_gz_;
8333 - (id) initWithDatabase:(Database *)database;
8334 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated;
8338 @implementation SourcesController
8340 - (void) _releaseConnection:(NSURLConnection *)connection {
8341 if (connection != nil) {
8342 [connection cancel];
8343 //[connection setDelegate:nil];
8344 [connection release];
8349 [self _releaseConnection:trivial_gz_];
8350 [self _releaseConnection:trivial_bz2_];
8355 - (NSURL *) navigationURL {
8356 return [NSURL URLWithString:@"cydia://sources"];
8359 - (void) viewDidAppear:(BOOL)animated {
8360 [super viewDidAppear:animated];
8361 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
8364 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8368 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
8370 return UCLocalize("INDIVIDUAL_SOURCES");
8374 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8377 case 1: return [sources_ count];
8382 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
8383 @synchronized (database_) {
8384 if ([database_ era] != era_)
8386 if ([indexPath section] != 1)
8388 NSUInteger index([indexPath row]);
8389 if (index >= [sources_ count])
8391 return [sources_ objectAtIndex:index];
8394 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8395 static NSString *cellIdentifier = @"SourceCell";
8397 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
8398 if (cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
8399 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
8401 Source *source([self sourceAtIndexPath:indexPath]);
8403 [cell setAllSource];
8405 [cell setSource:source];
8410 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
8411 SectionsController *controller([[[SectionsController alloc]
8412 initWithDatabase:database_
8413 source:[self sourceAtIndexPath:indexPath]
8416 [controller setDelegate:delegate_];
8417 [[self navigationController] pushViewController:controller animated:YES];
8420 - (BOOL) tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
8421 if ([indexPath section] != 1)
8423 Source *source = [self sourceAtIndexPath:indexPath];
8424 return [source record] != nil;
8427 - (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
8428 _assert([indexPath section] == 1);
8429 if (editingStyle == UITableViewCellEditingStyleDelete) {
8430 Source *source = [self sourceAtIndexPath:indexPath];
8431 if (source == nil) return;
8433 [Sources_ removeObjectForKey:[source key]];
8436 [delegate_ _saveConfig];
8437 [delegate_ reloadDataWithInvocation:nil];
8441 - (void) tableView:(UITableView *)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath {
8442 [self updateButtonsForEditingStatusAnimated:YES];
8446 [delegate_ addTrivialSource:href_];
8449 [delegate_ syncData];
8452 - (NSString *) getWarning {
8453 NSString *href(href_);
8454 NSRange colon([href rangeOfString:@"://"]);
8455 if (colon.location != NSNotFound)
8456 href = [href substringFromIndex:(colon.location + 3)];
8457 href = [href stringByAddingPercentEscapes];
8458 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
8460 NSURL *url([NSURL URLWithString:href]);
8462 NSStringEncoding encoding;
8463 NSError *error(nil);
8465 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
8466 return [warning length] == 0 ? nil : warning;
8470 - (void) _endConnection:(NSURLConnection *)connection {
8471 // XXX: the memory management in this method is horribly awkward
8473 NSURLConnection **field = NULL;
8474 if (connection == trivial_bz2_)
8475 field = &trivial_bz2_;
8476 else if (connection == trivial_gz_)
8477 field = &trivial_gz_;
8478 _assert(field != NULL);
8479 [connection release];
8483 trivial_bz2_ == nil &&
8486 NSString *warning(cydia_ ? [self yieldToSelector:@selector(getWarning)] : nil);
8488 [delegate_ releaseNetworkActivityIndicator];
8490 [delegate_ removeProgressHUD:hud_];
8494 if (warning != nil) {
8495 UIAlertView *alert = [[[UIAlertView alloc]
8496 initWithTitle:UCLocalize("SOURCE_WARNING")
8499 cancelButtonTitle:UCLocalize("CANCEL")
8501 UCLocalize("ADD_ANYWAY"),
8505 [alert setContext:@"warning"];
8506 [alert setNumberOfRows:1];
8509 // XXX: there used to be this great mechanism called yieldToPopup... who deleted it?
8515 } else if (error_ != nil) {
8516 UIAlertView *alert = [[[UIAlertView alloc]
8517 initWithTitle:UCLocalize("VERIFICATION_ERROR")
8518 message:[error_ localizedDescription]
8520 cancelButtonTitle:UCLocalize("OK")
8521 otherButtonTitles:nil
8524 [alert setContext:@"urlerror"];
8529 UIAlertView *alert = [[[UIAlertView alloc]
8530 initWithTitle:UCLocalize("NOT_REPOSITORY")
8531 message:UCLocalize("NOT_REPOSITORY_EX")
8533 cancelButtonTitle:UCLocalize("OK")
8534 otherButtonTitles:nil
8537 [alert setContext:@"trivial"];
8547 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
8548 switch ([response statusCode]) {
8554 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
8555 lprintf("connection:\"%s\" didFailWithError:\"%s\"\n", [href_ UTF8String], [[error localizedDescription] UTF8String]);
8557 [self _endConnection:connection];
8560 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
8561 [self _endConnection:connection];
8564 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
8565 NSURL *url([NSURL URLWithString:href]);
8567 NSMutableURLRequest *request = [NSMutableURLRequest
8569 cachePolicy:NSURLRequestUseProtocolCachePolicy
8573 [request setHTTPMethod:method];
8575 if (Machine_ != NULL)
8576 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
8578 if (UniqueID_ != nil)
8579 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
8581 if ([url isCydiaSecure]) {
8582 if (UniqueID_ != nil)
8583 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Cydia-Id"];
8586 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
8589 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8590 NSString *context([alert context]);
8592 if ([context isEqualToString:@"source"]) {
8595 NSString *href = [[alert textField] text];
8597 static RegEx href_r("(http(s?)://|file:///)[^# ]*");
8598 if (!href_r(href)) {
8599 UIAlertView *alert = [[[UIAlertView alloc]
8600 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("INVALID_URL")]
8601 message:UCLocalize("INVALID_URL_EX")
8603 cancelButtonTitle:UCLocalize("OK")
8604 otherButtonTitles:nil
8607 [alert setContext:@"badurl"];
8613 if (![href hasSuffix:@"/"])
8614 href_ = [href stringByAppendingString:@"/"];
8618 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
8619 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
8623 // XXX: this is stupid
8624 hud_ = [delegate_ addProgressHUD];
8625 [hud_ setText:UCLocalize("VERIFYING_URL")];
8626 [delegate_ retainNetworkActivityIndicator];
8635 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8636 } else if ([context isEqualToString:@"trivial"])
8637 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8638 else if ([context isEqualToString:@"urlerror"])
8639 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8640 else if ([context isEqualToString:@"warning"]) {
8643 [self performSelector:@selector(complete) withObject:nil afterDelay:0];
8652 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8656 - (void) updateButtonsForEditingStatusAnimated:(BOOL)animated {
8657 BOOL editing([list_ isEditing]);
8660 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8661 initWithTitle:UCLocalize("ADD")
8662 style:UIBarButtonItemStylePlain
8664 action:@selector(addButtonClicked)
8665 ] autorelease] animated:animated];
8666 else if ([delegate_ updating])
8667 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8668 initWithTitle:UCLocalize("CANCEL")
8669 style:UIBarButtonItemStyleDone
8671 action:@selector(cancelButtonClicked)
8672 ] autorelease] animated:animated];
8674 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
8675 initWithTitle:UCLocalize("REFRESH")
8676 style:UIBarButtonItemStylePlain
8678 action:@selector(refreshButtonClicked)
8679 ] autorelease] animated:animated];
8681 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8682 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
8683 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
8685 action:@selector(editButtonClicked)
8686 ] autorelease] animated:animated];
8690 list_ = [[[UITableView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame] style:UITableViewStylePlain] autorelease];
8691 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8692 [list_ setRowHeight:53];
8693 [(UITableView *) list_ setDataSource:self];
8694 [list_ setDelegate:self];
8695 [self setView:list_];
8698 - (void) viewDidLoad {
8699 [super viewDidLoad];
8701 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
8702 [self updateButtonsForEditingStatusAnimated:NO];
8705 - (void) viewWillAppear:(BOOL)animated {
8706 [super viewWillAppear:animated];
8708 [list_ setEditing:NO];
8709 [self updateButtonsForEditingStatusAnimated:NO];
8712 - (void) releaseSubviews {
8717 [super releaseSubviews];
8720 - (id) initWithDatabase:(Database *)database {
8721 if ((self = [super init]) != nil) {
8722 database_ = database;
8726 - (void) reloadData {
8728 [self updateButtonsForEditingStatusAnimated:YES];
8730 @synchronized (database_) {
8731 era_ = [database_ era];
8733 sources_ = [NSMutableArray arrayWithCapacity:16];
8734 [sources_ addObjectsFromArray:[database_ sources]];
8736 [sources_ sortUsingSelector:@selector(compareByName:)];
8739 int count([sources_ count]);
8741 for (int i = 0; i != count; i++) {
8742 if ([[sources_ objectAtIndex:i] record] == nil)
8750 - (void) showAddSourcePrompt {
8751 UIAlertView *alert = [[[UIAlertView alloc]
8752 initWithTitle:UCLocalize("ENTER_APT_URL")
8755 cancelButtonTitle:UCLocalize("CANCEL")
8757 UCLocalize("ADD_SOURCE"),
8761 [alert setContext:@"source"];
8763 [alert setNumberOfRows:1];
8764 [alert addTextFieldWithValue:@"http://" label:@""];
8766 UITextInputTraits *traits = [[alert textField] textInputTraits];
8767 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
8768 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
8769 [traits setKeyboardType:UIKeyboardTypeURL];
8770 // XXX: UIReturnKeyDone
8771 [traits setReturnKeyType:UIReturnKeyNext];
8776 - (void) addButtonClicked {
8777 [self showAddSourcePrompt];
8780 - (void) refreshButtonClicked {
8781 if ([delegate_ requestUpdate])
8782 [self updateButtonsForEditingStatusAnimated:YES];
8785 - (void) cancelButtonClicked {
8786 [delegate_ cancelUpdate];
8789 - (void) editButtonClicked {
8790 [list_ setEditing:![list_ isEditing] animated:YES];
8791 [self updateButtonsForEditingStatusAnimated:YES];
8797 /* Stash Controller {{{ */
8798 @interface StashController : CyteViewController {
8799 _H<UIActivityIndicatorView> spinner_;
8800 _H<UILabel> status_;
8801 _H<UILabel> caption_;
8806 @implementation StashController
8809 UIView *view([[[UIView alloc] initWithFrame:[[UIScreen mainScreen] applicationFrame]] autorelease]);
8810 [view setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight)];
8811 [self setView:view];
8813 [view setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8815 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8816 CGRect spinrect = [spinner_ frame];
8817 spinrect.origin.x = Retina([[self view] frame].size.width / 2 - spinrect.size.width / 2);
8818 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8819 [spinner_ setFrame:spinrect];
8820 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8821 [view addSubview:spinner_];
8822 [spinner_ startAnimating];
8825 captrect.size.width = [[self view] frame].size.width;
8826 captrect.size.height = 40.0f;
8827 captrect.origin.x = 0;
8828 captrect.origin.y = Retina([[self view] frame].size.height / 2 - captrect.size.height * 2);
8829 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8830 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8831 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8832 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8833 [caption_ setTextColor:[UIColor whiteColor]];
8834 [caption_ setBackgroundColor:[UIColor clearColor]];
8835 [caption_ setShadowColor:[UIColor blackColor]];
8836 [caption_ setTextAlignment:NSTextAlignmentCenter];
8837 [view addSubview:caption_];
8840 statusrect.size.width = [[self view] frame].size.width;
8841 statusrect.size.height = 30.0f;
8842 statusrect.origin.x = 0;
8843 statusrect.origin.y = Retina([[self view] frame].size.height / 2 - statusrect.size.height);
8844 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8845 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8846 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8847 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8848 [status_ setTextColor:[UIColor whiteColor]];
8849 [status_ setBackgroundColor:[UIColor clearColor]];
8850 [status_ setShadowColor:[UIColor blackColor]];
8851 [status_ setTextAlignment:NSTextAlignmentCenter];
8852 [view addSubview:status_];
8855 - (void) releaseSubviews {
8860 [super releaseSubviews];
8866 @interface CYURLCache : SDURLCache {
8871 @implementation CYURLCache
8873 - (void) logEvent:(NSString *)event forRequest:(NSURLRequest *)request {
8876 else if ([event isEqualToString:@"no-cache"])
8878 else if ([event isEqualToString:@"store"])
8880 else if ([event isEqualToString:@"invalid"])
8882 else if ([event isEqualToString:@"memory"])
8884 else if ([event isEqualToString:@"disk"])
8886 else if ([event isEqualToString:@"miss"])
8889 NSLog(@"%@: %@", event, [[request URL] absoluteString]);
8893 - (void) storeCachedResponse:(NSCachedURLResponse *)cached forRequest:(NSURLRequest *)request {
8894 if (NSURLResponse *response = [cached response])
8895 if (NSString *mime = [response MIMEType])
8896 if ([mime isEqualToString:@"text/cache-manifest"]) {
8897 NSURL *url([response URL]);
8900 NSLog(@"###: %@", [url absoluteString]);
8903 @synchronized (HostConfig_) {
8904 [CachedURLs_ addObject:url];
8908 [super storeCachedResponse:cached forRequest:request];
8911 - (void) createDiskCachePath {
8912 [super createDiskCachePath];
8917 @interface Cydia : UIApplication <
8918 ConfirmationControllerDelegate,
8922 _H<UIWindow> window_;
8923 _H<CydiaTabBarController> tabbar_;
8924 _H<CyteTabBarController> emulated_;
8925 _H<AppCacheController> appcache_;
8927 _H<NSMutableArray> essential_;
8928 _H<NSMutableArray> broken_;
8930 Database *database_;
8932 _H<NSURL> starturl_;
8937 _H<StashController> stash_;
8946 @implementation Cydia
8948 - (void) lockSuspend {
8949 if (locked_++ == 0) {
8950 if ($SBSSetInterceptsMenuButtonForever != NULL)
8951 (*$SBSSetInterceptsMenuButtonForever)(true);
8953 [self setIdleTimerDisabled:YES];
8957 - (void) unlockSuspend {
8958 if (--locked_ == 0) {
8959 [self setIdleTimerDisabled:NO];
8961 if ($SBSSetInterceptsMenuButtonForever != NULL)
8962 (*$SBSSetInterceptsMenuButtonForever)(false);
8966 - (void) beginUpdate {
8967 [tabbar_ beginUpdate];
8970 - (void) cancelUpdate {
8971 [tabbar_ cancelUpdate];
8974 - (bool) requestUpdate {
8975 if (IsReachable("cydia.saurik.com")) {
8979 UIAlertView *alert = [[[UIAlertView alloc]
8980 initWithTitle:[NSString stringWithFormat:Colon_, Error_, UCLocalize("REFRESH")]
8981 message:@"Host Unreachable" // XXX: Localize
8983 cancelButtonTitle:UCLocalize("OK")
8984 otherButtonTitles:nil
8987 [alert setContext:@"norefresh"];
8995 return [tabbar_ updating];
8999 if ([broken_ count] != 0) {
9000 int count = [broken_ count];
9002 UIAlertView *alert = [[[UIAlertView alloc]
9003 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
9004 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
9006 cancelButtonTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("FORCIBLY_CLEAR"), UCLocalize("UNSAFE")]
9008 UCLocalize("TEMPORARY_IGNORE"),
9012 [alert setContext:@"fixhalf"];
9013 [alert setNumberOfRows:2];
9015 } else if (!Ignored_ && [essential_ count] != 0) {
9016 int count = [essential_ count];
9018 UIAlertView *alert = [[[UIAlertView alloc]
9019 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
9020 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
9022 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
9024 UCLocalize("UPGRADE_ESSENTIAL"),
9025 UCLocalize("COMPLETE_UPGRADE"),
9029 [alert setContext:@"upgrade"];
9034 - (void) returnToCydia {
9038 - (void) _saveConfig {
9039 @synchronized (database_) {
9046 NSString *error(nil);
9048 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
9050 NSError *error(nil);
9051 if (!_root([data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error]))
9052 NSLog(@"failure to save metadata data: %@", error);
9057 NSLog(@"failure to serialize metadata: %@", error);
9061 _root(CydiaWriteSources());
9064 // Navigation controller for the queuing badge.
9065 - (UINavigationController *) queueNavigationController {
9066 NSArray *controllers = [tabbar_ viewControllers];
9067 return [controllers objectAtIndex:3];
9070 - (void) unloadData {
9071 [tabbar_ unloadData];
9074 - (void) _updateData {
9078 UINavigationController *navigation = [self queueNavigationController];
9080 id queuedelegate = nil;
9081 if ([[navigation viewControllers] count] > 0)
9082 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
9084 [queuedelegate queueStatusDidChange];
9085 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
9088 - (void) _refreshIfPossible:(NSDate *)update {
9089 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
9091 bool recently = false;
9092 if (update != nil) {
9093 NSTimeInterval interval([update timeIntervalSinceNow]);
9094 if (interval > -(15*60))
9098 // Don't automatic refresh if:
9099 // - We already refreshed recently.
9100 // - We already auto-refreshed this launch.
9101 // - Auto-refresh is disabled.
9102 // - Cydia's server is not reachable
9103 if (recently || loaded_ || ManualRefresh || !IsReachable("cydia.saurik.com")) {
9104 // If we are cancelling, we need to make sure it knows it's already loaded.
9107 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
9109 // We are going to load, so remember that.
9112 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
9118 - (void) refreshIfPossible {
9119 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible:) toTarget:self withObject:[Metadata_ objectForKey:@"LastUpdate"]];
9122 - (void) reloadDataWithInvocation:(NSInvocation *)invocation {
9123 _profile(reloadDataWithInvocation)
9124 @synchronized (self) {
9125 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
9127 [hud setText:UCLocalize("RELOADING_DATA")];
9129 [database_ yieldToSelector:@selector(reloadDataWithInvocation:) withObject:invocation];
9133 [essential_ removeAllObjects];
9134 [broken_ removeAllObjects];
9136 _profile(reloadDataWithInvocation$Essential)
9137 NSArray *packages([database_ packages]);
9138 for (Package *package in packages) {
9140 [broken_ addObject:package];
9141 if ([package upgradableAndEssential:YES] && ![package ignored]) {
9142 if ([package essential] && [package installed] != nil)
9143 [essential_ addObject:package];
9149 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
9152 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
9153 [changesItem setBadgeValue:badge];
9154 [changesItem setAnimatedBadge:([essential_ count] > 0)];
9155 [self setApplicationIconBadgeNumber:changes];
9158 [changesItem setBadgeValue:nil];
9159 [changesItem setAnimatedBadge:NO];
9160 [self setApplicationIconBadgeNumber:0];
9167 [self removeProgressHUD:hud];
9174 - (void) updateData {
9178 - (void) updateDataAndLoad {
9180 if ([database_ progressDelegate] == nil)
9186 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9189 - (void) disemulate {
9190 if (emulated_ == nil)
9193 if ([window_ respondsToSelector:@selector(setRootViewController:)])
9194 [window_ setRootViewController:tabbar_];
9196 [window_ addSubview:[tabbar_ view]];
9197 [[emulated_ view] removeFromSuperview];
9201 [window_ setUserInteractionEnabled:YES];
9204 - (void) presentModalViewController:(UIViewController *)controller force:(BOOL)force {
9205 UINavigationController *navigation([[[UINavigationController alloc] initWithRootViewController:controller] autorelease]);
9207 UIViewController *parent;
9208 if (emulated_ == nil)
9218 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
9219 [parent presentModalViewController:navigation animated:YES];
9222 - (ProgressController *) invokeNewProgress:(NSInvocation *)invocation forController:(UINavigationController *)navigation withTitle:(NSString *)title {
9223 ProgressController *progress([[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease]);
9225 if (navigation != nil)
9226 [navigation pushViewController:progress animated:YES];
9228 [self presentModalViewController:progress force:YES];
9230 [progress invoke:invocation withTitle:title];
9234 - (void) detachNewProgressSelector:(SEL)selector toTarget:(id)target forController:(UINavigationController *)navigation title:(NSString *)title {
9235 [self invokeNewProgress:[NSInvocation invocationWithSelector:selector forTarget:target] forController:navigation withTitle:title];
9238 - (void) repairWithInvocation:(NSInvocation *)invocation {
9240 [self invokeNewProgress:invocation forController:nil withTitle:@"REPAIRING"];
9244 - (void) repairWithSelector:(SEL)selector {
9245 [self performSelectorOnMainThread:@selector(repairWithInvocation:) withObject:[NSInvocation invocationWithSelector:selector forTarget:database_] waitUntilDone:YES];
9248 - (void) reloadData {
9249 [self reloadDataWithInvocation:nil];
9250 if ([database_ progressDelegate] == nil)
9256 [self detachNewProgressSelector:@selector(update_) toTarget:self forController:nil title:@"UPDATING_SOURCES"];
9259 - (void) addSource:(NSDictionary *) source {
9260 CydiaAddSource(source);
9263 - (void) addSource:(NSString *)href withDistribution:(NSString *)distribution andSections:(NSArray *)sections {
9264 CydiaAddSource(href, distribution, sections);
9267 - (void) addTrivialSource:(NSString *)href {
9268 CydiaAddSource(href, @"./");
9271 - (void) updateValues {
9276 pkgProblemResolver *resolver = [database_ resolver];
9278 resolver->InstallProtect();
9279 if (!resolver->Resolve(true))
9284 // XXX: this is a really crappy way of doing this.
9285 // like, seriously: this state machine is still broken, and cancelling this here doesn't really /fix/ that.
9286 // for one, the user can still /start/ a reloading data event while they have a queue, which is stupid
9287 // for two, this just means there is a race condition between the refresh completing and the confirmation controller appearing.
9288 if ([tabbar_ updating])
9289 [tabbar_ cancelUpdate];
9291 if (![database_ prepare])
9294 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
9295 [page setDelegate:self];
9296 UINavigationController *confirm_([[[UINavigationController alloc] initWithRootViewController:page] autorelease]);
9299 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
9300 [tabbar_ presentModalViewController:confirm_ animated:YES];
9306 @synchronized (self) {
9311 - (void) clearPackage:(Package *)package {
9312 @synchronized (self) {
9319 - (void) installPackages:(NSArray *)packages {
9320 @synchronized (self) {
9321 for (Package *package in packages)
9328 - (void) installPackage:(Package *)package {
9329 @synchronized (self) {
9336 - (void) removePackage:(Package *)package {
9337 @synchronized (self) {
9344 - (void) distUpgrade {
9345 @synchronized (self) {
9346 if (![database_ upgrade])
9355 if (UpgradeCydia_ && Finish_ > 0) {
9357 system("su -c /usr/bin/uicache mobile");
9359 system("/usr/bin/uicache");
9366 UIProgressHUD *hud([self addProgressHUD]);
9367 [hud setText:UCLocalize("LOADING")];
9368 [self yieldToSelector:@selector(_uicache)];
9369 [self removeProgressHUD:hud];
9373 [database_ perform];
9374 [self performSelectorOnMainThread:@selector(reloadData) withObject:nil waitUntilDone:YES];
9375 [self performSelectorOnMainThread:@selector(uicache) withObject:nil waitUntilDone:YES];
9378 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
9381 [self detachNewProgressSelector:@selector(perform_) toTarget:self forController:navigation title:@"RUNNING"];
9382 [self unlockSuspend];
9385 - (void) retainNetworkActivityIndicator {
9386 if (activity_++ == 0)
9387 [self setNetworkActivityIndicatorVisible:YES];
9390 NSLog(@"retainNetworkActivityIndicator->%d", activity_);
9394 - (void) releaseNetworkActivityIndicator {
9395 if (--activity_ == 0)
9396 [self setNetworkActivityIndicatorVisible:NO];
9399 NSLog(@"releaseNetworkActivityIndicator->%d", activity_);
9404 - (void) cancelAndClear:(bool)clear {
9405 @synchronized (self) {
9417 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
9418 NSString *context([alert context]);
9420 if ([context isEqualToString:@"conffile"]) {
9421 FILE *input = [database_ input];
9422 if (button == [alert cancelButtonIndex])
9423 fprintf(input, "N\n");
9424 else if (button == [alert firstOtherButtonIndex])
9425 fprintf(input, "Y\n");
9428 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9429 } else if ([context isEqualToString:@"fixhalf"]) {
9430 if (button == [alert cancelButtonIndex]) {
9431 @synchronized (self) {
9432 for (Package *broken in (id) broken_) {
9434 NSString *id = [broken id];
9437 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
9438 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
9439 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
9440 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
9447 } else if (button == [alert firstOtherButtonIndex]) {
9448 [broken_ removeAllObjects];
9452 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9453 } else if ([context isEqualToString:@"upgrade"]) {
9454 if (button == [alert firstOtherButtonIndex]) {
9455 @synchronized (self) {
9456 for (Package *essential in (id) essential_)
9457 [essential install];
9462 } else if (button == [alert firstOtherButtonIndex] + 1) {
9464 } else if (button == [alert cancelButtonIndex]) {
9468 [alert dismissWithClickedButtonIndex:-1 animated:YES];
9472 - (void) system:(NSString *)command {
9473 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
9476 system([command UTF8String]);
9482 - (void) applicationWillSuspend {
9484 [super applicationWillSuspend];
9487 - (BOOL) isSafeToSuspend {
9490 NSLog(@"isSafeToSuspend: locked_ != 0");
9495 if ([tabbar_ modalViewController] != nil)
9498 // Use external process status API internally.
9499 // This is probably a really bad idea.
9500 // XXX: what is the point of this? does this solve anything at all?
9501 uint64_t status = 0;
9503 if (notify_register_check("com.saurik.Cydia.status", ¬ify_token) == NOTIFY_STATUS_OK) {
9504 notify_get_state(notify_token, &status);
9505 notify_cancel(notify_token);
9510 NSLog(@"isSafeToSuspend: status != 0");
9516 NSLog(@"isSafeToSuspend: -> true");
9521 - (void) suspendReturningToLastApp:(BOOL)returning {
9522 if ([self isSafeToSuspend])
9523 [super suspendReturningToLastApp:returning];
9527 if ([self isSafeToSuspend])
9531 - (void) applicationSuspend {
9532 if ([self isSafeToSuspend])
9533 [super applicationSuspend];
9536 - (void) applicationSuspend:(__GSEvent *)event {
9537 if ([self isSafeToSuspend])
9538 [super applicationSuspend:event];
9541 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
9542 if ([self isSafeToSuspend])
9543 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
9546 - (void) _setSuspended:(BOOL)value {
9547 if ([self isSafeToSuspend])
9548 [super _setSuspended:value];
9551 - (UIProgressHUD *) addProgressHUD {
9552 UIProgressHUD *hud([[[UIProgressHUD alloc] init] autorelease]);
9553 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
9555 [window_ setUserInteractionEnabled:NO];
9557 UIViewController *target(tabbar_);
9558 if (UIViewController *modal = [target modalViewController])
9561 [hud showInView:[target view]];
9567 - (void) removeProgressHUD:(UIProgressHUD *)hud {
9568 [self unlockSuspend];
9570 [hud removeFromSuperview];
9571 [window_ setUserInteractionEnabled:YES];
9574 - (CyteViewController *) pageForPackage:(NSString *)name withReferrer:(NSString *)referrer {
9575 return [[[CYPackageController alloc] initWithDatabase:database_ forPackage:name withReferrer:referrer] autorelease];
9578 - (CyteViewController *) pageForURL:(NSURL *)url forExternal:(BOOL)external withReferrer:(NSString *)referrer {
9579 NSString *scheme([[url scheme] lowercaseString]);
9580 if ([[url absoluteString] length] <= [scheme length] + 3)
9582 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
9583 NSArray *components([path componentsSeparatedByString:@"/"]);
9585 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"]) {
9586 CyteViewController *controller([self pageForPackage:[components objectAtIndex:1] withReferrer:referrer]);
9587 if (controller != nil)
9588 [controller setDelegate:self];
9592 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
9595 NSString *base([components objectAtIndex:0]);
9597 CyteViewController *controller = nil;
9599 if ([base isEqualToString:@"url"]) {
9600 // This kind of URL can contain slashes in the argument, so we can't parse them below.
9601 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
9602 controller = [[[CydiaWebViewController alloc] initWithURL:[NSURL URLWithString:destination]] autorelease];
9603 } else if (!external && [components count] == 1) {
9604 if ([base isEqualToString:@"sources"]) {
9605 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9608 if ([base isEqualToString:@"home"]) {
9609 controller = [[[HomeController alloc] init] autorelease];
9612 if ([base isEqualToString:@"sections"]) {
9613 controller = [[[SectionsController alloc] initWithDatabase:database_ source:nil] autorelease];
9616 if ([base isEqualToString:@"search"]) {
9617 controller = [[[SearchController alloc] initWithDatabase:database_ query:nil] autorelease];
9620 if ([base isEqualToString:@"changes"]) {
9621 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
9624 if ([base isEqualToString:@"installed"]) {
9625 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
9627 } else if ([components count] == 2) {
9628 NSString *argument = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9630 if ([base isEqualToString:@"package"]) {
9631 controller = [self pageForPackage:argument withReferrer:referrer];
9634 if (!external && [base isEqualToString:@"search"]) {
9635 controller = [[[SearchController alloc] initWithDatabase:database_ query:argument] autorelease];
9638 if (!external && [base isEqualToString:@"sections"]) {
9639 if ([argument isEqualToString:@"all"] || [argument isEqualToString:@"*"])
9641 controller = [[[SectionController alloc] initWithDatabase:database_ source:nil section:argument] autorelease];
9644 if (!external && [base isEqualToString:@"sources"]) {
9645 if ([argument isEqualToString:@"add"]) {
9646 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
9647 [(SourcesController *)controller showAddSourcePrompt];
9649 Source *source([database_ sourceWithKey:argument]);
9650 controller = [[[SectionsController alloc] initWithDatabase:database_ source:source] autorelease];
9654 if (!external && [base isEqualToString:@"launch"]) {
9655 [self launchApplicationWithIdentifier:argument suspended:NO];
9658 } else if (!external && [components count] == 3) {
9659 NSString *arg1 = [[components objectAtIndex:1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9660 NSString *arg2 = [[components objectAtIndex:2] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
9662 if ([base isEqualToString:@"package"]) {
9663 if ([arg2 isEqualToString:@"settings"]) {
9664 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
9665 } else if ([arg2 isEqualToString:@"files"]) {
9666 if (Package *package = [database_ packageWithName:arg1]) {
9667 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
9668 [(FileTable *)controller setPackage:package];
9673 if ([base isEqualToString:@"sections"]) {
9674 Source *source([arg1 isEqualToString:@"*"] ? nil : [database_ sourceWithKey:arg1]);
9675 NSString *section([arg2 isEqualToString:@"*"] ? nil : arg2);
9676 controller = [[[SectionController alloc] initWithDatabase:database_ source:source section:section] autorelease];
9680 [controller setDelegate:self];
9684 - (BOOL) openCydiaURL:(NSURL *)url forExternal:(BOOL)external {
9685 CyteViewController *page([self pageForURL:url forExternal:external withReferrer:nil]);
9688 [tabbar_ setUnselectedViewController:page];
9693 - (void) applicationOpenURL:(NSURL *)url {
9694 [super applicationOpenURL:url];
9699 [self openCydiaURL:url forExternal:YES];
9702 - (void) applicationWillResignActive:(UIApplication *)application {
9703 // Stop refreshing if you get a phone call or lock the device.
9704 if ([tabbar_ updating])
9705 [tabbar_ cancelUpdate];
9707 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
9708 [super applicationWillResignActive:application];
9711 - (void) saveState {
9712 [Metadata_ setObject:[tabbar_ navigationURLCollection] forKey:@"InterfaceState"];
9713 [Metadata_ setObject:[NSDate date] forKey:@"LastClosed"];
9714 [Metadata_ setObject:[NSNumber numberWithInt:[tabbar_ selectedIndex]] forKey:@"InterfaceIndex"];
9720 - (void) applicationWillTerminate:(UIApplication *)application {
9724 - (void) applicationDidEnterBackground:(UIApplication *)application {
9725 if (kCFCoreFoundationVersionNumber < 1000 && [self isSafeToSuspend])
9726 return [self terminateWithSuccess];
9730 - (void) applicationWillEnterForeground:(UIApplication *)application {
9731 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9735 NSTimeInterval interval([closed timeIntervalSinceNow]);
9737 if (interval <= -(30*60)) {
9738 [tabbar_ setSelectedIndex:0];
9739 [[[tabbar_ viewControllers] objectAtIndex:0] popToRootViewControllerAnimated:NO];
9742 if (interval <= -(15*60)) {
9743 if (IsReachable("cydia.saurik.com")) {
9744 [tabbar_ beginUpdate];
9745 [appcache_ reloadURLWithCache:YES];
9750 - (void) setConfigurationData:(NSString *)data {
9751 static RegEx conffile_r("'(.*)' '(.*)' ([01]) ([01])");
9753 if (!conffile_r(data)) {
9754 lprintf("E:invalid conffile\n");
9758 NSString *ofile = conffile_r[1];
9759 //NSString *nfile = conffile_r[2];
9761 UIAlertView *alert = [[[UIAlertView alloc]
9762 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
9763 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
9765 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
9767 UCLocalize("ACCEPT_NEW_COPY"),
9768 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
9772 [alert setContext:@"conffile"];
9773 [alert setNumberOfRows:2];
9777 - (void) addStashController {
9779 stash_ = [[[StashController alloc] init] autorelease];
9780 [window_ addSubview:[stash_ view]];
9783 - (void) removeStashController {
9784 [[stash_ view] removeFromSuperview];
9786 [self unlockSuspend];
9790 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
9791 UpdateExternalStatus(1);
9792 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/cydo /usr/libexec/cydia/free.sh"];
9793 UpdateExternalStatus(0);
9795 [self removeStashController];
9797 pid_t pid(ExecFork());
9799 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
9800 perror("launchctl stop");
9806 - (void) setupViewControllers {
9807 tabbar_ = [[[CydiaTabBarController alloc] initWithDatabase:database_] autorelease];
9809 NSMutableArray *items;
9810 if (kCFCoreFoundationVersionNumber < 800) {
9811 items = [NSMutableArray arrayWithObjects:
9812 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage imageNamed:@"home.png"] tag:0] autorelease],
9813 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage imageNamed:@"install.png"] tag:0] autorelease],
9814 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage imageNamed:@"changes.png"] tag:0] autorelease],
9815 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage imageNamed:@"manage.png"] tag:0] autorelease],
9816 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage imageNamed:@"search.png"] tag:0] autorelease],
9819 items = [NSMutableArray arrayWithObjects:
9820 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage imageNamed:@"home7.png"] selectedImage:[UIImage imageNamed:@"home7s.png"]] autorelease],
9821 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage imageNamed:@"install7.png"] selectedImage:[UIImage imageNamed:@"install7s.png"]] autorelease],
9822 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage imageNamed:@"changes7.png"] selectedImage:[UIImage imageNamed:@"changes7s.png"]] autorelease],
9823 [[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage imageNamed:@"manage7.png"] selectedImage:[UIImage imageNamed:@"manage7s.png"]] autorelease],
9824 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage imageNamed:@"search7.png"] selectedImage:[UIImage imageNamed:@"search7s.png"]] autorelease],
9828 NSMutableArray *controllers([NSMutableArray array]);
9829 for (UITabBarItem *item in items) {
9830 UINavigationController *controller([[[UINavigationController alloc] init] autorelease]);
9831 [controller setTabBarItem:item];
9832 [controllers addObject:controller];
9834 [tabbar_ setViewControllers:controllers];
9836 [tabbar_ setUpdateDelegate:self];
9839 - (void) _sendMemoryWarningNotification {
9840 if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: maybe 4_0?
9841 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationMemoryWarningNotification" object:[UIApplication sharedApplication]];
9843 [[NSNotificationCenter defaultCenter] postNotificationName:@"UIApplicationDidReceiveMemoryWarningNotification" object:[UIApplication sharedApplication]];
9846 - (void) _sendMemoryWarningNotifications {
9848 [self performSelectorOnMainThread:@selector(_sendMemoryWarningNotification) withObject:nil waitUntilDone:NO];
9854 - (void) applicationDidReceiveMemoryWarning:(UIApplication *)application {
9856 [[NSURLCache sharedURLCache] removeAllCachedResponses];
9859 - (void) applicationDidFinishLaunching:(id)unused {
9860 //[NSThread detachNewThreadSelector:@selector(_sendMemoryWarningNotifications) toTarget:self withObject:nil];
9863 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
9864 [self setApplicationSupportsShakeToEdit:NO];
9866 @synchronized (HostConfig_) {
9867 [BridgedHosts_ addObject:[[NSURL URLWithString:CydiaURL(@"")] host]];
9870 [NSURLCache setSharedURLCache:[[[CYURLCache alloc]
9871 initWithMemoryCapacity:524288
9872 diskCapacity:10485760
9873 diskPath:Cache("SDURLCache")
9876 [CydiaWebViewController _initialize];
9878 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
9880 // this would disallow http{,s} URLs from accessing this data
9881 //[WebView registerURLSchemeAsLocal:@"cydia"];
9883 Font12_ = [UIFont systemFontOfSize:12];
9884 Font12Bold_ = [UIFont boldSystemFontOfSize:12];
9885 Font14_ = [UIFont systemFontOfSize:14];
9886 Font18_ = [UIFont systemFontOfSize:18];
9887 Font18Bold_ = [UIFont boldSystemFontOfSize:18];
9888 Font22Bold_ = [UIFont boldSystemFontOfSize:22];
9890 essential_ = [NSMutableArray arrayWithCapacity:4];
9891 broken_ = [NSMutableArray arrayWithCapacity:4];
9893 // XXX: I really need this thing... like, seriously... I'm sorry
9894 appcache_ = [[[AppCacheController alloc] initWithURL:[NSURL URLWithString:[NSString stringWithFormat:@"%@/appcache/", UI_]]] autorelease];
9895 [appcache_ reloadData];
9897 window_ = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
9898 [window_ orderFront:self];
9899 [window_ makeKey:self];
9900 [window_ setHidden:NO];
9903 [self addStashController];
9904 // XXX: this would be much cleaner as a yieldToSelector:
9905 // that way the removeStashController could happen right here inline
9906 // we also could no longer require the useless stash_ field anymore
9907 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9912 int error(stat("/", &root));
9913 _assert(error != -1);
9915 #define Stash_(path) do { \
9916 struct stat folder; \
9917 int error(lstat((path), &folder)); \
9918 if (error != -1 && ( \
9919 folder.st_dev == root.st_dev && \
9920 S_ISDIR(folder.st_mode) \
9921 ) || error == -1 && ( \
9922 errno == ENOENT || \
9927 Stash_("/Applications");
9928 Stash_("/Library/Ringtones");
9929 Stash_("/Library/Wallpaper");
9930 //Stash_("/usr/bin");
9931 Stash_("/usr/include");
9932 Stash_("/usr/share");
9933 //Stash_("/var/lib");
9935 database_ = [Database sharedInstance];
9936 [database_ setDelegate:self];
9938 [window_ setUserInteractionEnabled:NO];
9939 [self setupViewControllers];
9941 CydiaLoadingViewController *loading([[[CydiaLoadingViewController alloc] init] autorelease]);
9942 UINavigationController *navigation([[[UINavigationController alloc] init] autorelease]);
9943 [navigation setViewControllers:[NSArray arrayWithObject:loading]];
9945 emulated_ = [[[CyteTabBarController alloc] init] autorelease];
9946 [emulated_ setViewControllers:[NSArray arrayWithObject:navigation]];
9947 [emulated_ setSelectedIndex:0];
9949 if ([emulated_ respondsToSelector:@selector(concealTabBarSelection)])
9950 [emulated_ concealTabBarSelection];
9952 if ([window_ respondsToSelector:@selector(setRootViewController:)])
9953 [window_ setRootViewController:emulated_];
9955 [window_ addSubview:[emulated_ view]];
9957 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9961 - (NSArray *) defaultStartPages {
9962 NSMutableArray *standard = [NSMutableArray array];
9963 [standard addObject:[NSArray arrayWithObject:@"cydia://home"]];
9964 [standard addObject:[NSArray arrayWithObject:@"cydia://sources"]];
9965 [standard addObject:[NSArray arrayWithObject:@"cydia://changes"]];
9966 [standard addObject:[NSArray arrayWithObject:@"cydia://installed"]];
9967 [standard addObject:[NSArray arrayWithObject:@"cydia://search"]];
9973 if ([emulated_ modalViewController] != nil)
9974 [emulated_ dismissModalViewControllerAnimated:YES];
9975 [window_ setUserInteractionEnabled:NO];
9977 [self reloadDataWithInvocation:nil];
9978 [self refreshIfPossible];
9981 int savedIndex = [[Metadata_ objectForKey:@"InterfaceIndex"] intValue];
9982 NSArray *saved = [[[Metadata_ objectForKey:@"InterfaceState"] mutableCopy] autorelease];
9983 int standardIndex = 0;
9984 NSArray *standard = [self defaultStartPages];
9991 NSDate *closed = [Metadata_ objectForKey:@"LastClosed"];
9992 if (valid && closed != nil) {
9993 NSTimeInterval interval([closed timeIntervalSinceNow]);
9994 if (interval <= -(30*60))
9998 if (valid && [saved count] != [standard count])
10002 for (unsigned int i = 0; i < [standard count]; i++) {
10003 NSArray *std = [standard objectAtIndex:i], *sav = [saved objectAtIndex:i];
10004 // XXX: The "hasPrefix" sanity check here could be, in theory, fooled,
10005 // but it's good enough for now.
10006 if ([sav count] == 0 || ![[sav objectAtIndex:0] hasPrefix:[std objectAtIndex:0]]) {
10013 NSArray *items = nil;
10015 [tabbar_ setSelectedIndex:savedIndex];
10018 [tabbar_ setSelectedIndex:standardIndex];
10022 for (unsigned int tab = 0; tab < [[tabbar_ viewControllers] count]; tab++) {
10023 NSArray *stack = [items objectAtIndex:tab];
10024 UINavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:tab];
10025 NSMutableArray *current = [NSMutableArray array];
10027 for (unsigned int nav = 0; nav < [stack count]; nav++) {
10028 NSString *addr = [stack objectAtIndex:nav];
10029 NSURL *url = [NSURL URLWithString:addr];
10030 CyteViewController *page = [self pageForURL:url forExternal:NO withReferrer:nil];
10032 [current addObject:page];
10035 [navigation setViewControllers:current];
10038 // (Try to) show the startup URL.
10039 if (starturl_ != nil) {
10040 [self openCydiaURL:starturl_ forExternal:YES];
10045 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
10046 if (item != nil && IsWildcat_) {
10047 [sheet showFromBarButtonItem:item animated:YES];
10049 [sheet showInView:window_];
10053 - (void) addProgressEvent:(CydiaProgressEvent *)event forTask:(NSString *)task {
10054 id<ProgressDelegate> progress([database_ progressDelegate] ?: [self invokeNewProgress:nil forController:nil withTitle:task]);
10055 [progress setTitle:task];
10056 [progress addProgressEvent:event];
10059 - (void) addProgressEventForTask:(NSArray *)data {
10060 CydiaProgressEvent *event([data objectAtIndex:0]);
10061 NSString *task([data count] < 2 ? nil : [data objectAtIndex:1]);
10062 [self addProgressEvent:event forTask:task];
10065 - (void) addProgressEventOnMainThread:(CydiaProgressEvent *)event forTask:(NSString *)task {
10066 [self performSelectorOnMainThread:@selector(addProgressEventForTask:) withObject:[NSArray arrayWithObjects:event, task, nil] waitUntilDone:YES];
10072 id Alloc_(id self, SEL selector) {
10073 id object = alloc_(self, selector);
10074 lprintf("[%s]A-%p\n", self->isa->name, object);
10079 id Dealloc_(id self, SEL selector) {
10080 id object = dealloc_(self, selector);
10081 lprintf("[%s]D-%p\n", self->isa->name, object);
10085 Class $NSURLConnection;
10087 MSHook(id, NSURLConnection$init$, NSURLConnection *self, SEL _cmd, NSURLRequest *request, id delegate, BOOL usesCache, int64_t maxContentLength, BOOL startImmediately, NSDictionary *connectionProperties) {
10088 NSMutableURLRequest *copy([[request mutableCopy] autorelease]);
10090 NSURL *url([copy URL]);
10092 NSString *host([url host]);
10093 NSString *scheme([[url scheme] lowercaseString]);
10095 NSString *compound([NSString stringWithFormat:@"%@:%@", scheme, host]);
10097 @synchronized (HostConfig_) {
10098 if ([copy respondsToSelector:@selector(setHTTPShouldUsePipelining:)])
10099 if ([PipelinedHosts_ containsObject:host] || [PipelinedHosts_ containsObject:compound])
10100 [copy setHTTPShouldUsePipelining:YES];
10102 if (NSString *control = [copy valueForHTTPHeaderField:@"Cache-Control"])
10103 if ([control isEqualToString:@"max-age=0"])
10104 if ([CachedURLs_ containsObject:url]) {
10106 NSLog(@"~~~: %@", url);
10109 [copy setCachePolicy:NSURLRequestReturnCacheDataDontLoad];
10111 [copy setValue:nil forHTTPHeaderField:@"Cache-Control"];
10112 [copy setValue:nil forHTTPHeaderField:@"If-Modified-Since"];
10113 [copy setValue:nil forHTTPHeaderField:@"If-None-Match"];
10117 if ((self = _NSURLConnection$init$(self, _cmd, copy, delegate, usesCache, maxContentLength, startImmediately, connectionProperties)) != nil) {
10123 static CGSize $WAKWindow$screenSize(WAKWindow *self, SEL _cmd) {
10124 CGSize size([[UIScreen mainScreen] bounds].size);
10125 /*if ([$WAKWindow respondsToSelector:@selector(hasLandscapeOrientation)])
10126 if ([$WAKWindow hasLandscapeOrientation])
10127 std::swap(size.width, size.height);*/
10131 Class $NSUserDefaults;
10133 MSHook(id, NSUserDefaults$objectForKey$, NSUserDefaults *self, SEL _cmd, NSString *key) {
10134 if ([key respondsToSelector:@selector(isEqualToString:)] && [key isEqualToString:@"WebKitLocalStorageDatabasePathPreferenceKey"])
10135 return Cache("LocalStorage");
10136 return _NSUserDefaults$objectForKey$(self, _cmd, key);
10139 int main(int argc, char *argv[]) {
10140 setreugid(501, 501);
10142 NSAutoreleasePool *pool([[NSAutoreleasePool alloc] init]);
10146 UpdateExternalStatus(0);
10148 UIScreen *screen([UIScreen mainScreen]);
10149 if ([screen respondsToSelector:@selector(scale)])
10150 ScreenScale_ = [screen scale];
10154 UIDevice *device([UIDevice currentDevice]);
10155 if ([device respondsToSelector:@selector(userInterfaceIdiom)]) {
10156 UIUserInterfaceIdiom idiom([device userInterfaceIdiom]);
10157 if (idiom == UIUserInterfaceIdiomPad)
10161 Idiom_ = IsWildcat_ ? @"ipad" : @"iphone";
10163 RegEx pattern("([0-9]+\\.[0-9]+).*");
10165 if (pattern([device systemVersion]))
10166 Firmware_ = pattern[1];
10167 if (pattern(Cydia_))
10168 Major_ = pattern[1];
10170 SessionData_ = [NSMutableDictionary dictionaryWithCapacity:4];
10172 HostConfig_ = [[[NSObject alloc] init] autorelease];
10173 @synchronized (HostConfig_) {
10174 BridgedHosts_ = [NSMutableSet setWithCapacity:4];
10175 TokenHosts_ = [NSMutableSet setWithCapacity:4];
10176 InsecureHosts_ = [NSMutableSet setWithCapacity:4];
10177 PipelinedHosts_ = [NSMutableSet setWithCapacity:4];
10178 CachedURLs_ = [NSMutableSet setWithCapacity:32];
10181 NSString *ui(@"ui/ios");
10183 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"~%@", Idiom_]];
10184 ui = [ui stringByAppendingString:[NSString stringWithFormat:@"/%@", Major_]];
10185 UI_ = CydiaURL(ui);
10187 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
10189 /* Library Hacks {{{ */
10190 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
10192 $WAKWindow = objc_getClass("WAKWindow");
10193 if ($WAKWindow != NULL)
10194 if (Method method = class_getInstanceMethod($WAKWindow, @selector(screenSize)))
10195 method_setImplementation(method, (IMP) &$WAKWindow$screenSize);
10197 $NSURLConnection = objc_getClass("NSURLConnection");
10198 Method NSURLConnection$init$(class_getInstanceMethod($NSURLConnection, @selector(_initWithRequest:delegate:usesCache:maxContentLength:startImmediately:connectionProperties:)));
10199 if (NSURLConnection$init$ != NULL) {
10200 _NSURLConnection$init$ = reinterpret_cast<id (*)(NSURLConnection *, SEL, NSURLRequest *, id, BOOL, int64_t, BOOL, NSDictionary *)>(method_getImplementation(NSURLConnection$init$));
10201 method_setImplementation(NSURLConnection$init$, reinterpret_cast<IMP>(&$NSURLConnection$init$));
10204 $NSUserDefaults = objc_getClass("NSUserDefaults");
10205 Method NSUserDefaults$objectForKey$(class_getInstanceMethod($NSUserDefaults, @selector(objectForKey:)));
10206 if (NSUserDefaults$objectForKey$ != NULL) {
10207 _NSUserDefaults$objectForKey$ = reinterpret_cast<id (*)(NSUserDefaults *, SEL, NSString *)>(method_getImplementation(NSUserDefaults$objectForKey$));
10208 method_setImplementation(NSUserDefaults$objectForKey$, reinterpret_cast<IMP>(&$NSUserDefaults$objectForKey$));
10211 /* Set Locale {{{ */
10212 Locale_ = CFLocaleCopyCurrent();
10213 Languages_ = [NSLocale preferredLanguages];
10215 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
10216 //NSLog(@"%@", [Languages_ description]);
10219 if (Locale_ != NULL)
10220 lang = [(NSString *) CFLocaleGetIdentifier(Locale_) UTF8String];
10221 else if (Languages_ != nil && [Languages_ count] != 0)
10222 lang = [[Languages_ objectAtIndex:0] UTF8String];
10224 // XXX: consider just setting to C and then falling through?
10227 if (lang != NULL) {
10228 RegEx pattern("([a-z][a-z])(?:-[A-Za-z]*)?(_[A-Z][A-Z])?");
10229 lang = !pattern(lang) ? NULL : [pattern->*@"%1$@%2$@" UTF8String];
10232 NSLog(@"Setting Language: %s", lang);
10234 if (lang != NULL) {
10235 setenv("LANG", lang, true);
10236 std::setlocale(LC_ALL, lang);
10239 /* Index Collation {{{ */
10240 if (Class $UILocalizedIndexedCollation = objc_getClass("UILocalizedIndexedCollation")) { @try {
10241 NSBundle *bundle([NSBundle bundleForClass:$UILocalizedIndexedCollation]);
10242 NSString *path([bundle pathForResource:@"UITableViewLocalizedSectionIndex" ofType:@"plist"]);
10243 //path = @"/System/Library/Frameworks/UIKit.framework/.lproj/UITableViewLocalizedSectionIndex.plist";
10244 NSDictionary *dictionary([NSDictionary dictionaryWithContentsOfFile:path]);
10245 _H<UILocalizedIndexedCollation> collation([[[$UILocalizedIndexedCollation alloc] initWithDictionary:dictionary] autorelease]);
10247 CollationLocale_ = MSHookIvar<NSLocale *>(collation, "_locale");
10249 if (kCFCoreFoundationVersionNumber >= 800 && [[CollationLocale_ localeIdentifier] isEqualToString:@"zh@collation=stroke"]) {
10250 CollationThumbs_ = [NSArray arrayWithObjects:@"1",@"•",@"4",@"•",@"7",@"•",@"10",@"•",@"13",@"•",@"16",@"•",@"19",@"A",@"•",@"E",@"•",@"I",@"•",@"M",@"•",@"R",@"•",@"V",@"•",@"Z",@"#",nil];
10251 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})
10252 CollationOffset_.push_back(offset);
10253 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];
10254 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];
10257 CollationThumbs_ = [collation sectionIndexTitles];
10258 for (size_t index(0), end([CollationThumbs_ count]); index != end; ++index)
10259 CollationOffset_.push_back([collation sectionForSectionIndexTitleAtIndex:index]);
10261 CollationTitles_ = [collation sectionTitles];
10262 CollationStarts_ = MSHookIvar<NSArray *>(collation, "_sectionStartStrings");
10264 NSString *&transform(MSHookIvar<NSString *>(collation, "_transform"));
10265 if (&transform != NULL && transform != nil) {
10266 /*if ([collation respondsToSelector:@selector(transformedCollationStringForString:)])
10267 CollationModify_ = [=](NSString *value) { return [collation transformedCollationStringForString:value]; };*/
10268 const UChar *uid(reinterpret_cast<const UChar *>([transform cStringUsingEncoding:NSUnicodeStringEncoding]));
10269 UErrorCode code(U_ZERO_ERROR);
10270 CollationTransl_ = utrans_openU(uid, -1, UTRANS_FORWARD, NULL, 0, NULL, &code);
10271 if (!U_SUCCESS(code))
10272 NSLog(@"%s", u_errorName(code));
10276 } @catch (NSException *e) {
10280 CollationLocale_ = [[[NSLocale alloc] initWithLocaleIdentifier:@"en@collation=dictionary"] autorelease];
10282 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];
10283 for (NSInteger offset(0); offset != 28; ++offset)
10284 CollationOffset_.push_back(offset);
10286 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];
10287 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];
10290 /* Parse Arguments {{{ */
10291 bool substrate(false);
10297 for (int argi(1); argi != argc; ++argi)
10298 if (strcmp(argv[argi], "--") == 0) {
10300 argv[argi] = argv[0];
10306 for (int argi(1); argi != arge; ++argi)
10307 if (strcmp(args[argi], "--substrate") == 0)
10310 fprintf(stderr, "unknown argument: %s\n", args[argi]);
10314 App_ = [[NSBundle mainBundle] bundlePath];
10317 Cache_ = [[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia", @"/var/mobile"] retain];
10319 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
10320 alloc_ = alloc->method_imp;
10321 alloc->method_imp = (IMP) &Alloc_;*/
10323 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
10324 dealloc_ = dealloc->method_imp;
10325 dealloc->method_imp = (IMP) &Dealloc_;*/
10327 void *gestalt(dlopen("/usr/lib/libMobileGestalt.dylib", RTLD_GLOBAL | RTLD_LAZY));
10328 $MGCopyAnswer = reinterpret_cast<CFStringRef (*)(CFStringRef)>(dlsym(gestalt, "MGCopyAnswer"));
10330 /* System Information {{{ */
10334 size = sizeof(maxproc);
10335 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
10336 perror("sysctlbyname(\"kern.maxproc\", ?)");
10337 else if (maxproc < 64) {
10339 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
10340 perror("sysctlbyname(\"kern.maxproc\", #)");
10343 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
10344 char *osversion = new char[size];
10345 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
10346 perror("sysctlbyname(\"kern.osversion\", ?)");
10348 System_ = [NSString stringWithUTF8String:osversion];
10350 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
10351 char *machine = new char[size];
10352 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
10353 perror("sysctlbyname(\"hw.machine\", ?)");
10355 Machine_ = machine;
10357 int64_t usermem(0);
10358 size = sizeof(usermem);
10359 if (sysctlbyname("hw.usermem", &usermem, &size, NULL, 0) == -1)
10362 SerialNumber_ = (NSString *) CYIOGetValue("IOService:/", @"IOPlatformSerialNumber");
10363 ChipID_ = [CYHex((NSData *) CYIOGetValue("IODeviceTree:/chosen", @"unique-chip-id"), true) uppercaseString];
10364 BBSNum_ = CYHex((NSData *) CYIOGetValue("IOService:/AppleARMPE/baseband", @"snum"), false);
10366 UniqueID_ = UniqueIdentifier(device);
10368 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
10369 Product_ = [info objectForKey:@"SafariProductVersion"];
10370 Safari_ = [info objectForKey:@"CFBundleVersion"];
10373 NSString *agent([NSString stringWithFormat:@"Cydia/%@ CyF/%.2f", Cydia_, kCFCoreFoundationVersionNumber]);
10375 if (RegEx match = RegEx("([0-9]+(\\.[0-9]+)+).*", Safari_))
10376 agent = [NSString stringWithFormat:@"Safari/%@ %@", match[1], agent];
10377 if (RegEx match = RegEx("([0-9]+[A-Z][0-9]+[a-z]?).*", System_))
10378 agent = [NSString stringWithFormat:@"Mobile/%@ %@", match[1], agent];
10379 if (RegEx match = RegEx("([0-9]+(\\.[0-9]+)+).*", Product_))
10380 agent = [NSString stringWithFormat:@"Version/%@ %@", match[1], agent];
10382 UserAgent_ = agent;
10384 /* Load Database {{{ */
10386 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
10388 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
10390 if (Metadata_ == NULL)
10391 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
10393 Settings_ = [Metadata_ objectForKey:@"Settings"];
10395 Packages_ = [Metadata_ objectForKey:@"Packages"];
10397 Values_ = [Metadata_ objectForKey:@"Values"];
10398 Sections_ = [Metadata_ objectForKey:@"Sections"];
10399 Sources_ = [Metadata_ objectForKey:@"Sources"];
10401 Token_ = [Metadata_ objectForKey:@"Token"];
10403 Version_ = [Metadata_ objectForKey:@"Version"];
10406 if (Values_ == nil) {
10407 Values_ = [[[NSMutableDictionary alloc] initWithCapacity:4] autorelease];
10408 [Metadata_ setObject:Values_ forKey:@"Values"];
10411 if (Sections_ == nil) {
10412 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
10413 [Metadata_ setObject:Sections_ forKey:@"Sections"];
10416 if (Sources_ == nil) {
10417 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
10418 [Metadata_ setObject:Sources_ forKey:@"Sources"];
10421 if (Version_ == nil) {
10422 Version_ = [NSNumber numberWithUnsignedInt:0];
10423 [Metadata_ setObject:Version_ forKey:@"Version"];
10426 if ([Version_ unsignedIntValue] == 0) {
10427 CydiaAddSource(@"http://apt.thebigboss.org/repofiles/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10428 CydiaAddSource(@"http://apt.modmyi.com/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10429 CydiaAddSource(@"http://cydia.zodttd.com/repo/cydia/", @"stable", [NSMutableArray arrayWithObject:@"main"]);
10430 CydiaAddSource(@"http://repo666.ultrasn0w.com/", @"./");
10432 Version_ = [NSNumber numberWithUnsignedInt:1];
10433 [Metadata_ setObject:Version_ forKey:@"Version"];
10435 [Metadata_ removeObjectForKey:@"LastUpdate"];
10440 _H<NSMutableArray> broken([NSMutableArray array]);
10441 for (NSString *key in (id) Sources_)
10442 if ([key rangeOfCharacterFromSet:[NSCharacterSet characterSetWithCharactersInString:@"# "]].location != NSNotFound)
10443 [broken addObject:key];
10444 if ([broken count] != 0) {
10445 for (NSString *key in (id) broken)
10446 [Sources_ removeObjectForKey:key];
10451 _root(CydiaWriteSources());
10454 mkdir("/var/mobile/Library/Cydia", 0755);
10455 MetaFile_.Open("/var/mobile/Library/Cydia/metadata.cb0");
10458 if (Packages_ != nil) {
10460 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, &fail);
10464 [Metadata_ removeObjectForKey:@"Packages"];
10470 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
10472 #define MobileSubstrate_(name) \
10473 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", F_OK) == 0) { \
10474 void *handle(dlopen("/Library/MobileSubstrate/DynamicLibraries/" #name ".dylib", RTLD_LAZY | RTLD_GLOBAL)); \
10475 if (handle == NULL) \
10476 NSLog(@"%s", dlerror()); \
10479 MobileSubstrate_(Activator)
10480 MobileSubstrate_(libstatusbar)
10481 MobileSubstrate_(SimulatedKeyEvents)
10482 MobileSubstrate_(WinterBoard)
10484 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
10485 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
10487 if (kCFCoreFoundationVersionNumber > 1000)
10488 system("/usr/libexec/cydia/cydo /usr/libexec/cydia/setnsfpn /var/lib");
10490 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
10492 if (access("/User", F_OK) != 0 || version != 6) {
10494 system("/usr/libexec/cydia/cydo /usr/libexec/cydia/firmware.sh");
10498 if (access("/tmp/cydia.chk", F_OK) == 0) {
10499 if (unlink([Cache("pkgcache.bin") UTF8String]) == -1)
10500 _assert(errno == ENOENT);
10501 if (unlink([Cache("srcpkgcache.bin") UTF8String]) == -1)
10502 _assert(errno == ENOENT);
10505 /* APT Initialization {{{ */
10506 _assert(pkgInitConfig(*_config));
10507 _assert(pkgInitSystem(*_config, _system));
10510 _config->Set("APT::Acquire::Translation", lang);
10512 // XXX: this timeout might be important :(
10513 //_config->Set("Acquire::http::Timeout", 15);
10515 _config->Set("Acquire::http::MaxParallel", usermem >= 384 * 1024 * 1024 ? 16 : 3);
10517 mkdir([Cache_ UTF8String], 0755);
10518 mkdir([Cache("archives") UTF8String], 0755);
10519 mkdir([Cache("archives/partial") UTF8String], 0755);
10520 _config->Set("Dir::Cache", [Cache_ UTF8String]);
10522 mkdir([Cache("lists") UTF8String], 0755);
10523 mkdir([Cache("lists/partial") UTF8String], 0755);
10524 mkdir([Cache("periodic") UTF8String], 0755);
10525 _config->Set("Dir::State::Lists", [Cache("lists") UTF8String]);
10527 std::string logs("/var/mobile/Library/Logs/Cydia");
10528 mkdir(logs.c_str(), 0755);
10529 _config->Set("Dir::Log::Terminal", logs + "/apt.log");
10531 _config->Set("Dir::Bin::dpkg", "/usr/libexec/cydia/cydo");
10533 /* Color Choices {{{ */
10534 space_ = CGColorSpaceCreateDeviceRGB();
10536 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
10537 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
10538 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
10539 Folder_.Set(space_, 0x8e/255.f, 0x8e/255.f, 0x93/255.f, 1.0);
10540 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
10541 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
10542 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
10543 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
10544 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
10545 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
10547 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
10548 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
10550 /* UIKit Configuration {{{ */
10551 // XXX: I have a feeling this was important
10552 //UIKeyboardDisableAutomaticAppearance();
10555 $SBSSetInterceptsMenuButtonForever = reinterpret_cast<void (*)(bool)>(dlsym(RTLD_DEFAULT, "SBSSetInterceptsMenuButtonForever"));
10557 const char *symbol(kCFCoreFoundationVersionNumber >= 800 ? "MGGetBoolAnswer" : "GSSystemHasCapability");
10558 BOOL (*GSSystemHasCapability)(CFStringRef) = reinterpret_cast<BOOL (*)(CFStringRef)>(dlsym(RTLD_DEFAULT, symbol));
10559 bool fast = GSSystemHasCapability != NULL && GSSystemHasCapability(CFSTR("armv7"));
10561 PulseInterval_ = fast ? 50000 : 500000;
10563 Colon_ = UCLocalize("COLON_DELIMITED");
10564 Elision_ = UCLocalize("ELISION");
10565 Error_ = UCLocalize("ERROR");
10566 Warning_ = UCLocalize("WARNING");
10569 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
10571 CGColorSpaceRelease(space_);
10572 CFRelease(Locale_);